http://stackoverflow.com/q/50132383
has title: Checking the existence of string characters in list of strings in another list?
possible better answer: http://stackoverflow.com/a/50132562
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87283848
has answer: http://stackoverflow.com/a/50132562
upvote count: 2
accepted answer: http://stackoverflow.com/a/50132549
downvote count: 0
has answer: http://stackoverflow.com/a/50132615
has answer: http://stackoverflow.com/a/50132549
tagged with: string
has answer: http://stackoverflow.com/a/50132568
favorite count: 0
linked to: http://stackoverflow.com/q/48541444
type: Question
tagged with: python-3.x
answer count: 5
has comment: http://stackoverflow.com/comment/87282841
has answer: http://stackoverflow.com/a/50132663
tagged with: python
has comment: http://stackoverflow.com/comment/87283219
has body: Is there a more efficient way to compare a list of strings rather than using a for loops? I would like to check the existence of x strings in y (at any part of y strings). x = ['a1' , 'a2', 'bk'] y = ['a1aa' , 'a2lop' , 'bnkl', 'a1sss', 'flask'] for i in x: print([i in str_y for str_y in y]) Results: [True, False, False, True, False] [False, True, False, False, False] [False, False, False, False, False]
has comment: http://stackoverflow.com/comment/87283021

python
tags question: http://stackoverflow.com/q/50179796
tags question: http://stackoverflow.com/q/50145465
tags question: http://stackoverflow.com/q/50118568
tags question: http://stackoverflow.com/q/50115125
tags question: http://stackoverflow.com/q/50195694
tags question: http://stackoverflow.com/q/50127352
tags question: http://stackoverflow.com/q/50223019
tags question: http://stackoverflow.com/q/50227854
tags question: http://stackoverflow.com/q/50074853
tags question: http://stackoverflow.com/q/50169443
tags question: http://stackoverflow.com/q/50077751
tags question: http://stackoverflow.com/q/50090997
tags question: http://stackoverflow.com/q/50187667
tags question: http://stackoverflow.com/q/50204698
tags question: http://stackoverflow.com/q/50211310
tags question: http://stackoverflow.com/q/50078995
tags question: http://stackoverflow.com/q/50104637
tags question: http://stackoverflow.com/q/50127899
tags question: http://stackoverflow.com/q/50123600
tags question: http://stackoverflow.com/q/50190928
tags question: http://stackoverflow.com/q/50174656
tags question: http://stackoverflow.com/q/50225264
tags question: http://stackoverflow.com/q/50088536
tags question: http://stackoverflow.com/q/50156607
tags question: http://stackoverflow.com/q/50209797
tags question: http://stackoverflow.com/q/50214621
tags question: http://stackoverflow.com/q/50223735
tags question: http://stackoverflow.com/q/50203732
tags question: http://stackoverflow.com/q/50100307
tags question: http://stackoverflow.com/q/50133484
tags question: http://stackoverflow.com/q/50128142
tags question: http://stackoverflow.com/q/50077264
tags question: http://stackoverflow.com/q/50228397
tags question: http://stackoverflow.com/q/50147095
tags question: http://stackoverflow.com/q/50142427
tags question: http://stackoverflow.com/q/50218124
tags question: http://stackoverflow.com/q/50206222
tags question: http://stackoverflow.com/q/50144717
tags question: http://stackoverflow.com/q/50139469
tags question: http://stackoverflow.com/q/50217722
tags question: http://stackoverflow.com/q/50156311
tags question: http://stackoverflow.com/q/50161691
tags question: http://stackoverflow.com/q/50091331
tags question: http://stackoverflow.com/q/50170011
tags question: http://stackoverflow.com/q/50082549
tags question: http://stackoverflow.com/q/50183725
tags question: http://stackoverflow.com/q/50090101
tags question: http://stackoverflow.com/q/50097648
tags question: http://stackoverflow.com/q/50193538
tags question: http://stackoverflow.com/q/50171829
tags question: http://stackoverflow.com/q/50175299
tags question: http://stackoverflow.com/q/50217878
tags question: http://stackoverflow.com/q/50134054
tags question: http://stackoverflow.com/q/50146473
tags question: http://stackoverflow.com/q/50096846
tags question: http://stackoverflow.com/q/50134221
tags question: http://stackoverflow.com/q/50087319
tags question: http://stackoverflow.com/q/50110321
tags question: http://stackoverflow.com/q/50225795
tags question: http://stackoverflow.com/q/50111164
tags question: http://stackoverflow.com/q/50198633
tags question: http://stackoverflow.com/q/50223662
tags question: http://stackoverflow.com/q/50165953
tags question: http://stackoverflow.com/q/50091000
tags question: http://stackoverflow.com/q/50180123
tags question: http://stackoverflow.com/q/50146735
tags question: http://stackoverflow.com/q/50123028
tags question: http://stackoverflow.com/q/50171128
tags question: http://stackoverflow.com/q/50218050
tags question: http://stackoverflow.com/q/50139993
tags question: http://stackoverflow.com/q/50119083
tags question: http://stackoverflow.com/q/50094461
tags question: http://stackoverflow.com/q/50101119
tags question: http://stackoverflow.com/q/50190131
tags question: http://stackoverflow.com/q/50165115
tags question: http://stackoverflow.com/q/50080087
tags question: http://stackoverflow.com/q/50220333
tags question: http://stackoverflow.com/q/50207292
tags question: http://stackoverflow.com/q/50089210
tags question: http://stackoverflow.com/q/50110073

http://stackoverflow.com/comment/87227920
score: 0
type: Comment
type: AnswerComment
has text: This one works as well :-o
comment on: http://stackoverflow.com/a/50105041

http://stackoverflow.com/comment/87319431
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50150459
has text: @Tom92 we cannot properly answer your question without having a representative sample of your file's content.
type: Comment

http://stackoverflow.com/q/50109718
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
answer count: 0
score: 1
downvote count: 0
tagged with: tfrecord
upvote count: 1
tagged with: tensorflow
has title: Creating images from time series features during graph execution using Tensorflow tf.data
favorite count: 0
type: Question
has body: Setup The data are one dimensional time series data. A sliding window (frame) runs across the data and extracts a 100 dimensional vector of features f_{i}( t_{j} ), where i is a file index, and j is the time index of the frame. Energies from n consecutive frames are stacked to form a 2D "image", which is the input to the classifier. Basic Approach Just save the stacked vectors in a tfrecords file and you are good to go. The drawback is that the stacked vectors have a lot of duplicate data and consume a lot of space. If the we have 10 gigs of feature vectors, then stacking 10 frames of history would require 50 gigs (+ overhead) of space. However, we can let tf.data do the shuffling, prefetching, batch creation and what not. Very convenient! Desired Approach A implementation where we save only the feature vectors as a tfrecords file, and create the stacked feature vector (images) on the fly. Question Has this been encountered and dealt with before? Would most people just not care about the high level of repetition in their data or the amount of space consumed? How difficult is it to get the desired implementation. Even naively shuffling the data would mess up the time ordering. I've also only used tf.data in a way where I call iterator.get_next() to get the feature and label form one example, and then give it to the graph. I suppose I'd also need to figure out how to get not only the current example's feat and label, but also those of it's predecessors in time! So I'm looking for some tips on how to accomplish this. Here is an image of the process for images formed from 2 frames of feature vectors. Note that in this case, each feature vector would appear twice in the tfrecords data file :

http://stackoverflow.com/comment/87205706
has text: now I used virtual environment but the error still there my databse settings:DATABASES = { 'default' :{ 'ENGINE' : 'django.db.backends.mysql', 'NAME' :'MasterQuote', 'USER' : 'root', 'PASSWORD' : 'root', 'HOST' : 'localhost', 'PORT' : '' } }
comment on: http://stackoverflow.com/q/50094716
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50228351
tagged with: python
tagged with: airflow-scheduler
has title: Airflow Scheduler creating PID for same dag to generate tasks every time
has answer: http://stackoverflow.com/a/50238688
score: 2
answer count: 1
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: airflow
downvote count: 0
has body: I am using Local Executor. I have a situation where i have unique dags getting generated for each request id for eg 1.py , 2.py . 1.py assume has two tasks and 2.py has 3 tasks. I would also receive more dags periodically for eg 3.py,4.py etc. Is there any problem of creating a dag for every new id/request ID. I have observed that Scheduler keeps giving this log. Started a process (PID: 92186) to generate tasks for /Users/nshar141/airflow/dags/3.py - logging into /Users/nshar141/airflow/logs/scheduler/2018-05-07/3.py.log My question here is why scheduler keeps generating separate PIDs for generating tasks. I tried changing different parameters in the config related to concurrency and parallelism but scheduler seems to be executing that statement everytime for every dag present in dags folder. I am attaching my dag definition. I want to run dag as soon as it is created. What are the parameters i should give in start_time and scheduler_interval? dag = DAG('3', description='Sample DAG',schedule_interval=@once,start_date=datetime(2018, 5, 07), catchup=False) Since i have a need to generate dags dynamically with unique dag id and place it in the dags folder my concern here is scheduler would generate too many process IDS for every dag in the folder which already has been executed.
linked to: http://stackoverflow.com/q/39133376

http://stackoverflow.com/q/50080929
answer count: 3
tagged with: python
has title: Is it possible to compute per-example gradients efficiently in TensorFlow, in just one graph run?
has body: TD;DR: is there a way to evaluate f'(x1), f'(x2), ..., f'(xn) in just one graph run, in a vectorized form? Where f'(x) is the derivative of f(x). Something like: x = tf.placeholder(tf.float32, shape=[100]) f = tf.square(x) f_grad = tf.multiple_gradients(x) # f_grad contains f'(x[0]), f'(x[1]), ... More specifically, I'm trying to implement Black Box Stochastic Variational Inference (BBSVI) manually (I know I could use a library like Edward, but I'm trying to implement it myself). At one point, I need to compute the mean of f'(x)g(x) across many different values of x (x1, x2, ..., xn), where f(x) and g(x) are two functions, and f'(x) is the derivative of f(x). Using TensorFlow's autodiff feature, I can compute f'(x1), f'(x2), ..., f'(xn), by simply calling f_prime.eval(feed_dict={x: xi}) once for each value xi in (x1, x2, ..., xn). This is not efficient at all: I would like to use a vectorized form instead, but I'm not sure how to do this. Perhaps using tf.stop_gradient() somehow? Or using the grad_ys argument in tf.gradients()?
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/58227264
tagged with: gradient
has answer: http://stackoverflow.com/a/50085879
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/60838898
score: 3

http://stackoverflow.com/q/50119792
has body: I tried to import an excel file which is not within the same folder than the script. I need to get one folder above, then into another folder (B_folder) and there is file 2_file.xlsx I tried: df = pd.read_excel(r'..\B_folder\2_file.xlsx') and got: FileNotFoundError: [Errno 2] No such file or directory: '..\\B_folder\\2_file.xlsx' also tried: foreslash instead of backslash without the 'r' before path but I always get the error message above or this one: OSError: [Errno 22] Invalid argument: '..\\B_folder\2_file.xlsx' what is wrong?
has comment: http://stackoverflow.com/comment/87257058
tagged with: python
has comment: http://stackoverflow.com/comment/87257067
has comment: http://stackoverflow.com/comment/87257117
has comment: http://stackoverflow.com/comment/87257358
has comment: http://stackoverflow.com/comment/87257038
has title: Python: Import excel file using relative path
tagged with: importerror
duplicate of: http://stackoverflow.com/q/12201928
tagged with: pandas
type: AnsweredQuestion
score: 7
possible better answer: http://stackoverflow.com/a/50120018
has comment: http://stackoverflow.com/comment/87257094
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50120018
tagged with: import-from-excel
has comment: http://stackoverflow.com/comment/87257160
upvote count: 8
accepted answer: http://stackoverflow.com/a/50251905
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50251905
linked to: http://stackoverflow.com/q/12201928

http://stackoverflow.com/comment/87232253
type: Comment
type: QuestionComment
score: 0
has text: If I would place it, just above Installed Apps, would this be considered the proper structure? Oh and thanks for the very fast replies!
comment on: http://stackoverflow.com/q/50107306

http://stackoverflow.com/comment/87387733
score: 0
has text: do you mean `eval()`?
type: QuestionComment
comment on: http://stackoverflow.com/q/50185280
type: Comment

http://stackoverflow.com/comment/87299270
has text: Something seems to be wrong with your check routine, because it finds only the smaller of two squares for `[ (0,0), (0,2), (0,4), (2,0), (2,2), (2,6), (4,4) ]`. Those are the green points in the picture above.
comment on: http://stackoverflow.com/a/50124425
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50092276
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50091995
type: Answer
has body: def arith(x, y, operation): if operation == 'add': return x + y if operation == 'mult': return x * y arith(2, 3, 'add') arith(2, 3, 'mult') The problem is that add and mult are not defined. By wrapping them each in quotes, 'add' and 'mult', you define them as string. Check out this documentation on strings for more information.
score: 1

http://stackoverflow.com/q/50229140
linked to: http://stackoverflow.com/q/816391
has answer: http://stackoverflow.com/a/58418288
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87475758
accepted answer: http://stackoverflow.com/a/50229345
favorite count: 0
possible better answer: http://stackoverflow.com/a/58418288
has answer: http://stackoverflow.com/a/50229345
type: Question
tagged with: python-3.x
has title: how can pylint msg "too many local variables" be disabled
upvote count: 12
tagged with: pylint
tagged with: python
has body: I am working on eclipse editor and using eclipse plugin pydev. I have also installed pylint plugin. But pylint is throwing me warning messages in some functions like "too many local arguments". I don't want to change my code. Is there any way to disable those warnings, especially this one. I do have a ~/.pylintrc file. What should I add to that file to disable these warning messages.
score: 12
type: AnsweredQuestion

http://stackoverflow.com/q/50138925
has answer: http://stackoverflow.com/a/50150744
possible better answer: http://stackoverflow.com/a/50150744
has answer: http://stackoverflow.com/a/50140810
accepted answer: http://stackoverflow.com/a/50140810
favorite count: 0
tagged with: laravel
type: Question
tagged with: redis
linked to: http://stackoverflow.com/q/8793448
linked to: http://stackoverflow.com/q/32389158
tagged with: python
tagged with: php
linked to: http://stackoverflow.com/q/5935501
type: AnsweredQuestion
tagged with: phpredis
answer count: 2
has title: Redis : is it possible to share datetimes directly between php/laravel and python?
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/11875770
has body: I'm using Redis (phpredis) to share data between my Laravel and my Python app. Within Laravel, I save on a specific channel my array: $data = MyModel::where('start_date','&gt;', "2018-05-02 10:00:00")-&gt;get(); // $data = [{'id':1, 'start_date': "2018-05-03 12:00:00", 'name': "}…] Redis::set("barChannel", json_encode($data)); Within Python, I read this data: import redis import json myredis = redis.Redis() data = json.loads(myredis.get('barChannel')); // data = [{'id':1, 'start_date': "2018-05-03 12:00:00", 'name': "}…] So basically the data passes successfully but instead of having directly a datetime value in my python list, I have a string which I have to convert. With the above example I can use then datetime.datetime.strptime but in the case of more complicated data structure (nested lists of dicts)... it's quite a pain to convert each variable. Is there a way to store datetimes in Redis which would be natively recognized in Python?

http://stackoverflow.com/q/50100067
accepted answer: http://stackoverflow.com/a/50103776
answer count: 1
has comment: http://stackoverflow.com/comment/87216818
has answer: http://stackoverflow.com/a/50103776
has comment: http://stackoverflow.com/comment/87216618
downvote count: 1
type: AnsweredQuestion
tagged with: python
score: -1
has body: I want to UPDATE an image in a local FileMaker database using the ODBC connection. I expected that the following code would work, but it fails: import pyodbc with open('myimage.jpg', 'rb') as f: img = f.read() # ensure we have a valid image assert isinstance(img, bytes) assert len(img) == 10506 dsn = 'DRIVER=/Library/ODBC/FileMaker ODBC.bundle/Contents/MacOS/fmodbc.so;Server=127.0.0.1;Port=2399;Database=MyDatabase;UID=Admin;PWD=' cnxn = pyodbc.connect(dsn) cnxn.setencoding(encoding='utf-8') cnxn.setdecoding(pyodbc.SQL_CHAR, encoding='macroman') cursor = cnxn.cursor() q = "UPDATE MyTable SET PutAs(Image, 'JPEG')=? WHERE Id=?" cursor.execute(q, img, 37370) It raises an exception: ProgrammingError: '42000', '[42000] [FileMaker][FileMaker] FQL0001/(1:18): There is an error in the syntax of the query. (8310) (SQLPrepare)'. Reading an images with SELECT GetAs(Image, 'JPEG') FROM MyTable WHERE Id=37370) works fine. I receive a bytes objects which is the image.
tagged with: odbc
tagged with: filemaker
favorite count: 0
type: Question
has title: Updating container (binary blob) to FileMaker via pyodbc
upvote count: 0

http://stackoverflow.com/comment/87270834
has text: This worked with some minor modifications. Since some of my results are Empty Sets (SQL) or np.nan (Python float), using a pandas join on `name` worked best. I'd rather join on a numerical field but that's not always possible. Thanks much!
comment on: http://stackoverflow.com/a/50112099
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87320313
has text: As i expected, it was something obvious! thanks to both Susensio & @mihai-alexandru-ionut
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50150151

edit-distance
type: Tag
tag name: edit-distance
tags question: http://stackoverflow.com/q/50170288

http://stackoverflow.com/q/50210715
has body: I am new to Python, and I want to determine the type of each column in a data frame, I wrote the code below, but the results are not as expected, I only get 'object' for type. This is my data frame (just the first 7 th column): IDINDUSANALYSE IDINDUS IDINDUSEFFLUENT DATEANALYSE IDTYPEECHANTILLON IDPRELEVEUR IDLABO IDORIGINEVAL CONFORME CONFCALC IDINDDOSS CONFFORCE 672 635 6740 10/01/13 2 1 3 1 1 1 531 0 673 635 6740 11/01/13 2 1 3 1 1 1 531 0 674 635 6740 14/01/13 2 1 3 1 1 1 531 0 675 635 6740 15/01/13 2 1 3 1 1 1 531 0 676 635 6740 16/01/13 2 1 3 1 1 1 531 0 677 635 6740 18/01/13 2 1 3 1 1 1 531 0 This is my code: import pandas as pd import csv with open("/home/***/Documents/Table3.csv") as f: r = csv.reader(f) df = pd.DataFrame().from_records(r) for index, row in df.iterrows(): print(df.dtypes) As a result I get this : 0 object 1 object 2 object 3 object 4 object Please tell we what I did wrong ?
has answer: http://stackoverflow.com/a/50211309
score: 0
tagged with: types
has title: Why did I get dtype 'object' on reading in my data frame?
possible better answer: http://stackoverflow.com/a/50210791
type: Question
has answer: http://stackoverflow.com/a/50210791
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50211515
has comment: http://stackoverflow.com/comment/87439792
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50211309
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/50218702
answer count: 1
tagged with: neo4j
tagged with: nodes
type: Question
has title: How to delete a node from Neo4j databse with python 3.6
has body: I've trying to delete a node from neo4j database, using python code but I can't get to work. I've tried a few things and yet nothing. This is the documentation in Neo4j to delete a node: MATCH (n) DETACH DELETE n I've searched online for examples, but I don't know how code this same lines in python. Nodes relationships and characteristics This is an image of my nodes, I only want to delete the red ones. How do I delete just one of them?
tagged with: database
accepted answer: http://stackoverflow.com/a/50220374
tagged with: python
has answer: http://stackoverflow.com/a/50220374
has comment: http://stackoverflow.com/comment/87454379
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87440184
score: 1
type: QuestionComment
has text: replace word[-1:] by word[::-1]
type: Comment
comment on: http://stackoverflow.com/q/50211578

http://stackoverflow.com/comment/87220673
comment on: http://stackoverflow.com/q/50100996
has text: Ahaa!!! There is a missing `return` in the recurring function `find_starting_day`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87256587
type: Comment
has text: Yep, but at a given time, there would be only one python process running at a time. The other option can be running the `ffmpeg` process from python itself and then processing it's output in python and then upload them to the cloud. But then you will have to manage a lot of edge cases and concurrency/async/timeouts for uploads. Another option could be the `inotify` in conjunction with multiprocessing. `inotify` is basically a system hook which tells you if there are new files are created in a given directory and then process those newly created files in parallel if you want.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50118006

http://stackoverflow.com/q/50078791
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87174067
has comment: http://stackoverflow.com/comment/87174286
answer count: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87173952
tagged with: function
tagged with: user-interface
downvote count: 0
tagged with: button
upvote count: 1
has answer: http://stackoverflow.com/a/66264090
has comment: http://stackoverflow.com/comment/87179725
has comment: http://stackoverflow.com/comment/87174450
type: AnsweredQuestion
has body: I'm trying to create a basic game in tkinter to get familiar with GUI programming with Python. I'm not trying to make it efficient, hence the copy and paste of the same statement many times. I'm trying to make it so when a user clicks a button it changes the text of the button to either 'X' or 'O' depending on who's turn it is. In my button I have the command = followed by my function to change the text to either of the two options. However when I click on one button, the whole grid of buttons changes to that text. So I'm trying to find out if there is something like this I could use: command = lambda:[placeX() or placeO()] My code is below: import tkinter as tk, sys as s Startwindow = tk.Tk() Startwindow.title("Tic-Tac-Toe") Startwindow.resizable(0,0) Startwindow.geometry("1200x600") image = tk.PhotoImage(file="C:\\Users\\Joshua Brown\\Desktop\\tic tac toe\\download.gif") renderImage = tk.Label(image=image) renderImage.grid() def exe(): print("Game has exited.") Startwindow.destroy() s.exit("Requested to close.") def start(): print("Game window opening...") gameWindow = tk.Tk() gameWindow.title("Tic-Tac-Toe: Game Window") gameWindow.geometry("450x483") gameWindow.resizable(0,0) Startwindow.iconbitmap(r'C:\Users\Joshua Brown\Desktop\tic tac toe\tictactoe_H4a_icon.ico') board1 = tk.Button(gameWindow, text = "1", command = lambda:[placeX(), placeO()], height = 10, width = 20) board1.grid(row=0, column=0) board2 = tk.Button(gameWindow, text = "2", command = lambda:[placeX(),placeO()], height = 10, width = 20) board2.grid(row=1, column=0) board3 = tk.Button(gameWindow, text = "3", command = lambda:[placeX(),placeO()], height = 10, width = 20) board3.grid(row=2, column=0) board4 = tk.Button(gameWindow, text = "4", command = lambda:[placeX(),placeO()], height = 10, width = 20) board4.grid(row=0, column=1) board5 = tk.Button(gameWindow, text = "5", command = lambda:[placeX(),placeO()], height = 10, width = 20) board5.grid(row=1, column=1) board6 = tk.Button(gameWindow, tex…
has title: How to call two functions separately on condition using tkinter buttons?
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50080403
possible better answer: http://stackoverflow.com/a/66264090
has answer: http://stackoverflow.com/a/50080403

http://stackoverflow.com/comment/87292655
type: QuestionComment
has text: now is it using `numpy` or `list` ? [mcve] please
comment on: http://stackoverflow.com/q/50137159
score: 0
type: Comment

http://stackoverflow.com/comment/87378266
type: QuestionComment
comment on: http://stackoverflow.com/q/50178477
has text: `print os.path.join(folder,img)` -- does that give you a path you expect? Your script only creates the "test" directory, but you're quite likely trying to save things like "test/samples/foo.jpg"...
type: Comment
score: 1

http://stackoverflow.com/comment/87241623
type: QuestionComment
comment on: http://stackoverflow.com/q/50109138
score: 0
has text: @SufiyanGhori yes. I tried setting the setuid bit however apparently I would need to do it to the interpreter, not the script
type: Comment

http://stackoverflow.com/q/50149789
has body: I am looking to apply an OR query on a list of elements in expertiseParams My code is : queryset_list = Profile.objects.all() for expertise in expertiseParams: queryset_list = queryset_list.filter(Q(expertisematch__expertise=expertise)) My question is : how can I implement an OR logic on all the Q objects filtered? Thank you!
tagged with: django
tagged with: python
has title: Apply OR logic on Q objects query in a list
has comment: http://stackoverflow.com/comment/87317563
score: 0
tagged with: sql
has comment: http://stackoverflow.com/comment/87317453
answer count: 1
has comment: http://stackoverflow.com/comment/87317617
type: Question
linked to: http://stackoverflow.com/q/9304908
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50150043

http://stackoverflow.com/a/50133463
has comment: http://stackoverflow.com/comment/87294965
score: 1
downvote count: 0
upvote count: 1
has body: Check your cassandra.yaml, it ca be a configuration problem. Set your Cassandra to listen for connections on the local machine’s IP address instead of on “localhost” This is required to connect to Cassandra from remote clients. Check the variables “listen_address” and “rpc_address” in the cassandra.yaml, e.g: listen_address: 54.244.59.178 rpc_address: 54.244.59.178 Use your machine’s IP address in your setup.
answers question: http://stackoverflow.com/q/50133234
type: Answer
has comment: http://stackoverflow.com/comment/87290738

http://stackoverflow.com/comment/87492566
type: AnswerComment
comment on: http://stackoverflow.com/a/50205861
has text: @JohnFisher It did
type: Comment
score: 0

http://stackoverflow.com/comment/87178184
type: QuestionComment
comment on: http://stackoverflow.com/q/50081086
score: 1
has text: If you want a JSON object, not a JSON string, then why are you passing a *string* to `json.dump` instead of the corresponding data python data type (a `dict`)?
type: Comment

http://stackoverflow.com/comment/87431275
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50207157
has text: No, but the `json` module does.

http://stackoverflow.com/comment/87191359
type: QuestionComment
has text: I added my own variant of implementing the model and the results I got. I got nothing sensible for your initial values, physically impossible large results.
score: 0
comment on: http://stackoverflow.com/q/50085520
type: Comment

http://stackoverflow.com/comment/87405140
type: AnswerComment
has text: I initially used the lesk algorithm (from nltk.wsd import lesk) but the results were not satisfying so I thought word2vec would be a better approach. Could you recommend me an alternative?
type: Comment
comment on: http://stackoverflow.com/a/50191902
score: 0

http://stackoverflow.com/q/50122543
possible better answer: http://stackoverflow.com/a/50122581
tagged with: excel
tagged with: timestamp
has answer: http://stackoverflow.com/a/50122707
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50122707
has comment: http://stackoverflow.com/comment/87263609
answer count: 3
has title: Convert a large list of timestamps in an excel file from one format to another with python
has comment: http://stackoverflow.com/comment/87263458
downvote count: 1
tagged with: python
score: -1
has body: I have an excel file named "hello123.xlsx". There is a column of timestamps that has a lot of rows (more than 80,000 rows for now). The excel file basically looks like this: Tue Mar 13 14:51:04 +0000 2018 Tue Mar 13 14:51:10 +0000 2018 Tue Mar 13 14:51:11 +0000 2018 Tue Mar 13 14:51:12 +0000 2018 Tue Mar 13 14:51:13 +0000 2018 Tue Mar 13 14:51:13 +0000 2018 Tue Mar 13 14:51:15 +0000 2018 Tue Mar 13 14:51:35 +0000 2018 Tue Mar 13 14:51:43 +0000 2018 Tue Mar 13 14:52:12 +0000 2018 And so on... As can be seen above, the timestamps I have is in the format of this: %a %b %d %H:%M:%S +0000 %Y. But I need to convert it to the standard format like %m/%d/%Y %H:%M:%S. So basically I have to read a column of numerous timestamps in an excel file and then to convert them to a new format in a new column. I'm very new to python and I searched some methods online but failed to do so. I hope someone can help figure it out I would really appreciate that. :)
has answer: http://stackoverflow.com/a/50123083
favorite count: 0
has answer: http://stackoverflow.com/a/50122581
type: Question
has comment: http://stackoverflow.com/comment/87263138
upvote count: 0
has comment: http://stackoverflow.com/comment/87263118
has comment: http://stackoverflow.com/comment/87263643

http://stackoverflow.com/comment/87309203
comment on: http://stackoverflow.com/q/50145529
score: 0
has text: at least one of these is wrong `self.filter_lowcut, self.filter_highcut, self.signal_frequency`
type: Comment
type: QuestionComment

python-2.7
tags question: http://stackoverflow.com/q/50201787
tags question: http://stackoverflow.com/q/50225203
tags question: http://stackoverflow.com/q/50118036
tags question: http://stackoverflow.com/q/50196322
tags question: http://stackoverflow.com/q/50218877
tags question: http://stackoverflow.com/q/50075118
tags question: http://stackoverflow.com/q/50081211
tags question: http://stackoverflow.com/q/50118568
tags question: http://stackoverflow.com/q/50211310
tags question: http://stackoverflow.com/q/50127494
tags question: http://stackoverflow.com/q/50090101
tags question: http://stackoverflow.com/q/50134221
tags question: http://stackoverflow.com/q/50119083
tags question: http://stackoverflow.com/q/50091231
tags question: http://stackoverflow.com/q/50209216
tags question: http://stackoverflow.com/q/50160791
tags question: http://stackoverflow.com/q/50189993
tags question: http://stackoverflow.com/q/50140588
tags question: http://stackoverflow.com/q/50211209
tags question: http://stackoverflow.com/q/50081796
tags question: http://stackoverflow.com/q/50126058
tags question: http://stackoverflow.com/q/50102202
tags question: http://stackoverflow.com/q/50077928
tags question: http://stackoverflow.com/q/50105250
tags question: http://stackoverflow.com/q/50107909
tags question: http://stackoverflow.com/q/50212051
tags question: http://stackoverflow.com/q/50090072
tags question: http://stackoverflow.com/q/50122268
tags question: http://stackoverflow.com/q/50183728
tags question: http://stackoverflow.com/q/50153092
tags question: http://stackoverflow.com/q/50182546
tags question: http://stackoverflow.com/q/50115755
tags question: http://stackoverflow.com/q/50195971
tags question: http://stackoverflow.com/q/50139114
tags question: http://stackoverflow.com/q/50220004
tags question: http://stackoverflow.com/q/50082127
tags question: http://stackoverflow.com/q/50227636
tags question: http://stackoverflow.com/q/50164743
tags question: http://stackoverflow.com/q/50175564
tags question: http://stackoverflow.com/q/50194909
tags question: http://stackoverflow.com/q/50111820
tags question: http://stackoverflow.com/q/50209580
tags question: http://stackoverflow.com/q/50164024
type: Tag
tags question: http://stackoverflow.com/q/50075979
tags question: http://stackoverflow.com/q/50113861
tags question: http://stackoverflow.com/q/50178052
tags question: http://stackoverflow.com/q/50141788
tags question: http://stackoverflow.com/q/50132985
tags question: http://stackoverflow.com/q/50089785
tags question: http://stackoverflow.com/q/50081301
tags question: http://stackoverflow.com/q/50148731
tags question: http://stackoverflow.com/q/50113927
tags question: http://stackoverflow.com/q/50186129
tags question: http://stackoverflow.com/q/50195029
tags question: http://stackoverflow.com/q/50177211
tags question: http://stackoverflow.com/q/50112966
tags question: http://stackoverflow.com/q/50114657
tags question: http://stackoverflow.com/q/50202010
tags question: http://stackoverflow.com/q/50220573
tags question: http://stackoverflow.com/q/50085360
tags question: http://stackoverflow.com/q/50091548
tags question: http://stackoverflow.com/q/50177804
tags question: http://stackoverflow.com/q/50084497
tags question: http://stackoverflow.com/q/50106345
tags question: http://stackoverflow.com/q/50092876
tags question: http://stackoverflow.com/q/50155728
tags question: http://stackoverflow.com/q/50153699
tags question: http://stackoverflow.com/q/50195991
tags question: http://stackoverflow.com/q/50181469
tags question: http://stackoverflow.com/q/50152689
tags question: http://stackoverflow.com/q/50137762
tags question: http://stackoverflow.com/q/50104225
tags question: http://stackoverflow.com/q/50093674
tags question: http://stackoverflow.com/q/50151905
tags question: http://stackoverflow.com/q/50194070
tags question: http://stackoverflow.com/q/50125582
tags question: http://stackoverflow.com/q/50075703
tags question: http://stackoverflow.com/q/50120633
tags question: http://stackoverflow.com/q/50142019

http://stackoverflow.com/comment/87479343
type: Comment
type: QuestionComment
has text: **Post the code you wrote and explain specifically what's wrong**. Otherwise unfortunately this comes across as seemingly a *"Give me teh codez"* question, which is detested on SO and will get instantly downvoted and closed. See [this](https://meta.stackoverflow.com/questions/253137/what-close-reason-should-i-use-for-give-me-teh-codez) for why, and how to avoid that when asking a question. Actually this one was essentially a duplicate, too, which is another reason it would be closed.
comment on: http://stackoverflow.com/q/50204440
score: 0

http://stackoverflow.com/a/50138695
has body: Without regex, and assuming the same format for all your strings, you could do this: mylist.sort(key = lambda x: int(''.join([i for i in x.split(',')[2] if i.isnumeric()]))) The list comprehension [i for i in x.split(',')[2] if i.isnumeric()] splits your string at the commas, takes the element at index 2 (which would be "Count=___"), and extracts all the numeric strings. Then, int(''.join joins those together and casts it to an integer. You can then use this as your key to sort your list.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50138556

http://stackoverflow.com/q/50079139
has body: I'm learning programming in Python and I'm stuck with a syntax error in the line 8 in the following code x = int(input('Add x:\n')) y = int(input('Add y:\n')) if x == y : print('x and y are equal') else : if x &lt; y : print('x is less than y') else x &gt; y : print('x is greater than y') I just don't see what's wrong there. The full error is: Traceback (most recent call last): File "compare.py", line 8 else x &gt; y : ^ SyntaxError: invalid syntax
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: nested
upvote count: 1
favorite count: 0
tagged with: conditional-statements
tagged with: if-statement
has comment: http://stackoverflow.com/comment/87174374
linked to: http://stackoverflow.com/q/16474599
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87174355
type: Question
has title: syntax error in if...else condition
has answer: http://stackoverflow.com/a/50079146
tagged with: syntax

http://stackoverflow.com/q/50170505
has answer: http://stackoverflow.com/a/50171277
tagged with: python
linked to: http://stackoverflow.com/q/245192
type: AnsweredQuestion
has body: I was asked to write a function in Python 3 for: Write a function called general_poly, that would, for example, evaluate general_poly([1, 2, 3, 4])(10) to 1234 because 1*10^3 + 2*10^2 + 3*10^1 + 4*10^0. Now I don't understand what the second parenthesis, (10), means. How would my function general_poly know, to take that value inside itself and use it?
linked to: http://stackoverflow.com/q/42874825
has title: What does the parenthesis after the function mean
answer count: 3
score: 7
has answer: http://stackoverflow.com/a/50170734
downvote count: 0
upvote count: 7
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87358648
accepted answer: http://stackoverflow.com/a/50170566
possible better answer: http://stackoverflow.com/a/50170734
tagged with: function
has answer: http://stackoverflow.com/a/50170566

http://stackoverflow.com/comment/87167646
comment on: http://stackoverflow.com/q/50075650
type: QuestionComment
score: 0
has text: i put self.textEdit.setHtml(str(fileName)) on the same level of print inside the loop and still only displaying the last record
type: Comment

http://stackoverflow.com/comment/130798821
score: 0
type: QuestionComment
has text: @DanRosenstark I searched pretty extensively at the time. Sad to see after 4 years nothing has changed. My project on GitHub below actually works really slick for me. I started writing my own python webserver to do it, but I don't know enough about possible hazards to do it well, so I let PHP and apache take care of that for me. Input would be appreciated.
comment on: http://stackoverflow.com/q/50196358
type: Comment

http://stackoverflow.com/comment/87466912
type: Comment
has text: I've have updated my solutions, Much appreciate if you can check if this make sense to you. thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/50210347
score: 0

http://stackoverflow.com/comment/87250600
score: 0
comment on: http://stackoverflow.com/a/50114871
type: Comment
type: AnswerComment
has text: Well, you could store the known data in a large numpy array (so that an instance of S only keeps an index to this) and then the dynamic list as one numpy array per S. That should already reduce the memory footprint significantly.

http://stackoverflow.com/q/50090438
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50090780
has body: I'm doing a simple chatbot with watson. I have a python script. Assume script is this for simplicity: x=5 x And in watson i want to return : result is 5 However, I'm not sure, how to interact with python. My research showed that it is something related to NodeJS and JSON, but I couldn't find any example or tutorial that suites my requirements. Could someone route me what course of actions should i take or any documentation?
favorite count: 0
type: Question
has title: Working with Watson Assistant / Watson Conversation from Python
has comment: http://stackoverflow.com/comment/87197524
score: 1
tagged with: watson
tagged with: python
tagged with: watson-conversation
tagged with: ibm-cloud
type: UnansweredQuestion
downvote count: 0

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/50190520
tags question: http://stackoverflow.com/q/50174149
tags question: http://stackoverflow.com/q/50189134
tags question: http://stackoverflow.com/q/50095916
tags question: http://stackoverflow.com/q/50187640
tags question: http://stackoverflow.com/q/50191711
tags question: http://stackoverflow.com/q/50202236
tags question: http://stackoverflow.com/q/50109321
tags question: http://stackoverflow.com/q/50174393
tags question: http://stackoverflow.com/q/50203403
tags question: http://stackoverflow.com/q/50086621
tags question: http://stackoverflow.com/q/50115831
tags question: http://stackoverflow.com/q/50133222
tags question: http://stackoverflow.com/q/50097688
tags question: http://stackoverflow.com/q/50148545
tags question: http://stackoverflow.com/q/50113912
tags question: http://stackoverflow.com/q/50174878
tags question: http://stackoverflow.com/q/50106007
tags question: http://stackoverflow.com/q/50194176
tags question: http://stackoverflow.com/q/50101064
tags question: http://stackoverflow.com/q/50083878
tags question: http://stackoverflow.com/q/50149707
tags question: http://stackoverflow.com/q/50211184
tags question: http://stackoverflow.com/q/50113417
tags question: http://stackoverflow.com/q/50227310
tags question: http://stackoverflow.com/q/50159803
tags question: http://stackoverflow.com/q/50145502
tags question: http://stackoverflow.com/q/50130424
tags question: http://stackoverflow.com/q/50095511
tags question: http://stackoverflow.com/q/50172456
tags question: http://stackoverflow.com/q/50216749
tags question: http://stackoverflow.com/q/50167525
tags question: http://stackoverflow.com/q/50086172
tags question: http://stackoverflow.com/q/50228397
tags question: http://stackoverflow.com/q/50198633
tags question: http://stackoverflow.com/q/50190131
tags question: http://stackoverflow.com/q/50083682
tags question: http://stackoverflow.com/q/50196124
tags question: http://stackoverflow.com/q/50206800
tags question: http://stackoverflow.com/q/50084468
tags question: http://stackoverflow.com/q/50204011
tags question: http://stackoverflow.com/q/50152598
type: Tag
tags question: http://stackoverflow.com/q/50090117

http://stackoverflow.com/q/50158467
score: 1
upvote count: 1
has title: How to penalise negative weights in TensorFlow?
has comment: http://stackoverflow.com/comment/87335540
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I'm building a neural network with TensorFlow and I'm trying to implement a quadratic penalization to negative values in the weight matrix, i.e. P(W[i,j]) = W[i,j]^2 if W[i,j] &lt; 0. In summary, I initialized the weights, performed some operations, defined the main objective function to minimize, and defined this nonnegativity penalization as follows: self.W = tf.Variable(tf.random_uniform((input_dim, hidden_dim), minval=-k, maxval=k, dtype=np.float32), dtype=tf.float32) objective = ... nonnegativity = tf.nn.l2_loss(tf.nn.relu(tf.negative(self.W))) loss = objective + 0.01*nonnegativity self.train_op = tf.train.AdamOptimizer(0.1).minimize(loss) I'm wondering if this is a correct way to implement such penalization.
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/87409479
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50196186
has text: I meant `var2`. Where is `var2` in the code snippet? `var1` is already defined.

http://stackoverflow.com/comment/87459507
type: QuestionComment
comment on: http://stackoverflow.com/q/50220019
score: 1
has text: @MelissaStewart your class needs [`total_ordering`](https://docs.python.org/3/library/functools.html#functools.total_ordering)
type: Comment

http://stackoverflow.com/comment/87733555
type: Comment
has text: @Lutz Horn. Even I felt it very weird. I have not developed this website. This is somehow working. For now, i'm just right clicking the element, then copy xpath and giving * for the maximum possible hierarchy covering. i.e., xpath: //*/div[2]/div[1]/div/div/div/input This obviously works, but I know this is very bad solution. Hence asked for the solution.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50132257

pandas
tags question: http://stackoverflow.com/q/50162272
tags question: http://stackoverflow.com/q/50104197
tags question: http://stackoverflow.com/q/50199829
tags question: http://stackoverflow.com/q/50158941
tags question: http://stackoverflow.com/q/50226332
tags question: http://stackoverflow.com/q/50208189
tags question: http://stackoverflow.com/q/50202272
tags question: http://stackoverflow.com/q/50204585
tags question: http://stackoverflow.com/q/50136252
tags question: http://stackoverflow.com/q/50139614
tags question: http://stackoverflow.com/q/50181895
tags question: http://stackoverflow.com/q/50159071
tags question: http://stackoverflow.com/q/50217206
tags question: http://stackoverflow.com/q/50217059
tags question: http://stackoverflow.com/q/50170814
tags question: http://stackoverflow.com/q/50150560
tags question: http://stackoverflow.com/q/50146279
tags question: http://stackoverflow.com/q/50143400
tags question: http://stackoverflow.com/q/50218532
tags question: http://stackoverflow.com/q/50223849
tags question: http://stackoverflow.com/q/50101483
tags question: http://stackoverflow.com/q/50161537
tags question: http://stackoverflow.com/q/50128438
tags question: http://stackoverflow.com/q/50218849
tags question: http://stackoverflow.com/q/50162212
tags question: http://stackoverflow.com/q/50214308
tags question: http://stackoverflow.com/q/50148708
tags question: http://stackoverflow.com/q/50163284
tags question: http://stackoverflow.com/q/50196681
tags question: http://stackoverflow.com/q/50173442
tags question: http://stackoverflow.com/q/50096429
tags question: http://stackoverflow.com/q/50141179
tags question: http://stackoverflow.com/q/50077751
tags question: http://stackoverflow.com/q/50206526
tags question: http://stackoverflow.com/q/50104637
tags question: http://stackoverflow.com/q/50100089
tags question: http://stackoverflow.com/q/50198820
tags question: http://stackoverflow.com/q/50143481
tags question: http://stackoverflow.com/q/50204902
tags question: http://stackoverflow.com/q/50093330
tags question: http://stackoverflow.com/q/50164229
tags question: http://stackoverflow.com/q/50096846
tags question: http://stackoverflow.com/q/50159602
tags question: http://stackoverflow.com/q/50121397
tags question: http://stackoverflow.com/q/50076930
tags question: http://stackoverflow.com/q/50181734
tags question: http://stackoverflow.com/q/50105268
tags question: http://stackoverflow.com/q/50206520
tags question: http://stackoverflow.com/q/50187849
tags question: http://stackoverflow.com/q/50160450
tags question: http://stackoverflow.com/q/50222286
tags question: http://stackoverflow.com/q/50155703
tags question: http://stackoverflow.com/q/50113565
tags question: http://stackoverflow.com/q/50139187
tags question: http://stackoverflow.com/q/50148374
tags question: http://stackoverflow.com/q/50152137
tags question: http://stackoverflow.com/q/50164369
tags question: http://stackoverflow.com/q/50171596
tags question: http://stackoverflow.com/q/50170288
tags question: http://stackoverflow.com/q/50183126
tags question: http://stackoverflow.com/q/50188852
tags question: http://stackoverflow.com/q/50224730
tags question: http://stackoverflow.com/q/50167809
tags question: http://stackoverflow.com/q/50139421
tags question: http://stackoverflow.com/q/50123845
tags question: http://stackoverflow.com/q/50126550
tags question: http://stackoverflow.com/q/50114132
tags question: http://stackoverflow.com/q/50126154
tags question: http://stackoverflow.com/q/50209259
tags question: http://stackoverflow.com/q/50088134
tags question: http://stackoverflow.com/q/50229388
tags question: http://stackoverflow.com/q/50127638
tags question: http://stackoverflow.com/q/50088193
tags question: http://stackoverflow.com/q/50143974
tags question: http://stackoverflow.com/q/50157773
tags question: http://stackoverflow.com/q/50108650
tags question: http://stackoverflow.com/q/50201057
tags question: http://stackoverflow.com/q/50189575
tags question: http://stackoverflow.com/q/50080530
tags question: http://stackoverflow.com/q/50105114

http://stackoverflow.com/comment/87455599
comment on: http://stackoverflow.com/q/50209585
type: Comment
has text: I applied it to zi `mean_data = ndimage.uniform_filter(zi, size=0.3, mode='constant')` -- size > 1 gives an error; size <= 1 gives same as above.
type: QuestionComment
score: 0

http://stackoverflow.com/q/50173642
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: I have to use characters from English and Hindi on x and y axes to display the confusion matrix. Since the default font is sans-serif, I set the Hindi font as: plt.xticks(fontname='Lohit Devanagari') plt.yticks(fontname='Lohit Devanagari') I also enable ticks labels on both sides of the axes: ax.tick_params(labeltop=True, labelright=True, labelsize=6) ax.yaxis.set_ticks_position('both') ax.xaxis.set_ticks_position('both') Expected outcome I expected to get Hindi and English characters properly displayed on both the axes, but as observed, English is properly rendered on above and right axes and Hindi is displayed on left and below axes. Matplotlib version: 2.2.2 Matplotlib backend (print(matplotlib.get_backend())): TkAgg Python version: 3.5.2 Other libraries: seaborn==0.8.1 I installed matplotlib inside a virtualenv using pip. Kindly provide your suggestions to render both the fonts properly on all axes. It will be a great help!
has title: Using multiple fonts for tick labels on the same axis in matplotlib
has comment: http://stackoverflow.com/comment/87364544
tagged with: python
has comment: http://stackoverflow.com/comment/126004807
tagged with: heatmap
answer count: 0
tagged with: matplotlib
score: 1
has comment: http://stackoverflow.com/comment/87364389
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50085222
duplicate of: http://stackoverflow.com/q/44564414
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
has answer: http://stackoverflow.com/a/50085384
answer count: 1
accepted answer: http://stackoverflow.com/a/50085384
has comment: http://stackoverflow.com/comment/87186341
linked to: http://stackoverflow.com/q/44564414
tagged with: flask-sqlalchemy
has title: querying from table and returning as JSON
tagged with: sqlalchemy
favorite count: 0
type: Question
has body: So I'm trying to query from a table in my db. I'm using python btw. I want to return them as JSON over a loop. But I only return one row from my table, which looks like this: { "content": "content1", "date": "date1", "title": "title1" } Here's my code: ann = Announcements.query.all() for data in ann: return jsonify({'date': data.date, 'title': data.title, 'content': data.content }) I want to return something like this: { "content": "content1", "date": "date1", "title": "title1" }, { "content": "content2", "date": "date2", "title": "title2" }, { "content": "content3", "date": "date3", "title": "title3" } What am I missing here?
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/87422299
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50202410
has text: First thing I'd do is check the value of the parameters I pass to`calibrateCamera`. What is the actual value of `objpoints`, `imgpoints`, and `gray.shape[::-1]` at that point?
type: Comment

http://stackoverflow.com/a/50125224
has body: Would this work? You can simply make an alias for the existing CssMixin variable. from breaffy.helper import CssMixin as CssMixin Helper = CssMixin # Rest of the code ...
has comment: http://stackoverflow.com/comment/87268649
answers question: http://stackoverflow.com/q/50124954
has comment: http://stackoverflow.com/comment/87268732
score: 0
type: Answer

http://stackoverflow.com/comment/87474385
score: 0
type: Comment
type: QuestionComment
has text: Added an image of data now!
comment on: http://stackoverflow.com/q/50224867

http://stackoverflow.com/a/50134865
answers question: http://stackoverflow.com/q/50134518
downvote count: 0
upvote count: 1
has body: You can also use itertools.groupby: import itertools dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]} d= {a:sum(c for _, [c, d] in b) for a, b in itertools.groupby(sorted(dictionary.items(), key=lambda x:x[-1][-1]), key=lambda x:x[-1][-1])} Output: {'string2': 2, 'string1': 8}
score: 1
type: Answer

http://stackoverflow.com/a/72019157
upvote count: 1
has comment: http://stackoverflow.com/comment/127261695
answers question: http://stackoverflow.com/q/50110474
score: 1
type: Answer
has body: I was facing the same issue while using vim or vi commands because the package was not installed on my machine. To use the vim command of anaconda prompt with windows os, then use this given command ' conda install -c conda-forge vim '. This command will install the required dependencies and then just simply use the vim command example - vim file_name. Reference
downvote count: 0

http://stackoverflow.com/q/50162502
has title: Disable Session Cookie generation in Python Flask-login
type: AnsweredQuestion
score: 2
tagged with: python
favorite count: 0
type: Question
tagged with: flask-login
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50178856
has body: After searching through the Python Flask-Login, I found ways to utilize header/api-key authentication instead of the default cookie authentication. https://flask-login.readthedocs.io/en/latest/#disabling-session-cookie-for-apis However, in the initial / request, Flask still responds with a cookie in the session. The above method only ensures that any new request (@login_required) is able to authenticate without the cookie (and use header or whatever method my implementation requires). Is there a way to disable it? Or am I missing something.
tagged with: flask
has answer: http://stackoverflow.com/a/50178856

http://stackoverflow.com/a/50088589
has body: Python wheels — and even less eggs or sdists — are not full-blown packages, they don't have post-install or pre-uninstall script. And they probably shouldn't. Anyway, users expect config files to remain in place after a program is uninstalled — just in case they reinstall the program again. And of course they expect the config will not be overwritten on the second installation.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87193086
accepted answer of: http://stackoverflow.com/q/50088440
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50088440

http://stackoverflow.com/a/50157440
type: Answer
accepted answer of: http://stackoverflow.com/q/50156657
has body: I think the solution is to create the zipfile in a different directory. From there, something like shutil.make_archive('zip_file', 'zip', 'C:\\Users\\test', "bbb") should give you an archive of the bbb directory.
has comment: http://stackoverflow.com/comment/87333727
answers question: http://stackoverflow.com/q/50156657
has comment: http://stackoverflow.com/comment/87333279
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/87340226

http://stackoverflow.com/comment/87348786
has text: Also, https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html
comment on: http://stackoverflow.com/q/50165419
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87180155
comment on: http://stackoverflow.com/q/50082069
type: Comment
type: QuestionComment
score: 0
has text: `{v:[w for w in t.split() if w.endswith(v)] for v in 'aeiou'}` try that...

http://stackoverflow.com/q/50086188
tagged with: split
answer count: 1
has body: I have a file trial.txt containing This can stay // but this / and this // must go I will be happy To remove leading # I used in other cases os.system(" sed '/^#.*/d' trial.txt &gt; start.txt ") so to remove // I used os.system(" sed '/^//.*/d' trial.txt &gt; start.txt ") but this gives error sed: 1: "/^//.*/d": invalid command code / Any suggestions? with preferably Python or with Linux?
tagged with: python
has comment: http://stackoverflow.com/comment/87188420
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50086226
accepted answer: http://stackoverflow.com/a/50086226
has title: How to delete all lines containing the leading // or /
tagged with: character
type: Question

http://stackoverflow.com/comment/87382231
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50181118
has text: @AndreaCorbellini Right now, just SQLite, but I'll be moving to MySQL. I do not need to index them, and, while it would be nice to search them (eventually), it's not a necessity. (In fact, this whole question is not a necessity! ;) I'm just seeing if there's a way to eliminate a few lines)

http://stackoverflow.com/q/50198068
answer count: 1
tagged with: line
has answer: http://stackoverflow.com/a/50198135
type: Question
tagged with: field
tagged with: python
has body: I have a txt file that I wish to search for an 'id'. Each line in the file contains 5 fields (id, name, age, height, weight). If the id search finds a match, I want to display each field in the matched line as below: x 'player/s have been found:' print('Player ID: ', id) print('Player name: ', name) print('Age: ', age) print('Height: ', height) print('Weight: ', weight) So far I have only been able to print the matched line as a line and not pull individual fields out onto different print lines. Any help would be greatly appreciated! This is what I have so far, but python cant seem to readline any matches.. def search_enter_id(): '''Function allows user to search for a player ID from Players.txt file''' # Create a bool variable to use as a flag found = False # Get search value my_string = input('Please enter the player ID you want to search: ') # Open a file for reading player_file = open('Players.txt', 'r') # Read the first records ID field id_field = player_file.readline() # Read the rest of the file while id_field != '': # Read the name field name_field = player_file.readline() # Read Age field age_field = player_file.readline() #Read Height field height_field = player_file.readline() #Read weight field weight_field = player_file.readline() # Strip the \t\t from fields id_field = id_field.rstrip('\t\t') name_field = name_field.rstrip('\t\t') age_field = age_field.rstrip('\t') height_field = height_field.rstrip('\t\t') weight_field = weight_field.rstrip('\n') # Determine whether this record matches the search value if id_field == my_string: # Display the record print('Player ID: ', id_field) print('Player name: ', name_field) print('Age: ', age_field) print('Height: ', height_field) print('Weight: ', weight_field) print() # Set the found flag to true found = True # Read the next ID field id_field = player_file.readline() # Close the file player_file.close() # If the search value was not found in the file # display a message if not found: print('That ID was not fou…
type: UnansweredQuestion
has title: Search for a line in a file and display results on separate lines with text
tagged with: search
score: 0
tagged with: string

pyqt
type: Tag
tags question: http://stackoverflow.com/q/50164712
tags question: http://stackoverflow.com/q/50112785
tags question: http://stackoverflow.com/q/50177976
tags question: http://stackoverflow.com/q/50176661
tags question: http://stackoverflow.com/q/50180751
tags question: http://stackoverflow.com/q/50092615
tags question: http://stackoverflow.com/q/50118684
tags question: http://stackoverflow.com/q/50203452
tags question: http://stackoverflow.com/q/50077625
tags question: http://stackoverflow.com/q/50190433
tags question: http://stackoverflow.com/q/50162090
tags question: http://stackoverflow.com/q/50104099
tags question: http://stackoverflow.com/q/50222011
tags question: http://stackoverflow.com/q/50153689
tags question: http://stackoverflow.com/q/50222954
tags question: http://stackoverflow.com/q/50156607
tags question: http://stackoverflow.com/q/50196987
tags question: http://stackoverflow.com/q/50086893
tags question: http://stackoverflow.com/q/50196837
tags question: http://stackoverflow.com/q/50118255
tags question: http://stackoverflow.com/q/50127402
tags question: http://stackoverflow.com/q/50077356
tags question: http://stackoverflow.com/q/50167096
tags question: http://stackoverflow.com/q/50115934
tags question: http://stackoverflow.com/q/50081088
tags question: http://stackoverflow.com/q/50135339
tags question: http://stackoverflow.com/q/50084303
tags question: http://stackoverflow.com/q/50179516
tags question: http://stackoverflow.com/q/50161900
tags question: http://stackoverflow.com/q/50201738
tags question: http://stackoverflow.com/q/50078373
tags question: http://stackoverflow.com/q/50128066
tags question: http://stackoverflow.com/q/50081171
tags question: http://stackoverflow.com/q/50137395
tag name: pyqt
tags question: http://stackoverflow.com/q/50211133
tags question: http://stackoverflow.com/q/50124556
tags question: http://stackoverflow.com/q/50128293
tags question: http://stackoverflow.com/q/50083035
tags question: http://stackoverflow.com/q/50227128
tags question: http://stackoverflow.com/q/50142427
tags question: http://stackoverflow.com/q/50133693
tags question: http://stackoverflow.com/q/50093294
tags question: http://stackoverflow.com/q/50103167
tags question: http://stackoverflow.com/q/50134036
tags question: http://stackoverflow.com/q/50077228
tags question: http://stackoverflow.com/q/50127246
tags question: http://stackoverflow.com/q/50194909
tags question: http://stackoverflow.com/q/50196579

http://stackoverflow.com/q/50119370
tagged with: django
tagged with: python
score: 0
has body: I haven't touched a project in a long time and realized I upgraded my django to version 1.11.12. Trying to re-run project (runserver) and found several out of date packages (easy-thumbnails and psycopg2). Ran pip install upgrade on those. Now when I run, I get the following error and it seems like it is coming form my models? Not sure what it is telling me though or the proper course of action. Maybe there was another upgrade step I missed when I upgraded to django 1.11? (sorry been ages since I touched this code) Unhandled exception in thread started by &lt;function wrapper at 0x104ab2500&gt; Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/shane.thomas/programming/sw_nga_site/swsite/models.py", line 12, in &lt;module&gt; from filer.fields.image import FilerImageField File "/usr/local/lib/python2.7/site-packages/filer/fields/image.py", line 4, in &lt;module&gt; from ..models import Image File "/usr/local/lib/python2.7/si…
has comment: http://stackoverflow.com/comment/87258389
type: Question
has comment: http://stackoverflow.com/comment/87257724
has comment: http://stackoverflow.com/comment/87257072
answer count: 0
has title: upgrade to django 1.11.12 error in models/manager.py contribute_to_class
has comment: http://stackoverflow.com/comment/87258489
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87256115

http://stackoverflow.com/q/50152911
type: AnsweredQuestion
tagged with: python-2.7
score: 1
accepted answer: http://stackoverflow.com/a/50153115
downvote count: 0
has answer: http://stackoverflow.com/a/50153115
favorite count: 0
type: Question
has title: Re-order based on another array
has body: I have an array of dicts where there are the keys name, and val. I have another array of array where there are always two values: src_XX and dst_XX where XX are integers. I want to sort the first array of dicts using the name and the position its value in the other array (of arrays) s = [{'name': 'src_0', 'val': 0}, {'name': 'src_1', 'val': 1}, {'name': 'src_2', 'val': 2}, {'name': 'src_3', 'val': 3}, {'name': 'src_4', 'val': 4}, {'name': 'src_5', 'val': 5},] u= [['src_1', 'dst_2'], ['src_0', 'dst_0'], ['dst_1', 'src_2'], ['dst_3', 'src_3'], ['src_4', 'dst_4'], ['src_5', 'dst_5'],] the final result should be: s = [{'name': 'src_1', 'val': 1}, {'name': 'src_0', 'val': 0}, {'name': 'src_2', 'val': 2}, {'name': 'src_3', 'val': 3}, {'name': 'src_4', 'val': 4}, {'name': 'src_5', 'val': 5},] I've already tried many things and one is working but it's very ugly, not optimized and not Python-like.
tagged with: arrays
answer count: 1
upvote count: 1
tagged with: python

continuous-fourier
tags question: http://stackoverflow.com/q/50109197
type: Tag
tag name: continuous-fourier

http://stackoverflow.com/q/50106240
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87230044
has body: I am in the process of building a docker container that will run my automation tests. When I attempt to run the command below [this works locally and in jenkins] I get the following error: root@645ed3930434:/test_dir# pytest test_* -m smoke Traceback (most recent call last): File "/usr/local/bin/pytest", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/local/lib/python3.5/dist-packages/_pytest/config.py", line 49, in main config = _prepareconfig(args, plugins) File "/usr/local/lib/python3.5/dist-packages/_pytest/config.py", line 168, in _prepareconfig pluginmanager=pluginmanager, args=args) File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 745, in __call__ return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 339, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 334, in &lt;lambda&gt; _MultiCall(methods, kwargs, hook.spec_opts).execute() File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 613, in execute return _wrapped_call(hook_impl.function(*args), self.execute) File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 250, in _wrapped_call wrap_controller.send(call_outcome) File "/usr/local/lib/python3.5/dist-packages/_pytest/helpconfig.py", line 68, in pytest_cmdline_parse config = outcome.get_result() File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 279, in get_result raise ex[1].with_traceback(ex[2]) File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 265, in __init__ self.result = func() File "/usr/local/lib/python3.5/dist-packages/_pytest/vendored_packages/pluggy.py", line 614, in execute res = hook_impl.function(*args) File "/usr/local/lib/python3.5/dist-packages/_pytes…
upvote count: 1
tagged with: python
tagged with: docker
accepted answer: http://stackoverflow.com/a/50106434
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/860140
has answer: http://stackoverflow.com/a/50106434
tagged with: pytest
has title: pytest KeyError: 'USER' within docker container
score: 1

http://stackoverflow.com/comment/87242652
type: QuestionComment
type: Comment
has text: @juanpa.arrivillaga actually I have a big complex dict and I want to write it to file as string.....
score: 0
comment on: http://stackoverflow.com/q/50112684

http://stackoverflow.com/q/50229751
upvote count: 1
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9891814
score: 1
has answer: http://stackoverflow.com/a/50229785
downvote count: 0
answer count: 1
has title: How to get list of data found using patterns
duplicate of: http://stackoverflow.com/q/9891814
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am trying to filter data in an array with the help of a pattern \d\.\d. The elements in the array might sometimes consist of strings as well. I try to use the re.findall function to get a list of the decimal numbers within my strings in the array but my code doesn't recognise all decimal numbers. My code is as below - import re import itertools str1 = "2.7" str2 = ".3" str3 = "." str4 = "2" str5 = "sushruth" x = [str1,str2,str3,str4,str5] y = [] for a in x: z = re.findall(r'\d\.\d',a) if z: print(z) The output is only [2.7] whereas I need to also get [.3]. What change is required in my code
accepted answer: http://stackoverflow.com/a/50229785

http://stackoverflow.com/q/50148945
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/87327791
tagged with: handwriting-recognition
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87352756
tagged with: python
has comment: http://stackoverflow.com/comment/87350404
has title: Not Converging CTC Loss and Fluctuating Label Error Rate (Edit Distance) on Single Example?
has comment: http://stackoverflow.com/comment/87349740
score: 0
has body: I am trying to overfit a handwriting recognition model of this architecture: features = slim.conv2d(features, 16, [3, 3]) features = slim.max_pool2d(features, 2) features = mdrnn(features, 16) features = slim.conv2d(features, 32, [3, 3]) features = slim.max_pool2d(features, 2) features = mdrnn(features, 32) features = slim.conv2d(features, 64, [3, 3]) features = slim.max_pool2d(features, 2) features = mdrnn(features, 64) features = slim.conv2d(features, 128, [3, 3]) features = mdrnn(features, 128) features = slim.max_pool2d(features, 2) features = slim.conv2d(features, 256, [3, 3]) features = slim.max_pool2d(features, 2) features = mdrnn(features, 256) features = _reshape_to_rnn_dims(features) features = bidirectional_rnn(features, 128) features = bidirectional_rnn(features, 128) features = bidirectional_rnn(features, 128) features = bidirectional_rnn(features, 128) features = bidirectional_rnn(features, 128) With this mdrnn code from tensorflow (with a few modifications): def mdrnn(inputs, num_hidden): with tf.variable_scope(scope, "multidimensional_rnn", [inputs]): hidden_sequence_horizontal = _bidirectional_rnn_scan(inputs, num_hidden // 2) with tf.variable_scope("vertical"): transposed = tf.transpose(hidden_sequence_horizontal, [0, 2, 1, 3]) output_transposed = _bidirectional_rnn_scan(transposed, num_hidden // 2) output = tf.transpose(output_transposed, [0, 2, 1, 3]) return output def _bidirectional_rnn_scan(inputs, num_hidden): with tf.variable_scope("BidirectionalRNN", [inputs]): height = inputs.get_shape().as_list()[1] inputs = images_to_sequence(inputs) output_sequence = bidirectional_rnn(inputs, num_hidden) output = sequence_to_images(output_sequence, height) return output def images_to_sequence(inputs): _, _, width, num_channels = _get_shape_as_list(inputs) s = tf.shape(inputs) batch_size, height = s[0], s[1] return tf.reshape(inputs, [batch_size * height, width, num_channels]) def sequence_to_images(tensor, height): num_batches, width, depth = tensor.get_…
answer count: 0

http://stackoverflow.com/comment/87253811
comment on: http://stackoverflow.com/a/50117987
type: Comment
type: AnswerComment
has text: I'm trying to get this to work, but I can't figure out how to format it so that the slicing of the local dataframe happens correctly.
score: 0

http://stackoverflow.com/comment/87181023
type: AnswerComment
comment on: http://stackoverflow.com/a/50081774
has text: kod şu şekilde çalışmaya başladı : from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Firefox() driver.maximize_window() driver.set_page_load_timeout(4) driver.get("https://lp.darkorbit.com/") time.sleep(3)
score: 0
type: Comment

http://stackoverflow.com/comment/87270144
has text: Both. For instance, the first games listed all teams will be 0-0. The next game Cleveland appears in I'd like it to show they are 1-0 and if they win that game then 2-0 for the next game and so on. Also making sure that when the Season changes it resets back to 0-0.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50125428

http://stackoverflow.com/comment/87380449
comment on: http://stackoverflow.com/q/50181586
score: 0
has text: im not sure how your computer is set up, but it sounds like the alias you have set up for your account is different than that of the Virtual Env.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87437849
type: Comment
comment on: http://stackoverflow.com/a/50210347
score: 0
type: AnswerComment
has text: thank you very much, I never know that we can actually create our own initialiser, I will give a try on this and share my answer

http://stackoverflow.com/q/50162964
score: 2
has body: I have a list of jsons (that's originally response from TestRail API getcases) which I'm trying to parse. Here's a sample json: [ { "id": 1, "parent_id": null, }, { "id": 2, "parent_id": 1, }, { "id": 6, "parent_id": null, }, { "id": 16, "parent_id": 2, }, { "id": 7, "parent_id": 1, }, { "id": 3, "parent_id": 6 } ] What I wanna do is to figure out what Ids fall under original parent ID. for example id:1 and "id": 6, are the most top level parent nodes since "parent_id": null for them. I want to get all the child nodes fall under the top most parents. In this example here's the relationships based on the parent_id 1 -> [2,7] -> 16 6 -> 3 The main goal is to determine what are all the child (and subchild) nodes for a top-level parent node. I'm not interested in knowing sub-parent/subchild rellationships. what I want to parse is to get the following output: { 1: [2,7,16], 6: 3 } One approach is to go with a couple of nested for loops , for each top-parent node check if that's presented as parent_id and go with that recursively, but that doesn't look like a very good approach. would appreciate any comments/suggestions
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/87345420
tagged with: python
has title: Parse json response to get parent/child dictionary
tagged with: testrail
has answer: http://stackoverflow.com/a/50163736

http://stackoverflow.com/comment/87236265
has text: I think `tight_layout` will do the opposite of what you need here. Instead, make the figure margins *larger*, e.g. by using `bottom=0.3` or so.
comment on: http://stackoverflow.com/q/50109374
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87268788
comment on: http://stackoverflow.com/q/50125209
has text: Do you have VSCode and ArcPy set up to use the same Python installation?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87352086
score: 0
type: QuestionComment
type: Comment
has text: @jxc -- upon further inspection my solution is incorrect. However, the problem still stands-- I'm not sure how to get the desired output.
comment on: http://stackoverflow.com/q/50165614

http://stackoverflow.com/comment/129248983
type: AnswerComment
comment on: http://stackoverflow.com/a/50221371
has text: AsyncIO framework in stdlib also takes advantage of threads in order to use futures, right? That was interesting.
type: Comment
score: 0

http://stackoverflow.com/comment/87431117
comment on: http://stackoverflow.com/a/50206065
has text: make sure you replaced group(2) with group(3) as I added another group for breakline expression
score: 0
type: Comment
type: AnswerComment

record
type: Tag
tags question: http://stackoverflow.com/q/50111287
tag name: record

http://stackoverflow.com/q/50192731
score: 1
upvote count: 1
has title: IOError: [Errno 21] Is a directory: '/tmp/speech_dataset/'
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: io
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50193118
has body: I'm following the speech recognition tutorial from TensorFlow(link: https://www.tensorflow.org/versions/master/tutorials/audio_recognition#advanced_training), and when I'm running the following command, which downloads the dataset provided by TensorFlow, it runs perfectly. python tensorflow/examples/speech_commands/train.py However, when I'm changing the defaults, so that it points to my dataset, it throws the following error: Traceback (most recent call last): File "/home/users2/lmn/.local/lib/python2.7/site-packages/tensorflow/examples/speech_commands/train.py", line 428, in &lt;module&gt; tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) File "/home/users2/lmn/.local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 126, in run _sys.exit(main(argv)) File "/home/users2/lmn/.local/lib/python2.7/site-packages/tensorflow/examples/speech_commands/train.py", line 106, in main FLAGS.testing_percentage, model_settings) File "/home/users2/lmn/.local/lib/python2.7/site-packages/tensorflow/examples/speech_commands/input_data.py", line 158, in __init__ self.maybe_download_and_extract_dataset(data_url, data_dir) File "/home/users2/lmn/.local/lib/python2.7/site-packages/tensorflow/examples/speech_commands/input_data.py", line 204, in maybe_download_and_extract_dataset tarfile.open(filepath, 'r:gz').extractall(dest_directory) File "/usr/lib64/python2.7/tarfile.py", line 1693, in open return func(name, filemode, fileobj, **kwargs) File "/usr/lib64/python2.7/tarfile.py", line 1740, in gzopen fileobj = gzip.GzipFile(name, mode, compresslevel, fileobj) File "/usr/lib64/python2.7/gzip.py", line 94, in __init__ fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') IOError: [Errno 21] Is a directory: '/tmp/speech_dataset/' The command I'm running is: python tensorflow/examples/speech_commands/train.py --data_url=path/to/data/ --sample_rate=20000 --wanted_words=one,two,three,four,five,six,seven,eight,nine Now, the error says that '/tmp/speech_dataset…
downvote count: 0
tagged with: machine-learning

http://stackoverflow.com/a/50147415
has comment: http://stackoverflow.com/comment/87313271
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50146855
has comment: http://stackoverflow.com/comment/87316374
has comment: http://stackoverflow.com/comment/87321837
has comment: http://stackoverflow.com/comment/87316934
has body: Since your arduino will output only either 0 or 1 and 1234, just add else after your if statement. a = int(str) if str=="0": print("nobody") else: b = int(arduino.readline()[:-2].decode())
type: Answer
has comment: http://stackoverflow.com/comment/87313115
accepted answer of: http://stackoverflow.com/q/50146855
score: 0

http://stackoverflow.com/q/50144888
answer count: 2
has comment: http://stackoverflow.com/comment/87308038
has answer: http://stackoverflow.com/a/50144972
upvote count: 3
has body: I want to generate 200 random binary arrays of size 30, but I need all of them to be unique! I use to following to generate the arrays: import numpy as np parents = [] for i in range(200): parents.append(np.random.choice([0, 1], size=(30))) parents = np.vstack(parents) Are the arrays made in this way already unique (if so, how may I check that)? If not, how do I modify my code so I get unique arrays?
tagged with: arrays
downvote count: 0
has title: Generate unique random binary arrays in python
tagged with: python
possible better answer: http://stackoverflow.com/a/50145004
favorite count: 0
has comment: http://stackoverflow.com/comment/87308069
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87308005
tagged with: random
has comment: http://stackoverflow.com/comment/87307911
has comment: http://stackoverflow.com/comment/87308101
accepted answer: http://stackoverflow.com/a/50144972
has answer: http://stackoverflow.com/a/50145004
type: Question
tagged with: binary

http://stackoverflow.com/comment/87419743
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50200914
has text: I ran this command and it gives me nothing. Just shows me the next cmd terminal.
score: 0

http://stackoverflow.com/q/50229856
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50230934
possible better answer: http://stackoverflow.com/a/50230934
tagged with: web-scraping
tagged with: scrapy
favorite count: 0
has title: Making scrapy.Request deteministics?
type: Question
has answer: http://stackoverflow.com/a/50288905
has body: This is not issues for me, I can live without it but I am just curious is it possible and how. Today I have learned, that scrapy.Request will not finish in the same order as they have been started. Pseudocode example: class SomeSpider(scrapy.Spider): def parse(self, response): # get all ads(25) from ads list for ad in adList(): add_url = findAddUrl() yield scrapy.Request(add_url, callback=self.parseAd) # go to next page if some_condition_OK: next_page_url = findNextpageUrl() yield scrapy.Request(next_page_url) else: print 'Stoped at.' def parseAd(self, response): field_1 = get_field_1() field_n = get_field_n() # save field_1 to field_n to sqlite DB This is a simplified example of spider that I have coded and it is working fine. But what I have learned today is that yield scrapy.Request will not finish in the same order as they are started. In my example, on each page, there are 25 ads for each page, I start yield scrapy.Request(add_url, callback=self.parseAd) to get more information from each ad. And after that, I go to next page with yield scrapy.Request(next_page_url). But what I have noticed that some ads from page2 will finish before the all ads from page1. I understand why and I see the benefit of this approach. But my question is it possible to make scrapy.Request deterministic? What I mean by deterministic is that each scrapy.Request will finish in the same order as it is started.
tagged with: python
accepted answer: http://stackoverflow.com/a/50288905

http://stackoverflow.com/comment/87234262
has text: This is clever. I realise that in the 3 variable case this is slight overkill, but would be helpful if I did it with more.
type: Comment
comment on: http://stackoverflow.com/a/50108201
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87349763
has text: Both your examples have `for i in itertools.islice(enumerate(a), 2, 5)` - can you please [edit](https://stackoverflow.com/posts/50165733/edit) with the code you ran.
type: QuestionComment
comment on: http://stackoverflow.com/q/50165733
type: Comment
score: 0

http://stackoverflow.com/comment/87238142
score: 1
type: Comment
has text: `crorss_val_score` will internally ue StratifiedKFold for a classification task, so you should not get exact same results each time. Are you setting the numpy random seed anywhere? How large is your data?
type: QuestionComment
comment on: http://stackoverflow.com/q/50106143

http://stackoverflow.com/q/50077650
possible better answer: http://stackoverflow.com/a/50077790
has body: I managed to construct a Trie and now i want to return strings that matches a prefix from the Trie but I'm having issues writing the search function. For example, if i have a prefix "aa", i want to have the strings "aa" and "aac" as an output. class Node: def __init__(self): self.children = [None] * 26 self.end = False self.value = "" class Trie: def __init__(self): self.root = Node() def add_word(self, key): word_length = len(key) current = self.root for i in range(word_length): position = self.ord_char(key[i]) if current.children[position] is None: current.children[position] = Node() current = current.children[position] current.value = key[i] current.end = True def ord_char(self,key): ord_rep = ord(key) - ord('a') return ord_rep def prefix_search(self, prefix): lst = [] current = self.root prefix_length = len(prefix) for c in range(prefix_length): c_position = self.ord_char(prefix[c]) current = current.children[c_position] lst.append(current.value) #doesnt seem like I'm doing it right if __name__ == "__main__": trie = Trie() trie.add_word("aa") trie.add_word("aac") trie.add_word("b") trie.prefix_search("aa") I was thinking of just joining up the alphabets together to form the final string through the search function but i just couldn't think of any better way to do so.
has answer: http://stackoverflow.com/a/50077790
favorite count: 0
has title: Return strings that matches the prefix in a Trie
type: Question
upvote count: 2
score: 2
answer count: 2
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50077876
tagged with: trie
has answer: http://stackoverflow.com/a/50077876
type: AnsweredQuestion

http://stackoverflow.com/comment/87282875
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50132242
has text: There are quite a few questions here about encoding issues... The point is: there's no "magic" solution to encoding problems, you have to spend some time understanding what unicode is, what encodings are, and how to use them. You can start here : https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/

http://stackoverflow.com/a/50173320
type: Answer
upvote count: 32
score: 32
type: AcceptedAnswer
downvote count: 0
has body: I want to pop first 5% of record There is no built-in method but you can do this: You can multiply the total number of rows to your percent and use the result as parameter for head method. n = 5 df.head(int(len(df)*(n/100))) So if your dataframe contains 1000 rows and n = 5% you will get the first 50 rows.
answers question: http://stackoverflow.com/q/50173283
accepted answer of: http://stackoverflow.com/q/50173283

http://stackoverflow.com/comment/87210329
has text: @ gokhansim Thanks for your advice! Will try to explore it more! But now i follow the code you given, it seem working, will try more on it again! Thanks again! :)
type: Comment
comment on: http://stackoverflow.com/a/50096644
score: 0
type: AnswerComment

http://stackoverflow.com/q/50203580
type: AnsweredQuestion
downvote count: 0
tagged with: matplotlib
tagged with: python
has body: Hey guys, I am using matplotlib to draw 3D barplot. I wonder whether it is possible to give each bar (total 9) a different color according to their value (dz) and also show the corresponding level in this figure. Many thanks in advance!!! My code is below: fig_stat=plt.figure(dpi=100) ax_stat = fig_stat.add_subplot(111, projection='3d') xpos = [1, 1, 1, 3, 3, 3, 5, 5, 5] ypos = [1, 3, 5, 1, 3, 5, 1, 3, 5] # initial z position (x-y plane), np.zeros(x), x zpos = [0, 0, 0, 0, 0, 0, 0, 0, 0] # x is the number of points you need dx = np.ones(9) dy = np.ones(9) # dz = [1, 2, 3, 4, 10, 6, 7, 8, 9] # signal intensity dz = col_stat.iloc[:, -2] ax_stat.set_xlabel('X axis') ax_stat.set_ylabel('Y axis') ax_stat.set_zlabel('Signal Intensity') ax_stat.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#00ceaa') plt.title("Position_{}".format(L))
type: Question
upvote count: 2
tagged with: python-3.x
tagged with: 3d
has answer: http://stackoverflow.com/a/50204991
accepted answer: http://stackoverflow.com/a/50204991
answer count: 1
has title: How to use matplotlib to draw 3D barplot with specific color according to the bar height
favorite count: 0
score: 2

http://stackoverflow.com/q/50215808
answer count: 1
has title: Python - Function argument with a comma
accepted answer: http://stackoverflow.com/a/50215861
linked to: http://stackoverflow.com/q/16296643
type: Question
tagged with: function
tagged with: arrays
linked to: http://stackoverflow.com/q/919680
tagged with: python
duplicate of: http://stackoverflow.com/q/919680
has answer: http://stackoverflow.com/a/50215861
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87448399
has comment: http://stackoverflow.com/comment/87448365
has body: I want to have an argument in a function that fills an array with multiple strings, so that i have def Test(colors): colorarray = [colors] which i can fill with Test(red,blue) but i always get either the takes 2 positional arguments but 3 were given error or the single strings do not get accepted (e.g. TurtleColor(Color[i]) tells me "bad color string: "red","blue") i know i can pass the strings as seperate arguments, but i kind of want to avoid having that many different arguments.

http://stackoverflow.com/a/50076371
answers question: http://stackoverflow.com/q/50076241
score: 0
has body: you can store start and end point of each edge in two tuples: E1 and E2. additionally you may store weight of each edge into tuple W and search for appropriate edge by iterating through elements of E1 and E2 finally you can access to appropriate weight by using W tuple. G = ('a', 'b', 'c', 'd') E1 = ('a', 'a', 'a') E2 = ('b', 'c', 'd') W = (4, 6, 8) for i in range(len(E1)): if E1[i] == 'a' and E2[i] == 'b': print(W[i])
type: Answer

http://stackoverflow.com/q/50140480
has comment: http://stackoverflow.com/comment/88625775
has title: Error while crawling using scrapy
favorite count: 0
has comment: http://stackoverflow.com/comment/88567954
has body: I am using scrapy to scrap some pages, however whenever I am trying to start the crawler, it stops with following error. from OpenSSL._util import lib as pyOpenSSLlib ImportError: No module named _util I have installed pyopenssl v13.1. Also the brew link openssl is executed. Please let me know if I am missing something. Operating System - Mac OS High Sierra Python - V2.7 PIP - 10.1
score: 2
has answer: http://stackoverflow.com/a/50833611
tagged with: scrapy
type: Question
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/q/50192121
accepted answer: http://stackoverflow.com/a/50228205
has answer: http://stackoverflow.com/a/50230769
has answer: http://stackoverflow.com/a/50228205
type: Question
upvote count: 4
tagged with: seaborn
has title: Custom color palette intervals in seaborn heatmap
downvote count: 0
tagged with: python
has body: I am trying to plot a heatmap using seaborn library. The plotting function looks like this: def plot_confusion_matrix(data, labels, **kwargs): """Visualize confusion matrix as a heat map.""" col_map = kwargs.get('color_palette', sns.light_palette('navy', n_colors=5, as_cmap=False)) sns.heatmap( vmin=0.0, vmax=1.0, data=data, cmap=col_map, xticklabels=labels, yticklabels=labels, linewidths=0.75, ) The histogram of the data, however, looks like this: Now the issue I am struggling with is that seaborn heatmap(view bellow) splits evenly the color scale and hence most of the data has the same color (since the data is not evenly distributed). I was not able to find out how to set some sort of intervals or boundaries for the color levels. Suppose I have the following array of hex color values: ['#e5e5ff', '#acacdf', '#7272bf', '#39399f', '#000080'] Is there a way to set up a color such as [(threshold_0, hex_0), (threshold_1, hex_1), ..., (threshold_n, hex_n)] where threshold_i is a value in range [0, 1) Appreciate any help. PS: current heatmap for illustration:
favorite count: 0
tagged with: heatmap
score: 4
type: AnsweredQuestion
answer count: 3
tagged with: data-visualization
has answer: http://stackoverflow.com/a/50209191
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/50230769

http://stackoverflow.com/a/50307862
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50217968
has body: import itertools dfres = pd.DataFrame([j+(i[2],) for i in df.values for j in itertools.product(*i[0:2])] ,columns=df.columns) Job position Job type id 0 6 1 3 1 2 3 4 2 2 6 4 3 2 5 4 4 6 3 4 5 6 6 4 6 6 5 4 7 1 9 43

http://stackoverflow.com/a/50145677
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50145412
upvote count: 2
type: Answer
has body: You need to parse your string first to find out which Destiny substrings are inside a tag, and which aren't. I have done this below with re.split. My use of re.split returns a list of substrings surrounding the regex pattern TAG:?{.*?}, and because I enclose the pattern in parentheses, the tags are included in the list as well. In this use of re.split, the non-tags will always have an even index, and the tags will always have an odd index. So I check if the index is even, and if so I replace Destiny with TAG:{Destiny,Destiny}. import re s = 'TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny' result = [] for i, substring in enumerate(re.split('(TAG:?{.*?})', s)): if i % 2 == 0: substring = substring.replace('Destiny', 'TAG:{Destiny,Destiny}') result.append(substring) result = ''.join(result) print(result) # TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny,Destiny} This will work as long as you don't have tags nested inside other tags.

http://stackoverflow.com/q/50217445
tagged with: communication
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50219064
has body: So, I have this code here. This sender script give's me the output properly. import socket UDP_IP = "127.0.0.1" UDP_PORT = 0 MESSAGE = "Hi, can you listen to this?" print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "message:", MESSAGE sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(MESSAGE, (UDP_IP, UDP_PORT)) I tried to use this script on another host and try to establish a communication between the two. (Both the systems are on the same network ex. 00.000.00.xxx , only the xxx part varies) import socket UDP_IP = "127.0.0.1" UDP_PORT = 0 sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes print "received message:", data Here is the output Traceback (most recent call last): File "C:/Users/bshivaku/Desktop/SEnd_Udp_packets.py", line 9, in &lt;module&gt; sock.bind((UDP_IP, UDP_PORT)) File "C:\Python27\Lib\socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 10049] The requested address is not valid in its context I used the ip address of the receiver on the sender script and sender ip address on receiver I am sure I made a mistake with the UDP_PORT so i used PORT= 0 and tried. How to request for port number? How do I establish the connection? If not the port, where am I going wrong?
has answer: http://stackoverflow.com/a/50219064
type: Question
tagged with: network-programming
tagged with: packet
tagged with: python
tagged with: udp
has title: Establishing UDP communication with python
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/87306252
has text: You can also reduce the number of features (columns of c4)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50143825

http://stackoverflow.com/comment/87177157
type: Comment
comment on: http://stackoverflow.com/q/50080530
type: QuestionComment
has text: How do I add as a text? The info seems to look weird when I attempt to do so
score: 0

http://stackoverflow.com/a/50157439
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50157369
has body: You can just transpose the matrix: In [1]: import numpy as np In [2]: A = np.matrix( ...: [[1, 2, 3], ...: [4, 5, 6], ...: [7, 8, 9]]) ...: In [3]: B = np.matrix([10, 11, 12]).T In [4]: print(A * B) [[ 68] [167] [266]]
score: 3
has comment: http://stackoverflow.com/comment/87332871
type: Answer

http://stackoverflow.com/comment/87253567
score: 0
type: Comment
type: QuestionComment
has text: @jedwards Yes maybe it's too difficult for me. I have not yet tried to send messages with PyUSB, moreover (if I understood correctly) I need an OUT endpoint but I have only found an IN endpoint. But thank you, I can try to send a message and then try to read it.
comment on: http://stackoverflow.com/q/50117520

http://stackoverflow.com/comment/87443304
comment on: http://stackoverflow.com/a/50213141
type: Comment
has text: It is work in only one number phrase. But what I want is something that works in the case like: "4سعید5سعید"
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87187916
comment on: http://stackoverflow.com/a/50086108
type: Comment
has text: Thank you for your quick anser! I've tried to change the learning rate but still doesn't work. I don't understand how regularization works, could yo explain that? What happen with my weigth initialization? What I try to do there, is initialize a variable with 0 mean and std equals to 1.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50103294
answers question: http://stackoverflow.com/q/50103221
downvote count: 0
upvote count: 1
has body: You have misplaced the initialization of hand. With your current code, hand is set to [] during each iteration: z = 0 while z &lt; 5: hand = [] # Executed during each iteration hand.append(card) print(hand) z += 1 So after each iteration you get a list with only 1 element: ['1 of Spade'] ['3 of Spade'] ['2 of Clubs'] ['K of Hearts'] ['4 of Spade'] Instead, you should initialize hand before looping, like this: hand = [] # Executed once, before iterating z = 0 while z &lt; 5: hand.append(card) print(hand) z += 1 Now, you can see that the elements are being correctly appended to your list at each iteration: ['1 of Spade'] ['1 of Spade', '3 of Spade'] ['1 of Spade', '3 of Spade', '2 of Clubs'] ['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts'] ['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts', '4 of Spade'] When you exit the loop, hand contains the following list, as you wanted: ['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts', '4 of Spade']
score: 1
type: Answer

http://stackoverflow.com/comment/87352007
has text: I have Creator 4.6.1 (Community) from https://www.qt.io/download with default options. But I when I do, New File->QtQuick Application ... I am blocked at the "Kits" step because I dont have and dont want any Kits.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50167096
score: 0

http://stackoverflow.com/comment/87378593
has text: Perhaps try `sudo pip3 install glob2`? I'm not too familiar with Linux, but my little experience is telling me `glob2` is being installed under Python 2 instead
comment on: http://stackoverflow.com/q/50180683
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50089690
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/31080829
answer count: 1
downvote count: 0
has body: I am new to Flask (and quite new to python) and I have tried running the following very basic script: from flask import Flask app= Flask(__name__) @app.route('/') def home(): return "This is the homepage" if __name__=="__main__": app.run(debug=True) I am using Python 3.6 and IDLE on Windows 10. The problem is I keep getting the following error: Traceback (most recent call last): File "C:/Users/Susy/Desktop/provaflask.py", line 7, in &lt;module&gt; app.run(debug=True) File "C:\Users\Susy\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 936, in run cli.show_server_banner(self.env, self.debug, self.name, False) File "C:\Users\Susy\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\cli.py", line 630, in show_server_banner click.echo(message) File "C:\Users\Susy\AppData\Local\Programs\Python\Python36\lib\site-packages\click\utils.py", line 217, in echo file = _default_text_stdout() File "C:\Users\Susy\AppData\Local\Programs\Python\Python36\lib\site-packages\click\_compat.py", line 621, in func rv = wrapper_func() File "C:\Users\Susy\AppData\Local\Programs\Python\Python36\lib\site-packages\click\_compat.py", line 385, in get_text_stdout rv = _get_windows_console_stream(sys.stdout, encoding, errors) File "C:\Users\Susy\AppData\Local\Programs\Python\Python36\lib\site-packages\click\_winconsole.py", line 261, in _get_windows_console_stream func = _stream_factories.get(f.fileno()) io.UnsupportedOperation: fileno From this question, the problem seems to be related to the use of IDLE, however I would like to keep using it, so can you please help? Thank you!
accepted answer: http://stackoverflow.com/a/50089798
has title: Python: Hello world with Flask gives me an error related to app.run(debug=True)
upvote count: 8
linked to: http://stackoverflow.com/q/31080829
favorite count: 0
score: 8
type: Question
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/50089798

http://stackoverflow.com/a/50096201
score: 3
answers question: http://stackoverflow.com/q/50096134
type: Answer
has body: You can use Extended Iterable Unpacking operator. list_1 = [[1,2],[3,2]] store = [] def subtraction(z,l): total = z - l return total for y in list_1: store.append(subtraction(*y)) Another way is to use list comprehension. list = [a-b for a, b in list]
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50096134

http://stackoverflow.com/comment/87180705
comment on: http://stackoverflow.com/q/50082370
score: 3
has text: There is no reason whatsoever your variables would be magically saved and loaded. Take some time to learn the basics. Then implement save and load features should you need them.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87208224
has text: Show us what you have tried to solve this problem. Does it work? If not, what does not work?
comment on: http://stackoverflow.com/q/50096012
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50190677
has comment: http://stackoverflow.com/comment/87398236
answer count: 1
has comment: http://stackoverflow.com/comment/87398259
has comment: http://stackoverflow.com/comment/87398691
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87398501
has title: python generate fixed size (16 bytes) real random string
score: 3
upvote count: 5
tagged with: byte
has answer: http://stackoverflow.com/a/50190985
accepted answer: http://stackoverflow.com/a/50190985
has comment: http://stackoverflow.com/comment/87398292
has body: I want to generate a 16 bytes long random string for encryption purpose (AES encryption) in python3. urandom(n) seems to be the way to go to get real random characters: os.urandom(n): Return a string of n random bytes suitable for cryptographic use. As I need a 16 bytes random string, I thought this would do the job for me: EDIT I included now a more complex example, demonstrating the issues I have. from os import urandom from Crypto.Cipher import AES from base64 import b64encode import sys rnd=urandom(16) rnd_bytes=b64encode(rnd).decode('utf-8') print(sys.getsizeof(rnd_bytes)) print(len(rnd_bytes)) print(type(rnd_bytes)) AESencrypter=AES.new('my key',AES.MODE_CBC,rnd_bytes) Note: I used this answer for converting the urandom byte to a string. The output is: 73 24 File "/User/test.py", line 14, in AESencrypter=AES.new('my kes',AES.MODE_CBC,rnd_bytes) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 95, in new return AESCipher(key, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 59, in init blockalgo.BlockAlgo.init(self, _AES, key, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/Cipher/blockalgo.py", line 141, in init self._cipher = factory.new(key, *args, **kwargs) ValueError: IV must be 16 bytes long As you see, the length is not 16 (probably because of the conversion between byte and string). How can I fix that?
tagged with: python
has comment: http://stackoverflow.com/comment/87398698
linked to: http://stackoverflow.com/q/17958347
has comment: http://stackoverflow.com/comment/87398265
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 2
tagged with: random

http://stackoverflow.com/comment/87320346
score: 0
has text: Instead of giving minus can you provide a better solution please, We all try to learn. minus is unnecessary...
type: Comment
comment on: http://stackoverflow.com/a/50103961
type: AnswerComment

http://stackoverflow.com/comment/87362958
score: 0
comment on: http://stackoverflow.com/q/50129464
type: Comment
type: QuestionComment
has text: Try this: go to the GCP console, App Engine and services. Select the service in which you have deployed your application. In the right side click on tools and select "Logs". This will redirect the page to your app logs. Can you see them there?

http://stackoverflow.com/comment/87436838
has text: i'm sorry, where you get `payload` ?
type: Comment
comment on: http://stackoverflow.com/a/50209744
type: AnswerComment
score: 0

http://stackoverflow.com/a/50184968
upvote count: 1
downvote count: 0
type: Answer
has body: I found the solution to my problem External Link: If I am starting with a dict of lists, where lists contain non-unique hashable items, I can create another dict of lists as an inverse: def invert_dol_nonunique(d): newdict = {} for k in d: for v in d[k]: newdict.setdefault(v, []).append(k) return newdict
answers question: http://stackoverflow.com/q/50183936
score: 1

http://stackoverflow.com/comment/87448271
score: 0
comment on: http://stackoverflow.com/a/50206677
type: Comment
type: AnswerComment
has text: it did not filter out the correct rows see the should be at the bottom of my updated questions. I really appreciate the effort

http://stackoverflow.com/q/50142556
has answer: http://stackoverflow.com/a/50143515
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
tagged with: report
has answer: http://stackoverflow.com/a/78553649
downvote count: 0
accepted answer: http://stackoverflow.com/a/50143515
favorite count: 0
has title: Allure Framework Graph's not showing
type: Question
tagged with: graph
possible better answer: http://stackoverflow.com/a/78553649
tagged with: python-behave
has body: I am trying to fill up my allure reports with the graphs but only the defaults are being shown (Severity and Duration). I looked at the allure-reports/widgets, and the json files are there but it still not showing on the webpage. graph for categories trend missing btw, the Trend section on the Overview is empty as well. I am using allure 2.5.0 with python-behave
tagged with: python
tagged with: allure

http://stackoverflow.com/comment/87171385
type: Comment
comment on: http://stackoverflow.com/a/50076937
type: AnswerComment
has text: I checked the output and it shows the same result as the one you posted. Perhaps there are some rounding occurring inside ```statistics.mean()``` and that may result in slightly different values.
score: 0

http://stackoverflow.com/a/50209655
has body: First you want to find the node which is name "th" and id is "th2b".But these content is create by javascript.When you open the site,you will see that loading.So you should use "headless browser". chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gup") chrome_options.add_argument('--disable-infobars') chrome_options.add_argument("--hide-scrollbars") chrome_options.add_argument('--dns-prefetch-disable') chrome_options.add_argument("--disable-extensions") chrome_options.binary_location = "you chrome path" driver = webdriver.Chrome(chrome_options=chrome_options) driver.maximize_window() response = driver.get(quote_page) time.sleep(10) page = response.get_body() soup = BeautifulSoup(page, "html.parser") name_box = soup.find("th", attrs={"id": "th2b"}) name = name_box.text.strip() print(name) you will get text.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50209429

scikit-learn
tags question: http://stackoverflow.com/q/50216816
tags question: http://stackoverflow.com/q/50098066
tags question: http://stackoverflow.com/q/50111190
tags question: http://stackoverflow.com/q/50077562
tags question: http://stackoverflow.com/q/50092826
tags question: http://stackoverflow.com/q/50157531
tags question: http://stackoverflow.com/q/50197152
tags question: http://stackoverflow.com/q/50091331
tags question: http://stackoverflow.com/q/50134054
tags question: http://stackoverflow.com/q/50123028
tag name: scikit-learn
tags question: http://stackoverflow.com/q/50102719
tags question: http://stackoverflow.com/q/50081606
tags question: http://stackoverflow.com/q/50171143
tags question: http://stackoverflow.com/q/50094999
tags question: http://stackoverflow.com/q/50197326
tags question: http://stackoverflow.com/q/50127606
tags question: http://stackoverflow.com/q/50136880
tags question: http://stackoverflow.com/q/50111612
tags question: http://stackoverflow.com/q/50090767
tags question: http://stackoverflow.com/q/50214310
tags question: http://stackoverflow.com/q/50202199
tags question: http://stackoverflow.com/q/50222628
tags question: http://stackoverflow.com/q/50090673
type: Tag
tags question: http://stackoverflow.com/q/50143825
tags question: http://stackoverflow.com/q/50106143
tags question: http://stackoverflow.com/q/50185399
tags question: http://stackoverflow.com/q/50191729
tags question: http://stackoverflow.com/q/50127155
tags question: http://stackoverflow.com/q/50152377
tags question: http://stackoverflow.com/q/50145032
tags question: http://stackoverflow.com/q/50137134
tags question: http://stackoverflow.com/q/50179762
tags question: http://stackoverflow.com/q/50163393
tags question: http://stackoverflow.com/q/50218408
tags question: http://stackoverflow.com/q/50181272
tags question: http://stackoverflow.com/q/50184534
tags question: http://stackoverflow.com/q/50211534
tags question: http://stackoverflow.com/q/50117450
tags question: http://stackoverflow.com/q/50109324
tags question: http://stackoverflow.com/q/50131032
tags question: http://stackoverflow.com/q/50123230
tags question: http://stackoverflow.com/q/50103377
tags question: http://stackoverflow.com/q/50176861
tags question: http://stackoverflow.com/q/50096247
tags question: http://stackoverflow.com/q/50182411
tags question: http://stackoverflow.com/q/50152386
tags question: http://stackoverflow.com/q/50099623
tags question: http://stackoverflow.com/q/50181642
tags question: http://stackoverflow.com/q/50183202
tags question: http://stackoverflow.com/q/50213640
tags question: http://stackoverflow.com/q/50201913
tags question: http://stackoverflow.com/q/50101117
tags question: http://stackoverflow.com/q/50192763
tags question: http://stackoverflow.com/q/50151785
tags question: http://stackoverflow.com/q/50106516
tags question: http://stackoverflow.com/q/50145394
tags question: http://stackoverflow.com/q/50104050
tags question: http://stackoverflow.com/q/50125844
tags question: http://stackoverflow.com/q/50160086
tags question: http://stackoverflow.com/q/50090363
tags question: http://stackoverflow.com/q/50099322
tags question: http://stackoverflow.com/q/50149850
tags question: http://stackoverflow.com/q/50108258
tags question: http://stackoverflow.com/q/50213578
tags question: http://stackoverflow.com/q/50163386
tags question: http://stackoverflow.com/q/50123260
tags question: http://stackoverflow.com/q/50166457
tags question: http://stackoverflow.com/q/50122799
tags question: http://stackoverflow.com/q/50216691
tags question: http://stackoverflow.com/q/50143759
tags question: http://stackoverflow.com/q/50183080
tags question: http://stackoverflow.com/q/50116265
tags question: http://stackoverflow.com/q/50214040
tags question: http://stackoverflow.com/q/50099003
tags question: http://stackoverflow.com/q/50164737
tags question: http://stackoverflow.com/q/50177981

http://stackoverflow.com/comment/87385104
type: Comment
type: AnswerComment
has text: Oops, you're right. You can't change strings, they are immutable. Fixed answer.
score: 0
comment on: http://stackoverflow.com/a/50177602

http://stackoverflow.com/q/50160746
has comment: http://stackoverflow.com/comment/137442492
has title: Cookie not setting with Flask
score: 1
tagged with: flask
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I am trying to set a cookie with Flask after login and redirect on the front end in Javascript. @app.route("/login") @auth.login_required def get_auth_token(): token = g.user.generate_auth_token() request = make_response() token = str(token.decode("ascii")) request.set_cookie("token", value = token) return request, 200 No matter if I have the redirect in or not, the cookie never sets. I've tried commenting out my redirect on the front end, I've tried setting my cookie with secure = false but none of that seems to work. What am I missing? If needed, I can provide the generate_suth_token function, but I know that is working properly. I am serving on localhost:5000 and using Flask 0.12.2, and received no cookie warnings in the server log.
tagged with: python
accepted answer: http://stackoverflow.com/a/50164890
has answer: http://stackoverflow.com/a/50164890
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/50117209
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87258235
has comment: http://stackoverflow.com/comment/87253319
has title: Writing xyz coordinates in a csv file
tagged with: http://stackoverflow.com/tag/csv
has body: I am trying to write the co-ordinates (xyz coordinates) of a double-circle in a csv file. I have written following code now. import numpy as np import matplotlib.pyplot as plt import csv bLength=2.10e-10 numPoints=10 totalLength = bLength * numPoints Circumference = totalLength radius = Circumference / (2 * np.pi) totalAngle=360.0 angle = 360.0/numPoints # define a function frange to include fraction def frange(start, stop, step): i = start while i &lt; stop: yield i i += step # getting the x, y co-ordinates of the two circles displaced by angle/2) for i in frange(0.0, 360.0, angle): plt.plot(radius * np.cos(i), radius * np.sin(i), 'bo') for j in frange(angle/2, 360.0, angle): plt.plot(radius * np.cos(j), radius * np.sin(j), 'bo') plt.show() Here, I get a circle in the graph (in Jupyter Notebook). However, I would like to write the coordinates (xyz) of these circles (double-circle) in a "csv file". The syntax may be as follow. However, I am not able to proceed further. with open('data.csv', 'w') as f: csv.writer(f, delimiter=' ').writerows(f) The final output should contain three columns. The first two coummns of the csv will come from the above "for loops". The third coloumn of the csv file should be some constant (say 0 or 2.1). How can I do this?
accepted answer: http://stackoverflow.com/a/50118957
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87251993
has answer: http://stackoverflow.com/a/50118957
has comment: http://stackoverflow.com/comment/87251931
type: AnsweredQuestion
upvote count: 0
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87251838

http://stackoverflow.com/comment/87194193
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50086574
has text: This still contains a lot of unnecessary information such as the update loop of the portals, hiding the mouse, or the music code. If you strip the code down to the minimum required to reproduce the problem, it might help point you or us in the right direction

http://stackoverflow.com/comment/87417122
comment on: http://stackoverflow.com/q/50199660
type: QuestionComment
has text: I just ran the older file I described earlier, the one that wasn't supposed to break but now it breaks too when trying to input strings. I suspect it has something to do with my trainer going around doing some re-installing via Terminal that day when many of us trainees couldn't run codes with the Super() function. Prior, the .py files ran fine for me. The Python version must have changed along the way. I'll have to check with the trainer next time. Btw, thx for showing me how to read the Python version, I thought releaselevel=final simply meant the latest version but now I know better!
score: 0
type: Comment

http://stackoverflow.com/a/50152908
answers question: http://stackoverflow.com/q/50152754
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You have to pass named arguments to instantiate a user model: User(email=request.form['email'], password=request.form['password'])
accepted answer of: http://stackoverflow.com/q/50152754
score: 1

http://stackoverflow.com/q/50223084
tagged with: python-3.x
answer count: 1
downvote count: 0
has body: I need to run some python scripts from node. Since my python scripts use complex structures I figured would be better if I only loaded those structures once and then run some the specific scripts (tasks) using the structures. On node I want to run a script forever (or until I say it can terminate) and keep sending on-demand messages to this script. This script would create a process, using python multiprocessing, to run the specific task and start listening again. A use case would be: Node starts, and wakes python script Some action on the node client causes it to send a command to the python script The python script computes what it needs and returns the data I think python-shell can help me with this On node I have something like this: var app = express(); app.listen(8000, function () { console.log('Example app listening on port 8000!'); }); var pyshell = new PythonShell('start.py', options); pyshell.on('message', function (message) { handleAnswer(message); }); pyshell.end(function (err, code, signal) { handleEnd(err, code, signal); }); app.get('/hello', function (req, res) { pyshell.send('hello'); }); My start.py script is: import sys def listen(): while True: command = sys.stdin.readline() command = command.split('\n')[0] if command: print("Received CMD " + command) if __name__ == '__main__': data = json.loads(sys.argv[1]) listen() I tried the solution on this similar question but gets and error when wrapping the hello message in an endpoint. I properly require python-shell module and I'm able to execute a python script and return data (using print). My problem is to start the script and send the message after a (random) time period. When I open localhost:8000/hello I get Error: write after end Full error: Error: write after end at writeAfterEnd (_stream_writable.js:236:12) at Socket.Writable.write (_stream_writable.js:287:5) at Socket.write (net.js:717:40) at PythonShell.send (C:\Users\leonardo.schettini\Documents\recrutai\client\node_modules\python-shell\index…
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: stdin
has title: Continuously exchange data using python-shell
accepted answer: http://stackoverflow.com/a/50232089
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50232089
tagged with: node.js
upvote count: 4
linked to: http://stackoverflow.com/q/42462072

http://stackoverflow.com/comment/87427858
type: Comment
has text: You dropped your `:`
type: QuestionComment
comment on: http://stackoverflow.com/q/50205420
score: 2

http://stackoverflow.com/q/50100370
tagged with: dataframe
tagged with: python
upvote count: 6
possible better answer: http://stackoverflow.com/a/50100473
accepted answer: http://stackoverflow.com/a/50100476
has title: Python Pandas - Pivot table outputs floats unexpectedly
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50100476
has answer: http://stackoverflow.com/a/50100473
has answer: http://stackoverflow.com/a/60523361
score: 5
tagged with: pivot-table
has body: I have a dataframe that contains integers, however when I pivot it, it creates floats and I cannot work out why: My Dataframe (dfDis) looks like this: Year Type Total 0 2006 A talk or presentation 34 1 2006 A magazine, newsletter or online publication 33 2 2006 A formal working group, expert panel or dialogue 2 3 2006 Scientific meeting (conference/symposium etc.) 10 4 2006 A press release, press conference or response ... 6 .... My pivot code is: dfDisB = pd.pivot_table(dfDis, index=['Year'], columns = ['Type'],fill_value=0) And for some reason dfDisB ends up like this (sorry for formatting, I hope you get the gist): Total Type A broadcast e.g. TV/radio/film/podcast (other than news/press) A formal working group, expert panel or dialogue A magazine, newsletter or online publication A press release, press conference or response to a media enquiry/interview A talk or presentation Engagement focused website, blog or social media channel Participation in an activity, workshop or similar Participation in an open day or visit at my research institution Scientific meeting (conference/symposium etc.) Year 2006 1.000000 1.571429 6.125000 2.000000 3.235294 1.000000 4.222222 1.000000 5.500000 2007 0.000000 3.666667 24.500000 11.500000 32.250000 1.000000 5.250000 2.500000 28.000000 2008 0.000000 2.500000 21.333333 13.000000 38.230769 1.000000 7.909091 1.000000 37.000000 I am confused as I pivot some other data earlier on in my report, but I dont have the problem. Any suggestions? I have exported dfDis to a csv to check there were no floats in there and there are not, it is just whole numbers. Thank you
downvote count: 1
favorite count: 0
type: Question
answer count: 3
tagged with: pandas

django
tags question: http://stackoverflow.com/q/50229676
tags question: http://stackoverflow.com/q/50213779
tags question: http://stackoverflow.com/q/50113949
tags question: http://stackoverflow.com/q/50218539
tags question: http://stackoverflow.com/q/50142058
tags question: http://stackoverflow.com/q/50084996
tags question: http://stackoverflow.com/q/50137209
tags question: http://stackoverflow.com/q/50102481
tags question: http://stackoverflow.com/q/50126502
tags question: http://stackoverflow.com/q/50098611
tags question: http://stackoverflow.com/q/50199194
tags question: http://stackoverflow.com/q/50200002
tags question: http://stackoverflow.com/q/50166011
tags question: http://stackoverflow.com/q/50080520
tags question: http://stackoverflow.com/q/50216157
tags question: http://stackoverflow.com/q/50189134
tags question: http://stackoverflow.com/q/50125720
tags question: http://stackoverflow.com/q/50155291
tags question: http://stackoverflow.com/q/50158833
tags question: http://stackoverflow.com/q/50204240
tags question: http://stackoverflow.com/q/50092710
tags question: http://stackoverflow.com/q/50182001
tags question: http://stackoverflow.com/q/50140450
tags question: http://stackoverflow.com/q/50164201
tags question: http://stackoverflow.com/q/50214809
tags question: http://stackoverflow.com/q/50210427
tags question: http://stackoverflow.com/q/50162139
tags question: http://stackoverflow.com/q/50120089
tags question: http://stackoverflow.com/q/50205683
tags question: http://stackoverflow.com/q/50169019
tags question: http://stackoverflow.com/q/50138636
tags question: http://stackoverflow.com/q/50091266
tags question: http://stackoverflow.com/q/50095916
tags question: http://stackoverflow.com/q/50162738
tags question: http://stackoverflow.com/q/50198172
tags question: http://stackoverflow.com/q/50178120
tags question: http://stackoverflow.com/q/50187292
tags question: http://stackoverflow.com/q/50106138
tags question: http://stackoverflow.com/q/50179796
tags question: http://stackoverflow.com/q/50145465
tags question: http://stackoverflow.com/q/50109084
tags question: http://stackoverflow.com/q/50088536
tags question: http://stackoverflow.com/q/50214621
tags question: http://stackoverflow.com/q/50228397
tags question: http://stackoverflow.com/q/50147095
tags question: http://stackoverflow.com/q/50156311
tags question: http://stackoverflow.com/q/50198633
tags question: http://stackoverflow.com/q/50223662
tags question: http://stackoverflow.com/q/50157759
tags question: http://stackoverflow.com/q/50175557
tags question: http://stackoverflow.com/q/50083682
tags question: http://stackoverflow.com/q/50205666
tags question: http://stackoverflow.com/q/50170649
tags question: http://stackoverflow.com/q/50203403
tags question: http://stackoverflow.com/q/50204473
tags question: http://stackoverflow.com/q/50165717
tags question: http://stackoverflow.com/q/50204036
tags question: http://stackoverflow.com/q/50163152
tags question: http://stackoverflow.com/q/50111072
tags question: http://stackoverflow.com/q/50213369
tags question: http://stackoverflow.com/q/50194562
tags question: http://stackoverflow.com/q/50082875
tags question: http://stackoverflow.com/q/50160551
tags question: http://stackoverflow.com/q/50152591
tags question: http://stackoverflow.com/q/50085698
tags question: http://stackoverflow.com/q/50092605
tags question: http://stackoverflow.com/q/50180122
tags question: http://stackoverflow.com/q/50149341
tags question: http://stackoverflow.com/q/50086621
tags question: http://stackoverflow.com/q/50088819
tags question: http://stackoverflow.com/q/50096984
tags question: http://stackoverflow.com/q/50147137
tags question: http://stackoverflow.com/q/50115831
tags question: http://stackoverflow.com/q/50217842
tags question: http://stackoverflow.com/q/50077843
tags question: http://stackoverflow.com/q/50084468
tags question: http://stackoverflow.com/q/50142765
tags question: http://stackoverflow.com/q/50200023
tags question: http://stackoverflow.com/q/50123129
tags question: http://stackoverflow.com/q/50095233

http://stackoverflow.com/comment/87595154
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50155692
type: Comment
has text: Having Tweeted OWN, they say "In the JSON response the rain value is not provided. If it is measured - it is returned in the API response" So, if it's raining you get a response, it it's not you get {}, which screws up the SQL insert. I'm going to try a couple other things, but it's a not a huge loss to my project not having it for the moment.

http://stackoverflow.com/q/50192549
has title: display() in geojsonio gives 401 error
score: 1
tagged with: geojsonio
has answer: http://stackoverflow.com/a/52968926
downvote count: 0
answer count: 1
upvote count: 1
tagged with: geojson
favorite count: 0
has body: I am trying to Visualize a geojson file. import geojsonio as gj contents = open("taluk.geojson").read() gj.display(contents) But it gives the below error: AuthenticationFailed Traceback (most recent call last) &lt;ipython-input-27-2a5e2058a16e&gt; in &lt;module&gt;() ----&gt; 1 gj.display(contents) C:\Anaconda\lib\site-packages\geojsonio\geojsonio.py in display(contents, domain, force_gist) 34 35 """ ---&gt; 36 url = make_url(contents, domain, force_gist) 37 webbrowser.open(url) 38 return url C:\Anaconda\lib\site-packages\geojsonio\geojsonio.py in make_url(contents, domain, force_gist, size_for_gist) 91 url = data_url(contents, domain) 92 else: ---&gt; 93 gist = _make_gist(contents) 94 url = gist_url(gist.id, domain) 95 C:\Anaconda\lib\site-packages\geojsonio\geojsonio.py in _make_gist(contents, description, filename) 170 ghapi = github3.GitHub() 171 files = {filename: {'content': contents}} --&gt; 172 gist = ghapi.create_gist(description, files) 173 174 return gist C:\Anaconda\lib\site-packages\github3\decorators.py in auth_wrapper(self, *args, **kwargs) 35 '{"message": "Requires authentication"}' 36 ) ---&gt; 37 raise error_for(r) 38 return auth_wrapper 39 AuthenticationFailed: 401 Requires authentication
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52968926
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50091226
tagged with: python
has body: I was wondering how to generate a random 4 digit number that has no duplicates in python 3.6 I could generate 0000-9999 but that would give me a number with a duplicate like 3445, Anyone have any ideas thanks in advance
tagged with: random
score: 1
answer count: 1
linked to: http://stackoverflow.com/q/43351420
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: How would i generate a random number in python without duplicating numbers
duplicate of: http://stackoverflow.com/q/43351420
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87198833
linked to: http://stackoverflow.com/q/9690009
downvote count: 0
has answer: http://stackoverflow.com/a/50091280

http://stackoverflow.com/comment/87325148
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50150952
has text: There are several answers in that linked question. Which one did you try?
score: 0

http://stackoverflow.com/comment/87287918
type: Comment
type: QuestionComment
has text: Hint: in your first example, `b` is not "a copy of a" - `a` and `b` are two names pointing at the same object.
comment on: http://stackoverflow.com/q/50134883
score: 2

http://stackoverflow.com/q/50222523
type: UnansweredQuestion
tagged with: python
has title: RDD map+sortByKey - Error comprehension list python
tagged with: rdd
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87462768
has body: He Guys. I have been receiving an error when I do something like this: RDD = [(0, [1,2,3], 2),(1, [2,3,4], 4),(2, [4,5,6], 6),(3, [6,7,8], 8)] Dados = [4,5,6] TesteEuclediana = RDD.map(lambda x: (x[0], [math.sqrt((x[1][i][1]- Dados[i])^2) for i in range (0, int(len(Dados)))], x[2]) ).sortByKey() I catch this error: AttributeError: 'list' object has no attribute 'map'
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87463131

http://stackoverflow.com/q/50134687
has body: I am trying to filter a pandas dataframe using regular expressions. I want to delete those rows that do not contain any letters. For example: Col A. 50000 $927848 dog cat 583 rabbit 444 My desired results is: Col A. dog cat 583 rabbit 444 I have been trying to solve this problem unsuccessful with regex and pandas filter options. See blow. I am specifically running into problems when I try to merge two conditions for the filter. How can I achieve this? Option 1: df['Col A.'] = ~df['Col A.'].filter(regex='\d+') Option 2 df['Col A.'] = df['Col A.'].filter(regex=\w+) Option 3 from string import digits, letters df['Col A.'] = (df['Col A.'].filter(regex='|'.join(letters))) OR df['Col A.'] = ~(df['Col A.'].filter(regex='|'.join(digits))) OR df['Col A.'] = df[~(df['Col A.'].filter(regex='|'.join(digits))) &amp; (df['Col A.'].filter(regex='|'.join(letters)))]
tagged with: dataframe
has answer: http://stackoverflow.com/a/50134880
has answer: http://stackoverflow.com/a/50134854
tagged with: regex
possible better answer: http://stackoverflow.com/a/50134854
has comment: http://stackoverflow.com/comment/87287558
answer count: 4
accepted answer: http://stackoverflow.com/a/50134955
score: 8
type: Question
has comment: http://stackoverflow.com/comment/87287615
tagged with: python
has answer: http://stackoverflow.com/a/50135853
downvote count: 1
has answer: http://stackoverflow.com/a/50134955
favorite count: 0
has title: Filter all rows that do not contain letters (alpha) in ´pandas´
type: AnsweredQuestion
tagged with: python-2.7
linked to: http://stackoverflow.com/q/2039140
upvote count: 9
tagged with: pandas

http://stackoverflow.com/comment/87465644
score: 0
type: AnswerComment
type: Comment
has text: Your string with complex emoji is composed of 11 characters, and 11 underscores are returned.
comment on: http://stackoverflow.com/a/50218534

http://stackoverflow.com/q/50170288
score: 1
answer count: 1
downvote count: 0
tagged with: dataframe
favorite count: 0
type: Question
tagged with: edit-distance
has answer: http://stackoverflow.com/a/50170924
has body: I am interested in calculating the edit distances across all the columns of a given pandas DataFrame. Let's say we have a 3*5 DataFrame - I want to output something like this with the distance scores - (column*column matrix) col1 col2 col3 col4 col5 col1 col2 col3 col4 col5 I want each element of a column to match with every element of the other columns. Therefore, for every col1*col2 cell = summation of all the scores of the nested loop of col1 and col2. I would highly appreciate any help in this regards. Thanks in advance. INSPECTION_ID STRUCTURE_ID RELOCATE_FID HECO_ID HECO_ID_TAG_NOT_FOUND \ 0 100 95308 NaN 18/29 0.0 1 101 95346 NaN Nov-29 0.0 2 102 50008606 NaN 25/29 0.0 3 103 95310 NaN Dec-29 0.0 4 104 95286 NaN 17/29 0.0 OSMOSE_POLE_ID ALTERNATE_ID STREET_NBR STREET_DIRECTIONAL STREET_NAME \ 0 NaN NaN 1888 NaN KAIKUNANE 1 NaN NaN 1731 NaN MAKUAHINE 2 NaN NaN 1862 NaN MAKUAHINE 3 NaN NaN 1825 NaN KAIKUNANE 4 NaN NaN 1816 NaN KAIKUNANE Likewise, I got a (191795, 58) dataset. My objective is to find the edit distance between each column of the dataset so as to understand the patterns between them if any. For instance, I desire INSPECTION_ID 100 to be checked with all the values of column STRUCTURE_ID ans so on. I understand the need of an optimized iterator in this case. Kindly help me throwing some direction to solve this problem. Thanks in advance.
type: UnansweredQuestion
has title: Edit Distance between all the columns of a pandas dataframe
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87358668
tagged with: pandas

http://stackoverflow.com/comment/87213255
score: 0
comment on: http://stackoverflow.com/q/50098065
has text: I have just added the full code
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87466066
has text: @NaumanShahid The usual purpose of modifying the original list is so that all the variables that refer to it will see the changes. This does that.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50224237
score: 0

http://stackoverflow.com/q/50093634
has comment: http://stackoverflow.com/comment/87208943
tagged with: python
has title: abort(400) raising 500 internal server error - Flask 1.0
tagged with: flask
tagged with: debug-mode
accepted answer: http://stackoverflow.com/a/50097632
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87203585
has body: I have this function: if not (payload.get('password') == payload.get('password_cpy')): abort(400) when I run the app with flask run and debug is off, I get a pretty print of a BadRequest error which in raw shows the following info: 400 Bad Request Bad Request The browser (or proxy) sent a request that this server could not understand. And on terminal I see: 127.0.0.1 - - [30/Apr/2018 00:28:20] "POST /sign_in HTTP/1.1" 400 - When I run it and debug is on, the error I get is: werkzeug.exceptions.BadRequest werkzeug.exceptions.BadRequest: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. And in terminal I see a 500 error: 127.0.0.1 - - [30/Apr/2018 00:29:27] "POST /sign_in HTTP/1.1" 500 - Why do I get two different behaviors? Is there a way in which I can get the 400 error even in debug mode?
upvote count: 3
has comment: http://stackoverflow.com/comment/87203880
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50097632
tagged with: werkzeug
tagged with: exception

http://stackoverflow.com/q/50125979
has title: How to produce all combinations?
has comment: http://stackoverflow.com/comment/87270170
tagged with: python
has comment: http://stackoverflow.com/comment/87270034
has answer: http://stackoverflow.com/a/50126121
has comment: http://stackoverflow.com/comment/87270001
linked to: http://stackoverflow.com/q/11178061
tagged with: python-3.x
upvote count: 0
possible better answer: http://stackoverflow.com/a/50126049
downvote count: 2
has comment: http://stackoverflow.com/comment/87270007
score: -2
has answer: http://stackoverflow.com/a/50126049
has comment: http://stackoverflow.com/comment/87270005
has comment: http://stackoverflow.com/comment/87270433
has body: I am trying to make a python program that produces all combinations of an n-1 number with a length L: I've tried using the itertools but to not avail. I am trying to make it so that it produces the output above when I give it the arguments 5 3 in my terminal. I am using python3. An explanation would be great. Here is my code. import sys import itertools def comb(A,n,k,p,lo): stuff = [A, n, k,p,lo] return itertools.combinations(stuff, len(stuff) if __name__ == "__main__": d = len(sys.argv)&gt;3 n = int(sys.argv[1]) k = int(sys.argv[2]) A = [] for i in range(k): A.append(0) if d: print("n:",n,"k:",k) comb(A,n,k,0,0)
has comment: http://stackoverflow.com/comment/87269994
has answer: http://stackoverflow.com/a/50126134
accepted answer: http://stackoverflow.com/a/50126134
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87270134
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/87345855
comment on: http://stackoverflow.com/a/50146514
score: 0
type: Comment
has text: Sorry, I get the following message while trying with gurobi. `RuntimeError: Attempting to use an unavailable solver. The SolverFactory was unable to create the solver "gurobi" and returned an UnknownSolver object. This error is raised at the point where the UnknownSolver object was used as if it were valid (by calling method "solve"). The original solver was created with the following parameters: solver_io: direct type: gurobi _args: () options: {} `
type: AnswerComment

http://stackoverflow.com/a/50121031
upvote count: 1
has body: Your approach of handling indents in the lexer rather than the parser is correct. Well, it’s doable either way, but this is usually the easier way, and it’s the way Python itself (or at least CPython and PyPy) does it. I don’t know much about JFlex, and you haven’t given us any code to work with, but I can explain in general terms. For your first problem, you're already putting the lexer into a special state after the newline, so that "grab 0 or more spaces" should be doable by escaping from the normal flow of things and just running a regex against the line. For your second problem, the simplest solution (and the one Python uses) is to keep a stack of indents. I'll demonstrate something a bit simpler than what Python does. First: indents = [0] After each newline, grab a run of 0 or more spaces as spaces. Then: if len(spaces) == indents[-1]: pass elif len(spaces) &gt; indents[-1]: indents.append(len(spaces)) emit(INDENT_TOKEN) else: while len(spaces) != indents[-1]: indents.pop() emit(DEDENT_TOKEN) Now your parser just sees INDENT_TOKEN and DEDENT_TOKEN, which are no different from, say, OPEN_BRACE_TOKEN and CLOSE_BRACE_TOKEN in a C-like language. Of you’d want better error handling—raise some kind of tokenizer error rather than an implicit IndexError, maybe use &lt; instead of != so you can detect that you’ve gone too far instead of exhausting the stack (for better error recovery if you want to continue to emit further errors instead of bailing at the first one), etc. For real-life example code (with error handling, and tabs as well as spaces, and backslash newline escaping, and handling non-syntactic indentation inside of parenthesized expressions, etc.), see the tokenize docs and source in the stdlib.
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50120724
accepted answer of: http://stackoverflow.com/q/50120724
type: Answer

http://stackoverflow.com/comment/87385914
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50184284
type: Comment
has text: Why repost an answer that's been posted 2 minutes ago already?

http://stackoverflow.com/comment/87424237
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50124958
type: AnswerComment
has text: Thank you Mathias. Please allow me a favour.Could you up vote me somewhere? I have another question ban!! It's like they are shooting the ones that can't keep up !

http://stackoverflow.com/q/50181332
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50181371
has answer: http://stackoverflow.com/a/50181371
score: 2
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/78376860
upvote count: 3
possible better answer: http://stackoverflow.com/a/50181376
has title: Python Requests: assert status_code is not failing
has answer: http://stackoverflow.com/a/50181376
has body: I'm trying to fail a test with a specific error message if an api call returns a 403 code. I've tried a couple options: if int(addresses.status_code) is 403: fail("Auth Error: Missing Role {}".format(response.json())) assert addresses.status_code is not 403 assert addresses.status_code is not codes.forbidden assert addresses.status_code is codes.ok The only one of these that is failing is the last, assert addresses.status_code is codes.ok. However, the status code the api call is responding with is 403. I've played around with making sure the types are the same, etc, but not sure where else to go. How do I test that the status_code is not a specific value?
tagged with: python-requests
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87442207
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50212122
has text: You can check it using an online xml validator

http://stackoverflow.com/comment/87216560
has text: Can you please [edit](https://stackoverflow.com/posts/50100019/edit) and include your code? Really, we need a [mcve]. It's impossible otherwise to guess your logic.
comment on: http://stackoverflow.com/q/50100019
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/a/50186718
has comment: http://stackoverflow.com/comment/87392509
accepted answer of: http://stackoverflow.com/q/50182459
has body: This call is one of your bottlenecks (perhaps 2/3 of your time): if (neutron.distance(self.fuel[i][1]) &lt;= 1): it happens hundreds of thousands of times (possibly millions with the right parameters) and at it's heart it's doing expensive arithmetic: (self[0]**2 + self[1]**2)**0.5 when it calls abs() on the result of the Vec2D subtraction. (It's even testing if self.fuel[i][1] is a Vec2D when you know it is.) Since our target is &lt;= 1, we may not need exponentiation and square roots, we might be able to get away with a less expensive approximation like: distance = self.fuel[i][1] - neutron.position() # returns a Vec2D if abs(distance[0]) + abs(distance[1]) &lt;= 1: Reducing this bottleneck to something more like 1/3 of your time. (I.e. test a bounding square rather than test a bounding circle.) it is still relatively slow and I'd like it to be faster We'll use a traditional approach to this problem, trade off space for speed by turning self.fuel into a sparse matrix instead of a list. That way we eliminate the search altogether and just check if the current position is sitting on a fuel rod: from turtle import Turtle, Screen from random import randint BORDER = 100 MAGNIFICATION = 4 CURSOR_SIZE = 20 class Reactor: def __init__(self, spendfuel, board, startNeut, iterations, percent_fuel): width, height = board screen = Screen() screen.setup(width + BORDER * 2, height + BORDER * 2) screen.setworldcoordinates(-BORDER // MAGNIFICATION, -BORDER // MAGNIFICATION, (width + BORDER) // MAGNIFICATION, (height + BORDER) // MAGNIFICATION) screen.title("Reactor Top Down Reaction Model") screen.bgcolor("black") screen.tracer(0) scaled_width, scaled_height = width // MAGNIFICATION, height // MAGNIFICATION self.fuel = [[None for x in range(scaled_width)] for y in range(scaled_height)] self.fuel_t = self.newParticle('red', 'square', (0, 0)) self.spendfuel = spendfuel self.neutrons = [] self.setup(percent_fuel, scaled_width, scaled_height, startNeut) screen.update() for _ in range(…
has comment: http://stackoverflow.com/comment/87399741
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87400797
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50182459

http://stackoverflow.com/comment/87235334
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50109009
type: QuestionComment
has text: Add a space or tab '\t' (depending on what you have in the file) after 'p1' or use regular expressions

http://stackoverflow.com/q/50207185
tagged with: python
type: UnansweredQuestion
has title: How to quickly search for public methods of a class in python
answer count: 1
type: Question
score: 0
has answer: http://stackoverflow.com/a/50207247
has body: I used to program in Java and one good thing about Java is that it is always easy to find out what class type is an object and I am used to the Java API document format to browse through methods provided by a class. This is an advantage when I face a new third party package. However, when I learn python, one thing that frustrates me is it is not easy to quick see (without writing extra code) what class type is an object (especially for an object that is returned from a chain of methods) and the API documents lack the consistency comparing to Java. So I have more difficulty when picking up a new package in python than in Java. Am I missing any tricks or principles in python or what? How does everyone do when picking up a new package to use? Many thanks for any guides.

http://stackoverflow.com/comment/87308036
type: Comment
score: 0
has text: `df1.query("counts > 100").nsmallest(....)`
comment on: http://stackoverflow.com/q/50144934
type: QuestionComment

http://stackoverflow.com/q/50166773
has body: One of the distinctions between a list and a set is a list can be altered during iteration -- we can append to it in a loop, etc. However, if we try to add to a set during a for loop, runtime error is raised. However, how does Python detect that set.add() is being used in a loop and then raises the run time error? If I try to recreate my pseudo list class and raise runtime error in my class's append function, do I simply overload __iter__ to prevent any appending? For an example: a_set = {1,2,3,4} a_list = [1,2,3,4] for i in a_list: a_list.append(5) Which results in an infinite loop for j in a_set: a_set.add(5) Which results in runtime error. They both have __iter__ functions so in my pseudo list class, how should I overload __iter__ such that it will raise runtime error like a set does?
type: Question
has title: Runtime Error during iteration?
score: 2
has comment: http://stackoverflow.com/comment/87351342
has answer: http://stackoverflow.com/a/50167042
has answer: http://stackoverflow.com/a/50166899
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87351422
has comment: http://stackoverflow.com/comment/87352108
tagged with: iteration
favorite count: 0
has comment: http://stackoverflow.com/comment/87352130
answer count: 3
has comment: http://stackoverflow.com/comment/87351490
has comment: http://stackoverflow.com/comment/87351591
tagged with: python
has answer: http://stackoverflow.com/a/50167197

http://stackoverflow.com/q/50150862
has comment: http://stackoverflow.com/comment/87320242
has comment: http://stackoverflow.com/comment/87319891
has comment: http://stackoverflow.com/comment/87319430
tagged with: django
linked to: http://stackoverflow.com/q/23313941
tagged with: python
has comment: http://stackoverflow.com/comment/87321011
score: 0
answer count: 0
has body: I have a Question &amp; Answer model, where anyone can answer a question &amp; also follow a question. # question model class Question(models.Model): text = models.TextField() followers = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) # answer model class Answer(models.Model): text_answer = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE) How can I filter through Answer if request.user is followers list? I tried Answer.objects.filter(question.followers=request.user) but it didn't work.
has title: Django: Object Filtering from ManyToManyField
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/87377208
comment on: http://stackoverflow.com/a/50179933
type: Comment
has text: I see. Without AJAX, I can't think of another way than the 3 forms you mention in your question. Unless you're ok with some javascript, in which case you could probably capture the `onClick` on the buttons, and submit the form from the code. It feels a bit hacky though.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50108800
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87235118
score: 0
has body: I has tried solve this but I cannot. I'm trying determinate standard deviation in finance, I mean: Pr = Prob are equal [0.3, 0.4, 0.3] r = Return are equal [0.10 ,0.05, 0.30] So, first I calculate my average E(r) = 0.10*0.3 + 0.4*0.05 + 0.3*0.3 = 0.14 Second, calculate my variance: Var = 0.3*(0.1-0.14)^2 + 0.4*(0.05-0.14)^2 + 0.3*(0.3 - 0.14)^2 = 0.0114 Third, my Standard Deviation is Var^(1/2) = 0.10677078 rounded to 0.10677 In Python, I has tried solve using basic arhitmetic but I cannot do. My code is: import math def dev_stan(prob, ret): Pro = 0 Des_Stan = 0 Var = 0 for i in range(len(ret)): Pro += prob[i]*ret[i] Var += (ret[i] - Pro)**2*prob[i] Des_Stan = (math.sqrt(Var)) return Des_Stan, Var, Pro, ret, prob x = [0.30,0.4,0.30] y = [0.10,0.05,0.30] print(dev_stan(x,y)) This code result in : 0.0956556 but this is not the answer.
tagged with: finance
tagged with: python
tagged with: standard-deviation
has title: Accumulative sums and Standard Deviation with loops for in Python
type: Question
has answer: http://stackoverflow.com/a/50108950
has answer: http://stackoverflow.com/a/51605042
answer count: 2

http://stackoverflow.com/comment/87400797
has text: Thank you, this was the exact solution I was looking for. The sparse matrix does seem to handle this situation in a faster more efficient way. I'm sorry for the poor coding style, this was one of my first few versions of the code, as I wanted to post something short that cuts right into the problem. Thanks again! @cdlane
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50186718
type: Comment

http://stackoverflow.com/a/62017851
has body: Based on the error message, it seems the file is not found I came across similar problem, and I solved it by changing current working directory first In your case # Change working directory first os.chdir("C:\Users\mas\Desktop") # then do the loop for filename in os.listdir(r"C:\Users\mas\Desktop\"): ...
answers question: http://stackoverflow.com/q/50082649
score: 0
type: Answer

http://stackoverflow.com/q/50103918
has answer: http://stackoverflow.com/a/50104566
accepted answer: http://stackoverflow.com/a/50104566
linked to: http://stackoverflow.com/q/18180763
answer count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/87227993
favorite count: 0
type: Question
has title: How to compare two pandas dataframes and remove duplicates on one file without appending data from other file
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/18180763
has body: I am trying to compare two csv files using pandas dataframes. One is a master sheet that is going to have data appended to it daily (test_master.csv). The second is a daily report (test_daily.csv) that contains the data I want to append to the test_master.csv. I am creating two pandas dataframes from these files: import pandas as pd dfmaster = pd.read_csv(test_master.csv) dfdaily = pd.read_csv(test_daily.csv) I want the daily list to get compared to the master list to see if there are any duplicate rows on the daily list that are already in the master list. If so, I want them to remove the duplicates from dfdaily. I then want to write this non-duplicate data to dfmaster. The duplicate data will always be an entire row. My plan was to iterate through the sheets row by row to make the comparison, then. I realize I could append my daily data to the dfmaster dataframe and use drop_duplicates to remove the duplicates. I cannot figure out how to remove the duplicates in the dfdaily dataframe, though. And I need to be able to write the dfdaily data back to test_daily.csv (or another new file) without the duplicate data. Here is an example of what the dataframes could look like. test_master.csv column 1 | column 2 | column 3 | +-------------+-------------+-------------+ | 1 | 2 | 3 | | 4 | 5 | 6 | | 7 | 8 | 9 | | duplicate 1 | duplicate 1 | duplicate 1 | | duplicate 2 | duplicate 2 | duplicate 2 test_daily.csv +-------------+-------------+-------------+ | column 1 | column 2 | column 3 | +-------------+-------------+-------------+ | duplicate 1 | duplicate 1 | duplicate 1 | | duplicate 2 | duplicate 2 | duplicate 2 | | 10 | 11 | 12 | | 13 | 14 | 15 | +-------------+-------------+-------------+ Desired output is: test_master.csv +-------------+-------------+-------------+ | column 1 | column 2 | column 3 | +-------------+-------------+-------------+ | 1 | 2 | 3 | | 4 | 5 | 6 | | 7 | 8 | 9 | | duplicate 1 | duplicate 1 | duplicate 1 | | duplicate 2 | duplicate 2 | duplicate 2…
score: 5

http://stackoverflow.com/a/50100951
score: 0
has body: How about this: def filter_short_tweets(tweets): return [tweet for tweet in tweets if len(tweet['text']) &gt; 50] filter_short_tweets(k1_tweets)
answers question: http://stackoverflow.com/q/50100730
type: Answer

http://stackoverflow.com/comment/87210406
score: 0
type: QuestionComment
has text: thank for reply, i mean i've test success with render gameplay by 6 first line of code above, but when run entire code of kapathy'blog , just display result of script python file and not display(render) of gameplay of pong(like as image).And don't have any bug log or error message .
type: Comment
comment on: http://stackoverflow.com/q/50093401

http://stackoverflow.com/comment/87311884
score: 0
comment on: http://stackoverflow.com/q/50146570
type: QuestionComment
has text: What is "map" exactly? It seems to me that `df['id'][i]` maps to `X_clustered[i]` already (assuming column named so).
type: Comment

http://stackoverflow.com/comment/87205728
type: QuestionComment
comment on: http://stackoverflow.com/q/50094765
has text: You can try below link. I hope it help you https://stackoverflow.com/questions/27657570/how-to-convert-bytearray-with-non-ascii-bytes-to-string-in-python
score: 0
type: Comment

http://stackoverflow.com/q/50130605
score: 6
upvote count: 6
tagged with: file-writing
has answer: http://stackoverflow.com/a/55025135
possible better answer: http://stackoverflow.com/a/55025135
favorite count: 0
tagged with: file-read
type: AnsweredQuestion
has body: I have a question about Python 2.7 read/write csv file with 'utf-8-sig' code, my csv . header is ['\xef\xbb\xbfID;timestamp;CustomerID;Email'] there have some code("\xef\xbb\xbfID") I read from file A.csv and I want write the same code and header to file B.csv My print log is shows: ['\xef\xbb\xbfID;timestamp;CustomerID;Email'] But the actual output file header it looks like ÔªøID;timestamp Here is the code: def remove_gdpr_info_from_csv(file_path, file_name, temp_folder, original_header): new_temp_folder = tempfile.mkdtemp() new_temp_file = new_temp_folder + "/" + file_name # Blanked new file with open(new_temp_file, 'wb') as outfile: writer = csv.writer(outfile, delimiter=";") print original_header writer.writerow(original_header) # File from SFTP with open(file_path, 'r') as infile: reader = csv.reader(infile, delimiter=";") first_row = next(reader) email = first_row.index('Email') contract_detractor1 = first_row.index('Contact Detractor (Q21)') contract_detractor2 = first_row.index('Contact Detractor (Q20)') contract_detractor3 = first_row.index('Contact Detractor (Q43)') contract_detractor4 = first_row.index('Contact Detractor(Q26)') contract_detractor5 = first_row.index('Contact Detractor(Q27)') contract_detractor6 = first_row.index('Contact Detractor(Q44)') indexes = [] for column_name in header_list: ind = first_row.index(column_name) indexes.append(ind) for row in reader: output_row = [] for ind in indexes: data = row[ind] if ind == email: data = '' elif ind == contract_detractor1: data = '' elif ind == contract_detractor2: data = '' elif ind == contract_detractor3: data = '' elif ind == contract_detractor4: data = '' elif ind == contract_detractor5: data = '' elif ind == contract_detractor6: data = '' output_row.append(data) writer.writerow(output_row) s3core.upload_files(SPARKY_S3, DESTINATION_PATH, new_temp_file) shutil.rmtree(temp_folder) shutil.rmtree(new_temp_folder)
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50131187
accepted answer: http://stackoverflow.com/a/50131187
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: Question
has title: Python 2.7 CSV file read/write \xef\xbb\xbf code
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50165513
tagged with: sql
has answer: http://stackoverflow.com/a/50166022
has comment: http://stackoverflow.com/comment/87350712
type: Question
possible better answer: http://stackoverflow.com/a/50165543
has answer: http://stackoverflow.com/a/50165543
tagged with: python
has comment: http://stackoverflow.com/comment/87350914
has title: SQL rolling window unique count
tagged with: google-bigquery
accepted answer: http://stackoverflow.com/a/50166735
has body: Is there an SQL equivalent to this line of code in pandas? Assuming a is a DataFrame object and the index is a list of times (with hours, minutes, and seconds). x in this case would just be the other column in the DataFrame besides the index. a.rolling('1h').apply(lambda x: len(np.unique(x))).astype(int) Sample result: (Time formatted in HH:MM:SS) X 05:20:19 4 &lt;- 1 (only 1 unique number) 05:20:19 5 &lt;- 2 (4 and 5 are unique) * same time as before 05:37:18 7 &lt;- 3 (4, 5 and 7 are unique) 05:45:14 4 &lt;- 3 (4, 5, and 7) 05:56:04 4 &lt;- 3 (4, 5, and 7) 06:18:48 6 &lt;- 4 (now 4, 5, 6, and 7) 06:48:34 3 &lt;- 3 (only checks past hour, so now 3, 4, 6) 07:52:48 1 &lt;- 1 (only time in past hour, so only 1) I'm just using vanilla SQL for this as well. Thanks so much!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50166735
score: 0
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/87353484
comment on: http://stackoverflow.com/q/50167270
has text: @BasileStarynkevitch I've included what the code is doing, and that the reason for wanting to avoid the Python runtime is due to a high sampling/processing rate ("real time") robotics data.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50180297
has comment: http://stackoverflow.com/comment/87377884
type: Answer
has body: That's functional-style, which you can read from innermost expression towards outermost. Putting it on multiple lines with some comments can help readability: result = list( # (5) convert to list set( # (4) convert to set (remove dupes) filter( lambda x: x != word, # (3) filter items != to word map( lambda x: x.lower().replace('_',' '), # (2) apply transformation input_list # (1) take input_list ) ) ) )[:clip_length] # (6) limit number of results It's a matter of taste. I tend to prefer single expressions like this, with a minimal formatting that would allow it to fit nicely: result = list(set(filter(lambda x : x != word, map(lambda x : x.lower().replace('_',' '), input_list))))[:clip_length] An equivalent imperative-style processing is: result = set() for x in input_list: x = x.lower().replace('_', ' ') if x != word: result.add(x) result = list(result)[:clip_length]
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50180185

http://stackoverflow.com/q/50184873
type: Question
has title: Docker build fails if pip is installed and updated to 10.0.1 in a single RUN section
has body: How would you explain docker build failure with Dockerfile1, and it's success with Dockerfile2 (see below). 1) // Dockerfile1 FROM ubuntu:16.04 RUN apt-get -y update &amp;&amp; \ apt-get -y install python-pip python-dev build-essential &amp;&amp; \ pip install --upgrade pip &amp;&amp; \ pip install --upgrade virtualenv docker build . fails with the following err Collecting pip Downloading https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl (1.3MB) Installing collected packages: pip Found existing installation: pip 8.1.1 Not uninstalling pip at /usr/lib/python2.7/dist-packages, outside environment /usr Successfully installed pip-10.0.1 Traceback (most recent call last): File "/usr/bin/pip", line 9, in &lt;module&gt; from pip import main ImportError: cannot import name main The command '/bin/sh -c apt-get -y update &amp;&amp; apt-get -y install python-pip python-dev build-essential &amp;&amp; pip install --upgrade pip &amp;&amp; pip install --upgrade virtualenv &amp;&amp; virtualenv /venv' returned a non-zero code: 1 However, it succeeds if we split it into two RUN. 2) // Dockerfile2 FROM ubuntu:16.04 RUN apt-get -y update &amp;&amp; \ apt-get -y install python-pip python-dev build-essential &amp;&amp; \ pip install --upgrade pip RUN pip install --upgrade virtualenv The installation failure for pip is related to this reported issue. So my questions: Why does docker build fail in the first case? If we just run those command in bash, there wont be any error. Why does docker build succeed in the second case? How is it related to layering concept in docker? Why specifying pip version in Dockerfile1 (i.e. pip install --upgrade pip=0.9.3) solves the problem too? Update (May 6, 2018): I've figured out the issue. What happens here is as below: apt-get -y install python-pip installs an old version of pip whose shim script import pip's main directly. pip install --upgrade pip installs pip 10.…
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: docker
score: 0
has answer: http://stackoverflow.com/a/50194938
answer count: 1
tagged with: dockerfile

http://stackoverflow.com/comment/87413083
type: Comment
comment on: http://stackoverflow.com/a/50198000
score: 0
type: AnswerComment
has text: the output file is still showing up as blank txt file

http://stackoverflow.com/comment/87428666
has text: Yea exactly, but since the df is so large, I want to make sure the correct 'weight' value corresponds to the correct row. The df is only a part of the table, so I don't want to replace the entire table to df. Sorry for the confusion I hope that makes more sense
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50205742
score: 0

http://stackoverflow.com/comment/87368415
type: Comment
comment on: http://stackoverflow.com/q/50173419
score: 0
type: QuestionComment
has text: worked with ziped path?

http://stackoverflow.com/a/50121857
answers question: http://stackoverflow.com/q/50120079
upvote count: 1
has comment: http://stackoverflow.com/comment/87261594
downvote count: 1
type: Answer
has body: In a comment you said that you want a signal on the following update statement: Product.objects.filter(category = 'cat_AA').update(category = 'cat_BB') According to this question, the django signal docs and the django queryset docs, the update() method does NOT trigger the post_save signal. So you will have to find another way to accomplish your goal, like for example iterating over each item and calling its save method (but it will be slower).
has comment: http://stackoverflow.com/comment/87261680
score: 0

http://stackoverflow.com/comment/87282414
type: Comment
comment on: http://stackoverflow.com/q/50131596
score: 0
has text: Small correction - you are not creating new *threads*, you are creating new *processes*. They are significantly different things so shouldn't be confused.
type: QuestionComment

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

http://stackoverflow.com/q/50080353
has comment: http://stackoverflow.com/comment/87178096
possible better answer: http://stackoverflow.com/a/50081733
tagged with: python
has answer: http://stackoverflow.com/a/50081733
tagged with: nlp
has comment: http://stackoverflow.com/comment/87178148
has title: String replace with condition
answer count: 2
has comment: http://stackoverflow.com/comment/87178498
tagged with: pandas
upvote count: 3
accepted answer: http://stackoverflow.com/a/50083341
downvote count: 0
has body: I have two pandas dataframes. One contains text, the other a set of terms i'd like to search for and replace within the text. I have a method to do this, however I would like to add conditions. The conditions are, if the term contains the word either 'no' or 'none' up to three words before, to not replace. In the example below ID 2 is incorrectly replaced based on the conditions above. Example text: d = {'ID': [1, 2, 3], 'Text': ['here is some random text', 'no such random text, none here', 'more random text']} text_df = pd.DataFrame(data=d) Example terms: d = {'Replace_item': ['&lt;RANDOM_REPLACED&gt;', '&lt;HERE_REPLACED&gt;', '&lt;SOME_REPLACED&gt;'], 'Text': ['random', 'here', 'some']} replace_terms_df = pd.DataFrame(data=d) Method for replacing terms (with ID 2 being incorrect based on conditions): text_df['Text'] = [z.replace(x, y) for (x, y, z) in zip(replace_terms_df.Text, replace_terms_df.Replace_item, text_df.Text)] Target dataframe (considering the conditions): d = {'ID': [1, 2, 3], 'Text': ['&lt;HERE_REPLACED&gt; is &lt;SOME_REPLACED&gt; &lt;RANDOM_REPLACED&gt; text', 'no such random text, none here', 'more &lt;RANDOM_REPLACED&gt; text']} target_df = pd.DataFrame(data=d) Please ask if you need clarity. Thank you.
has answer: http://stackoverflow.com/a/50083341
has comment: http://stackoverflow.com/comment/87179106
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/87431550
type: AnswerComment
comment on: http://stackoverflow.com/a/50197737
score: 0
type: Comment
has text: Thanks for taking the time Anthon. Yes you are right, if data is loaded all at once then why not just iterating. However, I was looking for something similar to the way that I retrieved data from a SQL DB, but I guess that's not possible.

http://stackoverflow.com/comment/87362310
has text: Possible duplicate of [os.walk without hidden folders](https://stackoverflow.com/questions/13454164/os-walk-without-hidden-folders)
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/50172536

http://stackoverflow.com/comment/102802762
comment on: http://stackoverflow.com/a/50137686
has text: Is there any solution using `pyarrow` ? We had a similar problem and ran `repartition` (heavy process but worked)
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/50220333
has comment: http://stackoverflow.com/comment/87532976
answer count: 1
has title: Creating Pandas dataframe from nested unordered html lists
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87458203
has comment: http://stackoverflow.com/comment/87458577
has body: I have a webpage of unordered lists, and I want to turn them into a pandas dataframe as the first step of an NLP workflow. import pandas as pd from bs4 import BeautifulSoup html = ''' Name Many Stories More Stuff About ''' soup = BeautifulSoup(html, 'lxml') The goal is for each top level list to turn into a dataframe, that would look something like this output: 0 1 2 0 Name Many Stories 1 More null null 2 Stuff About null I tried to use the following code to get all the list items (complete with sublists) target = soup.find_all('ul') But it returns double outputs: [ Name Many Stories , Many , Stories , More , Stuff About , About ] Really lost here. Thanks.
tagged with: python
has comment: http://stackoverflow.com/comment/87458107
linked to: http://stackoverflow.com/q/11465555
tagged with: nlp
tagged with: elementtree
accepted answer: http://stackoverflow.com/a/50282986
has comment: http://stackoverflow.com/comment/87571771
has comment: http://stackoverflow.com/comment/87497185
type: Question
tagged with: xpath
has answer: http://stackoverflow.com/a/50282986
score: 0
tagged with: pandas

http://stackoverflow.com/q/50089046
accepted answer: http://stackoverflow.com/a/50090790
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50090790
score: 0
has comment: http://stackoverflow.com/comment/87194552
downvote count: 1
has comment: http://stackoverflow.com/comment/87195834
favorite count: 0
has comment: http://stackoverflow.com/comment/87197422
type: Question
has comment: http://stackoverflow.com/comment/87194642
has comment: http://stackoverflow.com/comment/87196283
upvote count: 1
tagged with: python
answer count: 1
has title: Filter a larger DataFrame using date ranges and column values from a smaller one
has body: I have a larger DataFrame, df1, that looks like this: Data PatId EntryDate Id 725 2005-01-03 1422 X 2005-01-04 1563 X 2005-01-05 1355 X 2005-01-06 118 X 2005-01-09 1400 X ... 117785 2004-12-31 799998 X 2005-01-03 796833 X 2005-01-05 798728 X 2005-01-08 798545 X 2005-01-11 797632 X And a smaller DataFrame, df2 that looks like this: PatId EntryDate ExitDate 2005-01-15 2005-04-15 22407 2005-01-30 2005-04-30 95938 2005-02-07 2005-05-07 116812 2005-02-18 2005-05-18 12163 2005-02-21 2005-05-21 22908 I'd like an elegant way to filter df1 to only include the rows for each PatId that lie between the EntryDate and ExitDate indexes in df2.
has comment: http://stackoverflow.com/comment/87197659

pyspark
tags question: http://stackoverflow.com/q/50127304
tags question: http://stackoverflow.com/q/50183775
tags question: http://stackoverflow.com/q/50209425
tags question: http://stackoverflow.com/q/50108533
tags question: http://stackoverflow.com/q/50137409
tags question: http://stackoverflow.com/q/50201717
tags question: http://stackoverflow.com/q/50182869
tags question: http://stackoverflow.com/q/50187800
tags question: http://stackoverflow.com/q/50205101
tags question: http://stackoverflow.com/q/50132075
tags question: http://stackoverflow.com/q/50101984
tags question: http://stackoverflow.com/q/50172210
tags question: http://stackoverflow.com/q/50134185
tags question: http://stackoverflow.com/q/50168018
tags question: http://stackoverflow.com/q/50101178
tags question: http://stackoverflow.com/q/50184938
tags question: http://stackoverflow.com/q/50104422
tags question: http://stackoverflow.com/q/50206582
tags question: http://stackoverflow.com/q/50186170
tags question: http://stackoverflow.com/q/50166012
tags question: http://stackoverflow.com/q/50183915
tags question: http://stackoverflow.com/q/50161556
tags question: http://stackoverflow.com/q/50133318
tags question: http://stackoverflow.com/q/50219311
tags question: http://stackoverflow.com/q/50105631
tags question: http://stackoverflow.com/q/50086216
tags question: http://stackoverflow.com/q/50145195
type: Tag
tags question: http://stackoverflow.com/q/50152946
tags question: http://stackoverflow.com/q/50210651
tags question: http://stackoverflow.com/q/50215791
tags question: http://stackoverflow.com/q/50108601
tags question: http://stackoverflow.com/q/50219200
tag name: pyspark
tags question: http://stackoverflow.com/q/50174227
tags question: http://stackoverflow.com/q/50180799
tags question: http://stackoverflow.com/q/50145024
tags question: http://stackoverflow.com/q/50092550
tags question: http://stackoverflow.com/q/50131892
tags question: http://stackoverflow.com/q/50209312
tags question: http://stackoverflow.com/q/50207995
tags question: http://stackoverflow.com/q/50193599
tags question: http://stackoverflow.com/q/50151214

http://stackoverflow.com/a/50158723
downvote count: 0
answers question: http://stackoverflow.com/q/50158420
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50158420
type: AcceptedAnswer
has body: This map the right format to the value in the list according to his type (str or int). values = [['s', 9], [0, 1]] for pair in values: print(*map(lambda value: ('{:o}' if isinstance(value, int) else '{}').format(value), pair)) output: s 11 0 1 You can add tick if you want with "'{}'" instead of '{}'.

scheduled-tasks
tags question: http://stackoverflow.com/q/50188207
type: Tag
tags question: http://stackoverflow.com/q/50139727
tag name: scheduled-tasks

http://stackoverflow.com/q/50197038
has title: list of arguments to python function
duplicate of: http://stackoverflow.com/q/919680
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50197071
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/919680
tagged with: arguments
tagged with: python
has answer: http://stackoverflow.com/a/50197072
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has body: Is there a way to build a list of the arguments to python function to use it inside the function? For example: def sum_of_middle_three(score1,score2,score3,score4,score5): """ Find the sum of the middle three numbers out of the five given. """ sum = (score1+score2+score3+score4+score5) return sum How to refer to the input argument list in the function, if possible this gives possibility to call that function by variable argument list
tagged with: function

http://stackoverflow.com/a/50096340
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50096247
has body: This is your training data: A B C # &lt;== feature names 0 0 3 1 1 0 0 2 1 1 0 2 Now as you see in enc.n_values_: array([2, 3, 4]) The first feature A has two possible values = 0 and 1. Similarly feature B has three possible values = 0, 1, 2 ... Now in the output, each feature will be assigned number of columns according to the above values. Something like this: A_0 A_1 B_0 B_1 B_2 C_0 C_1 C_2 C_3 Here A_0 means that 0 is present in data. So, A_0 will be 1 (hot) and A_1 will be 0. If 1 was present in that data, then A_1 will be 1 (hot) and A_0 will be 0. So for input: A B C [0, 1, 1] Here, A=0, so A_0 will be 1 and rest A_1 will be 0. for B, B=1, so B_1 will be 1 and others (B_0 and B_2) will be 0. Same for C. So final output is: A_0 A_1 B_0 B_1 B_2 C_0 C_1 C_2 C_3 1., 0., 0., 1., 0., 0., 1., 0., 0. Please see this for more information: http://scikit-learn.org/stable/modules/preprocessing.html#encoding-categorical-features
answers question: http://stackoverflow.com/q/50096247
type: Answer
score: 1

pvlib
tags question: http://stackoverflow.com/q/50197832
type: Tag
tag name: pvlib

http://stackoverflow.com/comment/87342066
comment on: http://stackoverflow.com/a/50160960
score: 0
type: AnswerComment
has text: You can edit the db using Python using a number of modules, `sqlite3` works well. The advice given above is good, and I would recommend following it while you're still learning!
type: Comment

http://stackoverflow.com/q/50175227
has comment: http://stackoverflow.com/comment/87367902
has title: numpy: arr[True] creates a new axis
downvote count: 1
favorite count: 0
type: Question
has body: I don't understand why True does not behave like a boolean mask: &gt;&gt;&gt; x = np.arange(5) &gt;&gt;&gt; x[(x&lt;3) &amp; True].shape (3,) &gt;&gt;&gt; x[np.repeat(True, 5)].shape (5,) &gt;&gt;&gt; x[True].shape (1, 5)
has comment: http://stackoverflow.com/comment/87385660
has comment: http://stackoverflow.com/comment/87368520
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87376521
tagged with: python
has comment: http://stackoverflow.com/comment/87371300
has comment: http://stackoverflow.com/comment/87367512
tagged with: numpy
has comment: http://stackoverflow.com/comment/87367528
tagged with: numpy-indexing
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/87213957
comment on: http://stackoverflow.com/q/50098767
has text: Make your functions take a value and return a value. Then you don't need a global variable at all.
score: 6
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50202272
has comment: http://stackoverflow.com/comment/87421618
has title: Remove duplicate values of a pandas dataframe particular columns
has comment: http://stackoverflow.com/comment/87421728
has body: I have a data frame with multiple columns and I want to select the subset of columns and remove the duplicate values from it. I do not want to remove rows, Only want to remove particular column duplicate values. My data frame looks like: I want to remove duplicates from these columns ["PLACEMENT # NAME", "IMPRESSIONS","ENGAGEMENTS","DPEENEGAGEMENTS"], so my out will look like.
has comment: http://stackoverflow.com/comment/87421322
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50202488
tagged with: pandas
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87431674
upvote count: 1
accepted answer: http://stackoverflow.com/a/50202488
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87421454
has comment: http://stackoverflow.com/comment/87431855
tagged with: dataframe
tagged with: python
score: -1

http://stackoverflow.com/q/50129907
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87294204
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/13243807
has body: Assume using Linux: In Perl, the exec function executes an external program and immediately exits itself, leaving the external program in same shell session. A very close answer using Python is https://stackoverflow.com/a/13256908 However, the Python solution using start_new_session=True starts an external program using setsid method, that means that solution is suitable for making a daemon, not an interactive program. Here is an simple example of using perl: perl -e '$para=qq(-X --cmd ":vsp");exec "vim $para"' After vim is started, the original Perl program has exited and the vim is still in the same shell session(vim is not sent to new session group). How to get the same solution with Python.
has answer: http://stackoverflow.com/a/50130021
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50130021
upvote count: 3
score: 3
has title: How to achieve Perl's exec function in Python?
tagged with: python

http://stackoverflow.com/comment/87585564
has text: The example was very helpful. After all this, I sort of ended up where I started. But I learned a lot. It turns out that cookiecutter_django apps only work on nginx unless you're using AWS Elastic Beanstalk.
type: AnswerComment
comment on: http://stackoverflow.com/a/50206139
score: 0
type: Comment

http://stackoverflow.com/q/50119960
has title: Success message in Django
tagged with: django
tagged with: python
has body: In my django app I am taking form input.Once that form is validated I am displaying a success message with help of Django Message Framework. Current State I am able to display a success message in the template after submission of form when I redirect it to same url(The url of the form itself) My views.py if form.is_valid(): form_data = form.save() messages.success(request, 'Submited Successfully') return redirect('form-url') What I want Once the form is submitted I want to display a success message on the same page(form-url) and then I want to redirect to a new url list-of-submitted-forms. For that I did something like this to my views.py if form.is_valid(): form_data = form.save() messages.success(request, 'Submited Successfully') return redirect('list-of-submitted-forms') The problem I am facing I am redirecting to a new url.But without getting success message on the form-url page.Also again when I go to form-url page(By clicking a button which redirects to that url) the message of 'Submited Successfully' is shown My HTML/JS &lt;script&gt; {% if messages %} {% for message in messages %} {% if message.tags == "success" %} swal({text:"{{ message }}",icon: "success",timer: "4000",buttons: false}) {% endif %} {% endfor %} {% endif %}
score: 0
has comment: http://stackoverflow.com/comment/87258005
answer count: 1
has answer: http://stackoverflow.com/a/50120490
type: Question
has comment: http://stackoverflow.com/comment/87257341
has comment: http://stackoverflow.com/comment/87257843
type: UnansweredQuestion

http://stackoverflow.com/a/50093910
downvote count: 0
answers question: http://stackoverflow.com/q/50093674
upvote count: 2
type: Answer
has body: Taking advantage of the fact that one list (not list of lists) will be matched only to one value of dictionary, you could make use of a generator expression with a default None: &gt;&gt;&gt; dict1 = {0:[0, 1, 3], 1:[0, 2, 3]} &gt;&gt;&gt; lst = [1, 0, 3] &gt;&gt;&gt; next((k for k, v in dict1.items() if sorted(v) == sorted(lst)), None) 0
score: 2

http://stackoverflow.com/comment/87278554
comment on: http://stackoverflow.com/q/50124599
has text: this is not the whole script, only the part, but the problem ocurre here. the script works and I get results for many ports, but when error ocurre script exit and does not scan further on next ports and ip
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50100882
has body: I'd like to use logging.config.dictConfig with a json config file. But I want to use a formatter from another class: pythonjsonlogger.jsonlogger.JsonFormatter What's wrong with this code/json: $ cat test.json { "version": 1, "disable_existing_loggers": "true", "formatters": { "json": { "class": "pythonjsonlogger.jsonlogger.JsonFormatter" # also tried "jsonlogger.JsonFormatter" (comment not in real file) } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "json", "stream": "ext://sys.stdout" } }, "loggers": { }, "root": { "handlers": ["console"], "level": "DEBUG" } } code: import sys sys.path.append('/usr/local/lib/python2.7/site-packages') import json import logging import logging.config from pythonjsonlogger import jsonlogger fp = open('/test.json') logging.config.dictConfig(json.load(fp)) fp.close() logging.info('test log line') output: test log line Expected something like { "message": "test log line" }
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
upvote count: 10
favorite count: 0
type: Question
has title: How do I configure JsonFormatter in logging dictConfig?
type: UnansweredQuestion
score: 10
answer count: 1
tagged with: python
tagged with: logging
has answer: http://stackoverflow.com/a/50142852

http://stackoverflow.com/a/50117671
answers question: http://stackoverflow.com/q/50113898
downvote count: 0
upvote count: 1
has body: There are different scenarios to do what you are looking for. This is an idea, you can adapt it to your exact need: At your place, I would rely on delete() function which takes the id of a created image to be deleted. It can also used to delete all the existing images on the canvas by pass 'all' parameter. To resolve your issue, you can for example stock the ids of the images you create (five of them, I guess) into a stack (list or whatever, depending, as I said, on your specific case, as your example here is quite vague to me) and then delete them following LIFO: from tkinter import * root = Tk() can = Canvas(root, height = 200, width = 300, bg = "white") can.tab = [{} for k in range(5)] nb = 0 stack_ids = [] # added this def bell(event): can.delete(stack_ids.pop()) #modified your function here def click(event): global can, nb x,y = (event.x)//50 * 50, (event.y)//50 * 50 can.tab[nb]['image'] = PhotoImage(master = can, file = "mouse_pointer.png", name = "mouse_pointer") id = can.create_image(x, y, anchor = NW, image = can.tab[nb]['image']) stack_ids.append(id) # save the ids somewhere can.focus_set() can.bind("&lt;Button-1&gt;", click) can.bind("&lt;Delete&gt;", bell) can.pack() root.mainloop()
has comment: http://stackoverflow.com/comment/87260880
score: 1
type: Answer

http://stackoverflow.com/comment/87183492
has text: @prabhakar should I need to give permission manually? I'm working one windows enviroment using spyder editor.
comment on: http://stackoverflow.com/q/50083806
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50133929
has body: Yes, unfortunately scipy doesn't deal with nans From the docs: Note that calling interp2d with NaNs present in input values results in undefined behaviour. Even masking the nans in a np.masked_array was not successful. So my advice would be to remove all the nan entries from z by taking the opportunity to give sp.interp2d the full list of x- and y-coordinates for only the valid data and leave z also 1D: X=[];Y=[];Z=[] # initialize new 1-D-lists for interp2 for i, xi in enumerate(x): # iterate through x for k, yk in enumerate(y): # iterate through y if not np.isnan(z[i, k]): # check if z-value is valid... X.append(xi) # ...and if so, append coordinates and value to prepared lists Y.append(yk) Z.append(z[i, k]) This way at least sp.interp2d works and gives a result: ip = sp.interpolate.interp2d(X,Y,Z) However, the values in the result won't please you: In: ip(x,y) Out: array([[ 18.03583061, -0.44933642, 0.83333333, -1. , -1.46105542], [ 9.76791531, 1.3014037 , 2.83333333, 1.5 , 0.26947229], [ 1.5 , 3.05214381, 4.83333333, 4. , 2. ], [ 2. , 3.78378051, 1.5 , 2. , 0.8364618 ], [ 5.5 , 3.57039277, 3.5 , -0.83019815, -0.7967441 ], [ 3.5 , 3.29227922, 17.29607177, 0. , 0. ]]) compared to the input data: In:z Out: array([[ nan, nan, 1.5, 2. , 5.5, 3.5], [ nan, 1. , 4. , 2.5, 4.5, 3. ], [ 2. , 0.5, 6. , 1.5, 3.5, nan], [ nan, 1.5, 4. , 2. , nan, nan], [ nan, nan, 2. , nan, nan, nan]]) But IMHO this is because the gradient changes in your data are far too high. Even more with respect to the low number of data samples. I hope this is just a test data set and your real application has smoother gradients and some more samples. Then I'd be glad to hear if it works... However, the trivial test with an array of zero gradient - only destructed by nans a little bit - could give a hint that interpolation should work, while extrapolation is only partly correct: In:ip(x,y) Out: array([[ 3. , 3. , 3. , 3. , 0. ], [ 3. , 3. , 3. , 3. , 1.94701008], [ 3. , 3. , 3. , 3. , 3. ], [ 3. , 3. , …
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50131099
has comment: http://stackoverflow.com/comment/87286236
type: Answer

http://stackoverflow.com/a/50186267
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50185926
has comment: http://stackoverflow.com/comment/104242031
has comment: http://stackoverflow.com/comment/99459527
score: 148
answers question: http://stackoverflow.com/q/50185926
has comment: http://stackoverflow.com/comment/112127557
upvote count: 148
type: Answer
has comment: http://stackoverflow.com/comment/121595399
has body: Simply change col = pd.DataFrame(data, columns=['runs','balls', 'wickets', 'ground_average', 'pp_balls_left', 'total_overs']) for col = pd.DataFrame([data], columns=['runs','balls', 'wickets', 'ground_average', 'pp_balls_left', 'total_overs']) You want [data] for pandas to understand they're rows. Simple illustration: a = [1, 2, 3] &gt;&gt;&gt; pd.DataFrame(a) 0 0 1 1 2 2 3 &gt;&gt;&gt; pd.DataFrame([a]) 0 1 2 0 1 2 3
type: AcceptedAnswer

http://stackoverflow.com/q/50159206
has comment: http://stackoverflow.com/comment/87374220
has answer: http://stackoverflow.com/a/71825673
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87336662
favorite count: 0
tagged with: bipartite
type: Question
has answer: http://stackoverflow.com/a/50179420
answer count: 2
has comment: http://stackoverflow.com/comment/87338205
has body: Assume following exemplary edgelist: source,target,weight 162600,117237,200 192084,50240,200 200854,125014,200 166729,37059,5 157279,77297,1 186788,35124,2 199103,112437,5 194523,125618,5 169139,103847,5 156565,85646,5 157159,85646,10 168455,115687,15 139567,108206,5 172702,120323,5 175029,120590,5 167596,85646,10 202163,83381,15 163786,109135,5 183035,124200,4 154266,124200,2 187899,124200,20 190849,124200,8 169657,118867,11 157848,101997,2 143224,87832,1 140758,101009,21 197618,101009,20 175454,50240,4 150071,112472,10 199517,121453,20 As you can see, some elements of source have a common target. Therefore, I thought it would make sense to calculate and visualize a bipartite graph in network X. The documentation shows how it's done with manual values but I wonder how it can be applied to the edgelist from above (including weights. I would be very thankful if someone could provide an example using the data above, though the input data might result in a sparse network.
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87336811
has title: Calculating bipartite graph in networkx
tagged with: networkx

http://stackoverflow.com/a/50214128
has comment: http://stackoverflow.com/comment/87445314
has body: CSV stands for comma-seperated values. Therefore, in order to split between cells, all you have to do is put a comma between values.
answers question: http://stackoverflow.com/q/50214084
has comment: http://stackoverflow.com/comment/87445229
type: Answer
score: 0

http://stackoverflow.com/comment/87399628
score: 0
has text: This question relates to runtime network stack configuration (routing table correctness), not to software development. The same issues would impact any other tool, including end-user tools such as `ping`, `telnet`, etc; and are thus not on-topic here.
comment on: http://stackoverflow.com/q/50190990
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87286557
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50134054
type: QuestionComment
has text: Since you get an error from mglearn or pandas here you need to make sure your question is tagged accordingly.

http://stackoverflow.com/q/50096474
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/87209267
answer count: 1
downvote count: 0
tagged with: selenium
accepted answer: http://stackoverflow.com/a/50096576
favorite count: 0
type: Question
score: 3
has title: Get links from a certain div using Selenium in Python
tagged with: python
has body: I have the following HTML page. I want to get all the links inside a specific div. Here is my HTML code: &lt;div class="rec_view"&gt; &lt;a href='www.xyz.com/firstlink.html'&gt; &lt;img src='imga.png'&gt; &lt;/a&gt; &lt;a href='www.xyz.com/seclink.html'&gt; &lt;img src='imgb.png'&gt; &lt;/a&gt; &lt;a href='www.xyz.com/thrdlink.html'&gt; &lt;img src='imgc.png'&gt; &lt;/a&gt; &lt;/div&gt; I want to get all the links that are present on the rec_view div. So those links that I want are, www.xyz.com/firstlink.html www.xyz.com/seclink.html www.xyz.com/thrdlink.html Here is the Python code which I tried with from selenium import webdriver; webpage = r"https://www.testurl.com/page/123/" driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe") driver.get(webpage) element = driver.find_element_by_css_selector("div[class='rec_view']&gt;a") link = element.get_attribute("href") print(link) How can I get those links using selenium on Python?
has answer: http://stackoverflow.com/a/50096576

http://stackoverflow.com/comment/87174531
type: Comment
has text: I did try pd.merge(df1, df2, on='ID')'ID', 'A', 'B', 'type', it didn't work. I also don't want to merge the data or join them. I only need to add one column from the df2. Both data are huge and have more than a hundred column in each. I can't specify 'A', 'B' in the code because they are many of them. Do you have any other suggestions, please?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50078977

http://stackoverflow.com/comment/87294693
comment on: http://stackoverflow.com/q/50138110
has text: Use regex to find which rows match the format of your expected 'correct' values. So if they should all be numbers followed by a space and then units you can match that.
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/50148738
has comment: http://stackoverflow.com/comment/87332783
favorite count: 0
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/87325723
has comment: http://stackoverflow.com/comment/87332238
type: UnansweredQuestion
tagged with: sockets
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87325253
has comment: http://stackoverflow.com/comment/87328835
has comment: http://stackoverflow.com/comment/87325366
answer count: 0
has title: Binary protocol throw socket in python
has comment: http://stackoverflow.com/comment/87315653
has comment: http://stackoverflow.com/comment/87325131
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87323572
has body: I am building c++ server that get the data from the client in Binary protocol. the protocol look like that: Message code: 1 BYTE | Data length: 4 BYTES | Data: X BYTE so i need to send information from the client that matching this protocol. so lets say that i want to send this data from the client: Message code: 100 Data length: 4 Data: nice How can i send in throw the socket? i mean the data length require only 1 byte, but in the protocol i want in to be 4 bytes permanently. so how can i complete the other 3 bytes? and how can i send data throw the socket that is not string? this is my code so far: import socket PORT, IP = 5280, '127.0.0.1' SERVER_ADDRESS = (IP, PORT) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(SERVER_ADDRESS) code = 100 length = 14 data = "nice" sock.sendall(code) sock.sendall(length) sock.sendall(data.encode("ASCII")) print "Server said:", sock.recv(1024) # Server response sock.close() I don't have a clue how to do it as i want... and how convert everything to binary. little fixes in my code will help, thank.

http://stackoverflow.com/q/50154652
has title: PyCharm can't locate gmpy2 (unresolved reference)
has comment: http://stackoverflow.com/comment/87326819
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm using Ubuntu 16.04 and just need a downloaded simple encryption script in python to run. I installed pyCharm to run the scripts but its giving unresolved reference errors at gmpy2 The script is using gmpy2 which I installed using the command: sudo apt-get install python-gmpy2. And apparently it worked as the following command managed to search for it: pip search gmpy2 gmpy2 (2.0.8) - GMP/MPIR, MPFR, and MPC interface to Python 2.6+ and 3.x INSTALLED: 2.0.7 LATEST: 2.0.8 But in PyCharm, this line is unable to locate it: from gmpy2 import mpz, powmod, invert, is_prime, random_state, mpz_urandomb, rint_round, log2, gcd giving error: unresolved reference `gmpy2`
tagged with: gmpy
has answer: http://stackoverflow.com/a/50154745
accepted answer: http://stackoverflow.com/a/50154745
type: Question
tagged with: pycharm

http://stackoverflow.com/q/50132493
has title: 1064, "You have an error in your SQL syntax; for the right syntax to use near '%s' at line 1")
favorite count: 0
type: Question
has body: I have the database which has the fields,id, source_server,source_path,destination_path I am trying to get the data from the mysql database using pymysql based on id: admin.html User UUID:: click here!! Admin.py: #!C:\Program Files\Python\Python36\python.exe print ("Content-type: text/html\r\n") print("") import cgi,cgitb import pymysql form = cgi.FieldStorage() cgitb.enable() UUID = form.getvalue('uuid') db = pymysql.connect(host="localhost", user="root", passwd="", db="fullstack")# name of the data base cur = db.cursor() def select_from_sql(uuid): #(self.cur).execute('''select (id, source_server,source_path,destination_path) values (%s, %s,%s,%s) from posts''', (self.id,self.source_server,self.source_path,self.destination_path) ) sql="SELECT * FROM posts WHERE id=%s" cur.execute(sql,(uuid)) row=cur.fetchall() select_from_sql(UUID) cur.close() print(" ") print(' ') print(' ') print(' ') print(' ') print(' ') print(" ") cur.close() db.close() **Approve_admin.py:** #!C:\Program Files\Python\Python36\python.exe from admin import UUID print("Content-type: text/html") print("") import cgi,cgitb def sending(): print (UUID) sending() I am trying to import the variable UUID to approve_mail.py from admin.py: But I am getting this error; Content-type: text/html --> --> ProgrammingError Python 3.6.0: C:\Program Files\Python\Python36\python.exe Wed May 2 15:55:10 2018 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. C:\xampp\htdocs\sample\approve_mail.py in () 24 import uuid 25 import pymysql => 26 from admin_1 import UUID 27 from time import sleep 28 form = cgi.FieldStorage() admin_1 undefined, UUID undefined C:\xampp\htdocs\sample\admin_1.py in () 29 print(" ") 30 print(" ") => 31 select_from_sql(UUID) 32 cur.close() 33 print(" ") select_from_sql = <function select_from_sql>, UUID = None C:\xampp\htdocs\sample\admin_1.py in select_from_sql(uuid=None) 15 #(self.cur).execute('''select (id, source…
tagged with: pymysql
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50133289
accepted answer: http://stackoverflow.com/a/50133289
downvote count: 1

http://stackoverflow.com/a/50134698
has comment: http://stackoverflow.com/comment/100478803
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50125844
has body: You'll have to fit and store a scaler for each channel from sklearn.preprocessing import StandardScaler scalers = {} for i in range(X_train.shape[1]): scalers[i] = StandardScaler() X_train[:, i, :] = scalers[i].fit_transform(X_train[:, i, :]) for i in range(X_test.shape[1]): X_test[:, i, :] = scalers[i].transform(X_test[:, i, :])
accepted answer of: http://stackoverflow.com/q/50125844
has comment: http://stackoverflow.com/comment/99137610
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/120598691
score: 22
upvote count: 22

http://stackoverflow.com/comment/87232558
score: 0
comment on: http://stackoverflow.com/q/50101984
type: QuestionComment
has text: Why the downvote?
type: Comment

http://stackoverflow.com/comment/87385196
has text: What is your desired output?
type: Comment
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/50183936

http://stackoverflow.com/a/50178539
has comment: http://stackoverflow.com/comment/87374849
has body: Using Pillow: from PIL import Image im = Image.open(path_to_image) width, height = im.size #get image size #since you do not specify the size of the center area in the question, just replace the below variables with what you want left = (width - your_width)/2 top = (height - your_height)/2 right = (width + your_width)/2 bottom = (height + your_height)/2 im.crop((left, top, right, bottom)) #crop the center of the image rgb = im.convert('RGB') # get three R G B values r, g, b = rgb.getpixel((1, 1)) print(r,g,b) With OpenCV replace the two first lines with: im = cv2.imread(path_to_image) height, width = im.shape[:2]
answers question: http://stackoverflow.com/q/50178248
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87374435

ffmpeg
tags question: http://stackoverflow.com/q/50159721
tags question: http://stackoverflow.com/q/50116513
tags question: http://stackoverflow.com/q/50138249
type: Tag
tags question: http://stackoverflow.com/q/50114993
tags question: http://stackoverflow.com/q/50228676
tags question: http://stackoverflow.com/q/50222743
tags question: http://stackoverflow.com/q/50134790
tag name: ffmpeg

http://stackoverflow.com/comment/87351379
type: Comment
has text: Apologies for not being clear, it does not work when running nosetests in PowerShell. I have pasted the error (in the original post) that I receive when I attempt to run it.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50166282

http://stackoverflow.com/a/64329074
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50087728
downvote count: 0
has comment: http://stackoverflow.com/comment/114438890
has comment: http://stackoverflow.com/comment/114359623
has body: From the mentioned forum in Mat's answer I verified that: [send_file()] does not work because the uWSGI file wrapper does not support file-like objects, only real files ...but applying Mat's solution still throws me a ValueError: I/O operation on closed file. Even with FileWrapper class. This way is even simpler: If you use a file_pointer based on io eg. io.StringIO() you must use Response() instead. Not with a fp but sending the content directly. Based on your code: with BytesIO() as output: writer = pd.ExcelWriter(output, engine='xlsxwriter') output.seek(0) headers = {"Content-disposition": "attachment; filename=testing.xlsx"} mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' return Response(output.read(), mimetype=mimetype, headers=headers)
type: Answer

http://stackoverflow.com/comment/87244561
comment on: http://stackoverflow.com/q/50113511
score: 0
type: Comment
type: QuestionComment
has text: try using pb.redirectErrorStream(true); before pb.start to redirect the stderr to stdout to see if there are any errors printed.

http://stackoverflow.com/q/50139413
has comment: http://stackoverflow.com/comment/87298886
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50140453
has answer: http://stackoverflow.com/a/50140453
linked to: http://stackoverflow.com/q/6269765
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/53648764
tagged with: python-3.x
answer count: 2
tagged with: raspberry-pi
upvote count: 2
has body: I'm new to MQTT and raspberry pi! I'm running a client script and I simply publish a message using another script. I'm using my own Mosquitto broker. Client: import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("Example/test") client.subscribe("Example/topic") def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) if msg.payload == "Hello": print("Received message #1, do something") if msg.payload == "World": print("Received message #2, do something else") client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("192.168.1.4", 1883) client.loop_forever() Publisher: import paho.mqtt.publish as publish publish.single("Example/test", "Hello", hostname="192.168.1.4") publish.single("Example/topic", "World", hostname="192.168.1.4") print("OK") That's where things seem weird and those things happen. 1.When I run both the client and the publisher using the python3 command the if statements are skipped and only topic + payload are printed 2.When I run the client using python command and publisher using both python3 and python command everything works fine! 3.When I do all the above, while running the client on virtualenv again the if statements are ignored, in all occasions! I would like to know if there is a compatibility reason for this to happen, or anything wrong in the code as I must run something more complicated like that on virtualenv! UPDATE: I found a solution that works fine ! In the client code in the if statement I used if msg.payload == b"Hello": and if msg.payload == b"World": As far as I know it must have been due to a variable type thing and they didn't match.
score: 2
has answer: http://stackoverflow.com/a/53648764
tagged with: mqtt
downvote count: 0
tagged with: python
has title: Paho mqtt client not working properly
tagged with: paho

http://stackoverflow.com/a/50108215
has body: quad returns 2 parameters, the integral and the absolute value of the error, you just have to unpack it. from scipy.signal import * from scipy.integrate import quad from numpy import * p = 10 def integrand(t, a): return square(t)*cos(((2*pi)/a)*t) i, err = quad(integrand,0,p, args=(p,)) y = (2/p)*i update: from scipy.signal import * from scipy.integrate import quad from numpy import * p = 10 na = arange(0,10,1) y = [] def integrand(t, a, b): return square(t)*cos(b*((2*pi)/a)*t) for e in na: i,err = quad(integrand,0,p, args=(p, e)) y.append(i) print(y)
type: Answer
accepted answer of: http://stackoverflow.com/q/50108003
score: 2
answers question: http://stackoverflow.com/q/50108003
has comment: http://stackoverflow.com/comment/87235140
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87235313

http://stackoverflow.com/q/50148273
has answer: http://stackoverflow.com/a/50156171
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87315176
has title: Could not find a version that satisfies the requirement Flask
tagged with: python
upvote count: 4
score: 4
linked to: http://stackoverflow.com/q/49768770
has body: Could not find a version that satisfies the requirement Flask pip install -U Flask Collecting Flask Could not fetch URL https://pypi.python.org/simple/flask/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping Could not find a version that satisfies the requirement Flask (from versions: ) No matching distribution found for Flask
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: pip

http://stackoverflow.com/a/77239535
has body: With pandas 2.1 it is easier with quantile method in the example below we get first 10 percent and last 10 percent of data df.loc[ (df['Column'] &lt; df['Column'].quantile(.10)) | (df['Column'] &gt; df['Column'].quantile(.90)) ]
has comment: http://stackoverflow.com/comment/136174913
answers question: http://stackoverflow.com/q/50173283
type: Answer
score: 0

http://stackoverflow.com/q/50075317
possible better answer: http://stackoverflow.com/a/50075371
tagged with: python
accepted answer: http://stackoverflow.com/a/50075844
tagged with: variables
tagged with: regex
has answer: http://stackoverflow.com/a/50075371
has answer: http://stackoverflow.com/a/50075844
type: AnsweredQuestion
tagged with: list
answer count: 3
has body: I have the following saved as a string in a variable: window.dataLayer=[{"articleCondition":"New","categoryNr":"12345","sellerCustomerNr":"88888888","articleStatus":"Open"}] How do I extract the values of each element? Goal would be to have something like this: articleCondition = 'new' categoryNr = '12345' ...
has title: regex matching and get into a python list
has answer: http://stackoverflow.com/a/50076142
favorite count: 0
type: Question
tagged with: beautifulsoup
upvote count: 0
score: -2
downvote count: 2

http://stackoverflow.com/comment/87420541
score: 0
comment on: http://stackoverflow.com/q/50201227
has text: [Duplicate](https://stackoverflow.com/questions/25328003/how-can-i-change-the-font-size-using-seaborn-facetgrid)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50207396
answers question: http://stackoverflow.com/q/50206874
has body: You want to do a merge on two dataframes on the region field. pandas library makes this really easy (also performant). The code looks like this (your CSV files are behind the Kaggle registration-wall): import pandas as pd loans = pd.read_csv('kiva_loans.csv') mpi_regions = pd.read_csv('kiva_mpi_region_locations.csv') df = loans.merge(mpi_regions, on='region') You really don't want to reinvent the wheel by writing your own join code in base Python, use pandas package already. (Note you're assuming region is unique across countries. It might be safer to merge both on=['country','region'])
type: Answer
score: 0

http://stackoverflow.com/comment/87182894
comment on: http://stackoverflow.com/q/50083475
has text: Thanks I saw this before but I did not understand what is its meaninng? if a is one dimension then what is meaning of tf.stack[tf.range?]
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/87378142
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50148114
has text: @Sam, This works since you import `drawing` namespace from openpyxel. Without doing it, your interpreter do not even know what is this `drawing` your are adressing. This is equivalent to : ``import openpyxl``, then ``sheet.add_image(openpyxl.drawing.image...)`` By the way, I'm happy if I helped. Maybe you could accept the answer?
type: Comment

http://stackoverflow.com/comment/87276283
comment on: http://stackoverflow.com/q/50114709
type: Comment
type: QuestionComment
score: 0
has text: @ChatterOne Indeed I did not know about this possibility when I coded my program... It's going to induce huge changes, but might be a solution :/

http://stackoverflow.com/a/50162138
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50161193
has body: histtype='step'draws step lines. They are by definition not filled (because they are lines. Instead, use histtype='bar' (which is the default, so you may equally leave it out completely).
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/87344776

http://stackoverflow.com/q/50105087
answer count: 1
tagged with: intervals
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50105117
accepted answer: http://stackoverflow.com/a/50105117
has body: Maybe I'm too spoiled with the usual awesomeness of Python, but is there a more natural way to iterate over intervals of a list? Instead of: L = [12, 15, 29, 100, 239] for i in range(len(L)-1): print L[i], L[i+1] 12 15 15 29 29 100 100 239 is there somthing like this: for i, j in intervals(L): print i, j ?
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/21303224
has title: Iterate over intervals of a list
type: AnsweredQuestion
tagged with: list
duplicate of: http://stackoverflow.com/q/21303224
upvote count: 0

http://stackoverflow.com/comment/87212671
type: QuestionComment
score: 0
has text: It seems that `image_np_expanded` evaluates to `None`, but it is impossible to say how or why without actually seeing any code.
comment on: http://stackoverflow.com/q/50098065
type: Comment

http://stackoverflow.com/comment/138676557
comment on: http://stackoverflow.com/a/73311271
type: Comment
type: AnswerComment
has text: This creates multiple separate threads though if you're running through WSGI with multiple worker processes.
score: 0

http://stackoverflow.com/comment/87259883
has text: r'pattern_combined' converts literal string 'pattern_combined' to raw string. consider changing `output = re.findall(r'pattern_combined',row)` to convert the value of pattern_combined variable into rawstring
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50118909

http://stackoverflow.com/q/50125423
has comment: http://stackoverflow.com/comment/87269471
tagged with: nginx
has comment: http://stackoverflow.com/comment/87269443
tagged with: symfony
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/50126122
has title: Laravel app using Symfony to execute a Python script on LEMP stack - Permission denied
has answer: http://stackoverflow.com/a/50126122
downvote count: 2
answer count: 1
upvote count: 1
has body: I have just uploaded my laravel app to the web using Digital Ocean (LEMP stack), however when I try to run a python process I am getting permission denied. This worked on local with no permission issues. I have tried giving access to the Find/process.py file and folder with the following but no progress: sudo find /var/www/sync/Find/*.py -type d -exec chmod 755 {} \; sudo find /var/www/sync/Find/*.py -exec chmod 644 {} \; sudo find /var/www/sync/Find/*.py -type d -exec chmod u+x {} \; Error Output: ================ sh: 1: /usr/lib/python3.5: Permission denied {"userId":1,"email":"admin@admin.com","exception":"[object] (Symfony\\Component\\Process\\Exception\\ProcessFailedException(code: 0): The command \"/usr/lib/python3.5 Find/process.py\" failed. Exit Code: 126(Invoked command cannot execute) Working directory: /var/www/sync Output: ================ Error Output: ================ sh: 1: /usr/lib/python3.5: Permission denied at /var/www/sync/App/Find/process.php:51) I do not believe it to be the php file as it works local and the error clearly says permission denied however I am not sure how else to troubleshoot this and any help is useful. Thanks
favorite count: 0
tagged with: laravel
type: Question
type: AnsweredQuestion
tagged with: linux

http://stackoverflow.com/comment/87420317
comment on: http://stackoverflow.com/q/50201842
type: Comment
score: 0
type: QuestionComment
has text: @John - I don't see how that affects the problem

http://stackoverflow.com/comment/87338482
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50146561
has text: Thanks guys, your answer got me on the right path. See answer below.
score: 0

http://stackoverflow.com/comment/87370180
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50175387
score: 0
has text: @HIYUM, are you sure it's _every time the snake moves_, not every frame? Right now your output is a row of the same exact coordinates, so it doesn't move.

http://stackoverflow.com/q/50163834
has comment: http://stackoverflow.com/comment/87346468
favorite count: 0
has comment: http://stackoverflow.com/comment/87346166
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/43801563
has body: I wrote a function which takes function definition as String and parameters (a,b) as a tuple and then executes defined function with parameters. Below is a simple test case with two functions which are executed with same arguments but have opposite conditions. import coverage import importlib def measure_coverage_from_string(code_string, params): a, b = params temp_filepath = "temp.py" with open(temp_filepath, "w") as f: f.write(code_string) cover = coverage.coverage(temp_filepath) cover.start() mod = importlib.import_module("temp") mod.fun(a, b) cover.stop() result = cover.xml_report() return result fun_def = """def fun(a, b): print(a) if a &lt; b: print(b)""" fun_def_new = """def fun(a, b): print(a) if a &gt; b: print(b)""" cover1 = measure_coverage_from_string(fun_def, (3, 1)) print("Original coverage:", cover1) print("------------------------------") cover2 = measure_coverage_from_string(fun_def_new, (3, 1)) print("New coverage:", cover2) The output when running the code would be as follows, the 75% coverage at the first case is still 50% of code + 25% from function definition which is not executed second time: 3 Original coverage: 75.0 ------------------------------ 3 New coverage: 50.0 This output is unexpected, because the second function "fun_def_new" should print out parameter b and import the function from scratch which means coverage should take account function definition. The expected output would be: 3 Original coverage: 75.0 ------------------------------ 3 1 New coverage: 100.0 I hope there is another option besides using timer of 1 sec or: code = exec(compile(code_string, "&lt;string&gt;", "exec")) locals()["fun"](a, b) In both of these cases it is not possible to use python coverage to measure code coverage on the functions with given attributes.
linked to: http://stackoverflow.com/q/43801563
tagged with: python
score: 4
type: Question
upvote count: 4
tagged with: python-import
answer count: 0
type: UnansweredQuestion
has title: Measuring code coverage of a Python function defined as a String, given certain arguments
downvote count: 0

http://stackoverflow.com/a/50265267
score: 0
answers question: http://stackoverflow.com/q/50163219
type: Answer
has body: Solved. The problem was the matplotlib version.
has comment: http://stackoverflow.com/comment/97226800

http://stackoverflow.com/q/50077743
score: -1
tagged with: list
has comment: http://stackoverflow.com/comment/87171645
has title: Custom Sort Function Python
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50077776
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87171670
tagged with: python
tagged with: sorting
has body: I have a class object which is 5 integer values. I understand that for sorting you override the __ls__ functions, but I want to be able to sort comparing any of the 5 values, so I would want to have 5 sort keys. Is there any way I can make it easier? I've thought of making a global class switch that keeps track of the correct value but is there an easier way?
tagged with: class

http://stackoverflow.com/q/50091089
downvote count: 0
has body: I have a Pandas dataframe which has a column date_closed of type datetime64[ns]. When I find the unique values there are some NaT there. How can I only filter the rows whose date_closed in not NaT df['date_closes'].unique() btw, what does NaT means? is it Null? When I value_counts() , the NaT's does not appear! Why? df['date_closed'].value_counts()
has comment: http://stackoverflow.com/comment/87198419
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50091109
answer count: 2
has title: How to find empty datatime in Pandas
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87198474
score: 2
has answer: http://stackoverflow.com/a/50091198
tagged with: pandas
linked to: http://stackoverflow.com/q/23747451

http://stackoverflow.com/comment/87432490
score: 0
type: AnswerComment
type: Comment
has text: Should `on_delete=models.CASCADE` be used with `many-to-many` relationship?
comment on: http://stackoverflow.com/a/50207717

http://stackoverflow.com/q/50217453
type: Question
possible better answer: http://stackoverflow.com/a/50217535
tagged with: python
has body: What i would like to do is to initialize an array which has 5 elements set to 0 and then copy the other array to the first one, something like this: a = [0, 0, 0, 0, 0] b = [1, 2, 3] print a | b [1, 2, 3, 0, 0] Is there any pythonic way in doing so except: for i, x in enumerate(b): a[i] = x Edit: I forgot to mention that buffer a will always be filled with plain zeroes at the beginning and condition len(b) &lt; len(a) is always true, also in each case buffer a will always start getting overwritten from index 0. Ill explain why i need this kind of behaviour in the first place, basicly I have a raw 256-byte UDP frame. Buffer a corresponds to bytes 16-31 in the frame. Depending on some conditions, those bytes will either be overwritten or be set at 0, length of b is always 12. def foo(b=12*[0]): a = 16*[0] return a[:12] = b[:]
has answer: http://stackoverflow.com/a/50217729
accepted answer: http://stackoverflow.com/a/50217514
answer count: 4
has comment: http://stackoverflow.com/comment/87452474
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50217514
score: 0
has answer: http://stackoverflow.com/a/50217739
has answer: http://stackoverflow.com/a/50217535
upvote count: 1
has comment: http://stackoverflow.com/comment/87460072
downvote count: 1
has title: How to apply bitwise-like XOR between lists of different lengths?
favorite count: 0

http://stackoverflow.com/q/50190116
has comment: http://stackoverflow.com/comment/87397734
tagged with: python
has comment: http://stackoverflow.com/comment/87398074
type: AnsweredQuestion
has title: Why wont these two scenarios return the same output?
has comment: http://stackoverflow.com/comment/87397183
score: 1
upvote count: 1
has body: Hello bellow there are two runs of the same function. They should both return AB as the answer. But only the first one does. What is going on with the global variables? txt='' def test(): global txt txt+='A' print(txt) return 'B' tmp=test() print('tmp: ', tmp) txt+=tmp print(txt) Second Run txt='' def test(): global txt txt+='A' print(txt) return 'B' print(txt) txt+=test() print(txt) EDIT
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50190213
accepted answer: http://stackoverflow.com/a/50190213
favorite count: 0
type: Question

http://stackoverflow.com/q/50205064
answer count: 4
upvote count: 2
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/50205291
has comment: http://stackoverflow.com/comment/87427206
linked to: http://stackoverflow.com/q/3476732
has comment: http://stackoverflow.com/comment/87427267
has answer: http://stackoverflow.com/a/50205104
has answer: http://stackoverflow.com/a/50205151
has answer: http://stackoverflow.com/a/50205089
has title: Python: not printing int, only string value
favorite count: 0
has comment: http://stackoverflow.com/comment/87427287
has comment: http://stackoverflow.com/comment/87427270
type: Question
has body: print ('Hello') for i in range(2,11,-2): print(i) Whats wrong with this code? I'm trying to print out : Hello 10 8 6 4 2 but it only prints out hello. I ctrl+enter twice after print hello
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87427227
tagged with: python-3.x

http://stackoverflow.com/q/50179783
has body: I wrote a simple script from a video tutorial: import bs4 as bs import urllib.request source = urllib.request.urlopen('https://pythonprogramming.net/parsememcparseface/').read() soup = bs.BeautifulSoup(source, 'lxml') print(source) And it returns this error when I run the program: Traceback (most recent call last): File "/Users/UntouchedDruid4/Projects/Web_Scraper/app.py", line 4, in <module> source = urllib.request.urlopen('https://pythonprogramming.net/parsememcparseface/').read() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1361, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1320, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)> And I have no idea what that means. Please help.
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/27835619
has comment: http://stackoverflow.com/comment/87377281
has answer: http://stackoverflow.com/a/50179980
answer count: 1
tagged with: web-scraping
has title: How to use Python urllib.request for Web Scraping 2018
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/comment/87417033
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50200023
has text: @Aiven true, i've read about it but how is it even possible to have django1.10 on the working server without any problems? The project is up and running right now on the previous server with the exact same versions...
type: Comment

http://stackoverflow.com/q/50114657
has title: passing commands to PUTTY
has body: I use the following code to open putty terminal and pass a command. The terminal opens fine, but further nothing happens. The script just stops until I close the terminal. What could cause a problem here? import subprocess, time test=subprocess.Popen('"C:\Program Files (x86)\PuTTY\putty.exe" -ssh -X -I p:\.ssh\id_dsa.ppk my_name@my_host', stdin=subprocess.PIPE, stdout=subprocess.PIPE) test.stdin.write("ls\n") test.stdin.flush() test.stdin.close() stdout_value = test.stdout.read() print repr(stdout_value) print 'done'
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: subprocess
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50123671
has answer: http://stackoverflow.com/a/50123671
tagged with: python

http://stackoverflow.com/a/50136544
type: Answer
downvote count: 0
upvote count: 1
has body: If you can make sure that Signal is never alter after its creation, you can make a __hash__ method by hashing the values you compare in __eq__: def __hash__(self): return hash((self.fq, self.t0, self.tf)) Then you can use sets for duplicate elimination.
answers question: http://stackoverflow.com/q/50136429
score: 1

http://stackoverflow.com/comment/87250134
score: 0
has text: Is the raspberry in question Raspberry Pi 1 (armv6)?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50116038

http://stackoverflow.com/comment/87178719
type: QuestionComment
has text: adding `del self.screen` just changes the error to `'Game' object has no attribute 'screen'`. Changing `pygame.display.init()` to `pygame.init()` makes no difference except that it makes some other things on my raspberry pi not work smoothly because it hogs system resources.
comment on: http://stackoverflow.com/q/50081067
score: 0
type: Comment

http://stackoverflow.com/q/50133637
has answer: http://stackoverflow.com/a/50133694
has comment: http://stackoverflow.com/comment/87285245
has comment: http://stackoverflow.com/comment/87285185
answer count: 1
accepted answer: http://stackoverflow.com/a/50133694
linked to: http://stackoverflow.com/q/4697882
has comment: http://stackoverflow.com/comment/87290887
type: Question
type: AnsweredQuestion
score: 0
has title: regex python group overwrite
tagged with: python
has body: the string is 'POSIX TAR ARCHIVE (GNU)' the regex pattern '(TAR)|(POSIX)' python code : import re pattern = '(TAR)|(POSIX)' string = 'POSIX TAR ARCHIVE (GNU)' match = re.search(pattern, string , re.IGNORECASE) match.groups() the result is only POSIX not tar why??
tagged with: regex

http://stackoverflow.com/comment/87221460
score: 0
comment on: http://stackoverflow.com/q/50102206
type: QuestionComment
has text: There is no need to 1-linise operations on separate objects. In this case, columns and index are separate arrays and should be converted explicitly.
type: Comment

http://stackoverflow.com/q/50159721
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87427846
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87370321
tagged with: decode
answer count: 0
tagged with: ffmpeg
tagged with: pydub
has body: I have individual audio frames encoded in MPEG-2 AAC. Each frame consists of 1024 16 bit PCM samples. I notice that each AAC frame is a different size. I assume this is a result of the MPEG-2 AAC compression algorithm and perfectly normal. I need a way to decode a single frame and get back the original 1024 PCM samples (with error from lossy compression, that's fine). I couldn't find information about the MPEG-2 AAC algorithm ANYWHERE online. It's kinda nuts. I've been trying a crude work around using a library called pydub, which contains a few methods which use FFMPEG's AAC decoder. Trying to load the audio frame as an AudioSegment using AAC encoding: audioData = BytesIO(frame) sound = AudioSegment.from_file(audioData, format="aac") gives the following error: [aac @ 000002d444c1aa00] Estimating duration from bitrate, this may be inaccurate\r\n Input #0, aac, from 'C:\\Users\\jmk_m\\AppData\\Local\\Temp\\tmpjl3x0xao':\r\n Duration: 00:00:00.19, bitrate: 23 kb/s\r\n Stream #0:0: Audio: aac (LC), 22050 Hz, mono, fltp, 23 kb/s\r\nStream mapping:\r\n Stream #0:0 -&gt; #0:0 (aac (native) -&gt; pcm_s16le (native))\r\n Press [q] to stop, [?] for help\r\n Output #0, wav, to 'C:\\Users\\jmk_m\\AppData\\Local\\Temp\\tmpxmp942e4':\r\n Metadata:\r\n ISFT : Lavf58.10.100\r\n Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 22050 Hz, mono, s16, 352 kb/s\r\n Metadata:\r\n encoder : Lavc58.13.100 pcm_s16le\r\n [aac @ 000002d444cc7480] Reserved bit set.\r\n [aac @ 000002d444cc7480] Prediction is not allowed in AAC-LC.\r\n Error while decoding stream #0:0: Invalid data found when processing input\r\n [aac @ 000002d444cc7480] Reserved bit set.\r\n [aac @ 000002d444cc7480] Prediction is not allowed in AAC-LC.\r\n Error while decoding stream #0:0: Invalid data found when processing input\r\n [aac @ 000002d444cc7480] Prediction is not allowed in AAC-LC.\r\n Error while decoding stream #0:0: Invalid data found when processing input\r\n size= 2kB time=00:00:00.04 bitrate= 366.2kbits…
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87347559
has comment: http://stackoverflow.com/comment/87502671
favorite count: 0
type: Question
tagged with: audio
has title: MPEG-2 AAC frame-by-frame audio decoding
has comment: http://stackoverflow.com/comment/87447227

http://stackoverflow.com/q/50179609
type: Question
has title: Trouble with running an application with python and watson
score: 0
tagged with: watson
tagged with: python
has body: I'm using the watson speech to text api with python 3 for a project, and I have to write a new command that will open a project but I'm having trouble figuring out how to do this. Here is the code I have for the command, # Adding a command to launch an application if x[0] ['alternatives'] [0] ['transcript'] == 'run ' and Command_State is 'Started': print("Running...") Command_State = 'Run' self.listening = True The program will see the command and set the Command_State to 'Run' I then have an if statement that I plan on putting the code to run the application. # If statement to, watch for Command_State to switch to 'Run". if Command_State == 'Run': print("Running chrome") # Code goes here pass Currently, I just have a print statement and a pass in the if statement but here is where I want to put the code to run an application. I was thinking about maybe running it through cmd but the only code that I found that talks about that is outdated and doesn't work. Anyways, thank you for helping.
has answer: http://stackoverflow.com/a/50183367
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/87429692
comment on: http://stackoverflow.com/a/50202918
type: Comment
has text: Sorry, I see a bit more information is needed. The XML file contains this line near the top: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> And so before I call into this function, I've parsed this line and set xmlns to {http://www.w3.org/2001/XMLSchema} so when we come across child.tag = '{http://www.w3.org/2001/XMLSchema}annotation' then xmlns+'annotation' does match... I am considering removing the prefixes from the tags with pre-process if that's what's throwing me off.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87451320
has text: The accepted answer was warning you against the solution he proposed, not the use of flags. He injected an exception into the thread and that can be risky - the thread gets an exception it didn't expect and may not exit gracefully.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50207315
score: 0

http://stackoverflow.com/q/50157031
has answer: http://stackoverflow.com/a/50363373
accepted answer: http://stackoverflow.com/a/50363373
answer count: 1
has title: Django form wizard quick finish button
tagged with: django
has comment: http://stackoverflow.com/comment/87332004
has body: I want to implement 2-page form using django-formtools form wizard and I want to add quick finish button in the first page, so that the user won't see the second page. I know that we can conditionally view/skip specific steps but I haven't seen an implementation that invokes the submission. My question is that how can I add a finish button to the first page of a 2-page form?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87332291
tagged with: python
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1

django-database
type: Tag
tags question: http://stackoverflow.com/q/50152598
tag name: django-database

http://stackoverflow.com/comment/87331561
comment on: http://stackoverflow.com/a/50120507
type: Comment
type: AnswerComment
score: 0
has text: Can you post the first ten rows of **first** csv in the body of your post from Notepad++? You can then format the content with code formatting, `{}`. I cannot access GDrive links from here.

http://stackoverflow.com/q/50162089
has body: I'm new to Python and I have just started learning how to use classes. I implemented an array-based list with a max size of 50. I also have an append method where self.count refers to the next available position in the list. Now I'm trying to write a unit test for my append method but I'm wondering, how do I check for the assertion error other than appending 50 times? Is there a way to manually change my self.count? This is my append method. def append(self,item): assert self.count&lt;=50 if self.count&gt;50: raise AssertionError("Array is full") self.array[self.count]=item self.count+=1 This is what I tried for my unit test: def testAppend(self): a_list=List() a_list.append(2) self.assertEqual(a_list[0],2) # test for assertion error Any help will be appreciated! EDIT: Okay after all the useful suggestions I realised I'm supposed to raise an exception instead. def append(self,item): try: self.array[self.count]=item except IndexError: print('Array is full') self.count+=1 Now this is my unit test but I got the warning Warning (from warnings module): File "C:\Users\User\Desktop\task1unitTest.py", line 57 self.assertRaises(IndexError,a_list.append(6)) DeprecationWarning: callable is None ....... def testAppend(self): a_list=List() a_list.append(2) self.assertEqual(a_list[0],2) a_list.count=51 self.assertRaises(IndexError,a_list.append(6))
tagged with: unit-testing
has title: Writing unit test for append method in my array based list implementation
has comment: http://stackoverflow.com/comment/87342619
has comment: http://stackoverflow.com/comment/87342006
has answer: http://stackoverflow.com/a/50162175
type: Question
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/40641019
has comment: http://stackoverflow.com/comment/87342830
has answer: http://stackoverflow.com/a/50162207
linked to: http://stackoverflow.com/q/1273211
score: 0
has comment: http://stackoverflow.com/comment/87342251
answer count: 2
has comment: http://stackoverflow.com/comment/87342392

http://stackoverflow.com/a/50202486
has body: There are several things going on: The file you are given is a gzipped-compressed tarball. Take a look at the tarfile module, it can read gzip-compressed files directly. You'll get an iterator over it's members, each of which is an individual file. AFAIKS librosa can't read from an in-memory buffer so you have to unpack the tar-members to temporary files. The tempfile-module is your friend here, a NamedTemporaryFile will provide you with a self-deleting file that you can uncompress to and provide to librosa. You probably want to implement this as a simple generator function that takes the tarfile-name as it's input, iterates over it's members and yields what librosa.load() provides you. That way everything gets cleaned up automatically. The basic loop would therefore be Open the tarball using the tarfile-module. For each member Get a new temporary file using NamedTemporaryFile. Copy the content of the tarball-member to that file. You may want to use shutil.copyfileobj to avoid reading the entire wav-file into memory before writing it to disk. The NamedTemporaryFile has a filename-attribute. Pass that to librosa.open. yield the return value of librosa.open to the caller.
type: Answer
accepted answer of: http://stackoverflow.com/q/50202350
answers question: http://stackoverflow.com/q/50202350
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2

http://stackoverflow.com/comment/87454565
score: 0
type: Comment
has text: tried this and I still have some permission issues, but the link helped the most so thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/50205707

http://stackoverflow.com/comment/87262449
type: QuestionComment
has text: Two objects can have the same *apparent* string representation without being equal. What's the output of `print(repr(find[i]), repr(X[j]))`?
comment on: http://stackoverflow.com/q/50122266
score: 0
type: Comment

http://stackoverflow.com/q/50104225
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm migrating a bunch of python 2.7 code to python 3 which has patterns like this in python 2.7: sorted(some_list, cmp=custom_compare, key=custom_key_getter) The best way I could figure out to migrate this was as follows: sorted(some_list, key=functools.cmp_to_key( lambda x,y: custom_compare(custom_key_getter(x), custom_key_getter(y))) Is there a better way? Or a more idiomatic way that conforms to python 3?
has title: Combining custom comparison with key selection in python 3
tagged with: python
tagged with: sorting
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50104774
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50104774
upvote count: 2
answer count: 1

http://stackoverflow.com/q/50135108
has comment: http://stackoverflow.com/comment/87290223
linked to: http://stackoverflow.com/q/4072150
has comment: http://stackoverflow.com/comment/87291971
has comment: http://stackoverflow.com/comment/87292056
has title: Recreating Tkinter Widgets with new Font and Size
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/50137284
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50137284
tagged with: tkinter
has body: I am trying to create a program that allows the user to change the font of the labels in the window. I am having trouble figuring out exactly how to recreate all the labels with the new fonts. Here is what I have so far: import tkinter as tk from tkinter import messagebox, colorchooser, simpledialog, filedialog, font root = tk.Tk() root.withdraw() screenHieght = root.winfo_screenheight() # height of the screen screenWidth = root.winfo_screenwidth() # width of the screen windowHieght = screenHieght / 2 # Turtle window is half of screen size windowWidth = screenWidth / 2 x = (screenWidth / 2) - (windowWidth / 2) y = (screenHieght / 2) - (windowHieght / 2) root.geometry('%dx%d+%d+%d' % (windowWidth, windowHieght, x, y)) # Some assistance from Google on centering the window root.columnconfigure(3, weight=2) root.columnconfigure(1, weight=1) root.columnconfigure(5, weight=1) root.rowconfigure(1, weight=2) root.rowconfigure(3, weight=1) root.rowconfigure(4, weight=1) root.rowconfigure(5, weight=1) root.configure(background="#a1dbcd") def changeFont(selection): global selectedfont global setfontstyle print(selection) selectedfont = selection print(setfontstyle) def changeSize(val): print(val) global setfontstyle global fontsize fontsize = val print(setfontstyle) def newfontstyle(): global setfontstyle global selectedfont global fontsize setfontstyle = font.Font(family = selectedfont, size = fontsize) fontsize = tk.IntVar(root) selectedfont = tk.StringVar(root) setfontstyle = font.Font(family=selectedfont, size=12, weight='normal') def atributes(): while True: global setfontstyle global selectedfont global fontsize fontchoose = ["Arial", "Courier New", "Comic Sans MS", "Fixedsys", "MS Sans Serif", "MS Serif", "Symbol", "System", "Times New Roman", "Verdana"] selectedfont.set("Arial") # Variables and stuff label1 = tk.Label(root, text="Select your options", font=setfontstyle).grid(row=1, column=3, pady=10, sticky=tk.E + tk.W + tk.N + tk.S) label2 = tk.Label(root, text="Font …
upvote count: 0
has comment: http://stackoverflow.com/comment/87292793
has comment: http://stackoverflow.com/comment/87292685
answer count: 1
tagged with: tk-toolkit
has comment: http://stackoverflow.com/comment/87289157
has comment: http://stackoverflow.com/comment/87289731
has comment: http://stackoverflow.com/comment/87288988
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87398188
has text: "I still don't quite get why" - because backspace and carriage return are symbols used in interactive typing (which is terminal build for). File editors don't have any interactivity, so they just dump all characters which are inside the file. When you write to the file using `print()`, you cannot delete characters from file, just append new ones to the end, and `\b` `\r` are actually regular characters, so they're stored inside a file
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50190148

http://stackoverflow.com/comment/87233155
has text: @Jean-FrançoisFabre it is not comparing string. it compare hashed string in dict, so it is O(1) speed. for memory usage, it should smaller than op's
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50107305
type: Comment

http://stackoverflow.com/q/50088092
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50286977
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50286977
favorite count: 0
has title: Tensorflow LSTM : ValueError: Shape must have rank at least 3
type: AnsweredQuestion
tagged with: python
tagged with: recurrent-neural-network
tagged with: lstm
type: Question
has body: How to use tf.unstack for feeding the input to LSTM rnn in tensorflow : So if my input shape is [4,5,2] which is [batch_size , time_stamp , n_input] Now if i try: dataet=[[[3, 5], [7, 2], [7, 6]], [[2, 5], [1, 3], [4, 3]], [[8, 1], [1, 8], [9, 3]], [[1, 5], [6, 7], [4, 9]]] import tensorflow as tf from tensorflow.contrib import rnn import numpy as np input_x=tf.placeholder(dtype=tf.int32,shape=[4,3,2]) input_x=tf.cast(input_x,tf.float32) data=tf.unstack(input_x,3,axis=1) with tf.variable_scope('encoder') as scope: cell=rnn.LSTMCell(num_units=250) model=tf.nn.bidirectional_dynamic_rnn(cell,cell,inputs=data,dtype=tf.float32) output,(fs,fc)=model with tf.Session() as sess: unstack_output,output_n=sess.run([output,data],feed_dict={input_x:dataet}) print(unstack_output,output_n) I am getting the error : /anaconda/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.5 return f(*args, **kwds) Traceback (most recent call last): File "/Users/exepaul/Desktop/limit_exceed/nad.py", line 25, in &lt;module&gt; model=tf.nn.bidirectional_dynamic_rnn(cell,cell,inputs=data,dtype=tf.float32) File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 416, in bidirectional_dynamic_rnn time_major=time_major, scope=fw_scope) File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 632, in dynamic_rnn dtype=dtype) File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 695, in _dynamic_rnn_loop for input_ in flat_input) File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 695, in &lt;genexpr&gt; for input_ in flat_input) File "/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 673, in with_rank_at_least raise ValueError("Shape %s must have rank at least %d" % (self, rank)) ValueError: Shape (2, 4) must have rank at least 3 How to shape the i…
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/comment/87354670
type: QuestionComment
has text: @Julien thanks, it's alphanumerical unfortunately..
score: 0
comment on: http://stackoverflow.com/q/50168122
type: Comment

http://stackoverflow.com/a/62360659
downvote count: 1
has comment: http://stackoverflow.com/comment/119848045
upvote count: 8
has body: I hope you have already solved this. But, my answer will help someone who has similar problem like that. I think this can be accomplished using the Find and Replace option which can be found under the edit menu of the notebook. If you're in command mode, you can easily press the F key and bring up the find and replace dialog. Thank you!
type: Answer
answers question: http://stackoverflow.com/q/50177616
score: 7

http://stackoverflow.com/a/55151241
has body: Not sure if you're still having trouble, but I think your problem may be the same as this one The solution is to change python fslinstaller.py to /usr/bin/python fslinstaller.py. If this doesn't work it may be the full path to your python is wrong. You can find the right one with which python, which python2, or which python2.7. One of these will probably work In my case I needed to run the command sudo /usr/bin/python2.7 fslinstaller.py and the installer worked
upvote count: 3
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50174864

http://stackoverflow.com/comment/87380637
type: Comment
has text: yes... I'm struggling... does my account have a different alias than the Virtual Env? Does each Virtual Env have its own alias? How can one check if so and fix the above issue?
type: QuestionComment
comment on: http://stackoverflow.com/q/50181586
score: 0

http://stackoverflow.com/comment/87390485
has text: No it's just downloading a blank file through the url contains image.
comment on: http://stackoverflow.com/q/50186384
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87418891
type: Comment
has text: This is the better answer.
comment on: http://stackoverflow.com/a/50200451
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87212356
comment on: http://stackoverflow.com/q/50097948
has text: @Aran-Fey Because it's a standalone script that doesn't make sense to be used as a module.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87950409
has text: arggh, I thought I had tried that, but I obviously hadn't.... That works as expected. Many thanks.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50444395
score: 0

http://stackoverflow.com/comment/87347607
score: 1
has text: Yes!: VS Code terminal: `>>> import sys >>> sys.executable 'C:\\Python27\\ArcGIS10.6\\python.exe'` CMD: `>>> import sys >>> sys.executable 'C:\\Python27\\ArcGIS10.6\\python.exe'` Arc (ha, ha): `>>> import sys >>> sys.executable 'C:\\Program Files (x86)\\ArcGIS\\Desktop10.6\\bin\\ArcMap.exe'` i could not get this to format as I wanted, but I hope you see the answer verified.
comment on: http://stackoverflow.com/q/50125209
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50159662
type: Question
tagged with: terminal
upvote count: 5
score: 5
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: executable
has answer: http://stackoverflow.com/a/55678557
tagged with: python
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50162596
has body: I am using macOS, and Anaconda 3 in order to manage my libraries and write the script. I want to create an executable for my script. I am using Pyinstaller in Terminal to run the command: pyinstaller --onefile /Directory/file.py However, Terminal returns this error: File "/anaconda3/lib/python3.6/site-packages/PyInstaller/hooks/hook-sysconfig.py", line 42, in &lt;module&gt; hiddenimports = [sysconfig._get_sysconfigdata_name()] TypeError: _get_sysconfigdata_name() missing 1 required positional argument: 'check_exists' How can I solve this problem; thank you for your assistance.
has title: Compiling a python script with Pyinstaller via terminal
favorite count: 0

http://stackoverflow.com/comment/87541260
has text: I'm having the same problem in Flask 0.12.2, which is over a year old. But the bug was only reported 12 days ago, and this question is only a week or so old. An incredible coincidence?
comment on: http://stackoverflow.com/a/50097632
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87549712
comment on: http://stackoverflow.com/a/50228584
score: 0
type: Comment
has text: the point was to save a different model for each number of hidden nodes so you can evaluate each later. str(hidden_nodes) would work. You are only saving the model after all training is done so num_iters isn't as important.
type: AnswerComment

http://stackoverflow.com/a/50081314
type: AcceptedAnswer
type: Answer
has body: Final code: from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot, Qt, QTimer import time class Main(QObject): divisible_by_4 = pyqtSignal() def __init__(self, parent=None): QObject.__init__(self, parent=parent) self.run = True def main(self): x = 1 while self.run: print(x) x += 1 if x%4 == 0: self.divisible_by_4.emit() time.sleep(1) def stop(self): self.run = False
accepted answer of: http://stackoverflow.com/q/50081088
score: 0
answers question: http://stackoverflow.com/q/50081088

http://stackoverflow.com/comment/87379903
score: 0
has text: it's close, but `type_copy('')` will give us `TypeError: type.__new__() takes exactly 3 arguments (1 given)`
comment on: http://stackoverflow.com/a/50176549
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87231666
has text: That's how the output is displayed when the API is called.
score: 0
comment on: http://stackoverflow.com/q/50106611
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50183419
type: UnansweredQuestion
downvote count: 0
answer count: 1
has body: Working in python with matplotlib, venn3 and venn3_circles. I am trying to get the list of elements of each intersection in a 3 circles venn diagram. I will use the example here from matplotlib import pyplot as plt import numpy as np from matplotlib_venn import venn3, venn3_circles A = set(['DPEP1', 'CDC42BPA', 'GNG4', 'RAPGEFL1', 'MYH7B', 'SLC13A3', 'PHACTR3', 'SMPX', 'NELL2', 'PNMAL1', 'KRT23', 'PCP4', 'LOX', 'CDC42BPA']) B = set(['ABLIM1','CDC42BPA','VSNL1','LOX','PCP4','SLC13A3']) C = set(['PLCB4', 'VSNL1', 'TOX3', 'VAV3']) v = venn3([A,B,C], ('GCPromoters', 'OCPromoters', 'GCSuppressors')) ppp=v.get_label_by_id('100').set_text('\n'.join(A-B-C)) v.get_label_by_id('110').set_text('\n'.join(A&amp;B-C)) v.get_label_by_id('011').set_text('\n'.join(B&amp;C-A)) v.get_label_by_id('001').set_text('\n'.join(C-A-B)) v.get_label_by_id('010').set_text('') plt.annotate(',\n'.join(B-A-C), xy=v.get_label_by_id('010').get_position() + np.array([0, 0.2]), xytext=(-20,40), ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.1), arrowprops=dict(arrowstyle='-&gt;', connectionstyle='arc',color='gray')) In the example, they can show in the graphical venn diagram the contents of each intersection How can I store in a variable/list the contents of each intersection? I want to get something like this: A:[MYH7B, PHACTR3,...,DPEP1] AB: [LOX,...,PCP4] B: [ABLIM1] ABC: empty B: empty BC: [VSNL1] C: [TOX3,VAV3,PLCB4] Where A, AB, ABC, C,... are lists in python
linked to: http://stackoverflow.com/q/42855256
score: 4
favorite count: 0
has title: Python: venn3_circles: How to get the values of the intersection in a Venn 3 circle diagram
tagged with: python
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50183737
tagged with: matplotlib-venn

http://stackoverflow.com/comment/87496322
type: AnswerComment
comment on: http://stackoverflow.com/a/50223489
type: Comment
has text: Tis doesn't append. It overlaps. The result I want is d={'a':[1,2],'b':[2,0],'c':1}
score: 0

http://stackoverflow.com/comment/87345776
has text: I've tried to enable c++11 in the VS I'm using but It won't work for me
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50163198

http://stackoverflow.com/a/50076612
answers question: http://stackoverflow.com/q/50076552
score: 0
has body: Just use path('api/v1/store/download/&lt;str:ix&gt;', DownloadVideoAPI.as_view(), name='download'), without / at the end.
type: Answer

http://stackoverflow.com/comment/87288039
score: 2
type: QuestionComment
has text: So it corresponds with a value of `''`? That doesn't look like a valid integer to me...
type: Comment
comment on: http://stackoverflow.com/q/50130913

http://stackoverflow.com/a/50167334
has body: If you want a QML project without using C ++ what you should do is follow the following steps └── File New File or Project ... └── Other Project └── Qt Quick Ui prototype
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50167096
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50167096
has comment: http://stackoverflow.com/comment/87352318

http://stackoverflow.com/a/50208910
answers question: http://stackoverflow.com/q/50208787
score: 1
downvote count: 0
upvote count: 1
has body: python passes lists by reference, meaning the original list can be modified by a function that was given that list as a parameter, so when you call the function with: mergeSort(lefthalf) mergeSort(righthalf) lefthalf and righthalf are themselves sorted, notice how the outside call to mergeSort() also assumes the original list is modified, it doesn't return a new sorted list, as i said it sorts the existing list
has comment: http://stackoverflow.com/comment/87434706
type: Answer

http://stackoverflow.com/q/50142298
has comment: http://stackoverflow.com/comment/87303658
favorite count: 0
tagged with: timestamp
has answer: http://stackoverflow.com/a/50142662
has title: Timezone conversion error found when converting the timezone of a large list of timestamps in an excle file with python
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87302857
score: -1
linked to: http://stackoverflow.com/q/50137360
type: AnsweredQuestion
tagged with: timezone
upvote count: 0
has comment: http://stackoverflow.com/comment/87302941
linked to: http://stackoverflow.com/q/45474316
accepted answer: http://stackoverflow.com/a/50142662
has body: I have an excel file named "hello.xlsx". There is a column of timestamps that has a lot of rows (more than 80,000 rows for now). The file basically looks like this: 04/19/2018 01:37:33 04/19/2018 01:37:54 04/19/2018 01:37:57 04/19/2018 01:37:59 04/19/2018 01:38:05 04/19/2018 01:38:10 04/19/2018 01:38:38 04/19/2018 01:39:29 04/19/2018 01:39:32 04/19/2018 01:39:44 04/19/2018 01:39:51 And so on... These timestamps are in UTC time, and I need to convert them to US Pacific Time (UTC, -7). I'm a beginner of python and actually I don't know how to do such conversion. I asked online and got a helpful answer. The code looks like this: df = pd.read_excel('hello.xlsx', header=None) local_tz = pytz.timezone('US/Pacific') df[0] = df[0].apply(lambda x: x.replace(tzinfo=pytz.utc).astimezone(local_tz).replace(tzinfo=None)) df.to_excel('out.xlsx', index=False, header=False) However, there was an error after I ran it: TypeError: replace() takes no keyword arguments I searched online to look for a solution but failed to make it right. I hope someone can help figure it out. New methods are also welcomed. Thanks~ :)
answer count: 1
downvote count: 1
tagged with: excel

http://stackoverflow.com/q/50091863
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50097532
score: 0
has title: How can I use output of a python script for a zap trigger?
tagged with: zapier
has body: I have a simple script shown below. I want to use the value of holiday_value to create a filter. I am thinking this could be done by putting the value into zap storage and then retrieving the value from storage and use it in a zap filter. I don't know how to get the value from the script into zap storage. from datetime import date import holidays us_holidays = holidays.US() if date.today() in us_holidays: holiday_value='true' else: holiday_value='false'

http://stackoverflow.com/comment/87270271
has text: @abarnert So it's definitely the sql writes that are slowing it down. Let me purse the options you've provided. Thank you.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50125094

http://stackoverflow.com/q/50128886
type: Question
has body: Currently I'm trying to Send information from python to Arduino through the serial port. I manage this using only one letter Serial.read() 'P' and executing an action on my Arduino with the following code. Arduino code: #define arduinoLED 12 // Arduino LED on board void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(arduinoLED, OUTPUT); // Configure the onboard LED for output digitalWrite(arduinoLED, LOW); // default to LED off } void loop() { // put your main code here, to run repeatedly: //delay (20000); //char comein=Serial.read(); //Serial.println(comein); char *arg = "hello"; if (Serial.read()== 'P'){ digitalWrite(arduinoLED, HIGH); delay(5000); } else { digitalWrite(arduinoLED, LOW); Serial.println("Hello World"); } } Python code: ser.open() ser.is_open my_string='P' my_string_as_bytes=str.encode(my_string) print(my_string_as_bytes) ser.write(my_string_as_bytes) This works well and turn my LED on but how could I manage more then one letter for the command for example 'P1 2018' for the led to turn on? But my real problem is that I try to do exactly the same thing, using the same Python code, but using SCmd.readSerial() to read the information in Arduino such as the following: Arduino code: #include &lt;SerialCommand.h&gt; #define arduinoLED 12 // Arduino LED on board SerialCommand SCmd; // The demo SerialCommand object void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(arduinoLED, OUTPUT); // Configure the onboard LED for output digitalWrite(arduinoLED, LOW); // default to LED off SCmd.addCommand("P1", process_command1); // Converts two arguments to integers and echos them back SCmd.addCommand("P", relay1_on); // Turns Relay1 on SCmd.addDefaultHandler(unrecognized); // Handler for command that isn't matched (says "What?") Serial.println("Ready"); } void loop() { // put your main code here, to run repeatedly: SCmd.readSerial(); // We don't do much, just process serial commands } void relay1_on() …
type: UnansweredQuestion
has title: Difference between SCmd.readSerial() and Serial.read()
tagged with: python
has answer: http://stackoverflow.com/a/50145253
tagged with: arduino
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87231758
type: Comment
has text: I have this file and I need to exchange these values, it's for my learning
score: 0
comment on: http://stackoverflow.com/q/50106975
type: QuestionComment

http://stackoverflow.com/q/50146392
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50218148
has answer: http://stackoverflow.com/a/50218148
tagged with: tensorflow
type: Question
has body: I have created a DLAMI (Deep Learning AMI (Amazon Linux) Version 8.0 - ami-9109beee on g2.8xlarge) and installed jupyter notebook to create a simple Keras LSTM. When I try to turn my Keras model into a GPU model using the multi_gpu_model function, I see the following error logged: Ignoring visible gpu device (device: 0, name: GRID K520, pci bus id: 0000:00:03.0, compute capability: 3.0) with Cuda compute capability 3.0. The minimum required Cuda capability is 3.5. I've tried reinstalling tensorflow-gpu to no avail. Is there any way to align the compatibilities on this AMI?
answer count: 2
tagged with: amazon-ec2
has comment: http://stackoverflow.com/comment/87310990
has title: AWS DLAMI - GPUs not showing up for Keras
tagged with: python
possible better answer: http://stackoverflow.com/a/50154333
tagged with: keras
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/50154333
has comment: http://stackoverflow.com/comment/87311195

http://stackoverflow.com/q/50097948
tagged with: python
has comment: http://stackoverflow.com/comment/87212356
has comment: http://stackoverflow.com/comment/87217417
has title: python practice for cli script with __main__
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has body: I have several cli python scripts and they are not targeted to be imported. So, I put this code on top : if __name__!='__main__': import sys sys.exit(0) Is it a bad practice or good one ? Main goal is to prevent to put all code into functions and put at the bottom if __name__=='__main__': mybig_main_run()
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87212415
has comment: http://stackoverflow.com/comment/87212255
has answer: http://stackoverflow.com/a/50098053
type: UnansweredQuestion

http://stackoverflow.com/q/50209913
score: 0
has answer: http://stackoverflow.com/a/50210007
has answer: http://stackoverflow.com/a/50210013
type: Question
has comment: http://stackoverflow.com/comment/87438254
has comment: http://stackoverflow.com/comment/87436755
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50209965
linked to: http://stackoverflow.com/q/36520120
has body: I know the title is quite vague, but I have no idea how to sum what I want to do. An example is a loading screen, I want to do something like this: Loading assets - 10% and then remove the output from the terminal and print Loading textures - 20% Every time I try something like this I get Loading assets - 10% Loading textures - 20% How can I do this?
tagged with: python
has title: Replacing individual characters in a print statement
answer count: 4
has answer: http://stackoverflow.com/a/50210045

http://stackoverflow.com/comment/87228868
score: 0
has text: ^ I can try that command
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50093121

http://stackoverflow.com/comment/87325238
type: Comment
has text: If your class has so many unused attributes, it might be a sign that your class hierarchy isn't right. Maybe consider splitting it into multiple smaller classes?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50153800

http://stackoverflow.com/q/50087301
has comment: http://stackoverflow.com/comment/87196376
answer count: 0
has title: IndexError while passing value to knn algorithm in the process of implementing aco-pants in python
tagged with: machine-learning
type: Question
tagged with: algorithm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87190350
tagged with: python
has body: import time import math import argparse import sys from datetime import timedelta from pants import World, Edge from pants import Solver import csv import random import math import operator a=b=c=d=e=f=g=h=0 def loadDataset(filename,trainingSet=[],testSet=[]): with open(filename, 'rt') as csvfile: lines = csv.reader(csvfile) dataset = list(lines) z = len(dataset)-1 for x in range(len(dataset)-2): for y in range(8,9): dataset[x][y] = float(dataset[x][y]) trainingSet.append(dataset[x]) for y in range(8,9): dataset[z][y] = float(dataset[z][y]) testSet.append(dataset[z]) def euclideanDistance(instance1, instance2): distance = 0 X= (float(instance1[9]) - float(instance2[9])) +(float(instance1[8]) - float(instance2[8])) distance += pow(X, 2) return math.sqrt(distance) def getNeighbors(trainingSet, testInstance, k): distances = [] for x in range(len(trainingSet)): dist = euclideanDistance(testInstance, trainingSet[x]) distances.append((trainingSet[x], dist)) distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors def main(): trainingSet=[] testSet=[] loadDataset('D:\ex.csv', trainingSet, testSet) print ('Train set: ' + repr(len(trainingSet))) print ('Test set: ' + repr(len(testSet))) k = 4 neighbors = getNeighbors(trainingSet, testSet[0], k) l=m=n=0 print(' Nearest Neighbour is '+a+ ' whose latitude difference is: '+b+ ' and longitude differnce is '+c ) a=neighbors[0][8] b=neighbors[0][9] c=neighbors[1][8] d=neighbors[1][9] e=neighbors[2][8] f=neighbors[2][9] g=neighbors[3][8] h=neighbors[3][9] # Real-world latitude longitude coordinates. TEST_COORDS_33 = [(a, b), (c, d), (e, f), (g,h)] # 45-45-90 triangle with unit length legs. TEST_COORDS_3 = [(0, 0), (1, 0), (0, 1)] # Unit square with diagonals. TEST_COORDS_4 = [(0, 0), (1, 0), (0, 1), (1, 1)] # Same as above except with additional node in center of left edge. TEST_COORDS_5 = [(0, 0), (1, 0), (0, 1), (1, 1), (0, 0.5)] def dist(a, b): """Return the d…
tagged with: knn
score: 0
tagged with: prediction

http://stackoverflow.com/comment/87422061
score: 0
type: QuestionComment
has text: @Shawn You showed expected output only for `list_a` with single element, can you update it for multiple elements?
type: Comment
comment on: http://stackoverflow.com/q/50200746

http://stackoverflow.com/a/50099648
has comment: http://stackoverflow.com/comment/87225798
score: 1
has comment: http://stackoverflow.com/comment/87243185
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87226658
has comment: http://stackoverflow.com/comment/87229167
has body: You need a proxy function to do the function call, and as you need to deliver arguments to the function, you will need partial as well. Consider this: from time import sleep from multiprocessing import Pool from functools import partial class Foo: def __init__(self, a): self.a = a self.b = None def evaluate(self, CostFunction, i): xyzzy = CostFunction(i) sleep(0.01) self.b = self.a*xyzzy return self def CostFunc(i): return i*i def proxy(gg, costf, i): return gg.evaluate(costf, i) def main(): Swarm = [] for i in range(0,10): nc = Foo(i) Swarm.append(nc) p = Pool() for i in range(100,102): results = p.map_async(partial(proxy, costf=CostFunc, i=i), Swarm) p.close() p.join() Swarm = [] for a in results.get(): Swarm.append(a) for s in Swarm: print (s.b) main() This creates a Swarm list of objects, and within each of these objects is evaluate that is the function you need to call. Then we have parameters (CostFunc and an integer as in your code). We will now use Pool.map_async to map your Swarm list to your pool. This gives each worker one instance of Foo from your Swarm list, and we have a proxy function that actually calls then evaluate(). However, as apply_async only sends an object from the iterable to the function, instead of using proxy as the target function to pool, we use partial to create the target function to pass the "fixed" arguments. And as you apparently want to get the modified objects back, this requires another trick. If you modify the target object in Pool process, it just modifies the local copy and throws it away as soon as the processing completes. There would be no way for the subprocess to modify main process memory anyway (or vice versa), this would cause a segmentation fault. Instead, after modifying the object, we return self. When your pool has completed its work, we discard the old Swarm and reassemble it from the result objects.
has comment: http://stackoverflow.com/comment/87225938
accepted answer of: http://stackoverflow.com/q/50098789
has comment: http://stackoverflow.com/comment/87225316
has comment: http://stackoverflow.com/comment/87226197
has comment: http://stackoverflow.com/comment/87226064
answers question: http://stackoverflow.com/q/50098789
type: Answer
has comment: http://stackoverflow.com/comment/87225062

http://stackoverflow.com/q/50096240
tagged with: python
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/87208733
has answer: http://stackoverflow.com/a/50096255
has title: python3: map list of sets to list of lists
has body: I have a list of sets like this: A=[{1,2},{3,4},{1,5}] I want to map A to a list of lists instead of list of sets like this: A=[[1,2],[3,4],[1,5]] can any body help me How can I do this?
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50096255
upvote count: 0
downvote count: 5

http://stackoverflow.com/q/50161533
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/87341025
score: 3
upvote count: 3
tagged with: rpython
downvote count: 0
has title: can't import package with rPython
answer count: 1
has body: I installed umap-learn on mac OS and tried to use it in r markdown file using rPython the way it is explained here: http://blog.schochastics.net/post/using-umap-in-r-with-rpython/#fn1 But when I run following code: ```{r} umap &lt;- function(x,n_neighbors=10,min_dist=0.1,metric="euclidean"){ x &lt;- as.matrix(x) colnames(x) &lt;- NULL rPython::python.exec( c( "def umap(data,n,mdist,metric):", "\timport umap" , "\timport numpy", "\tembedding = umap.UMAP(n_neighbors=n,min_dist=mdist,metric=metric).fit_transform(data)", "\tres = embedding.tolist()", "\treturn res")) res &lt;- rPython::python.call( "umap", x,n_neighbors,min_dist,metric) do.call("rbind",res) } data(iris) res &lt;- umap(iris[,1:4]) ``` I get the error: Error in python.exec(python.command) : No module named umap So, apparently Rstudio does not see the umap. I checked that the package is installed by conda list: umap-learn 0.2.3 py36_0 conda-forge How could I fix that? Update The version of python was wrong, so I added .Rprofile and made it point to the right version, however, the error persisted. system("python --version") Python 3.6.5 :: Anaconda, Inc. Update More detailed error (stack trace): Error in python.exec(python.command) : No module named umap 4.stop(ret$error.desc) 3.python.exec(python.command) 2.rPython::python.call("umap", x, n_neighbors, min_dist, metric) 1.umap(iris[, 1:4])
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/36705878
has answer: http://stackoverflow.com/a/50161617
linked to: http://stackoverflow.com/q/3387695
tagged with: python

http://stackoverflow.com/comment/87187971
type: AnswerComment
type: Comment
score: 0
has text: Thanks! This eventually worked, though apparently math and numpy don't work nicely together so I had to replace mh.log(DL,10) by np.log10(), else it would complain again.
comment on: http://stackoverflow.com/a/50081264

http://stackoverflow.com/q/50127633
favorite count: 0
has body: I have data as below. I want to plot a simple line graph in python where item on the X axis and total sales in the Y axis. Total sales is the aggregated sales at the item level. Can anyone help on this? Item Date Sales Item1 4/25/2018 55 Item2 4/25/2018 21 Item3 4/25/2018 50 Item4 4/25/2018 58 Item5 4/25/2018 81 Item6 4/25/2018 79 Item7 4/25/2018 61 Item8 4/25/2018 37 Item9 4/25/2018 51 Item10 4/25/2018 53 Item1 4/26/2018 27 Item2 4/26/2018 28 Item3 4/26/2018 26 Item4 4/26/2018 95 Item5 4/26/2018 15 Item6 4/26/2018 89 Item7 4/26/2018 42 Item8 4/26/2018 21 Item9 4/26/2018 39 Item10 4/26/2018 67 Item1 4/27/2018 14 Item2 4/27/2018 45 Item3 4/27/2018 35 Item4 4/27/2018 68 Item5 4/27/2018 76 Item6 4/27/2018 63 Item7 4/27/2018 73 Item8 4/27/2018 61 Item9 4/27/2018 59 Item10 4/27/2018 93 Item1 4/28/2018 27 Item2 4/28/2018 63 Item3 4/28/2018 55 Item4 4/28/2018 73 Item5 4/28/2018 58 Item6 4/28/2018 90 Item7 4/28/2018 67 Item8 4/28/2018 72 Item9 4/28/2018 64 Item10 4/28/2018 98 Regards, philip
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50202939
has title: how to aggregate data in Y axis and plot a line graph in python
tagged with: matplotlib
linked to: http://stackoverflow.com/q/37693600
tagged with: python
type: Question
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/50162887
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87278515
has answer: http://stackoverflow.com/a/50166879
downvote count: 1

http://stackoverflow.com/q/50079650
has comment: http://stackoverflow.com/comment/87175485
has title: Write Data from Multiple Site to JSON File BeautifulSoup
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I am trying to scrape multiple websites that have the same HTML structure and write the content to a JSON file. The results for each URL print out in the terminal, but only the content from the last URL listed is written into the JSON file. I have not been able to figure out a solution. Here is my code from urllib.request import urlopen from bs4 import BeautifulSoup as soup import json urls = ['https://scholarworks.gvsu.edu/books/', 'https://pdxscholar.library.pdx.edu/pdxopen/', 'https://oer.galileo.usg.edu/all-textbooks/index.html', 'https://oer.galileo.usg.edu/all-textbooks/index.2.html', 'https://digitalcommons.trinity.edu/textbooks/'] #scrape elements for url in urls: uClient = urlopen(url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") containers = page_soup.findAll("div",{"class":"content_block"}) source = page_soup.find("div",{"id":"series-header"}) data = [] for container in containers: item = {} item['type'] = "Textbook" item['title'] = container.h2.text item['author'] = container.p.text item['link'] = container.a["href"] item['source'] = source.h2.text data.append(item) # add the item to the list print(container.h2.text) with open("./json/multiple.json", "w") as writeJSON: json.dump(data, writeJSON, ensure_ascii=False)
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50079786
type: Question
tagged with: beautifulsoup
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50079786

http://stackoverflow.com/a/50088454
score: 0
answers question: http://stackoverflow.com/q/50088266
has body: if number not in numbers That will do the trick It checks if it is true that the selected number is in the list
type: Answer

http://stackoverflow.com/q/50159682
has comment: http://stackoverflow.com/comment/87337274
answer count: 1
has comment: http://stackoverflow.com/comment/87337702
type: Question
has body: File 1.txt File 2.txt Output File Reference Image I tried but i got the out put in another way `import re, glob, logging from itertools import izip def FindDiff (Doc1, Doc2, Doc3): doc1read = open (Doc1,'r') doc2read = open (Doc2,'r') doc3write = open (Doc3,'w+') find_pattern = r'\b\d*\.\d+|\d+\b' lineno = 1 lines1 = doc1read.readline() lines2 = doc2read.readline() while lines1: regex1 = re.findall(find_pattern, lines1) regex2 = re.findall(find_pattern, lines2) length = len(regex1)-1 for x in range (0, length): if (regex1[x] != regex2[x]): doc3write.write("File 1 has "+lines1+"and File 2 has "+lines2+"at line -" + str(lineno) + "\n") print regex1 print regex2 break lineno = lineno+1 lines1 = doc1read.readline() lines2 = doc2read.readline() doc1read.close() doc2read.close() doc3write.close() FindDiff('D:/F1.txt', 'D:/F2.txt','D:/F3.txt')`
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50160701
has comment: http://stackoverflow.com/comment/87337494
has comment: http://stackoverflow.com/comment/87337647
has title: Compare two Text Files, Output in Third File
score: 0

http://stackoverflow.com/a/55236734
score: -4
has comment: http://stackoverflow.com/comment/97678405
type: Answer
answers question: http://stackoverflow.com/q/50187902
downvote count: 4
upvote count: 0
has body: I had the same issue and solved it uninstalling the libqt5x11extras5l library: sudo apt-get remove libqt5x11extras5l

http://stackoverflow.com/comment/87379241
type: Comment
has text: What do you get when you run the four commands shown above (`noao`, `twodspec`, `apextract`, and`apedit dev$pix`)?
type: AnswerComment
comment on: http://stackoverflow.com/a/50170012
score: 0

http://stackoverflow.com/comment/87341383
type: Comment
score: 1
type: QuestionComment
has text: @TwistedSim psst, `map` replaces non-dict entries with NaN, probably not desirable in this case (you want `replace`).
comment on: http://stackoverflow.com/q/50161569

http://stackoverflow.com/comment/87258406
score: 0
has text: Yes, in my app.yaml it says 'env: flex' - as it is suggested in the flask demo on google cloud
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50120075

http://stackoverflow.com/q/50125472
has answer: http://stackoverflow.com/a/67653422
has title: Issues with installing python libraries on Windows : CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/win-64
has answer: http://stackoverflow.com/a/55401060
upvote count: 85
has answer: http://stackoverflow.com/a/54275601
has answer: http://stackoverflow.com/a/79203500
has answer: http://stackoverflow.com/a/54238978
has answer: http://stackoverflow.com/a/76788448
has answer: http://stackoverflow.com/a/62128153
downvote count: 0
has answer: http://stackoverflow.com/a/73742702
tagged with: ssl
tagged with: python
has answer: http://stackoverflow.com/a/73028450
has answer: http://stackoverflow.com/a/55943881
has answer: http://stackoverflow.com/a/62369135
tagged with: conda
answer count: 28
has answer: http://stackoverflow.com/a/75984074
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72378713
has answer: http://stackoverflow.com/a/51440710
has answer: http://stackoverflow.com/a/63087109
has answer: http://stackoverflow.com/a/73135474
tagged with: anaconda
has body: I'd like to install the pymongo library but I'm getting the following error: (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx> conda install -c anaconda pymongo Fetching package metadata ... CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/a naconda/win-64/repodata.json> Elapsed: - An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. ConnectTimeout(MaxRetryError("HTTPSConnectionPool(host='conda.anaconda.org', por t=443): Max retries exceeded with url: /anaconda/win-64/repodata.json (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000 00000054D6128>, 'Connection to conda.anaconda.org timed out. (connect timeout=9. 15)'))",),) Steps taken to resolve: 1. Update C:\Users\\xxxxxxx\.condarc file with the following: channels: - defaults ssl_verify: false proxy_servers: http: http://sproxy.fg.xxx.com:1000 https: https://sproxy.fg.xxx.com:1000 2. (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx> conda config --set ssl_verify False Additional Info: (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx> conda info Current conda install: platform : win-64 conda version : 4.3.27 conda is private : False conda-env version : 4.3.27 conda-build version : 3.0.22 python version : 3.6.2.final.0 requests version : 2.18.4 config file : C:\Users\xxxxxxx\.condarc netrc file : None offline mode : False user-agent : conda/4.3.27 requests/2.18.4 CPython/3.6.2 Windows/7 W indows/6.1.7601 administrator : False A number of posts online simply reinstalled Anaconda, any other options apart from a fresh install?
has answer: http://stackoverflow.com/a/55104289
has answer: http://stackoverflow.com/a/58528298
accepted answer: http://stackoverflow.com/a/62483686
has answer: http://stackoverflow.com/a/54315798
has answer: http://stackoverflow.com/a/71019774
has answer: http://stackoverflow.com/a/62483686
has answer: http://stackoverflow.com/a/59985610
has answer: http://stackoverflow.com/a/50128847
has answer: http://stackoverflow.com/a/59303097
possible better answer: http://stackoverflow.com/a/51719759
tagged with: https
favorite count: 0
has answer: http://stackoverflow.com/a/55258096
type: Question
score: 85
has answer: http://stackoverflow.com/a/72651207
has answer: http://stackoverflow.com/a/74337952
has answer: http://stackoverflow.com/a/51719759

http://stackoverflow.com/comment/87371176
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50176675
type: Comment
has text: With my minus values I'm still getting -1 days +23:58:00 which is correct, but a bit confusing - can I make it format it as just - minutes?

http://stackoverflow.com/q/50179694
has body: Hi I'm compiling mod_wsgi in virtualenv with python3.6 and apache2.4. I already have another virtualenv with python3.5 and mod_wsgi works. Compiling in my new virtualenv with python3.6 with: ./configure --with-python=/home/fgthct/.virtualenv/djangodev/bin/python This generates the Makefile. When I run make, I finally get the following error: /usr/bin/ ld: /usr/local/lib/libpython3.6m.a(abstract.o): relocation R_X86_64_32S against `_Py_NotImplementedStruct 'can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libpython3.6m.a: error adding symbols: Wrong value collect2: error: ld returned 1 exit status error: command 'gcc' failed with exit status 1. I reiterate that I already have another virtualenv with python3.5 and it works. Thanks in advance to those who want to help me. Fgthct
type: Question
upvote count: 5
tagged with: ubuntu-16.04
tagged with: python
type: UnansweredQuestion
has title: /usr/local/lib/libpython3.6m.a: error adding symbols: Bad value collect2: error: ld returned 1 exit status error: command 'gcc
tagged with: apache2.4
answer count: 0
tagged with: mod-wsgi
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/87376810
favorite count: 0
has comment: http://stackoverflow.com/comment/87384799

http://stackoverflow.com/q/50183728
has title: Performance of assigning multiple return values from function call
has answer: http://stackoverflow.com/a/50183738
possible better answer: http://stackoverflow.com/a/50183738
type: Question
linked to: http://stackoverflow.com/q/9752958
tagged with: function
tagged with: python
accepted answer: http://stackoverflow.com/a/50183760
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
upvote count: 1
has body: I'm wondering if there's a way to assign the outputs of a function to variables, while only having to run the function once. For example, say I have a function like this: def my_func(x): return x+1, x**2, x**3 And then I want to store each output as a variable, so normally I would code this afterwards: var1 = my_func(2)[0] var2 = my_func(2)[1] var3 = my_func(2)[2] But from my understanding, each line above requires the function to run again. If I have a longer function, it would be more convenient to assign them all at the same time, only running the function once. Is there a way to do this?
duplicate of: http://stackoverflow.com/q/9752958
downvote count: 1
favorite count: 0
tagged with: assign
has answer: http://stackoverflow.com/a/50183760

http://stackoverflow.com/a/50152481
answers question: http://stackoverflow.com/q/50152390
type: Answer
has body: You will need to use either separate threads or subprocesses, so it doesn't block the main process. Threading: https://docs.python.org/2/library/threading.html Subprocesses: https://docs.python.org/2/library/subprocess.html
score: 0

http://stackoverflow.com/q/50224808
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87467187
tagged with: python-3.x
has title: Can keyword argument default values be parameterized?
has comment: http://stackoverflow.com/comment/87467136
answer count: 0
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/21804615
has body: I'm writing a class definition with several methods. The __init__ method instantiates a list as an argument, and I'd like one of the methods to take a keyword argument with a default value that matches the list in length. Consider the code snippet: class widget(object): def __init__(self, *attr_list): self.attr_list = attr_list def fancy_method(self, arglist = (None,) * len(self.attr_list)): pass I suppose I can just run the code and try instantiating a widget, but can anyone provide enlightening commentary on the order of operations and acceptable variable references? Perhaps propose an alternative syntax that's easier to agree with? EDIT: A similar question was asked and answered here How can I make the default value of an argument depend on another argument (in Python)? but I'm curious to know how the interpreter treats the matter when the parameter, namely attr_list, isn't an argument in the same function as the keyword argument it parameterizes. Is fancy_method and its behavior defined upon the widget definition? Or can the default argument be defined upon instantiation instead? The other question doesn't include this ambiguity because the default argument would have to be defined upon the function's call, not its definition.
duplicate of: http://stackoverflow.com/q/21804615
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87467808

discord
tags question: http://stackoverflow.com/q/50204867
tags question: http://stackoverflow.com/q/50107559
tags question: http://stackoverflow.com/q/50193740
tags question: http://stackoverflow.com/q/50095209
tags question: http://stackoverflow.com/q/50198050
tags question: http://stackoverflow.com/q/50192452
tags question: http://stackoverflow.com/q/50140811
tag name: discord
type: Tag
tags question: http://stackoverflow.com/q/50165120
tags question: http://stackoverflow.com/q/50114952
tags question: http://stackoverflow.com/q/50084532
tags question: http://stackoverflow.com/q/50084002
tags question: http://stackoverflow.com/q/50183994
tags question: http://stackoverflow.com/q/50111010

http://stackoverflow.com/q/50229411
accepted answer: http://stackoverflow.com/a/50230153
has title: Tkinter: get variable from one frame to show as label in another frame
favorite count: 0
has body: Reference is made to How to get variable data from a class For convenience the code from the above mentioned post is repeated at the bottom in consolidated form. This code passes a variable entered in Frame PageOne to PageTwo, and when the button is pressed, the variable is printed to the console. Without success, I have been trying to set the label of PageTwo to show the variable entered on PageOne. Initially, I hoped that the code modification would be as simple as: class PageTwo(ttk.Frame): def __init__(self, parent, controller): self.controller=controller ttk.Frame.__init__(self, parent) ttk.Label(self, text='PageTwo').grid(padx=(20,20), pady=(20,20)) ... changing the last line to: ttk.Label(self, text=self.controller.app_data["name"].get()).grid(padx=(20,20), pady=(20,20)) I have tried various combinations using ideas from different posted, but it seems I am missing some fundamental reasoning. Any help would be very much appreciated by this newbie. Full code consolidated from the above referenced post: #!/usr/bin/python from Tkinter import * import ttk class MyApp(Tk): def __init__(self): Tk.__init__(self) container = ttk.Frame(self) container.pack(side="top", fill="both", expand = True) self.frames = {} self.app_data = {"name": StringVar(), "address": StringVar() } for F in (PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky = NSEW) self.show_frame(PageOne) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class PageOne(ttk.Frame): def __init__(self, parent, controller): self.controller=controller ttk.Frame.__init__(self, parent) ttk.Label(self, text='PageOne').grid(padx=(20,20), pady=(20,20)) self.make_widget(controller) def make_widget(self, controller): #self.some_input = StringVar self.some_entry = ttk.Entry(self, textvariable=self.controller.app_data["name"], width=8) self.some_entry.grid() button1 = ttk.Button(self, text='Next Page', command=lambda: controller.show_frame(PageTwo)) b…
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/32212408
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/50230153
has answer: http://stackoverflow.com/a/50229761
possible better answer: http://stackoverflow.com/a/50229761
downvote count: 0

http://stackoverflow.com/q/50209661
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87436499
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/87436406
has title: Easy way for medical image classification using neural networks (using python) without training it in my machine
score: 0
tagged with: conv-neural-network
has body: i have been searching for a way to use neural networks for medical image classification , but i havent found anything except tensorflow or keras code for 3d image classification which considering the size of the data, will probably take a lot of time to train. Is there a way to either find a pretrained nn for medical image classification , or use an existing pretrained nn combined with my own layers to train a 3d medical image classification nn in a short time? Thank you!
has comment: http://stackoverflow.com/comment/120861410
answer count: 0
has comment: http://stackoverflow.com/comment/87436347
has comment: http://stackoverflow.com/comment/87436388
tagged with: keras
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/87221560
score: 0
type: AnswerComment
has text: My mistake. Corrected the input and it works. But the code breaks if I have nested lists, like in the case of the example I've added (edited).
comment on: http://stackoverflow.com/a/50101183
type: Comment

http://stackoverflow.com/q/50080389
has comment: http://stackoverflow.com/comment/89983402
tagged with: python
has comment: http://stackoverflow.com/comment/123893005
tagged with: calculus
answer count: 0
score: 1
has body: I am trying to plot potential values as a function of x and y and use this to plot the electric field as a vector field. I am not succeeding in plotting the vector field as it seems that in order to use numpy.gradient I need to either know function for my data, or have my data in some other form. Currently I have data in the form: x = [3,3,3...9] y = [1,2,3...9] # v is potential as a function of the corresponding x and y values. v = [0.436744, 0.411724...3.626803] My code so far simply extracts the data from a file and then plots a contour and contourf plot using matplotlib as follows. import numpy as np from matplotlib import cm import matplotlib.pyplot as plt contours=plt.tricontour(x, y, v, colors='k',linewidths=2,linestyles='solid') plt.tricontourf(x, y, v, cmap=cm.hsv) plt.clabel(contours, inline=1, fontsize=14) plt.colorbar() plt.show() It seems that I should be using np.gradient coupled with plt.quiver(x, y, E) where E is the electric field - using the fact that E=-Grad(V). Here is an example of my current output: I am trying to get it to look something like this: Please notice the vector field overlaid. Here the following code was used: # Contour plot for regular grid dx = 0.1 dy = 0.1 xr = np.arange(-1, 1, dx) yr = np.arange(-1, 1, dy) # Create grid corresponding to xr and yr arrays xx, yy = np.meshgrid (xr, yr, indexing = 'ij') zz = xx + yy*yy gradx, grady = np.gradient (zz, dx, dy) n = 20 #l = np.array([0.0, 0.5, 1.0, 1.5, 2.0]) plt.contourf(xx, yy, zz, n) plt.contour(xx, yy, zz, levels = l, colors = 'k', linewidths = 1, linestyles = 'solid') plt.quiver(xx, yy, gradx , grady) plt.show() The difference in the two situations is that in my situation I don't have a known function which can be used to calculate the gradient of the scalar field. In the latter situation the function is known, and thus the gradient can be calculated. I'm not sure how to proceed from here because of this difference. Thanks in advance for any guidance and help you can provide.
has title: Python: Getting a Vector Field from Gradient of Scalar Field
downvote count: 1
has comment: http://stackoverflow.com/comment/87189673
linked to: http://stackoverflow.com/q/39168471
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
tagged with: physics
tagged with: matplotlib

http://stackoverflow.com/q/50223388
favorite count: 0
has title: Adding unique labels with matplotlib in for loop
tagged with: python-2.7
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87464454
has body: Is it possible to add a different label to each line that's plotted in a for loop? I want the label to depend on the iterating element i. Say I have a list of length 4 called my_list, and I want to do the following: import matplotlib.pyplot as plt my_list = [1, 2, 3, 4] other_list = [[1, 1.2, 1.4, 1.6], [0.8, 0.9, 0.7, 0.6], [1.9, 1.3, 1.4, 1.0], [0.1, 0.2, 0.4, 0.6]] for i in range(len(my_list)): plt.plot(my_list, other_list[i], label='Line %s' % i) plt.legend('upper left') I want the labels to appear as Line 0, ..., Line 3 depending on what i is in the loop. But I'm not getting this -- my labels are appearing as letters u, p, p, and e for some reason. I've also tried label='Line'+str(i), and got the same output.
type: Question
score: 0
tagged with: for-loop
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87464264
upvote count: 1
has comment: http://stackoverflow.com/comment/87464353
tagged with: label
downvote count: 1

http://stackoverflow.com/comment/87510062
has text: @NANGAPARBATSUMARNO you got it
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50231770

http://stackoverflow.com/q/50134183
upvote count: 3
tagged with: list
downvote count: 2
score: 1
has answer: http://stackoverflow.com/a/50134300
accepted answer: http://stackoverflow.com/a/50134300
possible better answer: http://stackoverflow.com/a/50134254
has answer: http://stackoverflow.com/a/50134316
has answer: http://stackoverflow.com/a/50134254
has comment: http://stackoverflow.com/comment/87286318
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87286293
has answer: http://stackoverflow.com/a/50134280
has body: I have two nested lists, like this: list_1 = [[4,9,2],[3,5,7],[8,1,5]] list_2 = [[4,9,2],[3,5,7],[8,1,6]] I want to find the different values in between this two nested lists, and also it's differences. In the above lists, the different values are 5 and 6, so the difference is: -1(5-6). Note that no common values will be listed. I want to store it in a list and print it's output: [-1] Another example: list_1 = [[3, 6, 7], [4, 9, 9], [7, 6, 9]] list_2 = [[6, 7, 2], [1, 5, 9], [8, 3, 4]] The output should be like this: [-3,-1,5,3,4,-1,3,5] If all of them are common, it should return an empty list: []
tagged with: python
has comment: http://stackoverflow.com/comment/87286325
answer count: 4
has title: How to find different values in a nested list and find it's differences in Python 3?
type: AnsweredQuestion

http://stackoverflow.com/comment/87225688
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50104182
score: 2
has text: `int(some_expression)` _doesn't_ say "use integer arithmetic to evaluate `some_expression`". `int()` is the integer constructor, and if you pass it some expression, it will evaluate that expression, and then try to construct an integer from it.

http://stackoverflow.com/a/50201511
downvote count: 1
has comment: http://stackoverflow.com/comment/87419709
has body: print("Your current score is %d out of 10" %score) Take a look at printf-style string formatting for details on formatting and inserting other types of data into a printed string.
answers question: http://stackoverflow.com/q/50201412
type: Answer
score: 0
upvote count: 1

list
tags question: http://stackoverflow.com/q/50151504
tags question: http://stackoverflow.com/q/50099100
type: Tag
tags question: http://stackoverflow.com/q/50095092
tags question: http://stackoverflow.com/q/50180035
tags question: http://stackoverflow.com/q/50180726
tags question: http://stackoverflow.com/q/50115038
tags question: http://stackoverflow.com/q/50137307
tags question: http://stackoverflow.com/q/50080854
tags question: http://stackoverflow.com/q/50083493
tags question: http://stackoverflow.com/q/50105087
tags question: http://stackoverflow.com/q/50101108
tags question: http://stackoverflow.com/q/50154261
tags question: http://stackoverflow.com/q/50180242
tags question: http://stackoverflow.com/q/50187956
tags question: http://stackoverflow.com/q/50148413
tags question: http://stackoverflow.com/q/50092680
tags question: http://stackoverflow.com/q/50218054
tags question: http://stackoverflow.com/q/50122098
tags question: http://stackoverflow.com/q/50116416
tags question: http://stackoverflow.com/q/50195991
tags question: http://stackoverflow.com/q/50085411
tags question: http://stackoverflow.com/q/50108648
tags question: http://stackoverflow.com/q/50180303
tags question: http://stackoverflow.com/q/50211352
tags question: http://stackoverflow.com/q/50122266
tags question: http://stackoverflow.com/q/50170673
tags question: http://stackoverflow.com/q/50078552
tags question: http://stackoverflow.com/q/50142116
tags question: http://stackoverflow.com/q/50137159
tags question: http://stackoverflow.com/q/50085431
tags question: http://stackoverflow.com/q/50078807
tags question: http://stackoverflow.com/q/50138511
tags question: http://stackoverflow.com/q/50166824
tags question: http://stackoverflow.com/q/50215117
tags question: http://stackoverflow.com/q/50213196
tags question: http://stackoverflow.com/q/50122334
tags question: http://stackoverflow.com/q/50098338
tags question: http://stackoverflow.com/q/50189457
tags question: http://stackoverflow.com/q/50172448
tags question: http://stackoverflow.com/q/50204441
tags question: http://stackoverflow.com/q/50100019
tags question: http://stackoverflow.com/q/50220182
tags question: http://stackoverflow.com/q/50186374
tags question: http://stackoverflow.com/q/50189243
tags question: http://stackoverflow.com/q/50160715
tags question: http://stackoverflow.com/q/50229639
tags question: http://stackoverflow.com/q/50122198
tags question: http://stackoverflow.com/q/50153281
tags question: http://stackoverflow.com/q/50184575
tags question: http://stackoverflow.com/q/50101507
tags question: http://stackoverflow.com/q/50205103
tags question: http://stackoverflow.com/q/50084903
tags question: http://stackoverflow.com/q/50155802
tags question: http://stackoverflow.com/q/50133876
tags question: http://stackoverflow.com/q/50219735
tags question: http://stackoverflow.com/q/50144717
tags question: http://stackoverflow.com/q/50094461
tags question: http://stackoverflow.com/q/50180289
tags question: http://stackoverflow.com/q/50143660
tags question: http://stackoverflow.com/q/50155943
tags question: http://stackoverflow.com/q/50199319
tags question: http://stackoverflow.com/q/50092665
tags question: http://stackoverflow.com/q/50126058
tags question: http://stackoverflow.com/q/50186723
tags question: http://stackoverflow.com/q/50161493
tags question: http://stackoverflow.com/q/50161630
tags question: http://stackoverflow.com/q/50221507
tags question: http://stackoverflow.com/q/50181969
tags question: http://stackoverflow.com/q/50124629
tags question: http://stackoverflow.com/q/50143769
tags question: http://stackoverflow.com/q/50176916
tags question: http://stackoverflow.com/q/50224226
tags question: http://stackoverflow.com/q/50165123
tags question: http://stackoverflow.com/q/50091949
tags question: http://stackoverflow.com/q/50134183
tags question: http://stackoverflow.com/q/50218908
tags question: http://stackoverflow.com/q/50224316
tags question: http://stackoverflow.com/q/50150148
tags question: http://stackoverflow.com/q/50124901

merge
type: Tag
tags question: http://stackoverflow.com/q/50192737
tags question: http://stackoverflow.com/q/50168532
tags question: http://stackoverflow.com/q/50226791
tags question: http://stackoverflow.com/q/50084992
tags question: http://stackoverflow.com/q/50119131
tags question: http://stackoverflow.com/q/50106519
tags question: http://stackoverflow.com/q/50089228
tag name: merge
tags question: http://stackoverflow.com/q/50124679
tags question: http://stackoverflow.com/q/50192970
tags question: http://stackoverflow.com/q/50100089
tags question: http://stackoverflow.com/q/50075175
tags question: http://stackoverflow.com/q/50126154
tags question: http://stackoverflow.com/q/50207995
tags question: http://stackoverflow.com/q/50157773

http://stackoverflow.com/comment/87286827
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50134463
has text: See [`datetime.date.strftime()`](https://docs.python.org/3/library/datetime.html#datetime.date.strftime)

http://stackoverflow.com/q/50196712
has answer: http://stackoverflow.com/a/50196891
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/3972872
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50196891
has title: elegant way to fill dictionary with variables in python
linked to: http://stackoverflow.com/q/1832940
linked to: http://stackoverflow.com/q/39818733
has comment: http://stackoverflow.com/comment/87410392
has body: I'm searching for an elegant more generic way to fill a dictionary with variables: dic = {} fruit = 'apple' vegetable = 'potato' dic['fruit'] = fruit dic['vegetable'] = vegetable is there a more generic way without using the variable-name in quotes ?
tagged with: python
has answer: http://stackoverflow.com/a/50196758
possible better answer: http://stackoverflow.com/a/50196758

http://stackoverflow.com/q/50198546
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: backtracking
tagged with: recursion
has title: How to fix my sudoku solver based on backtracking
score: 0
has answer: http://stackoverflow.com/a/50198595
has body: I tried to create a sudoku solver algorithm using python and based on backtracking but it always return nothing saying that the sudoku is incorrect. Here is my code: board = [[3,0,6,5,0,8,4,0,0], [5,2,0,0,0,0,0,0,0], [0,8,7,0,0,0,0,3,1], [0,0,3,0,1,0,0,8,0], [9,0,0,8,6,3,0,0,5], [0,5,0,0,9,0,6,0,0], [1,3,0,0,0,0,2,5,0], [0,0,0,0,0,0,0,7,4], [0,0,5,2,0,6,3,0,0]] e = [0, 0] def checkEmpty(): for i in range(0, 9): for j in range(0, 9): if board[i][j] == 0: e[0] = i e[1] = j return True return False def vLine(i, test): for j in range(9): if board[i][j] == test: return True return False def vColumn(j, test): for i in range(9): if board[i][j] == test: return True return False def vBlock(i, j, test): for I in range(3): for J in range(3): if(board[i+I][j + J] == test): return True return False def validMove(i, j, test): if vColumn(j, test) == False and vBlock(i, j, test) == False and vLine(i, test) == False: return True else: return False def solve(): e = [0, 0] if checkEmpty() == False: return True i = e[0] j = e[1] for k in range(1, 10): if validMove(i, j, k) == True: board[i][j] = k if solve() == True: return True board[i][j] = 0 return False if solve(): print("solved!") else: print("No solution exists") The problem is that the code inside this if function if validMove(i, j, k) == True: seems to never be executed. However I was unable to find any error in this function. In addition, I don't really know whether I should indent, dedent or keep this line board[i][j] = 0 here.
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50229210
has comment: http://stackoverflow.com/comment/87475837
has body: I use django-tenant-schemas and I need to change the way it selects the current tenant: from https:// tenant1.mydomain.com/ to https:// mydomain.com/tenant1/ To do that I've coded a middleware, it's quite simple and it's working, the tenant is selected. The problem comes in the url resolution in django. It raises a 404 cause there is no url mapping that includes that suffix "tenant1". How could I tell django that the urls now have a dinamic suffix that changes deppending on the tenant? This should be used reversing and generating urls.
score: 1
has comment: http://stackoverflow.com/comment/87477045
downvote count: 0
favorite count: 0
has title: Support for url suffix in django
type: Question
has comment: http://stackoverflow.com/comment/87477280
answer count: 0
tagged with: multi-tenant
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87478734

http://stackoverflow.com/comment/87391737
type: AnswerComment
comment on: http://stackoverflow.com/a/50187392
has text: This is what I've done: https://pastebin.com/Gc4vHshM. But it's still not working... `no such column: api_user.content_type_id`.
type: Comment
score: 0

http://stackoverflow.com/a/50217944
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has body: If the issue is simply to only use one random library (as you said in your comments), you could just use numpy.random.choice with the argument replace=False, which ensures each element is not repeated: import numpy as np a = np.stack([np.random.choice(range(10), 10, replace=False) for _ in range(5)]) &gt;&gt;&gt; a array([[0, 9, 3, 5, 8, 7, 1, 4, 6, 2], [5, 6, 8, 3, 0, 4, 7, 9, 2, 1], [7, 4, 9, 5, 0, 1, 6, 8, 3, 2], [9, 0, 3, 8, 5, 7, 6, 1, 4, 2], [5, 6, 0, 1, 3, 4, 9, 8, 7, 2]])
answers question: http://stackoverflow.com/q/50217834
type: Answer
accepted answer of: http://stackoverflow.com/q/50217834

http://stackoverflow.com/q/50080548
has title: Python: does gzip write to disk when opening a file for read?
type: Question
has comment: http://stackoverflow.com/comment/87177037
type: UnansweredQuestion
tagged with: gzip
tagged with: python
has answer: http://stackoverflow.com/a/50088560
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has body: I am writing a program that reads .gz archived log files from an SD card. If I open a .gz archive for reading using the gzip library, will it write a temporary copy to the SD card (I don't want it to), or does it decompress the file in RAM?
favorite count: 0

http://stackoverflow.com/q/50148502
tagged with: jupyter-notebook
has title: Jupyter Notebook; Cannot use columns which are not shown on Jupyter notebook
has answer: http://stackoverflow.com/a/50148675
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has body: I'm trying to do create plot using columns on pandas. But the number of columns are many and some of the columns are not shown on Jupyter notebook. And when I use the columns which are not shown on Jupyter Notebook, the plot cannot be created corrctly. Like when I do this, sns.pairplot(data'col1', 'col13(cannot see on Jupyter Notebook)') col1 is used as y-label instead of col13(cannot see on Jupyter Notebook). How can I fix this?
type: Question
accepted answer: http://stackoverflow.com/a/50148675
tagged with: python

http://stackoverflow.com/comment/87460534
has text: the packages mentioned on [THIS LIST](http://www.python-excel.org/) would help
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50221514

http://stackoverflow.com/q/50189575
has title: Error when trying to download stock price data from Morningstar
tagged with: pandas
tagged with: finance
has body: import math import pandas_datareader.data as web import matplotlib.pyplot as plot from datetime import datetime from matplotlib import style style.use('ggplot') import csv with open('sp500const.csv', newline='') as File: reader = csv.reader(File) dataa=[] for i in reader: dataa.extend(i) Dates=[] Prices=[] Tick=[] for stock in dataa[2:100]: for year in range(2010,2019): if year==2012: start = datetime(year,5,1) end=datetime(year,5,1) f = web.DataReader(stock, 'morningstar', start, end) temp=f['Close'] Prices.append(float(temp)) Dates.append(end.strftime('%m/%d/%Y')) Tick.append(stock) elif year==2013: start=datetime(year,5,3) end=datetime(year,5,3) f = web.DataReader(stock, 'morningstar', start, end) temp=f['Close'] Prices.append(float(temp)) Dates.append(end.strftime('%m/%d/%Y')) Tick.append(stock) elif year==2014: start=datetime(year,5,5) end=datetime(year,5,5) f = web.DataReader(stock, 'morningstar', start, end) temp=f['Close'] Prices.append(float(temp)) Dates.append(end.strftime('%m/%d/%Y')) Tick.append(stock) else: start=datetime(year,5,4) end=datetime(year,5,4) f = web.DataReader(stock, 'morningstar', start, end) temp=f['Close'] Prices.append(float(temp)) Dates.append(end.strftime('%m/%d/%Y')) Tick.append(stock) #datetime(Year,Month,Days) x=[Tick,Dates,Prices] z=[list(i) for i in zip(*x)] print(z) I want to download data for the S&amp;500 Constituents, whose tickers are in the sp500const.csv file[Tickers as reported from wikipedia.com] for the dates 2011-2018. When i change the number of tickers to be downloaded (for example in the code now, I want to download stock prices for tickers dataa[2:100]). When i choose for instance data[2:4] the code works perfectly. I get the following error: Traceback (most recent call last): File "&lt;ipython-input-5-5592627b16bf&gt;", line 44, in &lt;module&gt; f = web.DataReader(stock, 'morningstar', start, end) File "C:\Users\coxs\Miniconda3\lib\site-packages\pandas_datareader\data.py", line 391, in DataReader session=session,…
tagged with: stockquotes
tagged with: error-handling
has answer: http://stackoverflow.com/a/50826930
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87529742
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
downvote count: 1
score: 0

http://stackoverflow.com/comment/87351979
type: QuestionComment
comment on: http://stackoverflow.com/q/50164016
has text: Due to a change in how `argparse` tests for required arguments, subparsers are now optional, at least in PY3. https://stackoverflow.com/questions/23349349/argparse-with-required-subparser. Any ways I think the linked answer is still relevant to this issue.
score: 0
type: Comment

http://stackoverflow.com/comment/87368940
type: QuestionComment
has text: You can try `logger.log(exc.args[0])` since the KeyError was passed to the APIException constructor. But you would have to do more work if you have different Exception-ception levels.
comment on: http://stackoverflow.com/q/50175875
score: 0
type: Comment

http://stackoverflow.com/a/50181686
answers question: http://stackoverflow.com/q/50180707
has comment: http://stackoverflow.com/comment/87380700
has comment: http://stackoverflow.com/comment/87380732
type: Answer
has comment: http://stackoverflow.com/comment/87380934
has body: The following works for me if I put (exactly) the JSON data shown in your question into a jsonfile.txt file and run it: import json with open ("jsonfile.txt", 'r') as f: j = json.loads(f.read()) print(json.dumps(j, indent=4)) Output: [ { "sensorType": "Radarcape", "sensorLatitude": { "double": 51.758894 }, "sensorLongitude": { "double": -1.256654 }, "sensorAltitude": { "double": 200.0 }, "timeAtServer": 1429617600.000027, "timeAtSensor": null, "timestamp": { "double": 968628281.0 }, "rawMessage": "8d4008f999059a90c09719d7b430", "sensorSerialNumber": 13020235, "RSSIPacket": { "double": 52.0 }, "RSSIPreamble": null, "SNR": null, "confidence": null }, { "sensorType": "Radarcape", "sensorLatitude": { "double": 51.758894 }, "sensorLongitude": { "double": -1.256654 }, "sensorAltitude": { "double": 200.0 }, "timeAtServer": 1429617600.001544, "timeAtSensor": null, "timestamp": { "double": 974843812.0 }, "rawMessage": "8f406a9a5913d2d51fbe8ab14fdf", "sensorSerialNumber": 13020235, "RSSIPacket": { "double": 72.0 }, "RSSIPreamble": null, "SNR": null, "confidence": null } ]
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50180707
score: 1
upvote count: 1

http://stackoverflow.com/q/50091972
tagged with: string
has body: I want to replace a character on every line when the line match with my lookup_keyword. I managed to came up with below solutions. But the finaljoin only write the changes on the new file (only affected line is being written back) How can I write unaffected line together in a new file? I know that we can use fileinput inplace editing but that more suitable for keyword replacing. Example input file, 123456789 [Thanos] 123456789 [Thanos] 123456789 [Thor] 123456789 [Loki] Example output file, 1AA345KK789 [Thanos] 1AA345KK789 [Thanos] Expected output file that I actually wanted. 1AA345KK789 [Thanos] 1AA345KK789 [Thanos] 123456789 [Thor] 123456789 [Loki] lookup_keyword= "Thanos" with open(filename) as myFile: # myFile,1 means start reading the line at line number one. # By default python will read start from 0. for num, line in enumerate(myFile, 1): if lookup_keyword in line: #print ('Found at line:', num) s = list(line) s[1] = 'AA' s[5] = 'KK' # join the list to a original string form finaljoin = "".join(s) #print (finaljoin) with open(new_filename, 'a+') as f: f.write(finaljoin)
type: Question
tagged with: file-io
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50118393
tagged with: python
has comment: http://stackoverflow.com/comment/87200228
score: 0
has title: How to change a line in python without using fileinput inplace?
answer count: 2
has answer: http://stackoverflow.com/a/50092057

tensorflow
tags question: http://stackoverflow.com/q/50190486
tags question: http://stackoverflow.com/q/50099745
tags question: http://stackoverflow.com/q/50081333
tags question: http://stackoverflow.com/q/50152548
tags question: http://stackoverflow.com/q/50144314
tags question: http://stackoverflow.com/q/50101292
tags question: http://stackoverflow.com/q/50222149
tags question: http://stackoverflow.com/q/50137369
type: Tag
tags question: http://stackoverflow.com/q/50216161
tags question: http://stackoverflow.com/q/50130307
tags question: http://stackoverflow.com/q/50089597
tags question: http://stackoverflow.com/q/50125058
tags question: http://stackoverflow.com/q/50101699
tags question: http://stackoverflow.com/q/50104908
tags question: http://stackoverflow.com/q/50078288
tags question: http://stackoverflow.com/q/50100766
tags question: http://stackoverflow.com/q/50085955
tags question: http://stackoverflow.com/q/50166780
tags question: http://stackoverflow.com/q/50076420
tags question: http://stackoverflow.com/q/50179709
tags question: http://stackoverflow.com/q/50189748
tags question: http://stackoverflow.com/q/50171348
tags question: http://stackoverflow.com/q/50130936
tags question: http://stackoverflow.com/q/50210953
tags question: http://stackoverflow.com/q/50187342
tags question: http://stackoverflow.com/q/50167531
tags question: http://stackoverflow.com/q/50122440
tags question: http://stackoverflow.com/q/50142583
tags question: http://stackoverflow.com/q/50206619
tags question: http://stackoverflow.com/q/50107985
tags question: http://stackoverflow.com/q/50142626
tags question: http://stackoverflow.com/q/50166288
tags question: http://stackoverflow.com/q/50152572
tags question: http://stackoverflow.com/q/50180886
tags question: http://stackoverflow.com/q/50098065
tags question: http://stackoverflow.com/q/50113938
tags question: http://stackoverflow.com/q/50134090
tags question: http://stackoverflow.com/q/50149953
tags question: http://stackoverflow.com/q/50125944
tags question: http://stackoverflow.com/q/50222699
tags question: http://stackoverflow.com/q/50140500
tags question: http://stackoverflow.com/q/50210785
tags question: http://stackoverflow.com/q/50149638
tags question: http://stackoverflow.com/q/50169945
tags question: http://stackoverflow.com/q/50178850
tags question: http://stackoverflow.com/q/50116244
tags question: http://stackoverflow.com/q/50185888
tags question: http://stackoverflow.com/q/50166810
tags question: http://stackoverflow.com/q/50197878
tags question: http://stackoverflow.com/q/50176515
tags question: http://stackoverflow.com/q/50129898
tags question: http://stackoverflow.com/q/50127527
tags question: http://stackoverflow.com/q/50201953
tags question: http://stackoverflow.com/q/50203015
tags question: http://stackoverflow.com/q/50117745
tags question: http://stackoverflow.com/q/50077958
tags question: http://stackoverflow.com/q/50115858
tags question: http://stackoverflow.com/q/50081529
tags question: http://stackoverflow.com/q/50113009
tags question: http://stackoverflow.com/q/50097149
tags question: http://stackoverflow.com/q/50109629
tags question: http://stackoverflow.com/q/50083055
tags question: http://stackoverflow.com/q/50146239
tags question: http://stackoverflow.com/q/50109656
tags question: http://stackoverflow.com/q/50110070
tags question: http://stackoverflow.com/q/50205805
tags question: http://stackoverflow.com/q/50092110
tags question: http://stackoverflow.com/q/50128278
tags question: http://stackoverflow.com/q/50216747
tags question: http://stackoverflow.com/q/50169580
tags question: http://stackoverflow.com/q/50164004
tags question: http://stackoverflow.com/q/50198842
tags question: http://stackoverflow.com/q/50152743
tags question: http://stackoverflow.com/q/50210594
tags question: http://stackoverflow.com/q/50178711
tags question: http://stackoverflow.com/q/50114065
tags question: http://stackoverflow.com/q/50158402
tags question: http://stackoverflow.com/q/50113650
tags question: http://stackoverflow.com/q/50109718

http://stackoverflow.com/q/50166824
type: Question
tagged with: python-3.x
tagged with: list
tagged with: random
answer count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87351597
downvote count: 0
linked to: http://stackoverflow.com/q/306400
favorite count: 0
has title: Generate a random string from a list for each iteration
has comment: http://stackoverflow.com/comment/87352289
linked to: http://stackoverflow.com/q/12501956
has body: I need to generate a random amount of string for a certain amount of times; so for example: for k in range(5): print("Country", location) print("Animal", animal) so location and animal will be randomly generated from a list, and each of the 5 times it gets printed, it will have random number of locations and animal, so for every iteration a random number of locations and animals will be printed from a given list
has comment: http://stackoverflow.com/comment/87351474
duplicate of: http://stackoverflow.com/q/306400
has comment: http://stackoverflow.com/comment/87351538
tagged with: python
has comment: http://stackoverflow.com/comment/87351727
duplicate of: http://stackoverflow.com/q/12501956
has comment: http://stackoverflow.com/comment/87351752

http://stackoverflow.com/q/50107054
duplicate of: http://stackoverflow.com/q/22005911
tagged with: pandas
has answer: http://stackoverflow.com/a/50107101
tagged with: python
has comment: http://stackoverflow.com/comment/87231450
type: Question
has comment: http://stackoverflow.com/comment/87240383
type: UnansweredQuestion
answer count: 1
has title: I've Mixed values in a column (string+float) in data frame how can i change them to object
linked to: http://stackoverflow.com/q/22005911
has body: I have a data frame where few of columns have mixed type values string + float and when I'm writing them to_excel getting this notification after writing in excel enter image description here this is the dataframe df = placementsummaryfinalnew.loc[:,["Placement# Name","PRODUCT","Engagements Rate", "Viewer CTR","Engager CTR","Viewer VCR", "Engager VCR","Interaction Rate","Active Time Spent"]] I tried to convert them by using few of lines placementvdxsummaryfirst["Viewer VCR"] = placementvdxsummaryfirst["Viewer VCR"].astype(object) its not working then I tried this one. placementvdxsummaryfirst["Viewer VCR"] = placementvdxsummaryfirst["Viewer VCR"].astype(float) its giving error then I tried this one. placementvdxsummaryfirst['Viewer VCR'] = pd.to_numeric(placementvdxsummaryfirst['Viewer VCR'],errors='coerce') its working but its replacing the "N/A" values with blanks which I don't want. Kindly help.
score: 0

http://stackoverflow.com/q/50172958
tagged with: pandas
has body: I have this dataset (105233 rows x 32 columns matrix), from which I deleted the first column with .drop. At this point what I should do is to analyze each row (an array of 32 components) and look for those the first 16 terms are equal to the last 16. { import pandas as pd import numpy as np data = pd.read_csv('enummixed.txt', header = None, low_memory=False) data = data.drop(data.columns[[0]], axis=1) print data 1 2 3 4 5 6 7 8 9 10 ... \ 0 1 0 0 0 0 0 0 0 0 0 ... 1 1 0 0 0 0 0 0 0 0 0 ... 2 1 0 0 0 0 0 0 0 0 0 ... 3 1 0 0 0 0 0 0 0 0 0 ... 4 1 0 0 0 0 0 0 0 0 0 ... 5 1 0 0 0 0 0 0 0 0 0 ... 6 1 0 0 0 0 0 0 0 0 0 ... 7 1 0 0 0 0 0 0 0 0 0 ... 8 106/243 137/243 0 0 0 0 0 0 0 0 ... 9 106/243 137/243 0 0 0 0 0 0 0 0 ... 10 106/243 137/243 0 0 0 0 0 0 0 0 ... 11 106/243 137/243 0 0 0 0 0 0 0 0 ... 12 106/243 137/243 0 0 0 0 0 0 0 0 ... 13 106/243 137/243 0 0 0 0 0 0 0 0 ... 14 106/243 137/243 0 0 0 0 0 0 0 0 ... 15 106/243 137/243 0 0 0 0 0 0 0 0 ... 16 106/243 137/243 0 0 0 0 0 0 0 0 ... 17 106/243 137/243 0 0 0 0 0 0 0 0 ... 18 106/243 137/243 0 0 0 0 0 0 0 0 ... 19 106/243 137/243 0 0 0 0 0 0 0 0 ... 20 106/243 137/243 0 0 0 0 0 0 0 0 ... 21 106/243 137/243 0 0 0 0 0 0 0 0 ... 22 106/243 137/243 0 0 0 0 0 0 0 0 ... 23 106/243 137/243 0 0 0 0 0 0 0 0 ... 24 106/243 137/243 0 0 0 0 0 0 0 0 ... 25 106/243 137/243 0 0 0 0 0 0 0 0 ... 26 106/243 137/243 0 0 0 0 0 0 0 0 ... 27 106/243 137/243 0 0 0 0 0 0 0 0 ... 28 106/243 137/243 0 0 0 0 0 0 0 0 ... 29 106/243 137/243 0 0 0 0 0 0 0 0 ... ... ... ... .. .. .. .. .. .. .. .. ... 105203 0 0 0 0 0 0 0 0 0 0 ... 105204 0 0 0 0 0 0 0 0 0 0 ... 105205 0 0 0 0 0 0 0 0 0 0 ... 105206 0 0 0 0 0 0 0 0 0 0 ... 105207 0 0 0 0 0 0 0 0 0 0 ... 105208 0 0 0 0 0 0 0 0 0 0 ... 105209 0 0 0 0 0 0 0 0 0 0 ... 105210 0 0 0 0 0 0 0 0 0 0 ... 105211 0 0 0 0 0 0 0 0 0 0 ... 105212 0 0 0 0 0 0 0 0 0 0 ... 105213 0 0 0 0 0 0 0 0 0 0 ... 105214 0 0 0 0 0 0 0 0 0 0 ... 105215 0 0 0 0 0 0 0 0 0 0 ... 105216 0 0 0 0 0 0 0 0 0 0 ... 105217 0 0 0 0 0 0 …
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50174550
type: Question
has comment: http://stackoverflow.com/comment/87363065
answer count: 2
type: UnansweredQuestion
tagged with: dataset
has answer: http://stackoverflow.com/a/50180839
has title: python pandas analyze dataframe
score: 0

http://stackoverflow.com/a/50206717
has body: The first output for print tensor tells you the information (dimension) of that tensor. That is a tensor of three rows and one column. However, the tf.shape(tensor) returns a 1-D integer tensor representing the shape of input. Therefore the output you see is the information (shape) about the returned tensor which you can see using: tensor.get_shape() &gt; TensorShape([Dimension(3), Dimension(1)]) which indeed, has two values.
has comment: http://stackoverflow.com/comment/87431228
type: Answer
answers question: http://stackoverflow.com/q/50206619
has comment: http://stackoverflow.com/comment/87431120
has comment: http://stackoverflow.com/comment/87431133
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87431417

http://stackoverflow.com/comment/87467740
score: 0
type: Comment
type: QuestionComment
has text: I rewrote code using `requests`, but it didn't work.
comment on: http://stackoverflow.com/q/50223940

http://stackoverflow.com/a/55713417
score: 39
upvote count: 39
type: Answer
answers question: http://stackoverflow.com/q/50202238
has body: The best practice would be to make sure requests and its dependencies are up to date. Python 2 $ pip install --upgrade requests Python 3 $ pip3 install --upgrade requests
downvote count: 0

http://stackoverflow.com/a/50194777
answers question: http://stackoverflow.com/q/50194752
downvote count: 0
score: 2
type: Answer
has body: The difference is the number of dimensions: candidates[0:1] will return a 2 dimensional array, whereas candidates[0] will return a 1 dimensional array: &gt;&gt;&gt; candidates[0:1].ndim 2 &gt;&gt;&gt; candidates[0].ndim 1 You can also kind of "see" the dimensionality by the output of candidates[0:1]: notice the number of square brackets around the array? These can be a hint at the dimensionality of an array
upvote count: 2

http://stackoverflow.com/q/50123923
upvote count: 22
has comment: http://stackoverflow.com/comment/87266215
accepted answer: http://stackoverflow.com/a/50124135
has answer: http://stackoverflow.com/a/50124135
answer count: 1
has comment: http://stackoverflow.com/comment/87266250
downvote count: 0
has comment: http://stackoverflow.com/comment/87266202
favorite count: 0
type: Question
has title: replace values in xarray dataset with None
has comment: http://stackoverflow.com/comment/87266232
tagged with: python
score: 22
has body: I want to replace values in a variable in an xarray dataset with None. I tried this approach but it did not work: da[da['var'] == -9999.]['var'] = None I get this error: *** TypeError: unhashable type: 'numpy.ndarray' Is there something like numpy replace that I could use here? da is xarray dataset. here is what da looks like: &lt;xarray.Dataset&gt; Dimensions: (band: 1, time: 3, x: 4258, y: 2334) Coordinates: * band (band) int32 1 * y (y) float64 4.406e+06 4.406e+06 4.406e+06 4.406e+06 4.406e+06 ... * x (x) float64 1.125e+05 1.126e+05 1.127e+05 1.128e+05 1.129e+05 ... * time (time) datetime64[ns] 2005-12-31 2006-12-31 2007-12-31 Data variables: var (time, band, y, x) float32 dask.array&lt;shape=(3, 1, 2334, 4258), chunksize=(1, 1, 2334, 4258)&gt; Here is what da.var looks like: &lt;xarray.DataArray 'var' (time: 3, band: 1, y: 2334, x: 4258)&gt; dask.array&lt;shape=(3, 1, 2334, 4258), dtype=float32, chunksize=(1, 1, 2334, 4258)&gt; Coordinates: * band (band) int32 1 * y (y) float64 4.406e+06 4.406e+06 4.406e+06 4.406e+06 4.406e+06 ... * x (x) float64 1.125e+05 1.126e+05 1.127e+05 1.128e+05 1.129e+05 ... * time (time) datetime64[ns] 2005-12-31 2006-12-31 2007-12-31 Attributes: transform: (90.0, 0.0, 112500.0, 0.0, -90.0, 4406400.0, 0.0, 0.0, 1.0) crs: +ellps=GRS80 +no_defs +proj=utm +towgs84=0,0,0,0,0,0,0 +unit... res: (90.0, 90.0) is_tiled: 1 nodatavals: (-9999.0,)
tagged with: python-xarray
type: AnsweredQuestion

http://stackoverflow.com/a/50207078
type: AcceptedAnswer
has body: In the app GetDocList we are getting DocIds not app ids , So when requesting for OpenDoc method we need to provide doc_id not app_id
type: Answer
accepted answer of: http://stackoverflow.com/q/50133907
score: 0
answers question: http://stackoverflow.com/q/50133907

http://stackoverflow.com/q/50090810
has comment: http://stackoverflow.com/comment/87198389
has answer: http://stackoverflow.com/a/50090882
has body: My question is how can I implement a list within this program and make it so that when the user inputs a password it saves to a .txt document? I've tried but I can't make it work so this is the plain code that i need to add the feature too. Thanks for the help! The program also uses client/server but i haven't included that within this segment of my code as i didnt think it would be relevant. Thanks! users = {} status = "" def displayMenu(): status = input("Are you registered user? Please write yes or no. Press q to quit") if status == "yes": oldUser() elif status == "no": newUser() def newUser(): createLogin = input("Create login name: ") if createLogin in users: print("\nLogin name already exist!\n") else: createPassw = input("Create password: ") users[createLogin] = createPassw print("\nUser created\n") def oldUser(): login = input("Enter login name: ") passw = input("Enter password: ") if login in users and users[login] == passw: print("\nLogin successful! Your credentials have been saved.\n") else: print("\nUser doesn't exist or wrong password!\n") while status != "q": displayMenu()
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Save passwords to txt document and implement a list
tagged with: python
has comment: http://stackoverflow.com/comment/87197859
score: -1

http://stackoverflow.com/q/50161648
tagged with: python
tagged with: tree
has comment: http://stackoverflow.com/comment/87341322
has answer: http://stackoverflow.com/a/50161895
score: 0
has comment: http://stackoverflow.com/comment/87341241
answer count: 1
has body: Apologies in advance for the open-ended nature of this question but I'm currently brainstorming a way to tackle an automation problem using Python. A set of data I'm analyzing can be thought of as a tree that looks like the following: There are two parts to my question, first the tricky portion, and then more of a general implementation question. For a given top level parent node (a node which has no parent), how do I find the path to a bottom level child node (a node with no children) ONLY for bottom nodes that are in a set of values I define? For instance if I define the set of values as "B" and "F" only, I would only want to extract the path from A to B and A to F only. As in, I should get [A -> Y -> B] and [A -> Z -> C -> F] as an answer. Given the requirements above, what is the best way to represent these trees in Python? My original thought was nested dictionaries where each node is defined as a dictionary key. Keep in mind the example I gave is a simple one. I will be building these trees for many different top level parents, and each top level parent may have many, many child nodes.
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: Finding Paths between Parent Node and specific Child Nodes in a Tree

http://stackoverflow.com/comment/87358787
comment on: http://stackoverflow.com/q/50170649
type: QuestionComment
score: 0
has text: I don't understand at all what you are doing with that `answers` method. The data is found in `self.cleaned_data` directly, you don't ever want to reference `self.fields` there.
type: Comment

http://stackoverflow.com/q/50196561
tagged with: matplotlib
downvote count: 0
linked to: http://stackoverflow.com/q/45071628
tagged with: python
has answer: http://stackoverflow.com/a/50200567
linked to: http://stackoverflow.com/q/24886625
has body: This question is similar to the ones here and here but none of the solutions there work perhaps because I´m using a different environment (PyCharm on Mac OS). In a virtual environment with PyCharm running on 2.7.15, matplotlib installed without any complaints, and a one-line PyCharm python file with the following content... import matplotlib.pyplot as plt ...the console outputs the following error when running this one-line file: /Users/jbs/PycharmProjects/WakeUp/env/bin/python /Users/jbs/PycharmProjects/WakeUp/InputSound/WakeInputSound-and-plot-it-trial3.py Traceback (most recent call last): File "/Users/jbs/PycharmProjects/WakeUp/InputSound/WakeInputSound-and-plot-it-trial3.py", line 2, in &lt;module&gt; import matplotlib.pyplot as plt File "/Users/jbs/PycharmProjects/WakeUp/env/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/Users/jbs/PycharmProjects/WakeUp/env/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup [backend_name], 0) File "/Users/jbs/PycharmProjects/WakeUp/env/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py", line 17, in &lt;module&gt; from matplotlib.backends import _macosx RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. Any help resolving this would be most welcomed. I´ve tried about a dozen things and none seems to work... (import matplotlib alone does not give problems and this question may be related to this one but it´s clearly different...)
type: AnsweredQuestion
score: 2
tagged with: pycharm
tagged with: installation
linked to: http://stackoverflow.com/q/26289473
answer count: 1
tagged with: macos
favorite count: 0
type: Question
has title: Python on Mac OS Pycharm gives framework error with "import matplotlib.pyplot as plt"
linked to: http://stackoverflow.com/q/21784641
upvote count: 2
accepted answer: http://stackoverflow.com/a/50200567

http://stackoverflow.com/q/50145945
tagged with: python
has answer: http://stackoverflow.com/a/50146102
has title: Python extract quantifiable text (numbers)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87310171
score: 1
tagged with: regex
has answer: http://stackoverflow.com/a/50146044
has comment: http://stackoverflow.com/comment/87310215
tagged with: nlp
possible better answer: http://stackoverflow.com/a/50146102
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87310170
accepted answer: http://stackoverflow.com/a/50146044
has body: Hello I want to use python and extract text that is either a numeric value or a number spelled out plus the first word before and after the found value. Example text: I have 2 brothers and they bought one car each. My oldest brother invested 1,000 dollars. Expected Output: 'have 2 brothers', 'bought one car', 'invested 1,000 dollars' I have tried this > &gt;&gt;&gt; import re &gt;&gt;&gt; str = "I have 2 brothers and they bought one car each. My oldest brother invested 1,000 dollars." &gt;&gt;&gt; print re.findall("\d+", s) ['2'] however this only worked for finding a value not the spelled out term one. I also do not know what to use to get the word before and after the found word.
answer count: 2
has comment: http://stackoverflow.com/comment/87310292
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/96565188
score: 0
type: Comment
has text: Do you know how to do it using Keras layers?
comment on: http://stackoverflow.com/a/52750845
type: AnswerComment

http://stackoverflow.com/q/50105249
has answer: http://stackoverflow.com/a/50314278
score: 4
has title: Implementing back propagation using numpy and python for cleveland dataset
tagged with: backpropagation
tagged with: gradient-descent
tagged with: python
upvote count: 4
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87228076
has comment: http://stackoverflow.com/comment/87229889
downvote count: 0
type: UnansweredQuestion
has body: I wanted to predict heart disease using backpropagation algorithm for neural networks. For this I used UCI heart disease data set linked here: processed cleveland. To do this, I used the cde found on the following blog: Build a flexible Neural Network with Backpropagation in Python and changed it little bit according to my own dataset. My code is as follows: import numpy as np import csv reader = csv.reader(open("cleveland_data.csv"), delimiter=",") x = list(reader) result = np.array(x).astype("float") X = result[:, :13] y0 = result[:, 13] y1 = np.array([y0]) y = y1.T # scale units X = X / np.amax(X, axis=0) # maximum of X array class Neural_Network(object): def __init__(self): # parameters self.inputSize = 13 self.outputSize = 1 self.hiddenSize = 13 # weights self.W1 = np.random.randn(self.inputSize, self.hiddenSize) self.W2 = np.random.randn(self.hiddenSize, self.outputSize) def forward(self, X): # forward propagation through our network self.z = np.dot(X, self.W1) self.z2 = self.sigmoid(self.z) # activation function self.z3 = np.dot(self.z2, self.W2) o = self.sigmoid(self.z3) # final activation function return o def sigmoid(self, s): # activation function return 1 / (1 + np.exp(-s)) def sigmoidPrime(self, s): # derivative of sigmoid return s * (1 - s) def backward(self, X, y, o): # backward propgate through the network self.o_error = y - o # error in output self.o_delta = self.o_error * self.sigmoidPrime(o) # applying derivative of sigmoid to error self.z2_error = self.o_delta.dot( self.W2.T) # z2 error: how much our hidden layer weights contributed to output error self.z2_delta = self.z2_error * self.sigmoidPrime(self.z2) # applying derivative of sigmoid to z2 error self.W1 += X.T.dot(self.z2_delta) # adjusting first set (input --&gt; hidden) weights self.W2 += self.z2.T.dot(self.o_delta) # adjusting second set (hidden --&gt; output) weights def train(self, X, y): o = self.forward(X) self.backward(X, y, o) NN = Neural_Network() for i in range(100): # trains the …
answer count: 1
tagged with: neural-network

http://stackoverflow.com/comment/87409673
comment on: http://stackoverflow.com/q/50190681
type: QuestionComment
type: Comment
score: 0
has text: I just want the sender's mail and password in field can be used as EMAIL_HOST_USER and EMAIL_HOST_PASSWORD in settings.py file . Can it be possible?

http://stackoverflow.com/comment/87467173
type: Comment
type: QuestionComment
has text: 32-bit processes (native or WOW64) support up to 32 logical cores. 64-bit Windows uses processor groups that have up to 64 logical cores per group, and a 64-bit process executes in a single group by default (a thread can be moved to another group). multiprocessing has no support for Windows processor groups, and it certainly won't actively manage threads to distribute a workload evenly across all cores. One or more processor groups may be under-utilized if the processes that end up in that group aren't as CPU intensive.
comment on: http://stackoverflow.com/q/50221512
score: 1

http://stackoverflow.com/q/50214308
answer count: 2
has answer: http://stackoverflow.com/a/50214495
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50215753
has title: Creating a DataFrame from a list based on specific values in that list
type: Question
score: 0
tagged with: pandas
has body: I am helping my wife out with some work for her primary school. I have an excel looking like this simplified: score NameA test1 10 test2 23 test4 15 NameB test1 10 test3 17 NameC etc. What I would (ultimately) want is: Test1. Test2. Test3. Test4. etc NameA. 10 23 Nan Nan NameB 10 Nan. 17. Nan NameC etc So far I have imported the Excel with with all columns cocatenated, thinking to make a list of lists for all test of a given pupil, but cannot get it to work. Looking for inspiration so all suggestions are welcome. Maarten
tagged with: python

http://stackoverflow.com/q/50213740
downvote count: 0
has title: AWS S3 presigned urls with boto3 - Signature mismatch
tagged with: amazon-web-services
favorite count: 0
has answer: http://stackoverflow.com/a/51693060
tagged with: amazon-s3
upvote count: 5
tagged with: python
has body: I want to create a presigned url for the objects in my bucket. I use the following python code: client = boto3.client( 's3', aws_access_key_id=os.environ['AWS_ACCESS_KEY'], aws_secret_access_key=os.environ['AWS_SECRETS_KEY'], config=botocore.client.Config(signature_version='s3v4'), region_name='eu-central-1' ) url = client.generate_presigned_url( ClientMethod='get_object', ExpiresIn=60, Params={ 'Bucket': MYBUCKET, 'Key': MYKEY }) I then send the generated URL to my frontend. On the client I will create an a tag with the generated link and use the click() method on it. This worked fine in other projects but here I only get the error: The request signature we calculated does not match the signature you provided. Check your key and signing method. Which is strange. The user should have all the necessary rights. Because listing all the files in my bucket works fine. Can someone point me in the right direction why this isn't working? EDIT I'm using next.js on the frontend if this is of help.
tagged with: boto3
type: Question
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/50215524
type: UnansweredQuestion

http://stackoverflow.com/comment/87289991
type: Comment
has text: Instead of using `RandomSampler`, simply set `shuffle=True` in `DataLoader` constructor.
type: QuestionComment
comment on: http://stackoverflow.com/q/50124712
score: 1

http://stackoverflow.com/q/50150055
has comment: http://stackoverflow.com/comment/87318294
tagged with: python
duplicate of: http://stackoverflow.com/q/4588100
has comment: http://stackoverflow.com/comment/87318065
tagged with: copying
tagged with: numpy
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/87318151
score: 1
has title: Why do I explicitly need to .copy() a numpy array/list?
linked to: http://stackoverflow.com/q/2612802
tagged with: arrays
downvote count: 0
linked to: http://stackoverflow.com/q/4588100
answer count: 1
linked to: http://stackoverflow.com/q/575196
upvote count: 1
favorite count: 0
has body: Why do I have to .copy() a numpy array (or list, though those don't have .copy() but make for a good minimal example) when I want to get an independend copy of it, while I don't have to do so with a variable? What's the reason for this behaviour? E.g. setting a = 1 and b = a and then setting b = 2 does not change a, whereas a=([0]), b = a and b[0]=1 also changes a. Edit: It appears that this is a very common issue/question that can be asked in various ways, so I couldn't find it. For a quick "I just need to understand what's happening so that I can move on" I guess the answer (and the answers to the other same/similar questions) are good enough. For a better understanding I guess this link provided by @chthonicdaemon in the comments seems like a good starting point for me. longer Background In many situations I have to set up a numpy array with some starting values which then gets filled with other values while my program runs. I.e. logger = np.zeros(5) #various things happen logger[0] = 1 #more stuff happens logger[3] = 1 you get the idea. But often it is desirable to have the base array preserved in order to be able to compare the results to it, so I just set up the base first and then make copies from it. So I would expect that I simply could set it up like this: base = np.zeros(5) logger = base logger[0] = 1 so that In [1]:base Out[1]:array([ 0., 0., 0., 0., 0.]) In [2]:logger Out[2]:array([ 1., 0., 0., 0., 0.]) However with the above array, they stay "connected", so that I get In [1]:base Out[1]:array([ 1., 0., 0., 0., 0.]) I can fix that by explicitly using logger = base.copy() but I'm wondering why I have to.
type: Question
has comment: http://stackoverflow.com/comment/87318568
has comment: http://stackoverflow.com/comment/87317986
has answer: http://stackoverflow.com/a/50150242
has comment: http://stackoverflow.com/comment/87318937
accepted answer: http://stackoverflow.com/a/50150242
has comment: http://stackoverflow.com/comment/87317972
has comment: http://stackoverflow.com/comment/87318221

http://stackoverflow.com/comment/87382932
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50122329
type: Comment
has text: choosing this one as the answer as it answers the question using only `numpy`, but truthfully I like the `pandas.groupby` by @MadPhysicist better, it will actually work better for my final solution as I also need to group by month and year. Thanks all.

http://stackoverflow.com/q/50082649
has title: Renaming files with Chinese characters in Python
upvote count: 1
tagged with: unicode
downvote count: 1
favorite count: 0
type: Question
has body: I'm trying to rename some files that have Chinese characters. However, the following won't work: import os for filename in os.listdir(r"C:\Users\mas\Desktop\"): if filename.startswith("你好"): os.rename(filename, filename[7:]) it gives the error " The system cannot find the file specified: '你好 Hello.txt" Do I need to change some settings or something here?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87181609
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/87181208
tagged with: filesystems
has answer: http://stackoverflow.com/a/62017851
score: 0
answer count: 1

http://stackoverflow.com/a/50192975
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50192935
score: 1
has comment: http://stackoverflow.com/comment/87405548
answers question: http://stackoverflow.com/q/50192935
has body: First you put your mapping in a dictionary: cipher = { 'a': "v07u4tLKinfa", 'b': "zz45tTn8u4o0", 'c': "W46tEr10d01z", 'd': "5aPSCr36quA7", 'e': "Zg6pPrg17t15", 'f': "Po84cr3Ud25M", 'g': "L0l1crXtOO11", 'h': "7G1CaZ2wBg9f", 'i': "Z1Yd84we71y3", 'j': "LL6TRe0yR4tj", 'k': "kt426ug76Vz3", 'l': "26IzOZyrXCt4", 'm': "Z3uj09HJ6Iou", 'n': "0d2Wna13lERT", 'o': "N935efQef3JH", 'p': "7j43Ghnf6R4o", 'q': "dF13Rw9nX6i8", 'r': "DOu3fw073r81", 's': "3C0w23rTg5Ij", 't': "TE436nyWi5ee", 'u': "58Ybt78n3e06", 'v': "39j8rH9TYrcO", 'w': "0NAtO48veQM7", 'x': "K2uC2tgEVBn4", 'y': "9nRm03iH8ECn", 'z': "8brYHI304ld2" } Then you can "encrypt" a string in this way: &gt;&gt;&gt; s = 'this' &gt;&gt;&gt; ' '.join(cipher[c] for c in s) 'TE436nyWi5ee 7G1CaZ2wBg9f Z1Yd84we71y3 3C0w23rTg5Ij' In order to decrypt, build the inverse mapping of cipher: reverse_cipher = {v: k for k, v in cipher.items()} and "decrypt" in this way: &gt;&gt;&gt; sc = 'TE436nyWi5ee 7G1CaZ2wBg9f Z1Yd84we71y3 3C0w23rTg5Ij' &gt;&gt;&gt; ''.join(reverse_cipher[x] for x in sc.split()) 'this' After you have finished this learning experiment, if you really want to do encryption, never do it by yourself, and use an existing library. This substitution cipher can be broken very easily.
type: AcceptedAnswer

http://stackoverflow.com/a/50165412
accepted answer of: http://stackoverflow.com/q/50160676
has body: So after some helpful suggestions and intense googling, I came up with this below which does what I need. This script will go into each folder and rename each file as it copies it into another folder, which is titled the original file name. The final result has 22 folders (as described in the question) with 400 files each. The code below includes the snippet from the question stem. import os, shutil dest = r'C:\Users\MBobak\Documents\Target_Folder' all_folders_dir = r'C:\Users\MBobak\Documents\Staging_Folder' files_22 = r'C:\Users\MBobak\Documents\Staging_Folder\Raw Claims Data 050069\D#CJR\Y2018M02\P050069' ## pulling list of all the named files folders = os.listdir(all_folders_dir) files = os.listdir(files_22) ccn_list = [x[-6:] for x in folders] ccn_file_dir = [r'C:\Users\MBobak\Documents\Raw Claims Data ' + x + '\D#CJR\Y2018M02\P' + x for x in ccn_list] for file in files: for hosp_folder, ccn in zip(ccn_file_dir, ccn_list): if not os.path.exists(dest+'\\'+file): os.mkdir(dest+'\\'+file) shutil.copy(hosp_folder+"\\"+file ,dest +'\\'+ file +'\\'+ file + '_' + ccn)
has comment: http://stackoverflow.com/comment/87383258
type: Answer
answers question: http://stackoverflow.com/q/50160676
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87337818
type: QuestionComment
has text: After looking in the source code. In the file, the first line is graph = {}. So the graph has been defined as a dictionary. Thank you!
score: 0
comment on: http://stackoverflow.com/q/50145531
type: Comment

http://stackoverflow.com/comment/87219654
type: Comment
type: QuestionComment
has text: you can use regex
score: 2
comment on: http://stackoverflow.com/q/50101484

recursion
type: Tag
tags question: http://stackoverflow.com/q/50166476
tags question: http://stackoverflow.com/q/50100996
tags question: http://stackoverflow.com/q/50197930
tags question: http://stackoverflow.com/q/50139250
tags question: http://stackoverflow.com/q/50208787
tags question: http://stackoverflow.com/q/50112351
tags question: http://stackoverflow.com/q/50130038
tags question: http://stackoverflow.com/q/50200917
tags question: http://stackoverflow.com/q/50127177
tags question: http://stackoverflow.com/q/50193138
tag name: recursion
tags question: http://stackoverflow.com/q/50198546
tags question: http://stackoverflow.com/q/50108743
tags question: http://stackoverflow.com/q/50154032
tags question: http://stackoverflow.com/q/50079683
tags question: http://stackoverflow.com/q/50108641
tags question: http://stackoverflow.com/q/50200297
tags question: http://stackoverflow.com/q/50141123
tags question: http://stackoverflow.com/q/50146993
tags question: http://stackoverflow.com/q/50213116
tags question: http://stackoverflow.com/q/50106246
tags question: http://stackoverflow.com/q/50143769
tags question: http://stackoverflow.com/q/50153832
tags question: http://stackoverflow.com/q/50215907
tags question: http://stackoverflow.com/q/50109047

http://stackoverflow.com/comment/87350462
comment on: http://stackoverflow.com/q/50165908
has text: @Syzy A general "help me" post might be appropriate for a forum or a chat board or something less structured, but questions on Stack Overflow are held to a higher standard. A good question here is *very specific* about a particular part of programming, after you've boiled away everything not directly related to the specific programming problem. This refining process is good for Stack Overflow questions, but more importantly it's *a key skill* in programming: cut the problem into smaller and smaller pieces until you understand *exactly* what the problem is. Much easier to solve a small problem!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50103853
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50103666
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87224859
has comment: http://stackoverflow.com/comment/87224914
has comment: http://stackoverflow.com/comment/87225017
has body: Try this one: &gt;&gt;&gt; messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] &gt;&gt;&gt; [elem for elem in messy_list if type(elem) == int] [2, 3, 1]
has comment: http://stackoverflow.com/comment/87224995

http://stackoverflow.com/comment/87419923
type: QuestionComment
type: Comment
has text: `message.author` not `member`, you don't have a `member` in your code.
score: 0
comment on: http://stackoverflow.com/q/50192452

http://stackoverflow.com/a/50074959
score: 0
accepted answer of: http://stackoverflow.com/q/50074919
type: AcceptedAnswer
has body: You can't slice a number. Try this instead: &gt;&gt;&gt; def numslice(n,start,end): ... return int(str(n)[start:end]) ... &gt;&gt;&gt; numslice(123456789, 2, 4) 34
answers question: http://stackoverflow.com/q/50074919
type: Answer

http://stackoverflow.com/a/50167026
upvote count: 0
has body: it seems like the code has some syntax error.Please try the code below, it should be ok: from flask import Flask, render_template from flask import request, session, url_for, abort, redirect app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' @app.route('/') def first(): session['this_one'] = 'hello' return render_template('template.html') @app.route('/second') def second(): it = session.get('this_one', 'not found') return render_template('other_page.html') if __name__ == '__main__': app.run(debug=True)
answers question: http://stackoverflow.com/q/50166001
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/a/65492238
upvote count: 3
downvote count: 0
has body: Complementing Rafael's answer, on the bit size, with the relevant quote in the docs: Markers are comprised by an external black border and an inner region that encodes a binary pattern. The binary pattern is unique an identifies each marker. Depending on the dictionary, there are markers with more or fewer bits. The more bits, the more words in the dictionary, and the smaller the chance of a confusion. However, more bits means that more resolution is required for correct detection.
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50076117

http://stackoverflow.com/comment/87267657
has text: https://stackoverflow.com/a/34018827/2823755
comment on: http://stackoverflow.com/q/50106519
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87346778
type: QuestionComment
comment on: http://stackoverflow.com/q/50164016
has text: Both `REQUIRED_ARG` and `subcommand` are positionals. Values are allocated to positionals based on position, not value. If a string is not in the subparsers list of `choices` it raises an error.
score: 0
type: Comment

http://stackoverflow.com/q/50186575
favorite count: 0
possible better answer: http://stackoverflow.com/a/75784950
type: Question
tagged with: bale-messenger
has answer: http://stackoverflow.com/a/75784950
has body: I was trying my first bot in bale messenger but I couldn't and faced this error. Is there any one here to help me? 2018-05-05 11:13:47,938 network.py:112 WARNING:"network connection disconnected." 2018-05-05 11:13:47,939 network.py:36 ERROR:"connect error: 500, message='Invalid response status'" Traceback (most recent call last): File "/home/ehsan/PycharmProjects/example_bots/venv/lib/python3.5/site-packages/balebot/connection/network.py", line 31, in connect self._ws = await self._session.ws_connect(self.construct_url()) File "/home/ehsan/PycharmProjects/example_bots/venv/lib/python3.5/site-packages/aiohttp/helpers.py", line 109, in __await__ ret = yield from self._coro File "/home/ehsan/PycharmProjects/example_bots/venv/lib/python3.5/site-packages/aiohttp/client.py", line 465, in _ws_connect headers=resp.headers) aiohttp.client_exceptions.WSServerHandshakeError: 500, message='Invalid response status'
tagged with: python
score: 4
has title: Cannot connect bot to Bale messenger API: network connection disconnected
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50186685
answer count: 2
tagged with: bots
has answer: http://stackoverflow.com/a/50186685
downvote count: 0
tagged with: websocket
has comment: http://stackoverflow.com/comment/87900703

http://stackoverflow.com/q/50182317
has answer: http://stackoverflow.com/a/50182737
has comment: http://stackoverflow.com/comment/87381993
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50182915
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50182578
tagged with: http://stackoverflow.com/tag/html
tagged with: counter
tagged with: python
answer count: 3
has body: Write a program that asks the user for a URL. It should then retrieve the contents of the page at that URL and print how many &lt;p&gt; tags are on that page. Your program should just print an integer. Here's my code: import urllib.request link = input('Enter URL: ') response = urllib.request.urlopen(link) html = response.read() counter = 0 for '&lt;p&gt;' in html: counter += 1 print(counter) However, I got this error: Traceback (most recent call last): File "python", line 16 SyntaxError: can't assign to literal What would be the better method to execute this code? Should I use the find method instead?
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87382013
has title: Counting the number of p-tags ( ) in a website from a user's choice of link input in Python 3

http://stackoverflow.com/comment/87699147
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50198612
has text: @LatikaAgarwal Hi, i want to add a small program in your given solution. If the user inputs wrong size or wrong character, it should ask for the size again. Can you help me out please? This is what i have written for that but i want to combine that with your given solution: sizes = ["S", "M", "L", "XL"] size = input() while size.upper() not in sizes: size = input()

http://stackoverflow.com/comment/87236441
comment on: http://stackoverflow.com/a/50091199
type: AnswerComment
has text: @stefan It is true in idiomatic Python: in the vast majority of statements, only the things to the left of an `=` get assigned in an assignment statement, or the first object in an expression statement has a single mutating operation. Of course you can violate that by writing an expression full of a dozen `setattr` calls if you want. Or you can put nine statements on one huge lines with semicolons. Python doesn’t make it _impossible_ to write code that’s hard to follow; it just makes it _easy_ to write code that’s not hard to follow, and encourages doing so through opinionated idioms.
score: 3
type: Comment

http://stackoverflow.com/comment/87383695
comment on: http://stackoverflow.com/q/50183001
score: 0
type: Comment
has text: `pip show lit` is what you want; `which` is only for executable commands on the current path
type: QuestionComment

http://stackoverflow.com/comment/87275368
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50128593
has text: @user3121891 You need to give more details. Any exceptions? doesn't give the expected results? something else?
type: AnswerComment

http://stackoverflow.com/q/50226886
has answer: http://stackoverflow.com/a/50226992
type: Question
has title: Is there any way to stream online videos in python tkinter window?
tagged with: python
has body: I am doing a mini project, where I need to create labels using tkinter library of python. I need to attach a link to each of the label, so that whenever I will click on a particular label, it should stream its online video. Videos can be YouTube videos. So I was wondering is there any way to do this?
type: AnsweredQuestion
tagged with: tkinter
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50226992

http://stackoverflow.com/comment/87276446
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50128608
has text: `type(a)` returns totally something else. If you call `type('somestring')` you get its `type`, not the value. `__repr__` is printed to console and also when you call `print variable`

http://stackoverflow.com/q/50206288
tagged with: python
score: -1
upvote count: 0
answer count: 1
downvote count: 1
has body: im trying to make a tiny text adventure game. Why does this statement not return 90? orc = raw_input("Does the orc attack or miss?")#Replacing with a random number thing later health = 100 takeahit = 0 def damage(orc): if orc == "hit": return takeahit == 10 # Ive tried plus as well im having similar problems with choices in inventory elif orc == "miss": print "The Orc misses" healthtwo = health - takeahit print healthtwo
has title: Code not returning expected result
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50206300

http://stackoverflow.com/comment/87452521
score: 0
comment on: http://stackoverflow.com/q/50215962
type: QuestionComment
has text: Adding error/log messages
type: Comment

http://stackoverflow.com/comment/87299523
has text: Well, have you used the sqlite tools to inspect the DB? Are _any_ of the columns you expect present. I suspect it is failing on the first one in the SELECT, and the schema is not being created as you expect.
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50139439

http://stackoverflow.com/comment/87597621
score: 0
type: Comment
has text: Try: pip install --upgrade pip
comment on: http://stackoverflow.com/a/50156914
type: AnswerComment

insert
tags question: http://stackoverflow.com/q/50188852
tags question: http://stackoverflow.com/q/50075719
tag name: insert
type: Tag

http://stackoverflow.com/comment/87235688
comment on: http://stackoverflow.com/q/50109155
type: Comment
score: 0
type: QuestionComment
has text: have you tried `pipreqs`? check it here https://stackoverflow.com/questions/42237072/list-dependencies-in-python/42237244#42237244

http://stackoverflow.com/comment/87569278
has text: @Anony-Mousse I think you are correct. API in python has many parameters and hyper parameters. I was able to replicate results in other data set after many trial and error of combinations. I personally feel Python API gives more control and flexibility compared to R.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50180846
score: 2

http://stackoverflow.com/q/50128595
downvote count: 0
has body: When running code from the console, I'd like both the command and its output to be printed, and I was wondering if there was a way to avoid typing the expression twice. Instead of: print("max(3,4): ", max(3,4)) I'd like a function: f = def(x): print(.....) where f(max(3,4)) prints out the "Instead of" output: f(max(3,4)) &gt;&gt;max(3,4): 4 Is this possible at all?
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: Python: Create a function that takes an expression and prints both the expression as a string and its result
has answer: http://stackoverflow.com/a/50128631
has comment: http://stackoverflow.com/comment/87275076
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50129173
possible better answer: http://stackoverflow.com/a/50129173
answer count: 2
accepted answer: http://stackoverflow.com/a/50128631

http://stackoverflow.com/q/50183540
has comment: http://stackoverflow.com/comment/87384858
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87384782
has body: I have the following numpy array : ([[ 0, 0, 0, 0, 0, 0, 27, 541, 1296, 10000], [ 0, 0, 0, 0, 1, 44, 355, 1998, 3272, 10000], [ 0, 0, 0, 2, 18, 209, 1069, 3239, 4670, 10000], [ 0, 0, 0, 10, 96, 486, 1522, 3954, 5379, 10000], [ 0, 0, 2, 28, 216, 748, 2127, 4769, 6011, 10000], [ 0, 0, 18, 82, 379, 1200, 2867, 5395, 6528, 10000], [ 0, 3, 39, 147, 599, 1489, 3237, 5740, 6909, 10000], [ 0, 6, 48, 246, 759, 1777, 3610, 6034, 7144, 10000], [ 0, 12, 90, 324, 1009, 2072, 3980, 6365, 7466, 10000], [ 1, 12, 119, 438, 1103, 2337, 4215, 6594, 7568, 10000]]) what i want to is to create grey-colored table/image where bigger number is darker color. In addition I want to set the x&amp;y axis to defined values. x-axis : [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] y-axis : [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4200, 4500] I've been playing with imshow, with unsatisfactory results so far. fig, ax1 = plt.subplots(1,1) ax1.imshow(np.flipud(x), cmap='Greys', interpolation='nearest', extent=[100,1001,500,4501]) ax1.set_xticklabels(xaxis) ax1.set_yticklabels(yaxis) ax1.grid() fig.show() First the image should be square, second interpolation smears the exactness of the range (grid is in the middle of cell not the edge).
tagged with: matplotlib
tagged with: python
has title: numpy array to Colored table or image?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50184097
score: 0
has answer: http://stackoverflow.com/a/50184097
answer count: 1

http://stackoverflow.com/comment/87396795
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50187902
has text: Same error has been reported [here](https://github.com/skvark/opencv-python/issues/46). It seems there is no straightforward way to solve it. but I suggest uninstall any version of installed OpenCV and then install opencv using pip: `sudo pip uninstall opencv-python `

beautifulsoup
tags question: http://stackoverflow.com/q/50120344
tags question: http://stackoverflow.com/q/50218738
tags question: http://stackoverflow.com/q/50160675
tags question: http://stackoverflow.com/q/50176292
tags question: http://stackoverflow.com/q/50186384
tags question: http://stackoverflow.com/q/50219483
tags question: http://stackoverflow.com/q/50124914
type: Tag
tags question: http://stackoverflow.com/q/50110917
tags question: http://stackoverflow.com/q/50126725
tags question: http://stackoverflow.com/q/50075317
tags question: http://stackoverflow.com/q/50222051
tags question: http://stackoverflow.com/q/50116026
tags question: http://stackoverflow.com/q/50090122
tags question: http://stackoverflow.com/q/50201745
tags question: http://stackoverflow.com/q/50096918
tags question: http://stackoverflow.com/q/50144103
tags question: http://stackoverflow.com/q/50126952
tags question: http://stackoverflow.com/q/50096368
tags question: http://stackoverflow.com/q/50124228
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/50152424
tags question: http://stackoverflow.com/q/50141132
tags question: http://stackoverflow.com/q/50078736
tags question: http://stackoverflow.com/q/50198050
tags question: http://stackoverflow.com/q/50216172
tags question: http://stackoverflow.com/q/50193802
tags question: http://stackoverflow.com/q/50217439
tags question: http://stackoverflow.com/q/50105781
tags question: http://stackoverflow.com/q/50201692
tags question: http://stackoverflow.com/q/50185657
tags question: http://stackoverflow.com/q/50163463
tags question: http://stackoverflow.com/q/50114239
tags question: http://stackoverflow.com/q/50079650
tags question: http://stackoverflow.com/q/50153092
tags question: http://stackoverflow.com/q/50121519
tags question: http://stackoverflow.com/q/50178900
tags question: http://stackoverflow.com/q/50164915
tags question: http://stackoverflow.com/q/50077882
tags question: http://stackoverflow.com/q/50166927
tags question: http://stackoverflow.com/q/50111462
tags question: http://stackoverflow.com/q/50177007
tags question: http://stackoverflow.com/q/50150626
tags question: http://stackoverflow.com/q/50158644
tags question: http://stackoverflow.com/q/50095378
tags question: http://stackoverflow.com/q/50095114
tags question: http://stackoverflow.com/q/50219247
tags question: http://stackoverflow.com/q/50171839
tags question: http://stackoverflow.com/q/50181217
tags question: http://stackoverflow.com/q/50179783
tags question: http://stackoverflow.com/q/50122786
tags question: http://stackoverflow.com/q/50209429
tags question: http://stackoverflow.com/q/50125246
tags question: http://stackoverflow.com/q/50176051
tags question: http://stackoverflow.com/q/50096657
tags question: http://stackoverflow.com/q/50133887
tags question: http://stackoverflow.com/q/50124207
tags question: http://stackoverflow.com/q/50185679
tags question: http://stackoverflow.com/q/50125972
tags question: http://stackoverflow.com/q/50216854
tags question: http://stackoverflow.com/q/50078120
tags question: http://stackoverflow.com/q/50147236
tags question: http://stackoverflow.com/q/50106226
tags question: http://stackoverflow.com/q/50115190
tags question: http://stackoverflow.com/q/50223629
tags question: http://stackoverflow.com/q/50228781
tags question: http://stackoverflow.com/q/50217001
tags question: http://stackoverflow.com/q/50200629
tags question: http://stackoverflow.com/q/50138015
tags question: http://stackoverflow.com/q/50091000
tags question: http://stackoverflow.com/q/50165568
tags question: http://stackoverflow.com/q/50225173
tags question: http://stackoverflow.com/q/50199452

http://stackoverflow.com/q/50075383
score: 2
accepted answer: http://stackoverflow.com/a/50075483
type: AnsweredQuestion
tagged with: list
upvote count: 2
downvote count: 0
answer count: 1
has body: I have created the following program. It takes an input G, which consists of the vertices of a graph, along with the edges and the corresponding edge weights. The aim of the program is to extract just the edges def edges(G): E =[] for i in G[1]: E.append(i[0]) return E print (edges(G)) On the following input G = [({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8), ({'b', 'e'}, 1) , ({'b', 'f'}, 9), ({'c', 'f'}, 3), ({'d', 'g'}, 7), ({'d', 'h'}, 0)] The following output is produced: [{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'e', 'b'}, {'f', 'b'}, {'f', 'c'}, {'g', 'd'}, {'h', 'd'}] The output I am trying to get is: [{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'b', 'e'}, {'b', 'f'}, {'c', 'f'}, {'d', 'g'}, {'d', 'h'}] Can anyone explain why the tuples I have extracted are reordered?
tagged with: sorting
favorite count: 0
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/87167007
tagged with: kruskals-algorithm
has title: Extracting an edge set from a tuple
tagged with: python
has comment: http://stackoverflow.com/comment/87167093
has answer: http://stackoverflow.com/a/50075483

http://stackoverflow.com/a/50099379
answers question: http://stackoverflow.com/q/50098728
has body: Let f(x) = ax² + bx + c. If you want to solve f(x) = 0 in the field of real numbers, then you need to take care of the discriminant of f defined to be b² - 4ac. If the latter is negative, you do not have real solutions (and to have solutions you need to consider f as a complex polynomial, meaning that you want to find a solution to f(x) = 0 in the field of complex numbers). Now, for your problem, it appears that you have a sign problem. The coefficient c is equal to -510 and not 510. Thus, 68² - 4*34*510 should be 68² - 4*34*(-510) = 68² + 4 * 34 * 510.
score: 0
type: Answer

http://stackoverflow.com/q/50228360
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87473990
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I am beginner to python and I have a question which is I run the python program which is a program for saving a log file from gz format into csv format, but unfortunately when I try to terminate the program, I terminate the program forcefully, which makes the file not to be written in my computer, so how to terminate manually without deleting a file. Below is my code: # List of all gz files gz_files = (gz for gz in glob.glob(os.path.join(GZ_DIR, '*.gz'))) # Loop through all gz files for gz_file in gz_files: sql_file = gz_file[:-3] sql_file = sql_file[:-4] + '.csv' with open(sql_file, 'wb') as out_file: with gzip.open(gz_file, 'rb') as in_file: while True: chunk = in_file.read(1024) if not chunk: break out_file.write(chunk) # Step 2: import to sql import_sql(out_file, DB_HOST, DB_USER, DB_PASS, DB_NAME) # Step 3: remove uncompresed file # os.remove(sql_file) # Step 4: in loop, back to step 1 automatically for another gz files
score: 2
linked to: http://stackoverflow.com/q/1112343
linked to: http://stackoverflow.com/q/3167494
has comment: http://stackoverflow.com/comment/87474245
has title: How to terminate python programming process without deleting a file
has comment: http://stackoverflow.com/comment/87474334
favorite count: 0

http://stackoverflow.com/a/50134254
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87287127
type: Answer
answers question: http://stackoverflow.com/q/50134183
has body: from itertools import chain [l1-l2 for l1, l2 in zip(chain(*list_1),chain(*list_2)) if l1-l2]

http://stackoverflow.com/q/50187320
type: AnsweredQuestion
score: 0
answer count: 1
has body: I am writing a Flask webapp and having a hard time with SQLAlchemy. I am very new to SQLAlchemy and Flask. I have following three tables. User: [ user_id first_name last_name ] Picture: [ filename picture_type // eg: painting, photograph painter ] Comment [ user_id filename comment ] I am trying to query all filenames that was not reviewed by current user. So the condition would be "all filenames from the picture table with matching picture type where each filename should not have matching, in Comment table, filename and matching user_id with the current user Currently the current user user_id an picture_type information are available as incoming argument to the function I am trying to write. How should I write the query using session filter query?
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/50187554
type: Question
has title: SQLAlchemy filter query by conditions in multiple table
tagged with: python
tagged with: flask
tagged with: flask-sqlalchemy
has answer: http://stackoverflow.com/a/50187554

http://stackoverflow.com/q/50100174
tagged with: machine-learning
has body: I am trying to compare different machine learning models on my data (Austin animal shelter adoption data from data.world). A funny thing happened, the predicted outcome always turn out exactly the same regardless of the models I used (Decision Tree, Logistic Regression, Random Forest). from sklearn import tree modelDTC_Dog = tree.DecisionTreeClassifier(criterion='gini') modelDTC_Dog.fit(df_Dog_X, df_Dog_y) predictedDTC_Dog = modelDTC_Dog.predict(df_Dog_X) from sklearn.linear_model import LogisticRegression logreg = LogisticRegression() logreg.fit(df_Dog_X, df_Dog_y) logreg_predict = logreg.predict(df_Dog_X) from sklearn.ensemble import RandomForestClassifier modelRFC = RandomForestClassifier(n_estimators=100, criterion='entropy') modelRFC.fit(df_Dog_X, df_Dog_y) predictedRFC = modelRFC.predict(df_Dog_X) predictedDTC_Dog, logreg_predict, and predictedRFC turn out to have the same values. What am I doing wrong?
has comment: http://stackoverflow.com/comment/87238099
type: Question
has title: Trying out different machine learning models, the predicted list always turn out the same
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87217461
tagged with: python
has comment: http://stackoverflow.com/comment/87252941
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87237572
has comment: http://stackoverflow.com/comment/87239878

http://stackoverflow.com/q/50162201
answer count: 3
upvote count: 2
tagged with: procedural-generation
has answer: http://stackoverflow.com/a/50364894
downvote count: 0
tagged with: voxel
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50364894
possible better answer: http://stackoverflow.com/a/50653491
tagged with: terrain
has title: Fall-off function for mountains
has answer: http://stackoverflow.com/a/50653491
tagged with: python
has answer: http://stackoverflow.com/a/57103049
has comment: http://stackoverflow.com/comment/87556145
has body: I am writing mincraft-like game with voxel terrain. For mountains, I specify a location, a height and size. There is a function to return True if the block at the current (x, y, z) coordinate is part of a mountain. If a block is far away from the centre of a mountain, True is only returned if if the z coord is below a maximum height for the distance from the mountain, ie the further from a mountain a block is, the lower the maximum height. So at the centre of a mountain, the maximum height is high, and True will be returned even if the z is high (I am using a z-up system). However, further away from the mountain, the maximum height will be lower. However, my current function (below) returns them linearly, and real mountains do not have straight sides: def isMountain(self, x, y, z, mountainPos, mountainSize, mountainHeight): if math.hypot(mountainPos[0] - x, mountainPos[1] - y) &lt; mountainSize: if z &lt; (mountainHeight - math.hypot(mountainPos[0] - x, mountainPos[1] - y)): return True else: return False The line 3 checks if z is less than the maximum height for the position, if yes, returning True, otherwise, False. These are the maximum heights for distances: Distance: Max Height 0 - 10 1 - 9 2 - 8 ... 9 - 1 10 - 0 How could I re-write this function to make it return more mountain-like values: not linear, rather cubic or smooth fall-off (like blender proportianal edit mode), so it would give values more like this: 0 - 10 1 - 9 2 - 9 3 - 8 4 - 7 5 - 5 6 - 3 7 - 1
type: Question
score: 2

http://stackoverflow.com/a/50223537
answers question: http://stackoverflow.com/q/50223451
upvote count: 1
score: 1
has body: Let's say you start with the lists of rows and columns, and both contain strings and nothing but strings: from itertools import product import numpy as np import pandas as pd columns = list("abcdefg") rows = list("abcde") Take a Cartesian products of the lists, join the items in each pair, and convert the list to a NumPy array: products = np.array([''.join(x) for x in product(rows, columns)]) Reshape the list into a rectangular table, add row and column headers: pd.DataFrame(products.reshape(-1, len(columns)), index=rows, columns=columns) # a b c d e f g #a aa ab ac ad ae af ag #b ba bb bc bd be bf bg #c ca cb cc cd ce cf cg #d da db dc dd de df dg #e ea eb ec ed ee ef eg
downvote count: 0
type: Answer

http://stackoverflow.com/q/50131632
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87281184
score: 0
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/87281216
tagged with: string
has title: How to send muliptle lists of hex strings from af unix socket in python
has comment: http://stackoverflow.com/comment/87281606
has body: I am trying to send multiple hex strings in a list from AF unix socket from binascii import unhexlify message = [b'8501012a1b0ff5ff',b'8501012a1b000ff'] mess1 = unhexlify(message) print(mess1)
tagged with: hex
type: Question
tagged with: unix-socket
has comment: http://stackoverflow.com/comment/87281332

http://stackoverflow.com/a/50174357
has body: Functions in Python are first-class objects which means you can do almost whatever you want to do with them. Heck, you can even do this: def foo(): pass foo.inner_foo = lambda: print('inner foo') foo.inner_foo() # inner foo Yes, it is a function with an attribute which is a function. And yes, we can go deeper: def foo(): pass foo.inner_foo = lambda: None foo.inner_foo.inner_inner_foo = lambda: print('inner inner foo') foo.inner_foo.inner_inner_foo() # inner inner foo And yes, we can go deeper, but you get the idea...
downvote count: 0
has comment: http://stackoverflow.com/comment/87366038
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87365865
has comment: http://stackoverflow.com/comment/87365851
answers question: http://stackoverflow.com/q/50174305
type: Answer
has comment: http://stackoverflow.com/comment/87366000
has comment: http://stackoverflow.com/comment/87365801

http://stackoverflow.com/comment/87303251
comment on: http://stackoverflow.com/q/50142116
type: QuestionComment
has text: @FlorianBernard If the above two conditions hold, then I guess [my answer](https://stackoverflow.com/a/50142208/3160529) should work fine.
score: 0
type: Comment

http://stackoverflow.com/q/50078664
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87175343
downvote count: 0
has title: pass javascript variables to python flask
upvote count: 1
tagged with: variables
tagged with: flask
favorite count: 0
type: Question
score: 1
tagged with: python
has body: I'd like to pass variables (e.g. window.screen.width) from the HTML page to flask. How can I do that? (And I really need that variable in flask, I can't fix it by having a responsive webpage)
answer count: 0

http://stackoverflow.com/comment/87351490
type: Comment
comment on: http://stackoverflow.com/q/50166773
type: QuestionComment
has text: Sorry I guess it depends on how you use "list". I think of "list" as an iterable data type, which a set is. I guess you're thinking of 'list' as how I would put an "array". Anyways you're not wrong here, I was just confused for a minute...
score: 0

http://stackoverflow.com/q/50190544
type: Question
possible better answer: http://stackoverflow.com/a/50190563
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50190563
accepted answer: http://stackoverflow.com/a/50190629
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50190629
answer count: 2
upvote count: 2
tagged with: dictionary-comprehension
downvote count: 2
tagged with: nested
has body: I have searched around for possible answers for this, and could not find a way to do this with just dict comprehension or a form of functional programming with a dict of dicts without using for loops. I have a function: get_grades(theDict, hw) which takes a dict of dicts and a string such as 'hw1', or 'hw4' in that type of format. The format of theDict is: get_grades({'Ggg':{'hw1': 1, 'hw2': 2, 'hw3': 3},'Hhh':{'hw1': 4, 'hw2': 3,'hw3': 6}},'hw1') I am trying to take all the keys that match hw and sum all the values for that key. If hw = hw1 then the function would return: 5 (which is all the hw1 key values added together)
has title: Dict of Dict Sum Similar Keys with only dict comprehension
favorite count: 0

http://stackoverflow.com/comment/87421417
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50202236
has text: this `{% url 'appointments' Barber.id %}` should be `{% url 'appointments' barb.id %}`.. hovewer you will still get another issue in your view `appointments(request,name)`
type: Comment

http://stackoverflow.com/q/50152424
answer count: 0
tagged with: web-scraping
upvote count: 1
tagged with: python
type: UnansweredQuestion
type: Question
tagged with: pandas
has title: Scraping Tripadvisor Reviews, Location
has comment: http://stackoverflow.com/comment/87331976
has body: I am trying to scrape data from TripAdvisor for Top 30 Restaurants. I was able to get the list of these restaurants. Further, I am able to scrape data for review title and date successfully. I am using BeautifulSoup and Requests to get this data. However, following are the problem areas: While scraping reviews, firstly not able to get full length of reviews and secondly at some places there are replies from the owner which share the same tag and class as the review and thus are getting scraped as well. I want to exclude these replies Parse Link import requests import bs4 as bs link='https://www.tripadvisor.com.sg/Restaurant_Review-g294265-d1193730-Reviews-Entre_Nous_creperie-Singapore.html' openlink=requests.get(link) soup=bs.BeautifulSoup(openlink.text,'lxml') Reviewer Name rnamedata=soup.find_all('span',class_='expand_inline scrname') rnames=[] i=0 for i in range(len(rnamedata)): rnames.append(rnamedata[i].text) rnames[i]=rnames[i].replace("\n","") Length of list comes out to be 10 Review Text rdetaildata=soup.find_all('p',class_='partial_entry') rdetails=[] i=0 for i in range(len(rdetaildata)): rdetails.append(rdetaildata[i].text) rdetails[i]=rdetails[i].replace("\n","") Length of list comes out to be 20 because of replies from owners. I want to exclude these owner replies. Also, this only gives partial review Location of the reviewer is not available for all users, which is fine, but how do I scrape in such a way that i can input "NA" against those who have not mentioned their location. Because of this, I am not able to map location against reviews Review Location rlocdata=soup.find_all('span',class_='expand_inline userLocation') rlocs=[] i=0 for i in range(len(rlocdata)): rlocs.append(rlocdata[i].text) rlocs[i]=rlocs[i].replace("\n","") Length of the list comes out to be 9 as one reviewer has not mentioned location. I would want length to be 10 with one entry as NA for which data is not available. Reviewer contribution and helpful votes also share the same tag …
score: 1
has comment: http://stackoverflow.com/comment/87327636
favorite count: 0
tagged with: beautifulsoup
downvote count: 0

http://stackoverflow.com/a/50156090
score: 1
type: Answer
has body: fh = open("YourFileName") raw = fh.read() fh.close() data = [[float(i) for i in k.split(",")] for k in raw.split("\n")]
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50156049

http://stackoverflow.com/q/50158617
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87335594
has answer: http://stackoverflow.com/a/50158922
answer count: 3
tagged with: while-loop
has comment: http://stackoverflow.com/comment/87335016
has comment: http://stackoverflow.com/comment/87335086
possible better answer: http://stackoverflow.com/a/50158892
tagged with: counter
tagged with: python
has comment: http://stackoverflow.com/comment/87335003
has body: Simple question - I want a loop that counts up and returns to 0 when it reaches a certain number. Tried something like: while i &lt; 7: i += 1 if i == 7 i -= 1 #(or change i in any other way - you get the idea) My Python actually crashed when I tried the above. EDIT: Yes, the if condition is never met - it still crashes when I change it to if i == 6 though.
has answer: http://stackoverflow.com/a/50158892
has comment: http://stackoverflow.com/comment/87335624
has comment: http://stackoverflow.com/comment/87335331
type: Question
has comment: http://stackoverflow.com/comment/87335262
has comment: http://stackoverflow.com/comment/87335569
has title: Repeat counter when index ends
has comment: http://stackoverflow.com/comment/87335281
has comment: http://stackoverflow.com/comment/87335186
has comment: http://stackoverflow.com/comment/87335189
has comment: http://stackoverflow.com/comment/87335131
linked to: http://stackoverflow.com/q/285289
upvote count: 0
has answer: http://stackoverflow.com/a/50159161
downvote count: 3
has comment: http://stackoverflow.com/comment/87335304
score: -3
tagged with: loops
favorite count: 0
accepted answer: http://stackoverflow.com/a/50158922
has comment: http://stackoverflow.com/comment/87334989

http://stackoverflow.com/comment/87404670
comment on: http://stackoverflow.com/q/50193711
score: 0
type: Comment
type: QuestionComment
has text: Anyway, notice that the `unhexlify` part takes more time than accessing the bytes—e.g., on my laptop, it's 209ns to `unhexlify` a single byte, and then only 16ns to access the first element of it. So you may be focusing on the wrong thing in the first place. (Also, is a 16ns operation something you need to worry about optimizing here? If you're doing it billions of times, you may want to step back and find a higher-level way of doing whatever you're actually doing.)

http://stackoverflow.com/q/50079363
tagged with: tkinter
has title: TclError: invalid command name ".4318456072"
tagged with: canvas
tagged with: animation
tagged with: python
accepted answer: http://stackoverflow.com/a/50079973
has answer: http://stackoverflow.com/a/50079973
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: user-interface
has body: I'm writing a version of snake using tkinter. I've come across an issue when trying to make a canvas widget move for an indefinite amount of time using a while True loop. The code appears to work fine but I then get an exception in the console upon closing the window: Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1536, in __call__ return self.func(*args) File "/Users/rachkids/Documents/Coding/Ball Game.py", line 33, in move_ball_right canvas.move(ball, xspeed, yspeed) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2416, in move self.tk.call((self._w, 'move') + args) TclError: invalid command name ".4318456072" Here is the function to make the object move: def move_ball_right(event): global spaceright global spaceleft if spaceright != 400: while True: xspeed = 10 yspeed = 0 canvas.move(ball, xspeed, yspeed) Tk.update(window1) spaceright = spaceright + 10 spaceleft = spaceleft + 10 time.sleep(0.25) Here is all of my code so far: from Tkinter import * from Tkinter import Canvas import random import time window1 = Tk() window1.title("Ball Game") window1.config(background="black") window1.geometry("400x400") coord1 = 0 coord2 = 0 coord3 = 20 coord4 = 20 spaceright = 20 spaceleft = 400 spaceup = 400 spacedown = 20 random1 = random.choice([20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,330,340,350,360,370,380]) random2 = random1 + 20 def generate_food(): food = canvas.create_rectangle(random1, random1, random2, random2, fill="red") def move_ball_right(event): global spaceright global spaceleft if spaceright != 400: while True: xspeed = 10 yspeed = 0 canvas.move(ball, xspeed, yspeed) Tk.update(window1) spaceright = spaceright + 10 spaceleft = spaceleft + 10 time.sleep(0.25) def move_ball_left (event): global spaceright global spacele…
type: Question

http://stackoverflow.com/q/50220860
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50220971
downvote count: 0
tagged with: pip
score: 1
upvote count: 1
has body: I have local pypi server, where I download the packages from https://pypi.org/simple/ I ran command pip install -d /srv/pypi/ cryptography==2.2.2 And it installed cryptography-2.2.2-cp34-abi3-manylinux1_x86_64.whl in my local pypi server. When I try to use that pypi server to download package on non linux platform, it fails. Then I downloaded cryptography-2.2.2.tar.gz and put in local pypi, then it works fine. How can I say in pip install -d command to always download tar.gz for that package ?
has comment: http://stackoverflow.com/comment/87459068
answer count: 1
favorite count: 0
type: Question
tagged with: python
has title: Always download tar.gz from pypi server
tagged with: pypi
accepted answer: http://stackoverflow.com/a/50220971

http://stackoverflow.com/q/50133234
has body: I have deployed Cassandra on Amazon Linux EC2 instance in default public subnet, and have installed python driver. Then I am able to successfully run - https://github.com/datastax/python-driver/blob/master/example_core.py on that EC2 instance. It worked fine. Now, I spawned one more EC2 instance in default public subnet, have installed python cassandra driver on it, and have tried to execute the above-mentioned python file replacing 127.0.0.1 at line 33 with public IP address of the first EC2 instance where single node based cassandra installation is done, but it fails with the following error - [ec2-user@ip-172-31-43-142 ~]$ python example.py 2018-05-02 09:50:23,061 [WARNING] cassandra.cluster: Cluster.__init__ called with contact_points specified, but no load_balancing_policy. In the next major version, this will raise an error; please specify a load-balancing policy. (contact_points = ['54.244.59.178'], lbp = None) 2018-05-02 09:50:23,064 [DEBUG] cassandra.cluster: Connecting to cluster, contact points: ['54.244.59.178']; protocol version: 4 2018-05-02 09:50:23,064 [DEBUG] cassandra.io.asyncorereactor: Validated loop dispatch with cassandra.io.asyncorereactor._AsyncorePipeDispatcher 2018-05-02 09:50:23,064 [DEBUG] cassandra.pool: Host 54.244.59.178 is now marked up 2018-05-02 09:50:23,067 [DEBUG] cassandra.cluster: [control connection] Opening new connection to 54.244.59.178 2018-05-02 09:50:23,073 [WARNING] cassandra.cluster: [control connection] Error connecting to 54.244.59.178: Traceback (most recent call last): File "cassandra/cluster.py", line 2798, in cassandra.cluster.ControlConnection._reconnect_internal return self._try_connect(host) File "cassandra/cluster.py", line 2820, in cassandra.cluster.ControlConnection._try_connect connection = self._cluster.connection_factory(host.address, is_control_connection=True) File "cassandra/cluster.py", line 1205, in cassandra.cluster.Cluster.connection_factory return self.connection_class.factory(address, self.connec…
linked to: http://stackoverflow.com/q/26892330
tagged with: cassandra
score: 0
has comment: http://stackoverflow.com/comment/87369039
has comment: http://stackoverflow.com/comment/87329709
answer count: 1
tagged with: amazon-ec2
has title: Unable to connect to Cassandra server from a remote machine
type: Question
has comment: http://stackoverflow.com/comment/87294858
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50133463

http://stackoverflow.com/a/50222299
answers question: http://stackoverflow.com/q/50222253
has comment: http://stackoverflow.com/comment/87462421
has comment: http://stackoverflow.com/comment/87462462
score: 0
has body: You can draw a polygon around an image, but you can't fill a polygon with an image. You would have to calculate the space of a polygon, and then use an external library or program to change the size of the image. Tkinter can only double or halve the size of images.
has comment: http://stackoverflow.com/comment/87462870
type: Answer

http://stackoverflow.com/comment/87469762
score: 0
type: Comment
type: QuestionComment
has text: I have been writing python for 10 years and have never seen code like this. Please do not assume this is normal python code. In python, it is considered best practice to write clear code that is easy to understand - this code does not meet that criteria.
comment on: http://stackoverflow.com/q/50225783

http://stackoverflow.com/comment/87431303
type: AnswerComment
comment on: http://stackoverflow.com/a/50207084
type: Comment
has text: No sorting is allowed.
score: 0

http://stackoverflow.com/a/50410532
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50104971
score: 0
answers question: http://stackoverflow.com/q/50104971
type: Answer
has body: So answer is that the X and Y arrays are just positional, and the Z array is the dataset to be shown. They do have to be square arrays unfortunately, so in my case the arrays are 64 x 64, but this could be increased by adding more noise to the spatial array.

http://stackoverflow.com/a/50242383
has comment: http://stackoverflow.com/comment/87503874
has comment: http://stackoverflow.com/comment/87503035
has body: So Glennie's answer was close but not what would work in your case. The key thing was to select the right version of the dependencies. If you look at the virtual environment Everything points to one version which 2.7.3, which what you also need to use os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages "org.apache.hadoop:hadoop-aws:2.7.3" pyspark-shell' You should verify the version that your installation using by checking the path venv/Lib/site-packages/pyspark/jars inside your project's virtual env And after that you can use s3a by default or s3 by defining the handler class for the same # Only needed if you use s3:// sc._jsc.hadoopConfiguration().set("fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") sc._jsc.hadoopConfiguration().set('fs.s3a.access.key', 'awsKey') sc._jsc.hadoopConfiguration().set('fs.s3a.secret.key', 'awsSecret') s3File = sc.textFile("s3a://myrepo/test.csv") print(s3File.count()) print(s3File.id()) And the output is below
has comment: http://stackoverflow.com/comment/87502423
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/102344678
upvote count: 10
has comment: http://stackoverflow.com/comment/87503017
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50183915
answers question: http://stackoverflow.com/q/50183915
has comment: http://stackoverflow.com/comment/87503361
has comment: http://stackoverflow.com/comment/87502397

http://stackoverflow.com/a/50199591
score: 1
downvote count: 1
has body: This solves printing a list, one number a time, each on new line - without for loop. print( *[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47], sep = '\n') Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 All primes up to 50 - no for loops involved. As for the primes-list, I cheated by hardcoding them (you did not ask about creating, just printing - although your code tries to create them). you can get lists of prime numbers up to several million from the internet If you are interested in creating them efficiently, I suggest searching SO - f.e. you find Fastest way to list all primes below N
has comment: http://stackoverflow.com/comment/102021253
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50199518

http://stackoverflow.com/comment/87264527
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50123027
has text: This depends hardly on your setup, is only remotely programming related and also too broad. Not a good topic for SO.

http://stackoverflow.com/q/50195109
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has body: I need to send/receive data from one laptop to another, I'm using python 3.6 and it seems like this version of python needs the .encode() and .decode() functions, I was using python 2.7 and I had no troubles before, but now and with python 3.6 I've to use these functions, but I'm not quit sure where exactly I should use the .decode() command You'll find below my server file and my client file Server file : import socket import threading import os def RetrFile(name, sock): filename = sock.recv(1024) filename.decode() if os.path.isfile(filename): sock.send("EXISTS " + str(os.path.getsize(filename))) userResponse = sock.recv(1024) if userResponse[:2] == 'OK': with open(filename, 'rb') as f: bytesToSend = f.read(1024) sock.send(bytesToSend) while bytesToSend != "": bytesToSend = f.read(1024) sock.send(bytesToSend) else: sock.send("ERR ") sock.close() def MainServer(): host = '172.16.1.2' #my IP adress port = 5000 s = socket.socket() s.bind((host,port)) s.listen(5) print ("Server Started.") while True: c, addr = s.accept() print ("client connected ip:&lt;" + str(addr) + "&gt;") t = threading.Thread(target=RetrFile, args=("RetrThread", c)) t.start() s.close() if __name__ == '__main__': MainServer() and this is my client file : import socket def MainClient(): host = '172.16.1.2' port = 5000 s = socket.socket() s.connect((host, port)) filename = input("Filename? -&gt; ") byt=filename.encode() if byt != 'q': s.send(byt) data = s.recv(1024) if data[:6] == 'EXISTS': filesize = len(data[6:]) message = input("File exists, " + str(filesize) +"Bytes, download? (Y/N)? -&gt; ") if message == 'Y': s.send("OK") f = open('new_'+filename, 'wb') data = s.recv(1024) totalRecv = len(data) f.write(data) while totalRecv &lt; filesize: data = s.recv(1024) totalRecv += len(data) f.write(data) print ("{0:.2f}".format((totalRecv/float(filesize))*100)+ "% Done") print ("Download Complete!") f.close() else: print ("File Does Not Exist!") s.close() if __name__ == '__main__': MainClient() But when I…
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87407473
has answer: http://stackoverflow.com/a/50195303
has comment: http://stackoverflow.com/comment/87407540
has comment: http://stackoverflow.com/comment/87407485
favorite count: 0
type: Question
tagged with: tcp
has comment: http://stackoverflow.com/comment/87407258
accepted answer: http://stackoverflow.com/a/50195303
has title: where to add encode and decode in TCP/IP python

http://stackoverflow.com/q/50085839
answer count: 2
has answer: http://stackoverflow.com/a/50096309
has body: I have to find the frequency of a term in present across all the matching documents which have that term, for example: "sky". For ex: if doc1 has a sentence, "sky is blue. sky is blue." and doc2 has a sentence, "the plane is flying in the sky". Then the total frequency of the term "sky" should be 3. I found termvectors as mentioned here: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-termvectors.html and it's Python API, http://elasticsearch-py.readthedocs.io/en/master/api.html?highlight=term%20vector#elasticsearch.Elasticsearch.termvectors But when I tried implementing it: es.search(index="abc", body={"from":0, "size":0,"term vectors":{"fields":["sky"],"field_statistics":"true"}}) I get an error: raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, u'parsing_exception', u'Unknown key for a START_OBJECT in [term vectors].')
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: elasticsearch
has answer: http://stackoverflow.com/a/50086262
tagged with: python
has title: How to retrieve frequency of a term in elastic search using python?
score: 2

http://stackoverflow.com/q/50114964
has comment: http://stackoverflow.com/comment/87247358
has body: I am trying something in Python to concat ProdID based on ProdCategory. All I need is last two columns MainProdConcat and MainProdConcat_PCOnly. Let me know if its possible OrderN0 ProdID ProdCategory ItemNo ProdType MainItem MainProdConcat MainProdConcat_PConly 123334 1 PC 100 Main 100 1,2,3,4,5,6 1,2,3,4 123334 2 PC 110 Option 100 1,2,3,4,5,6 1,2,3,4 123334 3 PC 120 Option 100 1,2,3,4,5,6 1,2,3,4 123334 4 PC 130 Option 100 1,2,3,4,5,6 1,2,3,4 123334 5 Accessories 140 Option 100 1,2,3,4,5,6 123334 6 Accessories 150 Option 100 1,2,3,4,5,6 123334 7 PC 200 Main 200 7,8,9,10,11 7,8,9,10 123334 8 PC 210 Option 200 7,8,9,10,11 7,8,9,10 123334 9 PC 220 Option 200 7,8,9,10,11 7,8,9,10 123334 10 PC 240 Option 200 7,8,9,10,11 7,8,9,10 123334 11 Accessories 260 Option 200 7,8,9,10,11 for index, row in df_OrderNo_WithBase.iterrows(): orderid = row['Legacy Sales Order Identifier'] dealid = row['Deal ID'] df_Master.loc[(df_Master['OrderNo'] == orderid ) &amp; (df_Master['Deal ID'] == dealid)),'ProductConcatMain'] = df_Master[(df_Master['OrderNo'] == orderid) &amp; (df_Master['Deal ID'] == dealid) ]['ProdID'].str.cat(sep=',')
downvote count: 0
has comment: http://stackoverflow.com/comment/87250202
upvote count: 1
possible better answer: http://stackoverflow.com/a/50117609
has comment: http://stackoverflow.com/comment/87250558
accepted answer: http://stackoverflow.com/a/50117183
has answer: http://stackoverflow.com/a/50117609
has comment: http://stackoverflow.com/comment/87249384
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87250589
tagged with: pandas
score: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87248651
type: Question
has comment: http://stackoverflow.com/comment/87248322
answer count: 2
has title: Concat consecutive rows by grouping columns
has comment: http://stackoverflow.com/comment/87247248
has answer: http://stackoverflow.com/a/50117183

http://stackoverflow.com/comment/87481323
comment on: http://stackoverflow.com/q/50212082
score: 0
type: Comment
type: QuestionComment
has text: Have you changed your wsgi.py? The reentrant error generally means either your settings.py is incorrect, or something is misconfigured related to the loading of apache/WSGI. I assume the site runs normally on its own (and its just celery that's not working)?

http://stackoverflow.com/comment/87306803
score: 0
has text: Hi Nathan, thanks so much for the answer! This works perfectly! I am relatively new to Python, and had a a bit of problem understanding why this is the case. This issue of the list being copied from the original link rather than the updated one - why this is the case? Is it related specifically to the application of a recursive function?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50144022

http://stackoverflow.com/q/50107324
has comment: http://stackoverflow.com/comment/87231976
has answer: http://stackoverflow.com/a/50107413
score: 0
has title: Unknown error for Python in Maya
has answer: http://stackoverflow.com/a/50107367
type: Question
answer count: 2
type: UnansweredQuestion
has body: User Interface Window import maya.cmds as cmds class UserInterface(): def __init__(self): windowID = "myWindowID" if cmds.window(windowID, exists = True): cmds.deleteUI(windowID) cmds.window(windowID, title="User Interface", sizeable=False, resizetoFitChildren=True) cmds.rowColumnLayout(numberOfColumns=3,columnWidth=[(1,75), (2,60), (3,60)], columnOffset=[(1,"right",3)] cmds.showWindow() I'm working on a basic UI for Maya in Python however a minute ago this code was working, now all of a sudden it says # Error: invalid syntax # Any help on this please
has comment: http://stackoverflow.com/comment/87231937
tagged with: python

http://stackoverflow.com/q/50184327
has comment: http://stackoverflow.com/comment/87779363
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87460685
tagged with: web-scraping
has body: I am trying to make a scraper that gets all the values of a list of items sold on a web page. The problem is that I get in return for the whole loop just the first value. I don't get what I am doing wrong. Page source: https://allegro.pl/listing?string=windows&amp;where=%2Flisting&amp;order=m&amp;bmatch=ss-base-relevance-floki-5-nga-hcp-wp-eng-ele-1-4-0501 mains = browser.find_elements_by_xpath('//div[@class="_433675f"]') for main in mains: pname = main.find_element_by_xpath('//h2[@class="_342830a c3169ab "]').text print pname
has comment: http://stackoverflow.com/comment/87776198
type: Question
has comment: http://stackoverflow.com/comment/87387781
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87397965
tagged with: python
has comment: http://stackoverflow.com/comment/87819499
linked to: http://stackoverflow.com/q/27006698
has title: Selenium WebDriver "find_element_by_xpath" on multiple elements
tagged with: selenium-webdriver

http://stackoverflow.com/a/50076944
accepted answer of: http://stackoverflow.com/q/50076497
has comment: http://stackoverflow.com/comment/87225738
score: 0
has comment: http://stackoverflow.com/comment/87225879
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87225763
has body: Why are you comparing event.char to event.keysym? That will always be True for printable characters, and always be False for character sequences and special characters (like ⇦ and ↲). How about this (untested)? import string import tkinter as tk # See side note 1 def key_event(label, event): label_text = label.cget("text") if event.keysym == "backspace": label.config(text=label_text[:-1]) elif event.keysym == "return": # Disallow 'return' pass elif event.char in string.ascii_lowercase: # Character is an ASCII letter label.config(text=label_text + event.char) def main(): root = tk.Tk() prompt = " Press any key " label = tk.Label(root, text=prompt, bg="black", fg="green") label.grid(row=0, column=0) label.bind("&lt;Key&gt;", lambda e: key_event(label, e)) # See side note 2 label.focus() # Give keyboard focus root.mainloop() Side note 1: avoid using wildcard imports (from ... import *). Instead, alias tkinter 'as' tk: import tkinter as tk root = tk.Tk() ... Side note 2: avoid using global variables, prefer using a class (provided you know how to use them properly, see below section for an example), or for really small pieces of code, share variables using lambdas like I did. import string import tkinter as tk class EditableLabel(tk.Label): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bind("&lt;Key&gt;", self._key_event) def _key_event(self, event): keysym, char = event.keysym, event.char text = self.cget("text") if keysym == "backspace": self.config(text=text[:-1]) elif keysym == "return": pass elif char in string.ascii_lowercase + string.digits: self.config(text=text + char) class MyApplication(tk.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._add_and_draw_widgets() def _add_and_draw_widgets(self): for i in range(3): EditableLabel(self, text="Label #{}".format(i)).grid(column=0, row=i) def main(): root = tk.Tk() app = MyApplication(root) app.grid(column=0, row=0) root.mainloop() if __name__ == "__mai…
answers question: http://stackoverflow.com/q/50076497
type: Answer

http://stackoverflow.com/a/50191920
downvote count: 0
has body: The lists within the nlist define groupings of nodes that are going to be placed on concentric circles (shells). The nodes are defined by their ID which we defined in the grafoPetersen: 1, 2, ..., 10 networkx.draw_shell(g, nlist=[range(5,10), range(5)]) This call groups nodes range(5,10)=[5,6,7,8,9] on one concentric circle and range(5)=[0,1,2,3,4] on second concentric circle. There is, however, no node defined in grafoPetersen with ID 0. Furthermore, we have defined a node with ID 10, which is not represented by either of the two ranges. So in order to fix this, we have to fix the ranges: networkx.draw_shell(g, nlist=[range(6,11), range(1,6)]) and with all the fancy options: networkx.draw_shell(g, nlist=[range(6,11), range(1,6)], edge_color=colors, width=widths)
type: Answer
accepted answer of: http://stackoverflow.com/q/50190974
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50190974
type: AcceptedAnswer

http://stackoverflow.com/a/51768040
type: Answer
answers question: http://stackoverflow.com/q/50114648
has body: Use cursor.fetchone() is not None instead: book = db.execute("SELECT * FROM books WHERE isbn=:isbn", {"isbn": id}) book = book.fetchone() if book is None: return "Not found."
score: 0

http://stackoverflow.com/a/50207109
upvote count: 2
has body: This is how you can do this in R # Create dataframe original &lt;- data.frame(Vendor = c("M-Operations", "M-Operations", "Secure Total"), Category = c("Cybersecurity", "CERT", "CERT"), Problem = c("Bad", "Good", "Good")) # Create a list of all unique values in each column l &lt;- list( Vendor &lt;- unique(original$Vendor), Category &lt;- unique(original$Category), Problem &lt;- unique(original$Problem)) # Find all possible permutations new.data &lt;- do.call(expand.grid, l) # assign names to the new dataset names(new.data) &lt;- c("Vendor", "Category", "Problem") new.data # Vendor Category Problem # 1 M-Operations Cybersecurity Bad # 2 Secure Total Cybersecurity Bad # 3 M-Operations CERT Bad # 4 Secure Total CERT Bad # 5 M-Operations Cybersecurity Good # 6 Secure Total Cybersecurity Good # 7 M-Operations CERT Good # 8 Secure Total CERT Good After that you can subset this dataframe any way you want to leave as many records as needed for your test
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87432903
accepted answer of: http://stackoverflow.com/q/50206349
answers question: http://stackoverflow.com/q/50206349
type: Answer
score: 2

count
tags question: http://stackoverflow.com/q/50194856
tag name: count
tags question: http://stackoverflow.com/q/50093395
type: Tag

http://stackoverflow.com/comment/87364061
comment on: http://stackoverflow.com/a/50172371
type: AnswerComment
has text: @alexdayvi Any processing just can be packed as a function
score: 0
type: Comment

http://stackoverflow.com/q/50126648
answer count: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/47152691
has title: Pandas long to wide form to resample
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50126686
upvote count: 2
has comment: http://stackoverflow.com/comment/87271377
has body: I'm trying to work out how to resample the following data. The trick is that there are two variables which I need (identifier and variable) to maintain during that resample. I've tried re-sampling using the following code: df.set_index('date').to_period('d').resample('d').fillna(method='ffill') But it doesnt allow me to given the index is not unique. So, I thought maybe if i take it to wide form and make it multi-level columns i could resample the re-shaped dataframe while maintaining the identifier and variable information. original data format is as follows: date, identifier, variable, value 2018-04-01, BBN, M3M, 24 2018-04-07, BBN, M3M, 25 2018-04-14, BBN, M3M, 25 2018-04-21, BBN, M3M, 25 2018-04-01, BBN, M12M, 48 2018-04-07, BBN, M12M, 52 2018-04-14, BBN, M12M, 50 2018-04-21, BBN, M12M, 49 2018-04-01, MXP, M3M, 18 2018-04-07, MXP, M3M, 20 2018-04-14, MXP, M3M, 25 2018-04-21, MXP, M3M, 22 2018-04-01, MXP, M12M, -10 2018-04-07, MXP, M12M, -12 2018-04-14, MXP, M12M, -14 2018-04-21, MXP, M12M, -18 Expected reshape: identifier BBN, MXP variable M3M, M12M,M3M,M12M date 2018-04-01, 24, 48, 18, -10 date 2018-04-07, 25, 52, 20, -12 date 2018-04-14, 25, 50, 25, -14 date 2018-04-21, 25, 49, 22, -18 I think that once its in this format, the date index should be unique, then I'll be able to re-sample the data to include missing days. I'm just not sure how to pivot table to get the multiple level columns. Can any body point me in the right direction, or provide any help or suggestions???
linked to: http://stackoverflow.com/q/47152691
type: UnansweredQuestion

http://stackoverflow.com/a/50109281
score: 0
type: Answer
has body: You are passing a single string to function; it doesn't matter that that string has 2 values within it. Nor does it matter if you use variables or constants (or even a mix of the two) to build that string; the same single string is passed to function either way. I suppose you could split that string, but that seems a very roundabout way to pass 2 numbers.
has comment: http://stackoverflow.com/comment/87235970
answers question: http://stackoverflow.com/q/50109257
has comment: http://stackoverflow.com/comment/87236126
has comment: http://stackoverflow.com/comment/87235957

http://stackoverflow.com/a/50131625
type: AcceptedAnswer
downvote count: 0
has body: argparse store action allows the programmer to differentiate 3 use cases: option is not present (uses default) option is present and has no additional value (uses const) option is present and has a value (uses the passed value) Assuming that you want -s and -s Hello to perform the same, you could use parser = argparse.ArgumentParser(description = "Some desc.") parser.add_argument("-s", nargs='?', const='Hello', default = None) then you can test it: &gt;&gt;&gt; parser.parse_args([]) Namespace(s=None) &gt;&gt;&gt; parser.parse_args(["-s"]) Namespace(s='Hello') &gt;&gt;&gt; parser.parse_args(["-s", 'Hello']) Namespace(s='Hello') &gt;&gt;&gt; parser.parse_args(["-s", 'foo']) Namespace(s='foo')
answers question: http://stackoverflow.com/q/50130711
type: Answer
has comment: http://stackoverflow.com/comment/87284725
accepted answer of: http://stackoverflow.com/q/50130711
has comment: http://stackoverflow.com/comment/87282144
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87281204

http://stackoverflow.com/a/50163194
type: Answer
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: That is called a bound method. A bound method holds reference to the instance (i.e. self) and the function, so when it is called, the self is inserted into the list of arguments. The self then, of course holds references to all other member variables. In your example, try this: &gt;&gt;&gt; fn5 &lt;bound method Klass.ret_val of &lt;__main__.Klass object at 0x006B1270&gt;&gt; &gt;&gt;&gt; fn5.__self__ &lt;__main__.Klass object at 0x006B1270&gt; &gt;&gt;&gt; fn5.__self__.val 5 Then, calling fn5() is the same as calling fn5.__func__(fn5.__self__).
accepted answer of: http://stackoverflow.com/q/50163080
answers question: http://stackoverflow.com/q/50163080

http://stackoverflow.com/q/50164281
has comment: http://stackoverflow.com/comment/87346901
has comment: http://stackoverflow.com/comment/87346606
has body: So, I've seen this answer here, which is sensible for functions which return one output. What if my function has multiple outputs? More concretely, let's say I am cross-referencing some data on some ID. But when I call certain IDs, it returns multiple matches, which I want to put into different columns. An example of this would be something like the below, where worker 3 has two bosses, 0 and 2, while worker 1 has one boss, 2. Worker_ID Boss_ID 3 0 3 2 1 2 Is it possible to create the second column and populate without first going through, counting the number of matches and creating the relevant number of columns? EDIT: I'd like something like this in short-form: Worker_ID Boss_ID_1 Boss_ID_2 ...as necessary 3 0 2 1 2 nan
tagged with: pandas
score: 1
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50164452
favorite count: 0
has comment: http://stackoverflow.com/comment/87346875
type: Question
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/48338381
downvote count: 0
upvote count: 1
has title: Pandas add columns to a dataframe
linked to: http://stackoverflow.com/q/48338381
linked to: http://stackoverflow.com/q/30811301

http://stackoverflow.com/comment/87225771
score: 0
comment on: http://stackoverflow.com/q/50103259
has text: I can do the following `import app.my_module ... importlib.reload(app.my_module) ` and access the functions and variable as such `app.my_module.my_variable`. but that is somehow annoying/a lot of redundant in code/doesn't feel right . so maybe there is another way around it.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50166282
tagged with: powershell
tagged with: python
has comment: http://stackoverflow.com/comment/87351379
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50166592
has title: Trying to refactor by adding multiple values to a key in a dictionary. (Exercise 48 Learn Python the Hard Way
has body: It seems there have been a number of questions surrounding this exercise (48) from Learn Python the Hard Way, yet none answer my question. I have successfully completed the exercise in it's entirety and now wish to refactor it. Before I paste any code let me give you a brief explanation of what the exercise is for. The book provides you with a file (lexicon_tests.py) filled with various test functions and assert_equal statements. The objective is to create another file that contains the code that will allow the various tests to pass using nosetests command from the nose project. I've created a dictionary with the necessary key-value pairs as well as a scan function that will check for int, word, or error. And all my tests pass. Now I would like to shorten up the code. Below is what I've attempted so far: # from collections import defaultdict # What I'm trying to do lexicon = { "direction": ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'] } ''' *What I've already done* lexicon = { "north": 'direction', "south": 'direction', "east": 'direction', "west": 'direction', "down": 'down', "up": 'direction', "left": 'direction', "right": 'direction', "back": 'direction', "go": 'verb', "stop": 'verb', "kill": 'verb', "eat": 'verb', "the": 'stop', "in": 'stop', "of": 'stop', "from": 'stop', "at": 'stop', "it": 'stop', "bear": 'noun', "door": 'noun', "princess": 'noun', "cabinet": 'noun', "0": 'number', "1": 'number', "2": 'number', "3": 'number', "4": 'number', "5": 'number', "6": 'number', "7": 'number', "8": 'number', "9": 'number', } ''' ''' *Not sure how to incorporate this with my code below or if it will work* lexicon = defaultdict(list) for k, v in 1: d1[k].append(v) d = dict((k, tuple(v)) for k, v in d1.iteritems()) ''' # Scan Method - This works fine def scan(sentence): results = [] words = sentence.split() for word in words: try: temp = int(word) word_type = "number" results.append((word_type, temp)) except ValueError: word_type = lexicon.get(…
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/87192972
type: Comment
comment on: http://stackoverflow.com/a/50081499
score: 0
type: AnswerComment
has text: Harv, thanks for the response. My thinking was the `pd.read_html` returns a list and then the `weather_list = weather_list[4]` returns a dataframe of the 4th table in that list... can you clarify if this is my correct understanding? Maybe I didn't understand the documentation!

http://stackoverflow.com/comment/87210742
comment on: http://stackoverflow.com/a/50096549
type: AnswerComment
has text: I have updated the code to use a function just call the func on each list to get the new list then do what you want with it
score: 0
type: Comment

http://stackoverflow.com/comment/87414732
has text: You haven't shown enough of the template to see what's going wrong with the Ajax, but you *absolutely must not* use a global variable like that to keep state between requests.
comment on: http://stackoverflow.com/q/50198172
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87487806
has text: Yeah i works :D Thanks a lot but can i ask just one question? if i want to edit number at report class from makereport class what should i do? i tried to type that at "makereport" class ""reports.ATC = reports.ATC + 1""" but it changes for all users at "report" no for one persone?!
comment on: http://stackoverflow.com/q/50204011
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50163482
downvote count: 0
has comment: http://stackoverflow.com/comment/87394727
has comment: http://stackoverflow.com/comment/87394372
has body: The argument to writelines() is supposed to be a list of strings. That's what line is, you don't need to call str(). So the last line should be: f.writelines(line) If Counter contains an integer, you need to convert it to a string when putting it into line[8]: line[8] = str(Counter)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50163407
type: Answer
has comment: http://stackoverflow.com/comment/87394474

http://stackoverflow.com/comment/87351515
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50166726
type: Comment
has text: @user2357112 of course I realize that.... in the real code the lamdas in the second dictionary are very complicated.

http://stackoverflow.com/q/50142618
has answer: http://stackoverflow.com/a/50143304
score: 0
tagged with: bokeh
accepted answer: http://stackoverflow.com/a/50143304
type: Question
answer count: 1
tagged with: stacked-chart
tagged with: python
has title: Bokeh 12.0.15- stacked grouped bars
has body: Is there a way to create stacked-grouped bar charts in the current version of bokeh? Currently I'm attempting to create a list of tupled groupings to pass as an x-axis: i.e. from bokeh.io import show, output_file, curdoc from bokeh.models import ColumnDataSource, HoverTool, FactorRange from bokeh.plotting import figure factors = [ ("2017","jan"),("2017","feb"),("2017","mar"), ("2018",'jan'),("2018","feb"),("2018","mar") ] data = {'factors' : factors, 'Tammy' : [2, 1, 4, 3, 2, 4], 'Jim' : [5, 3, 4, 2, 4, 6], 'Mike' : [3, 2, 4, 4, 5, 3]} users=['Tammy','Jim','Mike'] source = ColumnDataSource(data=data) p = figure(x_range=FactorRange(*factors), plot_height=350) p.vbar_stack(users, x=factors, width=0.9) curdoc().add_root(p) It's not working all that great currently.. Keyword argument sequences for broadcasting must be the same length as stackers
type: AnsweredQuestion

http://stackoverflow.com/q/50204514
tagged with: python
has body: I just started dealing with pytest hooks and I immediately encountered strange behavior of pytest_runtest_protocol(item, nextitem) hook in case of calling pytest from python code. I tried to reproduce code from https://stackoverflow.com/a/29140467/3124227, but in pytest_runtest_protocol myPlugin object is passed as first argument and not testitem (see screenshot). After that line I get exception because MyPlugin object has no ihook property. This problem doesn't appear in case of athoner ways of calling pytest (with hook code in conftest.py). Project has only two files. test_main.py def test_first(): assert 2 + 2 == 4 def test_second(): assert 2 + 2 == 4 hooks.py import pytest from _pytest.runner import runtestprotocol class MyPlugin(object): def pytest_runtest_protocol(item, nextitem): reports = runtestprotocol(item, nextitem=nextitem) for report in reports: if report.when == 'call': print '\n%s --- %s' % (item.name, report.outcome) return True def main(): pytest.main(plugins=[MyPlugin()]) if __name__ == '__main__': main() Is it possible to solve this problem? Version of pytest: 3.2.1
linked to: http://stackoverflow.com/q/14121657
has comment: http://stackoverflow.com/comment/87426704
has comment: http://stackoverflow.com/comment/87426855
type: Question
has title: Wrong object passed to pytest hook
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87426107
has comment: http://stackoverflow.com/comment/87426802
score: 0
linked to: http://stackoverflow.com/q/735975
tagged with: pytest
has comment: http://stackoverflow.com/comment/87427030

http://stackoverflow.com/comment/87332099
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50144518
has text: I have used search_api to create index search.DateField(name='last_updated_date', value=instance.last_updated_date)
type: Comment

http://stackoverflow.com/q/50108911
has comment: http://stackoverflow.com/comment/87251916
possible better answer: http://stackoverflow.com/a/50108975
upvote count: 1
has answer: http://stackoverflow.com/a/50108975
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87235198
tagged with: python
accepted answer: http://stackoverflow.com/a/50117360
has body: I am doing this array pair sum problem which says: Given an integer array, output all the unique pairs that sum up to a specific value k. So the input: pair_sum([1,3,2,2],4) would return 2 pairs: (1,3) (2,2) Seems a pretty simple problem. This is what I my script looks like: def pair_sum(arr,k): count =0 l = [] y = [] for i in range(len(arr)-1): l.append((arr[i], arr[i+1])) y.append((arr[i-1],arr[i])) res = list(set(y+l)) for i,j in res: if i + j == k: print (i,j) count +=1 return count And I is working fine with few test cases except this one: pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10) My code is returning 5 but it should return 6. I know that this can be manually calculated and then I can check which pair is missing but what if the test case is sufficiently large. I can't check manually for each case. Can anyone tell what am I doing wrong here because I might have considered almost every possible pair. Also, like what if I don't want to use set here like can there be a more general solution which is not specific to any language. Because how can you get unique pair without using set?
answer count: 4
score: -1
has answer: http://stackoverflow.com/a/50117360
has comment: http://stackoverflow.com/comment/87236094
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50118699
has comment: http://stackoverflow.com/comment/87235391
has answer: http://stackoverflow.com/a/64596165
downvote count: 2
has title: Get sum of every pair unique pair in the array
has comment: http://stackoverflow.com/comment/87235218

http://stackoverflow.com/comment/87834304
score: 0
has text: Hi, I m a little bit busy. I will fix it as soon as possible. Sorry for the delay.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50182819

http://stackoverflow.com/a/50109445
type: AcceptedAnswer
has body: The actual sharing part is the same question as "how do I share a value with another object?" without threads, and all the same solutions will work. For example. you're already passing the foo instance into the bar initializer, so just get it from there: class bar(threading.Thread): def __init__(self,fooInstance): threading.Thread.__init__(self,name="bar") self.var1 = fooInstance.var1 But is this thread-safe? Well, yes, but only because you never actually start the background thread. But I assume in your real code, you're going to have two threads running at the same time, both accessing that var1 value. In which case it's not thread-safe without some kind of synchronization. For example: class foo(threading.Thread): def __init__(self): threading.Thread.__init__(self,name="foo=&gt;bar") self.var1 = {} self.var1lock = threading.Lock() class bar(threading.Thread): def __init__(self,fooInstance): threading.Thread.__init__(self,name="bar") self.var1 = fooInstance.var1 self.var1lock = fooInstance.var1lock And now, instead of this: self.var1[name] = value … you do this: with self.var1lock: self.var1[name] = value And likewise, instead of this: val = myOtherfunction(fooInstance.var1[arg]) //other function … you do this: with self.var1lock: var1arg = var1[arg] val = myOtherfunction(var1arg) Or… as it turns out, in CPython, updating a value for a single key in a dict (only a builtin dict, not a subclass or custom mapping class!) has always been atomic, and probably always will be. If you want to rely on that fact, you can. But I'd only do that if the lock turned out to be a significant performance issue. And I'd comment every use of it to make it clear, too. If you'd rather pass values instead of share them, the usual answer is queue.Queue or one of its relatives. But this requires a redesign of your program. For example, maybe you want to pass each new/changed key-value pair over the queue. That would go something like this: class foo(threading.Thread): def __init__(self): …
score: 0
accepted answer of: http://stackoverflow.com/q/50108831
type: Answer
answers question: http://stackoverflow.com/q/50108831

http://stackoverflow.com/a/50083915
answers question: http://stackoverflow.com/q/50083878
has body: Add the get_context_data() method to your view, like this: def get_context_data(self, **kwargs): context = {} context['your_custom_var'] = 'your_custom_value' return super(MySummary, self).get_context_data(**context)
score: 2
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50083878
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50095381
tagged with: cython
has comment: http://stackoverflow.com/comment/87208341
has comment: http://stackoverflow.com/comment/87207037
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87207178
has comment: http://stackoverflow.com/comment/87207239
has body: I am using python 3.53 cython 0.28.2 and Visual studio compiler 2017. The example was taken from: http://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html#cython-hello-world I am trying to compile a simple helloworld.pyx print ('hello world') using visualstudio 2017. I tried two setup.py files 1st setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("helloworld", ["helloworld.pyx"])] ) 2nd setup.py from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize("helloworld.pyx") ) both succeeded using python setup.py build_ext --inplace, and generated the following dll: helloworld.cp35-win_amd64.pyd But when I import the generated pyd file using: import helloworld.cp35-win_amd64 I get import helloworld.cp35-win_amd64 ^ SyntaxError: invalid syntax Renaming the pyd file to shorter name without - or _ did not work. Any suggestions are appreciated.
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87207089
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/4631377
downvote count: 1
has title: cython with python 3.5
has answer: http://stackoverflow.com/a/50129600
has comment: http://stackoverflow.com/comment/87210059
has comment: http://stackoverflow.com/comment/87206945
has comment: http://stackoverflow.com/comment/87207112
answer count: 1

http://stackoverflow.com/a/50174470
has comment: http://stackoverflow.com/comment/87365980
type: Answer
has comment: http://stackoverflow.com/comment/87368241
has comment: http://stackoverflow.com/comment/87365884
has comment: http://stackoverflow.com/comment/87372253
has comment: http://stackoverflow.com/comment/87367939
has body: Since the last product have the highest id then you can try like this last_product = Products.objects.order_by('-id')[0] What I'm doing here is ordered all the project in reverse order by id then get first element from that.
has comment: http://stackoverflow.com/comment/87368348
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87368112
answers question: http://stackoverflow.com/q/50174149
has comment: http://stackoverflow.com/comment/87366325
score: 3

http://stackoverflow.com/q/50200370
downvote count: 0
has answer: http://stackoverflow.com/a/50200536
has body: I was looking at this question: python3 replacing double backslash with single backslash [duplicate] and sifting through the responses to similar questions: Python Replace \ with \ , Why can't Python's raw string literals end with a single backslash? , How do I unescape a unicode escaped string in python? When I realised that none of the answers really solve this problem. Say I have a broken unicode string, it contains both escaped backslashes and escape characters: my_str = '\\xa5\\xc0\\xe6aK\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z' When I print it, some characters evaluate: print(my_str) \xa5\xc0\xe6aKù\x80\xb1\xc8*☺↕$\xfbp▲(4\xd6{;Z I can manually fix it like this: my_str = repr(my_str) my_str "'\\\\xa5\\\\xc0\\\\xe6aKù\\\\x80\\\\xb1\\\\xc8*\\x01\\x12$\\\\xfbp\\x1e(4\\\\xd6{;Z'" my_str = my_str.replace('\\\\','\\') print(my_str) '\xa5\xc0\xe6aKù\x80\xb1\xc8*\x01\x12$\xfbp\x1e(4\xd6{;Z' But at this point I have to manually copy and paste the result of print into a variable to finish the fix: my_str = '\xa5\xc0\xe6aKù\x80\xb1\xc8*\x01\x12$\xfbp\x1e(4\xd6{;Z' print(my_str) ¥ÀæaKù±È*☺↕$ûp▲(4Ö{;Z How do I do this without copying and pasting?
tagged with: python
tagged with: string
tagged with: unicode
linked to: http://stackoverflow.com/q/5186839
favorite count: 0
linked to: http://stackoverflow.com/q/50199840
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24886123
possible better answer: http://stackoverflow.com/a/50200931
linked to: http://stackoverflow.com/q/4020539
has answer: http://stackoverflow.com/a/50200931
linked to: http://stackoverflow.com/q/647769
linked to: http://stackoverflow.com/q/22601291
type: Question
answer count: 2
duplicate of: http://stackoverflow.com/q/4020539
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/50200536
has title: Fix a unicode string broken by (some) escaped backslashes

http://stackoverflow.com/q/50101833
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87220576
tagged with: python
tagged with: inspection
has comment: http://stackoverflow.com/comment/87220767
downvote count: 0
score: 1
upvote count: 1
has body: How to get the values of the call parameters of a function / method? It's for a debugging tool, and it would be used in a scenario like this one: import inspect def getCallParameter(): stack = inspect.stack() outer = stack[1] #This is an example, I have a smarter way of finding the right frame frame = outer.frame print("") #print at least a dict of the value of the parameters, and at best, give also which parameter are passed explicitly (e.g. with f(2, 4) an input of this kind : "a=2, b=4, c=5(default)") def f(a, b=4, c=5): a+=b+c getCallParameters() return a Note : I'm aware of inspect.formatargsvalues() but it doesn't meet my requirements since in the f(2,4) example, it would have printed "a=11, b=4, c=5)" What I though of, would be to watch on the outer frame the values passed. It's not a problem if I don't get the original state of the passed object, as long as I get the objects initially bound to the variable parameters. Example: # with f(4) def f(a, b=4, c=[]) c.append(5) getCallParameters() # a=4, b=4, c=[5] is ok even if I would have preferred c=[] c = [4] getCallParameters() # here, I expect c=[5] or c=[]
has comment: http://stackoverflow.com/comment/87220544
has comment: http://stackoverflow.com/comment/87220725
answer count: 1
has comment: http://stackoverflow.com/comment/87220617
has title: Is there a way to get in Python the original value of the parameters of a function given a frame?
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50102004

http://stackoverflow.com/q/50145702
has body: I am trying to bin a column into custom categories using a list as suggested in this answer- bins = [0, 1, 5, 10, 25, 50, 100] df = DataFrame({'Numbers':[0,1,2,7,11,16,45,200]}) df['Bins'] = pandas.cut(df['Numbers'], bins) df Numbers Bins 0 0 NaN 1 1 (0, 1] 2 2 (1, 5] 3 7 (5, 10] 4 11 (10, 25] 5 16 (10, 25] 6 45 (25, 50] 7 200 NaN How can I bin: 0 as [0,1] and 200 as (100,...) or >100 category?
downvote count: 0
linked to: http://stackoverflow.com/q/35763698
has answer: http://stackoverflow.com/a/50145720
favorite count: 0
accepted answer: http://stackoverflow.com/a/50145720
type: Question
tagged with: pandas
tagged with: python
has title: pandas.cut doesn't bin zero values
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 1

http://stackoverflow.com/a/50105301
answers question: http://stackoverflow.com/q/50105114
score: 0
has comment: http://stackoverflow.com/comment/87232372
has body: A simple naïve solution would be: s = 'do not-remove this-hyphen but remove-all of these-hyphens' words_to_keep = {'not-remove', 'this-hyphen'} new_s = [] for word in s.split(): if word not in words_to_keep: word = word.replace('-', ' ') new_s.append(word) print(' '.join(new_s)) # do not-remove this-hyphen but remove all of these hyphens Another approach with map: def unhyphen_word(word): return word.replace('-', ' ') if word not in words_to_keep else word print(' '.join(map(unhyphen_word, s.split()))) or list comprehension: print(' '.join([unhyphen_word(word) for word in s.split()]))
type: Answer
has comment: http://stackoverflow.com/comment/87232446

http://stackoverflow.com/q/50221507
downvote count: 1
has comment: http://stackoverflow.com/comment/87461015
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/87461151
possible better answer: http://stackoverflow.com/a/50221552
accepted answer: http://stackoverflow.com/a/50221568
has comment: http://stackoverflow.com/comment/87460774
has answer: http://stackoverflow.com/a/50221552
tagged with: python
has answer: http://stackoverflow.com/a/50221568
tagged with: nlp
type: AnsweredQuestion
has title: Convert list of string representations of sentences into vocabulary set
tagged with: list
score: 2
has body: I have a list of string representations of sentences that looks something like this: original_format = ["This is a question", "This is another question", "And one more too"] I want to convert this list into a set of unique words in my corpus. Given the above list, the output would look something like this: {'And', 'This', 'a', 'another', 'is', 'more', 'one', 'question', 'too'} I've figured out a way to do this, but it takes a very long time to run. I am interested in a more efficient way of converting from one format to another (especially since my actual dataset contains >200k sentences). FYI, what I'm doing right now is creating an empty set for the vocab and then looping through each sentence (split by spaces) and unioning with the vocab set. Using the original_format variable as defined above, it looks like this: vocab = set() for q in original_format: vocab = vocab.union(set(q.split(' '))) Can you help me run this conversion more efficiently?
has comment: http://stackoverflow.com/comment/87461053
upvote count: 3
has comment: http://stackoverflow.com/comment/87461656
tagged with: string

http://stackoverflow.com/comment/87236355
type: QuestionComment
comment on: http://stackoverflow.com/q/50108650
score: 0
has text: I can't create a dataset so small for my dataframes that it works. That is, if I cull both datasets to only 50 lines (with a few that ensure I would get an output), it still only gives the header as output using this code. This is why I thought it might be a `dtype` problem.
type: Comment

http://stackoverflow.com/q/50204440
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87427105
accepted answer: http://stackoverflow.com/a/50204534
has answer: http://stackoverflow.com/a/50204534
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/87479343
linked to: http://stackoverflow.com/q/3898574
has body: I am trying to create a program that takes a question with three answer choices. I want it to do a google search of the question and search the results for the answer choices and see which one comes up the most. I want to also make this more accurate with googling the question and the answer and seeing which returns the most results. Does anyone know how to do this? I know there is another question out there that answers a similar question to getting the URLs provided by the search result, but I want to get the number of results from the search.
has comment: http://stackoverflow.com/comment/87425918
type: AnsweredQuestion
has title: Advanced Google Search with Python
duplicate of: http://stackoverflow.com/q/3898574
score: -4
answer count: 1

http://stackoverflow.com/q/50106983
has comment: http://stackoverflow.com/comment/87231603
has comment: http://stackoverflow.com/comment/87231388
has comment: http://stackoverflow.com/comment/87231425
type: Question
has answer: http://stackoverflow.com/a/50107226
linked to: http://stackoverflow.com/q/16798811
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87234259
answer count: 1
duplicate of: http://stackoverflow.com/q/16798811
tagged with: python
has comment: http://stackoverflow.com/comment/87231418
tagged with: unicode
has title: Print format unicode list
tagged with: python-2.7
score: 0
has body: I have a list of unicode objects in Python 2.7. I want to format a print statement that will print this list. unicode_list = [u'something', u'\u25ba'] print u'Unicode list %s' % unicode_list The above code prints Unicode list [u'something', u'\u25ba']. But print unicode_list[1] prints ► as expected. How can I format string properly to print a unicode list? Like so: Unicode list ['something', '►']

http://stackoverflow.com/q/50148718
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50199041
score: 0
has body: I want to measure the time it takes my session to run inference operations. I measured it using time like so start = time.clock() sess.run([ops['pred']], feed_dict=feed_dict) end = time.clock() elapsed_time_batch = end-start I do this multiple times on the same dataset and average. The problem is - I get very different average time measurements ( 1.7ms vs 1.2 ms ). Even though its "just" 0.5ms difference its a big relative difference ( 0.5 vs 1.7 is about 30%). I tried setting some GPU options for the session like so : config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.95 config.gpu_options.allow_growth = False config.allow_soft_placement = True config.log_device_placement = False if limit_gpu: gpu_idx = str(gpu_idx) os.environ["CUDA_VISIBLE_DEVICES"] = gpu_idx else: os.environ["CUDA_VISIBLE_DEVICES"] = "0, 1" sess = tf.Session(config=config) But, this didn't solve it. What can be the cause of this change and how can I stabilize it to get a more reliable time read. I am running on a linux server with 4 GPUS ( for this test I limited to 1 GPU - a Titan Xp).
linked to: http://stackoverflow.com/q/17579357
answer count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50199041
tagged with: time
tagged with: python
has title: Tensorflow operation time fluctuations

http://stackoverflow.com/a/69219616
upvote count: 1
has body: For me the problem was the name of the file in s3 Bucket containing Spaces. So you have to make sure the key doesn't contain spaces while storing itself.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50181484
downvote count: 0

http://stackoverflow.com/q/50128278
answer count: 3
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/50130315
has answer: http://stackoverflow.com/a/50128576
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/50130315
has answer: http://stackoverflow.com/a/54247971
type: Question
downvote count: 0
tagged with: machine-learning
tagged with: python
has title: How to import a trained model to predict a single image?
tagged with: keras
accepted answer: http://stackoverflow.com/a/54247971
has body: I trained a CNN model by Keras, and I saved the model by model.save('model.h5') . But I want to test my model on a single image,I don't know how to import my own image to my model. # Image generators train_datagen = ImageDataGenerator(rescale= 1./255) validation_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(image_size, image_size), shuffle=True, batch_size=batch_size, class_mode='categorical' ) validation_generator = validation_datagen.flow_from_directory( validation_data_dir, target_size=(image_size, image_size), batch_size=batch_size, shuffle=True, class_mode='categorical' ) # Fit model history = model.fit_generator(train_generator, steps_per_epoch=(nb_train_samples // batch_size), epochs=nb_epoch, validation_data=validation_generator, callbacks=[early_stopping],# save_best_model], validation_steps=(nb_validation_samples // batch_size) ) # Save model model.save_weights('full_model_weights.h5') model.save('model.h5') I am new in keras. How can I do to deal an image to my model and classify my image to a certain class. The shape of input: if K.image_data_format() == 'channels_first': input_shape = (3, image_size, image_size) else: input_shape = (image_size, image_size, 3) My code of import a image: from keras.models import load_model m=load_model("model.h5") if K.image_data_format() == 'channels_first': input_shape = (3, image_size, image_size) else: input_shape = (image_size, image_size, 3) cloudy_pic="./Weather/weather_database/cloudy/4152.jpg" im=Image.open(cloudy_pic).convert('RGB') data=np.array(im,dtype=np.float32) data=np.reshape(500, 500,3) pre=m.predict_classes(data) pre And the error: AttributeError: 'int' object has no attribute 'reshape' During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) &lt;ipython-input-30-ebc72e185819&gt; in &lt;module&gt;() 10 im=Image.open(cloudy_pic).convert('RGB') 11 data=np.array(im,dtype=…
tagged with: deep-learning
type: AnsweredQuestion

web-scraping
tags question: http://stackoverflow.com/q/50219247
tags question: http://stackoverflow.com/q/50171839
tags question: http://stackoverflow.com/q/50202648
tags question: http://stackoverflow.com/q/50179783
tags question: http://stackoverflow.com/q/50100800
tags question: http://stackoverflow.com/q/50126725
tags question: http://stackoverflow.com/q/50220379
tags question: http://stackoverflow.com/q/50209429
tags question: http://stackoverflow.com/q/50164240
tags question: http://stackoverflow.com/q/50111041
tags question: http://stackoverflow.com/q/50211241
tags question: http://stackoverflow.com/q/50176051
tags question: http://stackoverflow.com/q/50216854
tags question: http://stackoverflow.com/q/50078120
tags question: http://stackoverflow.com/q/50082800
tags question: http://stackoverflow.com/q/50078229
tags question: http://stackoverflow.com/q/50194900
tags question: http://stackoverflow.com/q/50166782
tag name: web-scraping
tags question: http://stackoverflow.com/q/50145145
tags question: http://stackoverflow.com/q/50223629
tags question: http://stackoverflow.com/q/50151435
tags question: http://stackoverflow.com/q/50152424
tags question: http://stackoverflow.com/q/50138015
tags question: http://stackoverflow.com/q/50201692
tags question: http://stackoverflow.com/q/50185657
tags question: http://stackoverflow.com/q/50074995
tags question: http://stackoverflow.com/q/50144517
tags question: http://stackoverflow.com/q/50218738
tags question: http://stackoverflow.com/q/50153092
tags question: http://stackoverflow.com/q/50083325
tags question: http://stackoverflow.com/q/50186384
tags question: http://stackoverflow.com/q/50223024
tags question: http://stackoverflow.com/q/50205725
tags question: http://stackoverflow.com/q/50184327
type: Tag
tags question: http://stackoverflow.com/q/50150626
tags question: http://stackoverflow.com/q/50097551
tags question: http://stackoverflow.com/q/50151904
tags question: http://stackoverflow.com/q/50149940
tags question: http://stackoverflow.com/q/50190934
tags question: http://stackoverflow.com/q/50222051
tags question: http://stackoverflow.com/q/50227147
tags question: http://stackoverflow.com/q/50205073
tags question: http://stackoverflow.com/q/50093119
tags question: http://stackoverflow.com/q/50192215
tags question: http://stackoverflow.com/q/50098307
tags question: http://stackoverflow.com/q/50144103
tags question: http://stackoverflow.com/q/50148061
tags question: http://stackoverflow.com/q/50184850
tags question: http://stackoverflow.com/q/50091118
tags question: http://stackoverflow.com/q/50091655
tags question: http://stackoverflow.com/q/50229856
tags question: http://stackoverflow.com/q/50194819
tags question: http://stackoverflow.com/q/50166130
tags question: http://stackoverflow.com/q/50127821
tags question: http://stackoverflow.com/q/50209216
tags question: http://stackoverflow.com/q/50105364
tags question: http://stackoverflow.com/q/50175793
tags question: http://stackoverflow.com/q/50105015
tags question: http://stackoverflow.com/q/50195971
tags question: http://stackoverflow.com/q/50185605
tags question: http://stackoverflow.com/q/50144983
tags question: http://stackoverflow.com/q/50162457
tags question: http://stackoverflow.com/q/50158644
tags question: http://stackoverflow.com/q/50095378

http://stackoverflow.com/comment/87326143
comment on: http://stackoverflow.com/q/50146815
type: QuestionComment
type: Comment
has text: in php, I used to do that all the time, all I had to do was to add brackets next to the field name [] and values would be put inside an array. From the documentation, I read you use form.getlist instead of from.get but it does not work. Thanks
score: 0

http://stackoverflow.com/comment/87368556
type: Comment
has text: @Benjamin You're very welcome. Good luck with your FASTA.
comment on: http://stackoverflow.com/a/50172444
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87416521
type: QuestionComment
comment on: http://stackoverflow.com/q/50141228
has text: I think your question would benefit from including a [MVCE](https://stackoverflow.com/help/mcve) showing the parameters you are passing to `fmin_bfgs` and the expected result.
score: 1
type: Comment

http://stackoverflow.com/comment/87296287
type: AnswerComment
score: 0
has text: I am not against the downvotes sir, but the person should still mention the valid reason behind that. So, that I keep that in mind while answering and try to improve that in future.
type: Comment
comment on: http://stackoverflow.com/a/50128352

http://stackoverflow.com/q/50086395
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87188611
has answer: http://stackoverflow.com/a/50086825
tagged with: algorithm
type: UnansweredQuestion
score: -2
tagged with: java
has comment: http://stackoverflow.com/comment/87188686
tagged with: python
has title: Useful algorithms for TSP
tagged with: traveling-salesman
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/87188937
has comment: http://stackoverflow.com/comment/87189046
has body: I'm currently working on TSP which has been given to me as my end of year project in my computer science course. In this problem we are given a list of the top 1000 colleges in the world. Then starting at our own colleges, we have to travel to all the other colleges once and make it back to ours. But we are only allowed to travel to colleges that are within 100 rank of college that you are currently at, with no wraparound at either ends of the list. I tried to approach it using nearest neighbour but I kept on running to a problem where my code would get stuck at a certain university because it would have already travelled to all the other colleges within 100 rank of it. I am now currently trying to use a genetic algorithm to solve it but I'm running into some issues. Is there any other algorithm that would be good for this problem that I could use in the meantime while trying to fix my genetic algorithm?
tagged with: heuristics
answer count: 1
has comment: http://stackoverflow.com/comment/87188457
has comment: http://stackoverflow.com/comment/87188672

http://stackoverflow.com/a/50090150
type: Answer
has comment: http://stackoverflow.com/comment/87197040
answers question: http://stackoverflow.com/q/50089849
score: 2
downvote count: 0
has body: It's possible you are in a virtualized environment (like docker) and your virtual timezone is different from the one in your host. Your best shot would be to specify the timezone manually what's well described here.
upvote count: 2
has comment: http://stackoverflow.com/comment/87196978
has comment: http://stackoverflow.com/comment/87196887
has comment: http://stackoverflow.com/comment/87196562

http://stackoverflow.com/comment/87412872
has text: Have you seen this: https://docs.python.org/3.6/extending/windows.html?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50197984
score: 0

http://stackoverflow.com/comment/87372058
has text: @YannDroy The difference is, that that my regex requires at laest one digit, the answer you mention also accepts empty strings or strings consisting only of white-space. Depends of course what fits your needs better.
comment on: http://stackoverflow.com/a/50177224
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50203743
has answer: http://stackoverflow.com/a/50204053
possible better answer: http://stackoverflow.com/a/50204053
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50203813
has answer: http://stackoverflow.com/a/50204529
accepted answer: http://stackoverflow.com/a/50203813
answer count: 3
has comment: http://stackoverflow.com/comment/87424410
has title: How do I join the integers together in a list such that: ['a',1,2] becomes ['a',12]
has body: I have a list input as li = ['a',3,4,'b',6,'c',5,1] and I want to my output list as li = ['a',34,'b',6,'c',51].
downvote count: 7
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
score: -4
has comment: http://stackoverflow.com/comment/87424435
has comment: http://stackoverflow.com/comment/87424540

http://stackoverflow.com/a/67629666
score: 0
answers question: http://stackoverflow.com/q/50125824
has body: Had the same issue and your question answered it for me: "I have to stop anaconda." Thank you. One can do so by ensuring that conda is deactivated by running: conda deactivate Ensure that it does not have "(base)" before in the terminal or anything else in parentheses. NOT NOT YES So in this case, I had to run 'conda deactivate' twice.
type: Answer

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

http://stackoverflow.com/a/50114123
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/50099745
type: Answer
accepted answer of: http://stackoverflow.com/q/50099745
upvote count: 4
has body: I have figured what I was doing wrong. My thinking was right but I shouldn't have recreated the Graph and Session below. The bottom part of the code should simply be: thread_locker.acquire() with thread_graph.as_default(): with thread_session.as_default(): pred_data= model.predict(X_pred) thread_locker.release()
type: AcceptedAnswer

opencv
tags question: http://stackoverflow.com/q/50213162
tags question: http://stackoverflow.com/q/50178248
type: Tag
tags question: http://stackoverflow.com/q/50095730
tags question: http://stackoverflow.com/q/50188085
tags question: http://stackoverflow.com/q/50179822
tags question: http://stackoverflow.com/q/50204883
tags question: http://stackoverflow.com/q/50137181
tags question: http://stackoverflow.com/q/50199990
tags question: http://stackoverflow.com/q/50092730
tags question: http://stackoverflow.com/q/50222119
tags question: http://stackoverflow.com/q/50177330
tags question: http://stackoverflow.com/q/50210961
tags question: http://stackoverflow.com/q/50126492
tags question: http://stackoverflow.com/q/50227287
tags question: http://stackoverflow.com/q/50083366
tags question: http://stackoverflow.com/q/50185383
tags question: http://stackoverflow.com/q/50187902
tags question: http://stackoverflow.com/q/50180298
tags question: http://stackoverflow.com/q/50099347
tags question: http://stackoverflow.com/q/50146838
tags question: http://stackoverflow.com/q/50086404
tags question: http://stackoverflow.com/q/50197440
tags question: http://stackoverflow.com/q/50120777
tags question: http://stackoverflow.com/q/50221851
tags question: http://stackoverflow.com/q/50078086
tags question: http://stackoverflow.com/q/50110903
tags question: http://stackoverflow.com/q/50166214
tags question: http://stackoverflow.com/q/50201175
tags question: http://stackoverflow.com/q/50110153
tags question: http://stackoverflow.com/q/50076117
tags question: http://stackoverflow.com/q/50131912
tags question: http://stackoverflow.com/q/50160981
tags question: http://stackoverflow.com/q/50090997
tags question: http://stackoverflow.com/q/50164509
tags question: http://stackoverflow.com/q/50199603
tags question: http://stackoverflow.com/q/50214180
tags question: http://stackoverflow.com/q/50210304
tags question: http://stackoverflow.com/q/50209920
tags question: http://stackoverflow.com/q/50106050
tags question: http://stackoverflow.com/q/50176037
tags question: http://stackoverflow.com/q/50104362
tags question: http://stackoverflow.com/q/50120075
tags question: http://stackoverflow.com/q/50203766
tags question: http://stackoverflow.com/q/50152665
tags question: http://stackoverflow.com/q/50114747
tags question: http://stackoverflow.com/q/50170587
tags question: http://stackoverflow.com/q/50118869
tags question: http://stackoverflow.com/q/50208859
tags question: http://stackoverflow.com/q/50087098
tags question: http://stackoverflow.com/q/50165274
tags question: http://stackoverflow.com/q/50121703
tags question: http://stackoverflow.com/q/50114993
tags question: http://stackoverflow.com/q/50080949
tags question: http://stackoverflow.com/q/50213698
tags question: http://stackoverflow.com/q/50227719
tags question: http://stackoverflow.com/q/50128034
tags question: http://stackoverflow.com/q/50192622
tags question: http://stackoverflow.com/q/50229181
tags question: http://stackoverflow.com/q/50185654
tags question: http://stackoverflow.com/q/50178477
tags question: http://stackoverflow.com/q/50202410
tags question: http://stackoverflow.com/q/50229030
tags question: http://stackoverflow.com/q/50113684
tags question: http://stackoverflow.com/q/50076476
tags question: http://stackoverflow.com/q/50123428
tags question: http://stackoverflow.com/q/50163192
tags question: http://stackoverflow.com/q/50198103
tags question: http://stackoverflow.com/q/50183045
tags question: http://stackoverflow.com/q/50172934
tags question: http://stackoverflow.com/q/50092954
tag name: opencv
tags question: http://stackoverflow.com/q/50179799
tags question: http://stackoverflow.com/q/50113054
tags question: http://stackoverflow.com/q/50137059
tags question: http://stackoverflow.com/q/50193883
tags question: http://stackoverflow.com/q/50189331
tags question: http://stackoverflow.com/q/50110865
tags question: http://stackoverflow.com/q/50157416
tags question: http://stackoverflow.com/q/50229772

http://stackoverflow.com/comment/87225938
has text: Ok. that is a completely different problem then. Basically not solvable by multiprocessing, as your subprocesses only modify the local copy of the object passed to the subprocess. There is no way you can modify the object in the main process memory from a subprocess as this would cause a segmentation fault. Let me think if there is an easy workaround.
type: AnswerComment
comment on: http://stackoverflow.com/a/50099648
score: 0
type: Comment

http://stackoverflow.com/q/50159071
type: UnansweredQuestion
has body: I have the following data in the dataframe: df: Category date date_Count 0 CAT1 2017-05 144 1 CAT1 2017-11 67 2 CAT2 2017-06 76 3 CAT2 2017-11 57 4 CAT2 2018-04 220 5 CAT2 2018-07 52 There are ~ 8 differeent cats each sorted by time (Year + month) I would like to plot the count values of time , with a bar for each category. I was using Bokeh to do this, but failing miserably. This is the furthest I got. I would like to make the values appear as labels on each bar. Thanks, [EDIT] : Code: counts=[] countDates=df['date_Count'].Cat.dt.month]).agg('count') months=np.arange(1.0, 12.0,1.0) for month in months: if month in countDates[2018].keys(): counts.append(countDates[2018][month]) else: counts.append(0) output_file('bokTest.html') factors = [ ("Q1", "jan"), ("Q1", "feb"), ("Q1", "mar"), ("Q2", "apr"), ("Q2", "may"), ("Q2", "jun"), ("Q3", "jul"), ("Q3", "aug"), ("Q3", "sep"), ("Q4", "oct"), ("Q4", "nov"), ("Q4", "dec"), ] p = figure(x_range=FactorRange(*factors), plot_height=350, toolbar_location='right') p.vbar(x=factors, top=counts, width=0.9, alpha=0.5) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None show(p)
tagged with: python
tagged with: bokeh
has comment: http://stackoverflow.com/comment/87444228
score: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/87474687
has comment: http://stackoverflow.com/comment/87337220
has comment: http://stackoverflow.com/comment/87356373
type: Question
has title: Plotting timeseries Bokeh chart with multiple categories

http://stackoverflow.com/comment/131144878
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50137686
type: Comment
has text: @mdurant can you please clarify why using fastparquet works? I'm facing a similar issue with Dask DataFrames and can't figure out why I can store them to disk with fastparquet but not with pyarrow. In fact, dask's `to_parquet` method even ignores the argument `schema` when the engine being used is `fastparquet` and I really can't figure out why.

http://stackoverflow.com/comment/87285801
type: QuestionComment
has text: Have you tried the solution proposed here <https://stackoverflow.com/questions/24174821/how-to-change-default-install-location-for-pip>?
comment on: http://stackoverflow.com/q/50129159
score: 0
type: Comment

http://stackoverflow.com/a/50131077
type: Answer
has comment: http://stackoverflow.com/comment/87280901
upvote count: 1
answers question: http://stackoverflow.com/q/50131042
downvote count: 0
has body: Instead of using ::1 for the host, try use localhost. If that doesn't work, your system likely does not support IPv6. You can find more information about IPv6 support here.
score: 1

http://stackoverflow.com/q/50085411
has comment: http://stackoverflow.com/comment/87186873
has comment: http://stackoverflow.com/comment/87186683
tagged with: indexing
has title: Make a list of two indexes in Pyomo (Python)
has answer: http://stackoverflow.com/a/58286802
tagged with: list
tagged with: matrix
downvote count: 1
has comment: http://stackoverflow.com/comment/87186651
score: -1
has body: Good morning, I've been searching through the internet a way to make a list or table with 2 indexes. Currently I've build a code for 1 index that is mass = list(range(0,value(m.n)+1)) and I fill this list with this expression mass[i] = value(m.mass[i]). But now I have to introduce another variable that has two indexes as the following x[i,j] = value(m.x[i,j]). I've tried with x = []*value(m.ph). But what I want is to get something like x = [value(m.n)]*value(m.ph) in order to state that I have a table like. values (m.n) as rows and phases (m.ph) as columns. The goal of doing so is graphing those variables with this function plt.plot(time,x). Idk if it will be possible to do this kind of list, table or matrix as you want to call it, but it will be very useful to know it because I got kinda stuck because of it. My code is as following: n = Param(initialize = 10, within = Integers) N = Set(initialize = range(0,value(m.n)+1)) #What I got x1 = [0,1,2,3,4,5,6,7,8,9,10] x = list(range(0,value(m.n)+1)) for i in m.N: x[i] = x1[i] #What I try to do ph = Param(initialize = 2, within = Integers) Ph = Set(initialize = range(0,value(m.n)+1)) x2 = [[0,0],[1,1],[2,2],[3,3],[4,4]] x = []*value(m.ph) for i in m.N: for j in m.Ph: x[i,j] = x2[i,j] The error is as following: File "C:/Users/Manuel/Desktop/StackExample.py", line 38, in &lt;module&gt; x[i,j] = x2[i,j] TypeError: list indices must be integers or slices, not tuple Thank you so much. EDIT: What I want is create a list with two indexes in Python making those indexes have the length I required being these lenght defined by m.n = Param(initialize = 32, within = Integers) and m.ph = Param(initialize = 2, within = Integers).
type: Question
tagged with: pyomo
upvote count: 0
has answer: http://stackoverflow.com/a/50163795
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87186507
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/87282128
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50132075
has text: Could you post [reproducible example](https://stackoverflow.com/questions/48427185/how-to-make-good-reproducible-apache-spark-dataframe-examples/48428198). It is not clear how you get `[walmartsupercenter]` and what are the types? Is it nested array, formatted string, can it occur on every position?
score: 1

http://stackoverflow.com/q/50183196
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has body: I have a grid with some items and I´d like to sum val_itemservico column from selected rows. My template sums all rows. I´d like to sum val_itemservico column only for selected rows when I click on "Calcular" button. In this case, I need to know if ind_selecionado column is checked. So, how can I do that? HTML: ORÇAMENTO ORÇAMENTO {% csrf_token %} Serviço: {{filter.form.servico}} OK <!--width="100%" border="0" cellspacing="0" cellpadding="2">--> Selecionar ID Item Serviço Item Serviço Valor Serviço Serviço {% for item in response.object_list %} {{ item.id }} {{ item.desc_itemservico }} {{ item.val_itemservico }} {{ item.servico_id}} {% endfor %} {% if response.object_list %} Total: {% endif %} Valores: {% for item in response.object_list %} {{item.val_itemservico}} {% endfor %} Calcular
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50183501
has comment: http://stackoverflow.com/comment/87384084
has title: How to sum only selected rows from a list
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: javascript
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50183501

http://stackoverflow.com/q/50138967
has title: Passing list value to loadworkbook || Python
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87296349
linked to: http://stackoverflow.com/q/2711579
tagged with: python
accepted answer: http://stackoverflow.com/a/50139099
duplicate of: http://stackoverflow.com/q/2711579
type: AnsweredQuestion
has body: I have a list named tickets tickets = ['ITSVC-YY160044392', 'ITSVC-YY170045022', 'ITSVC-YY170045032'] I have excel attachments for same list tickets like ITSVC-YY160044392.xlsx,ITSVC-YY170045022.xlsx,ITSVC-YY170045032.xlsx for the items in tickets[] i had to open their respective excel files from xlwt import Workbook import openpyxl as xl for x in cdc_tickets(): wb = xl.load_workbook('x.xlsx') b = wb.active In the statement wb = xl.load_workbook('x.xlsx') in place of 'x' i want my list values that are stored in tickets to be passed to load the respective excel like wb = xl.load_workbook('ITSVC-YY160044392.xlsx') How to pass list value to loadwork statement?
score: 0
has answer: http://stackoverflow.com/a/50139099

http://stackoverflow.com/comment/87347069
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50163152
score: 1
has text: Possible duplicate of [Python3.2: Installing MySQL-python fails with error "No module named ConfigParser"](https://stackoverflow.com/questions/15140855/python3-2-installing-mysql-python-fails-with-error-no-module-named-configparse)

http://stackoverflow.com/q/50187907
has body: I have a dataset 100000 rows X 200 columns. I want to perform a classification. My target column, is an object (string) and has 1345 unique values. Let's suppose that my target column is 'names'. I am interested in keeping just the following names: John, Mary, Chris, Anna. How do I 'filter' my dataset, so that it contains only the rows that have these names in the target column? After filtering the dataset, I want to create a classifier that will have four classes, meaning the four names.I thought about using get_dummies,but then I will have 4 target columns. I just want to transform for example, John = 1, Mary = 2 , etc. Any ideas? Thanks a lot
has comment: http://stackoverflow.com/comment/87481390
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 3
has title: Filtering an object column in pandas
tagged with: pandas
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/50193265
tagged with: dataframe

http://stackoverflow.com/a/50082498
type: Answer
has comment: http://stackoverflow.com/comment/87192654
upvote count: 3
downvote count: 0
has body: Probably your python path is messed up. The message you are getting in 'idle' is just a warning you can ignore it for now. But the message you getting in your jupyter notebooks is a real error that you need to fix. Try running the following code both in your idle environment and in Jupyter notebook. Do it before you import Keras import sys print sys.path Then compare results. Probably jupyter is not picking up your virtual environment. Continuing based on your test results: Looks like you running Idle from virtualenv that you created called 'tensorflow', but you are running jupyter from regular anaconda environment. If you jupyter is simply installed as a module in Anaconda environmnet. You can just install it again into your tensorflow virtual env by running the following commands activate tensorflow pip install jupyter Then run jupyter-notebook This should fix your issue. Make sure to print out sys.path to double check
has comment: http://stackoverflow.com/comment/87181132
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50082388
answers question: http://stackoverflow.com/q/50082388
score: 3
has comment: http://stackoverflow.com/comment/87181662

http://stackoverflow.com/a/50165755
downvote count: 0
answers question: http://stackoverflow.com/q/50165501
type: Answer
score: 4
upvote count: 4
has body: Depending on your needs, it might be well worth the trouble to learn the Python datetime and time modules. If your code will do lots of different manipulations, then go with @abarnert's answer. If all you need is a time string (rather than a Python timestamp), this function will crank it out for you: import random def randomTime(): # generate random number scaled to number of seconds in a day # (24*60*60) = 86,400 rtime = int(random.random()*86400) hours = int(rtime/3600) minutes = int((rtime - hours*3600)/60) seconds = rtime - hours*3600 - minutes*60 time_string = '%02d:%02d:%02d' % (hours, minutes, seconds) return time_string for i in range(10): print(randomTime()) this outputs: 19:07:31 16:32:00 02:01:30 20:31:21 20:20:26 09:49:12 19:38:42 10:49:32 13:13:36 15:02:54 But if you don't want 24 hour time, then you can intercept the 'hours' variable before you stuff it in into the string: import random def randomTime(): # generate random number scaled to number of seconds in a day # (24*60*60) = 86,400 rtime = int(random.random()*86400) hours = int(rtime/3600) minutes = int((rtime - hours*3600)/60) seconds = rtime - hours*3600 - minutes*60 # figure out AM or PM if hours &gt;= 12: suffix = 'PM' if hours &gt; 12: hours = hours - 12 else: suffix = 'AM' time_string = '%02d:%02d:%02d' % (hours, minutes, seconds) time_string += ' ' + suffix return time_string for i in range(10): print(randomTime()) which gives : 05:11:45 PM 02:28:44 PM 08:09:19 PM 02:52:30 PM 07:40:02 PM 03:55:16 PM 03:48:44 AM 12:35:43 PM 01:32:51 PM 07:54:26 PM

http://stackoverflow.com/comment/87396971
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50188647
has text: What is the character that you are inserting?

http://stackoverflow.com/comment/87303917
has text: thank you, I will try out tomorrow, but I think that was it. Sometimes you don't even see the most obvious things ;) thx
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50142167
score: 0

http://stackoverflow.com/a/50106963
has comment: http://stackoverflow.com/comment/87235761
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87235792
has body: django-paseguro is trying to import patterns, so it doesn’t support Django 1.10+. The failing import django.conf.urls.defaults is a fallback for Django &lt; 1.6.
answers question: http://stackoverflow.com/q/50106372
score: 1
type: Answer

http://stackoverflow.com/comment/87315201
has text: @abarnert foo is a list of all elements and bar is sublist of foo, so there are duplicates. initially, foo was a string instead of list, so i converted to a list to be able to change its elements. i was able to remove the elements in foo that were also in bar using the two methods i mentioned earlier: the list comprehension and for loop.
type: AnswerComment
comment on: http://stackoverflow.com/a/50147963
score: 0
type: Comment

http://stackoverflow.com/comment/87172030
type: QuestionComment
has text: It'll be tough to get an answer to this question unless you (a) try it yourself first and let folks see what's NOT working or (b) ask a specific question. For now, I would add a few [Try/Catch blocks](http://www.pythonforbeginners.com/error-handling/python-try-and-except) to this code -- so you can catch errors and write them to file as needed
type: Comment
comment on: http://stackoverflow.com/q/50077959
score: 0

http://stackoverflow.com/a/50194798
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87407072
has comment: http://stackoverflow.com/comment/87407063
has body: In Python, [0] is indexing—it returns the first element, while [0:1] is slicing—it returns a collection of all of the first 1 elements. This may be easier to see with a plain old list: &gt;&gt;&gt; lst = [1, 2, 3] &gt;&gt;&gt; lst[0] 1 &gt;&gt;&gt; lst[0:1] [1] Numpy extends Python indexing and slicing, and some of these would give you a 2D result, for different reasons—e.g., you could index with [0] as an “array-like”, which would work as an index array), but the relevant basics are the same here. For a 2D numpy array, the elements are rows, so candidates[0] is the first row—a 1D array, while candidates[0:1] is an array of all of the first 1 rows—a 2D array. So the first one has shape (34,), and the second has shape (1, 34). The difference may not be obvious if you don't look closely, but compare how the two start: array([1, array([[1, They're not lined up, because the second one has two brackets instead of one, which is because it's a 2D array instead of 1D.
score: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/50194752
has comment: http://stackoverflow.com/comment/87407116
answers question: http://stackoverflow.com/q/50194752
downvote count: 0
upvote count: 10

weather
tags question: http://stackoverflow.com/q/50143155
tag name: weather
type: Tag

avro
type: Tag
tags question: http://stackoverflow.com/q/50106662
tags question: http://stackoverflow.com/q/50168243
tag name: avro

http://stackoverflow.com/q/50144570
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50144639
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
score: 1
has answer: http://stackoverflow.com/a/50144639
has body: I have a dictionary with an unequal list as values like this dict_data = { "Data 1": ["cool", "fantastic"], "Data 2": ["spam", "hello", "howdy", "foo"], "Data 3": ["good morning"], } I want something like this as output Data 1 Data 2 Data 3 cool spam good morning fantastic hello howdy foo I have tried this which I found on this forum def transpose(cols): return map(lambda *row: list(row), *cols) with open('result.csv','w') as out_file: writer = csv.writer(out_file,dialect = 'excel') headers = dict_data.keys() items = transpose(dict_data.values()) writer.writerow(headers) writer.writerows(items) But it only outputs the first row Data 1 Data 2 Data 3 cool spam good morning
has title: How do i convert a dictionary with unequal list as value to csv
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50144651
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50144651
has answer: http://stackoverflow.com/a/50193502
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87344092
type: Comment
comment on: http://stackoverflow.com/a/50148258
type: AnswerComment
has text: Thanks for doing so much work on this question. The Pytds suggestion is definitely the right answer. Unfortunately, I can't use it at my company, so we ended up asking the database manager to create a new procedure that takes XML as input, instead.
score: 1

http://stackoverflow.com/comment/87271617
type: QuestionComment
comment on: http://stackoverflow.com/q/50126307
has text: @minterm I added the info in the question.
score: 0
type: Comment

http://stackoverflow.com/a/50178378
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50178228
has body: you can process your task using regex easily as below: &gt;&gt;&gt; import re &gt;&gt;&gt; s = "1 80,982 163,8164 170,2620 145,648 200,8021 173,2069" &gt;&gt;&gt; re.findall(r'(\d+) (\d+),(\d+)', s) # pass your file content s as string [('1', '80', '982'), ('8164', '170', '2620'), ('648', '200', '8021')] Explanation: findall - returns list of all matched pattern \d+ - match one or more digits
type: Answer

http://stackoverflow.com/q/50117450
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87252283
has title: Multi-label classification methods for large dataset
tagged with: scikit-learn
tagged with: python
has body: I realize there's another question with a similar title, but my dataset is very different. I have nearly 40 million rows and about 3 thousand labels. Running a simply sklearn train_test_split takes nearly 20 minutes. I initially was using multi-class classification models as that's all I had experience with, and realized that since I needed to come up with all the possible labels a particular record could be tied to, I should be using a multi-label classification method. I'm looking for recommendations on how to do this efficiently. I tried binary relevance, which took nearly 4 hours to train. Classifier chains errored out with a memory error after 22 hours. I'm afraid to try a label powerset as I've read they don't work well with a ton of data. Lastly, I've got adapted algorithm, MlkNN and then ensemble approaches (which I'm also worried about performance wise). Does anyone else have experience with this type of problem and volume of data? In addition to suggested models, I'm also hoping for advice on best training methods, like train_test_split ratios or different/better methods.
tagged with: multilabel-classification
accepted answer: http://stackoverflow.com/a/50117662
has comment: http://stackoverflow.com/comment/87252386
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87252250
answer count: 1
has comment: http://stackoverflow.com/comment/87252343
has answer: http://stackoverflow.com/a/50117662
favorite count: 0

http://stackoverflow.com/comment/87405021
comment on: http://stackoverflow.com/a/50169022
type: Comment
score: 0
type: AnswerComment
has text: It recomputes the same distances O(k) times. But that is just because of the bad code you got from the blog. The real kmeans++ doesn't do that. You see: for your assignment you need to use a *good* code. You want to improve an algorithm, not fix a bug in a bad blog post.

http://stackoverflow.com/q/50181184
has comment: http://stackoverflow.com/comment/87382134
has comment: http://stackoverflow.com/comment/87379556
tagged with: python
type: UnansweredQuestion
score: -2
has body: The code below works until the final line: writer.writerow([Title, Views, Likes, Dislikes, datetime.now()]) and I receive this error: NameErrorTraceback (most recent call last) &lt;ipython-input-45-1666dd7f773b&gt; in &lt;module&gt;() ----&gt; 1 writer.writerow([Title, Views, Likes, Dislikes, datetime.now()]) NameError: name 'Title' is not defined Can someone tell me what going on???? (Using python2 with Jupyter) from urllib2 import urlopen from bs4 import BeautifulSoup import pandas as pd import re import requests myurl = 'https://www.youtube.com/results?search_query=sports' page = requests.get("https://www.youtube.com/results?search_query=sports") page.status_code soup = BeautifulSoup(page.content, 'html.parser') soup link_list = [] for link in soup.select('div.yt-lockup-content a[href^=/watch]'): newLink = link.attrs.get('href') link_list.append(newLink) print(link_list[0:6]) index = range(len(link_list)) columns = ['Links', 'Title', 'Views', 'Likes', 'Dislikes'] df = pd.DataFrame(index=index, columns=columns) df['Links'] = link_list df['Links'] = 'https://www.youtube.com/' + df['Links'] for i in range(len(link_list)): if i&lt;5 or i&gt;len(link_list)-5: print('{} out of {}'.format(i, len(link_list))) html = urlopen(df['Links'][i]).read() from bs4 import BeautifulSoup soup = BeautifulSoup(html.decode('utf-8', 'ignore')) df['Title'][i] = soup.title.get_text() df['Views'][i] = int(re.sub('[^0-9]', '',soup.select('.watch-view-count')[0].get_text().split()[0])) df['Title'][i] = soup.title.get_text() df['Views'][i] = int(re.sub('[^0-9]', '', soup.select('.watch-view-count')[0].get_text().split()[0])) a = str(soup.find_all('button', \ attrs={'title': 'I like this'})).replace(",","") df['Likes'][i] = float(re.findall(r'\d+', a)[0]) a = str(soup.find_all('button', \ attrs={'title': 'I dislike this'})).replace(",","") df['Dislikes'][i] = float(re.findall(r'\d+', a)[0]) print(df.sort_values('Views', ascending = False).head()) print(df.sort_values('Views', ascending = False…
has comment: http://stackoverflow.com/comment/87379551
has title: NameError: name 'Title' is not defined (Why is 'Title' not defined)
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87379570
has answer: http://stackoverflow.com/a/50181230
tagged with: syntax-error
type: Question
upvote count: 0

http://stackoverflow.com/a/50196145
answers question: http://stackoverflow.com/q/50145104
has comment: http://stackoverflow.com/comment/92790004
downvote count: 0
score: 1
upvote count: 1
has body: The if statement can do any condition at all. You just have to be a little more explicit. def switch(case): if case in 'a': doA() if case in 'ab': doB() if case in 'abc': doC() return if case in 'de': doDE() return if case in 'fg': doFG() if case in 'fgh': doH() return if case in 'i': doI() foo()
type: Answer

http://stackoverflow.com/comment/87304191
comment on: http://stackoverflow.com/q/50097149
score: 0
has text: That is the high-level idea. The `DynamicRnnEstimator` is being deprecated because one can effectively achieve the same functionality by a custom `model_fn`. You can also just take the code of `DynamicRnnEstimator`, remove all the options you don't need and refactor it do all the work in `model_fn`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87395103
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50189134
has text: How can you tell that you’re logged in as that user? Maybe the place with that information also uses `{{ user }}`?

http://stackoverflow.com/a/50092093
downvote count: 0
has body: This is due to the way GroupBy objects handle the different aggregation methods. In fact sum and mean are handled differently (see below for more details). But the bottom line is that mean only works for numeric types which are not present in your data frame: &gt;&gt;&gt; df.dtypes g object c1 object c2 object dtype: object By applying pd.to_numeric you convert them to numeric type and the agg works. But let's take a closer look: GroupBy.mean This function call dispatches to self._cython_agg_general which checks for numeric types and in case it doesn't find any (which is the case for your example) it raises a DataError. Though the call to self._cython_agg_general is wrapped in try/except in case of a GroupByError it just re-raises and DataError inherits from GroupByError. Thus the exception. GroupBy.sum This function is defined in a different way, namely here (via this function). The wrapper function similarly dispatches to self._cython_agg_general, wrapped in try/except, but it doesn't add a specific clause for GroupByErrors (no idea why though; maybe that's a good question for the developers, so they can unify the behavior of GroupBy objects). Because self._cython_agg_general again raises the DataError it will enter the except Exception clause for which it falls back to self.aggregate. From here you can trace it down through a dozen of additional function calls but in the end it will simply add the single items of the series (which are stored as objects but adding in Python is no problem since they are ints in fact). Summary So it all comes down to the different ways exceptions are handled by the two aggregation functions; mean re-raises on DataError but sum doesn't. The "why" still remains an open question to me as well. See also Inconsistencies in groupby aggregation with non-numeric types SeriesGroupby.cumsum raises on object dtype
answers question: http://stackoverflow.com/q/50091321
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/87210507
score: 8
accepted answer of: http://stackoverflow.com/q/50091321
type: AcceptedAnswer

http://stackoverflow.com/a/50159213
has body: Column specifies which column you wish the widget to appear in columnspan tells the layout manager that you wish for this widget to occupy more than 1 column i.e. spans across 2 columns See http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/grid.html https://users.tricity.wsu.edu/~bobl/cpts481/tkinter_nmt.pdf (New link to reference document) For example widget.grid(row=0, column=1, columnspan=3) Will create a widget in row 0 and that spans across columns 1, 2 and 3
has comment: http://stackoverflow.com/comment/111259526
accepted answer of: http://stackoverflow.com/q/50158866
has comment: http://stackoverflow.com/comment/112419937
type: Answer
upvote count: 11
score: 11
answers question: http://stackoverflow.com/q/50158866
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50190114
type: Answer
has comment: http://stackoverflow.com/comment/87437039
answers question: http://stackoverflow.com/q/50189134
score: 0
has body: The place where you are setting the variable user to display the logged-in user name is not shown in your code. Anyway, since you are getting the profile details of the user into the variable user, it's getting displayed across Signed in as: label. The logged-in user details could be easily obtained from request.user, without interfering with any context data. Check the output of the following... Signed in as: {{request.user}}

http://stackoverflow.com/comment/87462348
type: Comment
has text: @user9613318 as per my understanding, python udf are not efficient as serialisation deserialisation steps are involved from JVM to Python and vice versa.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50215791

http://stackoverflow.com/q/50203341
favorite count: 0
has title: Python - SQLite : Update two record with same identify value
type: Question
has body: i have a script like below : import psutil import sqlite3 DISK = {'1': ['C:\\', 'C:\\', 'NTFS', 'rw,fixed', '75.0Gb', '54.0Gb', '20.0Gb', '72.2%'], '2': ['D:\\', 'D:\\', 'NTFS', 'rw,fixed', '399.0Gb', '208.0Gb', '191.0Gb', '52.2%']} conn = sqlite3.connect("Test.db") c = conn.cursor() result = c.execute("SELECT * FROM clientinfo WHERE IP = ?", ("192.168.10.111",)) if (len(result.fetchall()) &gt; 0): for x in DISK : c.execute("UPDATE disk SET Device = ?, 'Mount Point' = ?, 'fstyle' = ?, 'opts' = ?, 'total' = ?, 'used' = ?, 'free' = ?, 'percent' = ? WHERE Client_IP = ?", (DISK[x][0], DISK[x][1], DISK[x][2], DISK[x][3], DISK[x][4], DISK[x][5], DISK[x][6], DISK[x][7], "192.168.10.111")) else : for x in DISK : c.execute("INSERT INTO disk('Client_IP', 'Device', 'Mount Point', 'fstyle', 'opts', 'total', 'used', 'free', 'percent') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ("192.168.10.111", DISK[x][0], DISK[x][1], DISK[x][2], DISK[x][3], DISK[x][4], DISK[x][5], DISK[x][6], DISK[x][7])) conn.commit() conn.close() Script will check in db if there is any record about IP "192.168.10.111". If db already have record about IP "192.168.10.111", Script will update data from dict DISK to table disk of db. If db don't have record about IP "192.168.10.111", Script will create record to insert **DISK"" to database. INSERT command work well but the UPDATE command don't work like i want. After INSERT command run, in table disk i will have two record about disk C and disk D with same value of column Client_IP (192.168.10.111). After UPDATE, two record of IP "192.168.10.111" get same value on every column ehich is very wrong. One record must be contain information about disk C and another record cotain disk D information. How can i make the UPDATE work right ? length of dict DISK depend on how many mounted devices the computer has. So i need to use for loop to UPDATE but not static UPDATE. Please tell me how to fix this, Many thanks, Francis
has comment: http://stackoverflow.com/comment/87651931
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87457929
has comment: http://stackoverflow.com/comment/87423579
tagged with: python
has comment: http://stackoverflow.com/comment/87650394
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50203435
has comment: http://stackoverflow.com/comment/87451330
score: 1
tagged with: sqlite
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87308898
score: 1
type: Comment
type: QuestionComment
has text: I HIGHLY recommend reading up about PCA and what it does. The values are different for a very good reason, and if you're trying to prevent that, then you're not doing PCA (you're doing something else, very very incorrect).
comment on: http://stackoverflow.com/q/50145394

http://stackoverflow.com/q/50189610
has body: I am new so plz help. i am writting a program that adds numbers. it asks for input and until "Q" is inputed it keeps asking for input def add_num(vari = "" , total = 0): vari = input("Enter a num or press \"Q\" to stop: ") while (vari.startswith("Q") and int(vari).isdigit() ) == False: print("Error") vari = input("plz enter again: ") else: print("Nice") there are no indentation error. The problem i have is how can i check if it starts with "Q" or it is a number. I think this is the code that has errors while (vari.startswith("Q") and int(vari).isdigit() ) == False:
has comment: http://stackoverflow.com/comment/87396126
has comment: http://stackoverflow.com/comment/87396022
has comment: http://stackoverflow.com/comment/87396075
has title: How can i check if an inputted variable either starts with "Q" or it is a number
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88317804
downvote count: 4
upvote count: 0
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/50189649
answer count: 1
has comment: http://stackoverflow.com/comment/87399626
tagged with: python

http://stackoverflow.com/q/50090313
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87203391
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87203392
has body: I've been trying on how to get synonyms for the words I pass. That's an easy piece of cake for wordnet to do. However I'm trying and failing with bigrams viz. 'i tried', 'horrible food', 'people go' I looked for these to learn more on sentiwordnet, since I read documentation. Perhaps, there are no examples on how to use it. Went on for source too, yet I'm here. I wrote the code for doing it in foll. way, point out what needs correction: from nltk.corpus import sentiwordnet as swn sentisynset = swn.senti_synset('so horrible') print(sentisynset) Well, this clear returns ValeError, not sure why though. Also, I tried this: from nltk.corpus.reader.lin import LinThesaurusCorpusReader as ltcr synon = ltcr.synonyms(ngram='so horrible') print(synon) and this returns TypeError, asking me for self parameter to be filled.
tagged with: synonym
upvote count: 2
has comment: http://stackoverflow.com/comment/87203399
tagged with: nltk
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87207846
tagged with: python
has comment: http://stackoverflow.com/comment/87207931
tagged with: nlp
linked to: http://stackoverflow.com/q/50009296
score: 2
has title: How to get Synonyms for ngrams using sentiwordnet in nltk Python
tagged with: n-gram

http://stackoverflow.com/comment/87411059
comment on: http://stackoverflow.com/q/50197056
score: 1
has text: Could you post your full error?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87224344
type: Comment
comment on: http://stackoverflow.com/q/50103549
has text: Would a simple replace of `__` to `_` then proceed as you've mentioned work?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87262776
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50112867
has text: @titanium not as concisely, but I'll give it a try.

http://stackoverflow.com/q/50083849
downvote count: 0
has comment: http://stackoverflow.com/comment/87183482
has comment: http://stackoverflow.com/comment/87183614
possible better answer: http://stackoverflow.com/a/50083921
favorite count: 0
has answer: http://stackoverflow.com/a/50083921
has comment: http://stackoverflow.com/comment/87183513
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87183489
type: Question
has comment: http://stackoverflow.com/comment/87183632
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/87183529
accepted answer: http://stackoverflow.com/a/50084106
has title: Using .join() to color all but first column in array in Python
has answer: http://stackoverflow.com/a/50084106
has body: I am trying to color all the elements of an array, after the first column. I finally got it to work, however I know there is more "pythonic" way of doing this, and look for some suggestions: for row in board: print row[0] + " " + " ".join(colored(element, element_colors[element]) for element in row[1:]) Any suggestions on how to perform this action in a more pythonic manner would be greatly appreciated! Edit: Desired output is as follows: [1] [W] [W] [W] [W] [W] [W] [W] [W] [2] [W] [W] [W] [W] [W] [W] [W] [W] [3] [W] [W] [W] [W] [W] [W] [W] [W] [4] [W] [W] [W] [W] [W] [W] [W] [W] [5] [W] [W] [W] [W] [W] [W] [W] [W] [6] [W] [W] [W] [W] [W] [W] [W] [W] [7] [W] [W] [W] [W] [W] [W] [W] [W] [8] [W] [W] [W] [W] [W] [W] [W] [W] Where 1-8 are not colored by the colored function, and all the [W] spaces are. That way I can keep the elements_color dictionary small: element_colors = {'[X]': 'red', '[H]': 'magenta', '[W]': 'cyan'}
has comment: http://stackoverflow.com/comment/87183504
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/87183472
answer count: 2

http://stackoverflow.com/comment/102079929
has text: On this last point of not wanting to mask `linkdata_set`, I think you could have used `Prefetch(..., to_attr="most_recent_linkdata_set_of_one")` to achieve a similar result but with a `Prefetch`, unless I'm mistaken.
type: AnswerComment
comment on: http://stackoverflow.com/a/50220347
score: 0
type: Comment

http://stackoverflow.com/q/50117875
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50117987
upvote count: 1
tagged with: matplotlib
downvote count: 1
has answer: http://stackoverflow.com/a/50131132
has title: Python: Graph function that takes multiple optional arguments
accepted answer: http://stackoverflow.com/a/50131132
linked to: http://stackoverflow.com/q/43279256
has comment: http://stackoverflow.com/comment/87253218
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/36901
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50117987
has comment: http://stackoverflow.com/comment/87253101
has answer: http://stackoverflow.com/a/50118084
has body: For my research I want to be able to quickly produce multiple graphs of a particular kind, but with slightly different data (e.g. different dates or different sensors). I'm trying to write a function that produces a graph using a few mandatory arguments and up to 20 optional arguments. I want this function to: 1) be able to produce a nice graph when I give it just one sensor as well as when I give it 10 sensors. 2) Show only the desired time between starttime and endtime The code I have so far is: import numpy as np import pvlib as pvl import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates def temp1_multiple_days(startdatetime, enddatetime, index, temp1, label1, windowtitle = 'Temperatures over time'): d = {'index':index, 'temp1': temp1} frame = pd.DataFrame(data = d) frame.set_index([index], inplace = True) frame = frame[startdatetime:enddatetime] #slicing right dates out of large dataset fig, ax1 = plt.subplots() fig.canvas.set_window_title(windowtitle) ax1.plot(frame.index, frame.temp1, label = label1) ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%b-'%y")) ax1.xaxis.set_major_locator(mdates.DayLocator()) ax1.set_xlim(startdatetime, enddatetime) ax1.set_ylabel('Temperature (°C)') ax1.legend(loc=1) fig.tight_layout fig.autofmt_xdate() plt.grid(True) plt.show This produces the desired results if I give it 1 sensor. For more sensors, I create a new function. So now I have defined 10 functions, with this being number 10: def temp10_multiple_days(startdatetime, enddatetime, index, temp1, label1, temp2, label2, temp3, label3, temp4, label4, temp5, label5, temp6, label6, temp7, label7, temp8, label8, temp9, label9, temp10, label10, windowtitle = 'Temperatures over time'): d = {'index':index, 'temp1': temp1, 'temp2': temp2, 'temp3': temp3, 'temp4': temp4, 'temp5': temp5, 'temp6': temp6, 'temp7': temp7, 'temp8': temp8, 'temp9': temp9, 'temp10': temp10} frame = pd.DataFrame(data = d) frame.set_index([index], inplace = True) frame = f…
tagged with: python
tagged with: optional-arguments
linked to: http://stackoverflow.com/q/16175874
type: AnsweredQuestion

http://stackoverflow.com/q/50107670
upvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87232826
has comment: http://stackoverflow.com/comment/87232770
tagged with: type-conversion
has title: Python: Convert 8 byte IEEE754 number to float
has body: I have the following 8 byte string that forms part of a binary file b = b'?\xf0\x00\x00\x00\x00\x00\x00' and I want to convert it to a floating point number (which should be equal to 7.371791007870371e+05). None of the approaches that I've tried so far have worked: literal_eval from ast import literal_eval literal_eval(b) ValueError: malformed node or string: b'?\xf0\x00\x00\x00\x00\x00\x00' following @martineau's answer in this post: How to convert a binary (string) into a float value? ValueError: invalid literal for int() with base 2: b'?\xf0\x00\x00\x00\x00\x00\x00' In both cases the errors raised suggest that the string 'b' is invalid, but I don't see how this is possible as it's read straight from the binary file.
has comment: http://stackoverflow.com/comment/87232934
answer count: 1
tagged with: floating-point
has answer: http://stackoverflow.com/a/50107797
favorite count: 0
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/87232812
linked to: http://stackoverflow.com/q/8751653
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/50087315
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50087828
type: AnsweredQuestion
score: 2
tagged with: performance
has answer: http://stackoverflow.com/a/50087828
answer count: 1
has title: Why itertools.groupby() is significantly slower than the equivalent approach using defaultdict?
has comment: http://stackoverflow.com/comment/87190630
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87190983
has body: I wanted to check which is faster between groupby() and a custom recipe based on defaultdict to group data: from collections import defaultdict from itertools import groupby def g1(data): groupdict = defaultdict(list) for value in data: group = value[0] value = value[1] groupdict[group].append(value) return [(key, ''.join(values)) for key, values in groupdict.items()] def g2(data): extractKey = lambda x: x[0] aggregate = lambda g: ''.join(x[1] for x in g) #return [(k, aggregate(g)) for k, g in groupby(data, extractKey)] return [(k, aggregate(g)) for k, g in groupby(sorted(data, key=extractKey), extractKey)] import random keys = list(range(1,100)) vals = 'abcdefghijklmnopqrstuvwxyz' data = [(random.choice(keys), random.choice(vals)) for _ in range(1000)] #data.sort() import timeit for g in ('g1', 'g2'): print(g, timeit.timeit(g + '(data)', number=1000, globals=globals())) To my surprise, groupby() is almost 3 times slower than defaultdict. g1 0.17048488299769815 g2 0.47328821099654306 Even if the data is pre-sorted, i.e. we do not count the time spent for sort()ing (uncomment the two commented lines), where supposedly groupby() should perform faster than the other recipe, it is almost 1.5 times as slower. g1 0.17607520399906207 g2 0.2464493800071068 Why? Is there some optimization in g2 that I did overlook?
has comment: http://stackoverflow.com/comment/87191086
has comment: http://stackoverflow.com/comment/87190576
has comment: http://stackoverflow.com/comment/87191493
upvote count: 2
has comment: http://stackoverflow.com/comment/87190912

http://stackoverflow.com/comment/87191514
score: 0
type: AnswerComment
has text: @felipe: that's a different problem, which resuls from your grammar not requiring semi-colons between statements. An expression can end with an ID, or it can start with a parenthesis. So without the semi-colon, there is no way to know whether `f(x)` is one statement or two. But you seem to want to require semi-colons; you need to fix your grammar so that they are required.
type: Comment
comment on: http://stackoverflow.com/a/50084207

http://stackoverflow.com/comment/87409251
type: QuestionComment
has text: Thanks @abarnert, i was writing my code for test multiprocessing, i've delete case A, Case B, and after Case C i added pool.close and now it works!
score: 0
comment on: http://stackoverflow.com/q/50083498
type: Comment

http://stackoverflow.com/q/50151240
tagged with: python
has answer: http://stackoverflow.com/a/50151735
has comment: http://stackoverflow.com/comment/87320597
type: AnsweredQuestion
has body: Any ideas on tackling an issue I am facing in Python... I have a nested list with items that are duplicated but in the opposite order (order stays the same but they switch in the middle): links = [['a', 'b', 'c', 'd'], ['c', 'd', 'a', 'b'], ['e', 'f', 'g', 'h'], ['g', 'h', 'e', 'f']] Does anyone have a suggestion on the best way to remove the duplicates so I end up with: links = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']] I want to detect the duplicate and remove it, the first instance needs to be kept exactly the same and in the same order, so in the above example I am removing list items 1 (['c', 'd', 'a', 'b']) and 3(['g', 'h', 'e', 'f']) Thanks in advance!
answer count: 3
has answer: http://stackoverflow.com/a/50152227
score: 1
has comment: http://stackoverflow.com/comment/87320401
downvote count: 1
possible better answer: http://stackoverflow.com/a/50151478
favorite count: 0
has answer: http://stackoverflow.com/a/50151478
type: Question
upvote count: 2
has title: Python - remove list duplicates that are in reverse order
accepted answer: http://stackoverflow.com/a/50151735

http://stackoverflow.com/q/50190520
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87398744
type: UnansweredQuestion
tagged with: django
has title: order_by does not sort Swedish UTF-8 characters ÅÄÖ correctly on production server
tagged with: django-models
tagged with: python
has body: I'm experiencing some issues with my production droplet @ DigitalOcean when sorting querysets. The Swedish characters ÅÄÖ are treated as A and O, which is not expected or desired. This works locally. I've dabbled with the locales on the server, and they seem to be alright. Django version: 1.11 Python version: 3.5.2 If anyone have experienced &amp; solved similar issues, it would be great to hear how you solved it! Model definition class County(TimeStampedModel): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name How the queryset is sorted. County.objects.all().order_by('name')
answer count: 0
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87263103
type: AnswerComment
comment on: http://stackoverflow.com/a/50122514
type: Comment
has text: I really don't see the problem with scaling it (except for the question of whether the human eye scales to it that well). You simply draw in a loop the sum of all columns, all columns except smallest (per row), all columns except two smallest (per row), and adjust the color accordingly. With 15.4K rep you should be able to figure it out :-)
score: 0

http://stackoverflow.com/a/50209193
score: 5
upvote count: 5
type: AcceptedAnswer
has body: It is very common to use the two-sided Kolmogorov-Smirnov test for this. In Python, you can do so with scipy.stats.ks_2samp: from scipy import stats merged = pd.merge( df.a.value_counts().to_frame(), df.b.value_counts().to_frame(), left_index=True, right_index=True) stats.ks_2samp(merged.a, merged.b) Broadly speaking, if the second value of the returned tuple is small (say less than 0.05), you should reject the hypothesis that the distributions are the same.
downvote count: 0
has comment: http://stackoverflow.com/comment/133400591
answers question: http://stackoverflow.com/q/50208918
type: Answer
has comment: http://stackoverflow.com/comment/87441168
accepted answer of: http://stackoverflow.com/q/50208918
has comment: http://stackoverflow.com/comment/97882039

apache-beam
tags question: http://stackoverflow.com/q/50214887
tags question: http://stackoverflow.com/q/50107909
tags question: http://stackoverflow.com/q/50141318
type: Tag
tags question: http://stackoverflow.com/q/50093478
tag name: apache-beam
tags question: http://stackoverflow.com/q/50214763

http://stackoverflow.com/comment/87369857
score: 2
has text: The F.softmax implementation is here https://github.com/pytorch/pytorch/blob/master/torch/nn/functional.py However, this just calls the C implementation. I suggest you just replace F.softmax(...) with your custom softmax function implemented in torch.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50170011

http://stackoverflow.com/a/50221742
type: Answer
answers question: http://stackoverflow.com/q/50199145
downvote count: 0
upvote count: 1
has body: OK, finally I could solve my problem: pip3 was linked to a local copy and I think my local pip3 was messed up: ~$ which pip3 /usr/local/bin/pip3 So I did: ~$ sudo mv /usr/local/bin/pip3 pip3_bak ~$ which pip3 /usr/bin/pip3 Then I had to reinstall python3-simplegeneric: ~$ sudo apt-get install python3-simplegeneric --reinstall Now I can start Spyder3 3.2.6 regularly or Spyder3 3.2.8 in my (dev) environment.
score: 1

http://stackoverflow.com/q/50170588
has answer: http://stackoverflow.com/a/50216621
tagged with: python-wheel
has comment: http://stackoverflow.com/comment/87434222
has comment: http://stackoverflow.com/comment/87360941
has answer: http://stackoverflow.com/a/50280947
tagged with: python
has title: List dependencies of Python wheel file
type: AnsweredQuestion
downvote count: 0
has body: I have Python wheel file: psutil-5.4.5-cp26-none-linux_x86_64.whl How can I list the dependencies this wheel has?
score: 54
has comment: http://stackoverflow.com/comment/87572668
has answer: http://stackoverflow.com/a/50214191
accepted answer: http://stackoverflow.com/a/50214191
has comment: http://stackoverflow.com/comment/87358555
has answer: http://stackoverflow.com/a/70356453
answer count: 7
has answer: http://stackoverflow.com/a/50208857
has comment: http://stackoverflow.com/comment/87360610
has answer: http://stackoverflow.com/a/50208939
favorite count: 0
possible better answer: http://stackoverflow.com/a/50208939
type: Question
linked to: http://stackoverflow.com/q/42237072
has comment: http://stackoverflow.com/comment/87359577
has answer: http://stackoverflow.com/a/50308083
upvote count: 54

http://stackoverflow.com/q/50091793
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50091956
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50092003
has body: I have two nested lists like this: list_1 = [[5, 3, 4], [1, 5, 8], [6, 4, 2]] list_2 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]] I want to list the different values from both of the nested lists, into a list like this: [5,8,8,9,4,7] Is there any way in Python 3 to do this? This what I have tried: list_1 = [[5, 3, 4], [1, 5, 8], [6, 4, 2]] list_2 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]] storer = [] for x in list_2: if x not in list_1: storer.append(x) print(storer) but it returns: [[8, 3, 4], [1, 5, 9], [6, 7, 2]]
possible better answer: http://stackoverflow.com/a/50092005
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87199897
tagged with: list
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/50092005
upvote count: 3
has title: How to list the difference between two nested lists in Python 3?
has answer: http://stackoverflow.com/a/50091956
favorite count: 0
type: Question

http://stackoverflow.com/comment/87182033
comment on: http://stackoverflow.com/a/50082857
type: AnswerComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ: `ENTRYPOINT tangelo` => `ENTRYPOINT ["tangelo"]` (I know, it's hard to spot and it bites me every time too)
type: Comment

http://stackoverflow.com/a/50159934
upvote count: 22
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 22
has body: You should mock the direct collaborators of the code under test. For Book that would be utils. For utils that would be requests. So for the BookModelTestCase: class BookModelTestCase(TestCase): @mock.patch('app.models.utils') def test_save_book_calls_google_api(self, mock_utils): mock_utils.get_original_title_and_name.return_value = { 'title': 'Google title', 'author': 'Google author' } book = Book( title='Some title', isbn='12345' ) book.save() self.assertEqual(book.title, 'Google title') self.assertEqual(book.author, 'Google author') mock_utils.get_original_title_and_name.assert_called_once_with('12345') And then you can create a separate test case to test get_original_title_and_name: class GetOriginalTitleAndNameTestCase(TestCase): @mock.patch('app.utils.requests.get') def test_get_original_title_and_name_from_google_api(self, mock_get): mock_response = mock.Mock() # Define response data from Google API expected_dict = { 'kind': 'books#volumes', 'totalItems': 1, 'items': [ { 'kind': 'books#volume', 'id': 'IHxXBAAAQBAJ', 'etag': 'B3N9X8vAMWg', 'selfLink': 'https://www.googleapis.com/books/v1/volumes/IHxXBAAAQBAJ', 'volumeInfo': { 'title': "Alice's Adventures in Wonderland", 'authors': [ 'Lewis Carroll' ] } } ] } # Define response data for my Mock object mock_response.json.return_value = expected_dict mock_response.status_code = 200 # Define response for the fake API mock_get.return_value = mock_response # Call the function result = get_original_title_and_name(12345) self.assertEqual(result, { 'title': "Alice's Adventures in Wonderland", 'author': 'Lewis Carroll' }) mock_get.assert_called_once_with(GOOGLE_API_URL, params={ 'key': GOOGLE_API_KEY, 'q': 'isbn:12345', 'printType': 'books', })
accepted answer of: http://stackoverflow.com/q/50157543
answers question: http://stackoverflow.com/q/50157543

http://stackoverflow.com/comment/87406104
type: QuestionComment
comment on: http://stackoverflow.com/q/50194378
has text: Firstly, you mention a specific library, what is its name (the one you have no password for). Secondly, it is generally good practice to include details of what you have tried, i.e. What is not working about the framework. If you can clarify these details it would help quite a bit.
score: 0
type: Comment

http://stackoverflow.com/comment/126384523
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51719759
has text: that is exactly what anaconda tells you to do in the docs [here](https://docs.anaconda.com/anaconda/user-guide/troubleshooting/?highlight=CondaHTTPError%3A%20HTTP%20000%20CONNECTION%20FAILED#id58). they don't explain why.

http://stackoverflow.com/a/50195035
score: 0
has body: To construct a scipy sparse matrix directly you have to map the letters onto unique indices, e.g. A == 1, B == 2, etc In [202]: txt='''A B ...: ...: C D ...: ...: A C ...: ...: D F ...: ...: G H ...: ...: K M ...: ...: M A'''.splitlines() In [203]: values = 'ABCDEFGHIJKLM' In [204]: data = [x.split() for x in txt if x] In [205]: data = [[values.index(x) for x in row] for row in data] In [206]: data Out[206]: [[0, 1], [2, 3], [0, 2], [3, 5], [6, 7], [10, 12], [12, 0]] So now we have coordinate pairs. There are various ways of constructing a sparse matrix from these. Perhaps the simplest, conceptually, is to do it iteratively with an lil format matrix (the best format for iterative construction): In [207]: from scipy import sparse In [208]: M = sparse.lil_matrix((len(values),len(values)),dtype=int) In [209]: for row in data: ...: M[tuple(row)] = 1 ...: In [210]: M Out[210]: &lt;13x13 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 7 stored elements in LInked List format&gt; In [211]: M.A Out[211]: array([[0, 1, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 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, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 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, 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, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
answers question: http://stackoverflow.com/q/50192719
type: Answer

http://stackoverflow.com/q/50120694
has title: Get individual graphs from Plotly using Flask and Python
tagged with: flask
has answer: http://stackoverflow.com/a/50121028
has body: I am trying to show graphs made in plotly on a webpage served by flask. The way it is set up now, they both display on the same page, one on top of the other. I want to show them individually on different pages. The solution I found for plotly displays all of the graphs made, and I'm not sure how to get individual graphs My flask/python graphs = [ dict( data=[thetaGraph, deltaGraph, alphaGraph, betaGraph,gammaGraph ], layout=dict( title='Brain Data' ) ), dict( data=[xGraph,yGraph,zGraph], layout=dict( title='Accelerometer Data' ) ), ] ids = ['graph-{}'.format(i) for i, _ in enumerate(graphs)] graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder) return render_template('index.html', title='Home',ids=ids, graphJSON=graphJSON) And then the webpage {% for id in ids %} {% endfor %} Im unsure how to get just the first graph in that html, and then the second graph elsewhere on the page. Ive tried using {% for id in range(0,1) %} just to get the first element, or just putting but I get 'ids' in undefined When printing out ids i get ['graph-0', 'graph-1'] which means that this is a list and I should be able to index it, but apparently that is not a thing with flask. I'm sure there is some strange way that flask needs it similarly to it's ways of reading from 2D arrays
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87259243
tagged with: web
has comment: http://stackoverflow.com/comment/87259044
linked to: http://stackoverflow.com/q/20233721
type: Question
has comment: http://stackoverflow.com/comment/87259152
tagged with: python
accepted answer: http://stackoverflow.com/a/50121028

http://stackoverflow.com/q/50217315
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87453652
has comment: http://stackoverflow.com/comment/87454409
has comment: http://stackoverflow.com/comment/87453897
has answer: http://stackoverflow.com/a/50218988
score: 0
has title: Generating Python Documentation with doxygen produces broken links to functions
has body: Doxygen version: 1.8.12 --Default Configuration I have been generating my Python doc using Doxygen. It have worked well while on documenting classes. I have built now, however, a couple of modules with some functions which I am documenting as follows: ## @file # my module comment ## # my function # @return 0 def func(): return 0 It then creates a tab Files where I can find my module files. However when I click them, a list of functions is shown as links, that are broken (when clicked upon the page is redirected to itself), and the actual definitions of the module are appended at the end of the page. What should I do to avoid having broken links, maybe a similar behavior as what happens with the classes (where functions have their separated html) is more desirable ====UPDATE==== While inspecting the generated html code, apparently the links are pointing towards an address in this style: Documtenation/myfilepy.html#some_hash Whereas the actual page sections have ids on this style: file_some_hash the correct way to call the links should be: Documentation/myfilepy#file_some_hash How can I make for doxygen to either drop the file_ or to correctly generate the links?
answer count: 1
tagged with: documentation
tagged with: doxygen
type: Question
tagged with: automation
has comment: http://stackoverflow.com/comment/87453003
has comment: http://stackoverflow.com/comment/87452302
has comment: http://stackoverflow.com/comment/87453072

http://stackoverflow.com/comment/87419406
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50200792
type: AnswerComment
has text: `np.shape(matrix)` or `matrix.shape` if it is numpy matrix

http://stackoverflow.com/q/50217285
type: Question
has body: I am using Python sockets to connect 50+ clients to a server to transfer images. I am using a wireless network to connect them. One issue I've come across is that when there is no communication for a while say 10 minutes, the software breaks. Otherwise it works fine. Here's the send method on the client side: f = open(fullpath, "rb") filesize = str(os.path.getsize(fullpath)) s.send(filesize.encode('utf-8')) while True: data = f.read(512) if not data: break s.send(data) f.close() print("Finished sending image to server") output("Finished sending image to server") And here is the receive method on the server side: client[0].send(str.encode("start")) data = client[0].recv(1024).decode('utf-8') filesize = int(data) f = open(filenames[count], "wb") currentSize = 0 while currentSize &lt; filesize: data = client[0].recv(512) if not data: break if len(data) + currentSize &gt; filesize: data = data[:filesize-currentSize] f.write(data) currentSize += len(data) f.close() On the client side I get the error: [Errno 32] Broken pipe. On the server side I get the error: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. The error happens when the client is sending the filesize. Is there an error in my code? Could I have the server and clients constantly send back and forth strings to keep the connection alive?
type: UnansweredQuestion
tagged with: sockets
downvote count: 0
tagged with: python
has title: How to avoid broken pipe error
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87535081
upvote count: 1
has comment: http://stackoverflow.com/comment/87452347
favorite count: 0
has comment: http://stackoverflow.com/comment/87451732

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

http://stackoverflow.com/comment/87194251
comment on: http://stackoverflow.com/a/50088595
type: Comment
score: 0
type: AnswerComment
has text: `if line.find("#")` is problematic: it will return `-1` if not found and `bool(-1)` evaluates to True in the conditional statement. That is why the succeeding `elif` didn't work in the original. The mutually exclusive `elif` structure could be kept by changing that check to `if '#' in L:`

http://stackoverflow.com/a/50100636
score: 1
upvote count: 1
has body: Instantiate the form with the instance you are editing: instance = MyModel.objects.get(pk=pk) form = MyForm(instance=instance, data=request.POST) Then in the form, you can access the balance via self.instance. You don't need to set self.balance in the __init__ method. def clean_amount(self): amount = self.cleaned_data['amount'] if not (self.instance.balance &gt; 0 and amount &gt; 0) or (self.instance.balance &lt; 0 and amount &lt; 0) raise forms.ValidationError( 'Cannot apply a negative amount to a positive balance and vice versa.') return amount
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50100561
type: Answer
answers question: http://stackoverflow.com/q/50100561

http://stackoverflow.com/comment/87303707
comment on: http://stackoverflow.com/q/50138622
score: 0
type: Comment
has text: month as string is an 'object' so it will have an alphabetical order. I'll get the same result. Another way is to apply a method that adjust all months to the beginning of the month (i.e. 4-Oct-17 becomes 1-Oct-17) and then pivot around columbs="first_of_month". df.SALE_DATE = pd.to_datetime(df.SALE_DATE).dt.month gives a number (9 for Sep. I need the year as well). Thanks
type: QuestionComment

histogram
tags question: http://stackoverflow.com/q/50146592
tags question: http://stackoverflow.com/q/50127226
type: Tag
tags question: http://stackoverflow.com/q/50224867
tags question: http://stackoverflow.com/q/50119819
tags question: http://stackoverflow.com/q/50157795
tag name: histogram
tags question: http://stackoverflow.com/q/50125846

http://stackoverflow.com/q/50090997
has comment: http://stackoverflow.com/comment/87198183
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87198346
downvote count: 0
tagged with: color-picker
upvote count: 1
has comment: http://stackoverflow.com/comment/87198899
favorite count: 0
has title: creating RGB color from empty array
has comment: http://stackoverflow.com/comment/87198562
type: Question
tagged with: opencv
tagged with: colors
type: UnansweredQuestion
tagged with: python
has body: I have an array img = cv2.imread("../heatmap.jpg",3) img = cv2.resize(img,(416,416)) heatmap = np.zeros_like(img) And now i would like to create RGB colors, accoring to this rgb(255, 26, 26) should be red, However using something like heatmap[i][j][0]=256 heatmap[i][j][1]=26 heatmap[i][j][2]=26 Does not produce red color, it produces blue color, why is this happening? How can i mix color like this then?

http://stackoverflow.com/a/50085685
accepted answer of: http://stackoverflow.com/q/50085655
upvote count: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50085655
has body: Code for printing the dimensions of the dataset: print(data.info()) # Descriptive info about the DataFrame print(data.shape) # gives a tuple with the shape of DataFrame Code for printing the top 3 lines: print(data.head(3)) Print mean and standard variation of the sepal-width: print(data.describe()) # General statistics print(data['Sepal_Width'].mean(), data['Sepal_Width'].std()) # Mean &amp; std dev of Sepal_Width only Code for plot box plot of each attribute: data.boxplot(namesOfColumns)
score: 3

http://stackoverflow.com/a/50159923
answers question: http://stackoverflow.com/q/50158588
type: Answer
has body: A quick test of my comment, about choosing Sunday as the arbitrary week day rather than Monday. &gt;&gt;&gt; import datetime &gt;&gt;&gt; d1=['201205','201305','201605','201705','201805','201905','202005','202105','202205','202305'] &gt;&gt;&gt; d2=['201209','201309','201609','201709','201809','201909','202009','202109','202209','202309'] &gt;&gt;&gt; for dat in d1: ... datetime.datetime.strptime(dat+ '0','%Y%W%w') ... datetime.datetime(2012, 2, 5, 0, 0) datetime.datetime(2013, 2, 10, 0, 0) datetime.datetime(2016, 2, 7, 0, 0) datetime.datetime(2017, 2, 5, 0, 0) datetime.datetime(2018, 2, 4, 0, 0) datetime.datetime(2019, 2, 10, 0, 0) datetime.datetime(2020, 2, 9, 0, 0) datetime.datetime(2021, 2, 7, 0, 0) datetime.datetime(2022, 2, 6, 0, 0) datetime.datetime(2023, 2, 5, 0, 0) &gt;&gt;&gt; for dat in d2: ... datetime.datetime.strptime(dat+ '0','%Y%W%w') ... datetime.datetime(2012, 3, 4, 0, 0) datetime.datetime(2013, 3, 10, 0, 0) datetime.datetime(2016, 3, 6, 0, 0) datetime.datetime(2017, 3, 5, 0, 0) datetime.datetime(2018, 3, 4, 0, 0) datetime.datetime(2019, 3, 10, 0, 0) datetime.datetime(2020, 3, 8, 0, 0) datetime.datetime(2021, 3, 7, 0, 0) datetime.datetime(2022, 3, 6, 0, 0) datetime.datetime(2023, 3, 5, 0, 0) &gt;&gt;&gt; Your mileage may vary. I haven't tested for weeks further into the year.
score: 0

http://stackoverflow.com/q/50146415
has comment: http://stackoverflow.com/comment/87311624
answer count: 2
upvote count: 2
duplicate of: http://stackoverflow.com/q/20510768
type: UnansweredQuestion
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50146777
score: 1
has title: One car, Two car, Red car, Blue car in Grok
tagged with: python
linked to: http://stackoverflow.com/q/20510768
has answer: http://stackoverflow.com/a/52494501
has body: I need help with this for my design class.. This is the question.. You are watching cars go past you while you wait to cross the road and want to see whether red or blue is a more popular colour for cars. Write a program that reads in a string of the colour of each car that drives past, and then prints out the number of red cars and the number of blue cars. and the output has to be like this Cars: silver red white white blue white black green yellow silver white red: 1 blue: 1 This is what I have done so far. line = input ("Cars: ") words = 'red blue'.split() word = len(words) while line != 'red': poop = +1 while line != 'blue': wah = +1 print("red:",poop) print("blue:",wah) Can someone please help me?

http://stackoverflow.com/q/50146187
has answer: http://stackoverflow.com/a/50152460
answer count: 1
tagged with: kaggle
tagged with: python
has title: DNN, targets[3] is out of range error
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/87381734
has body: I am currently building a triple-layered DNN to solve the Titanic Dataset problem. While building the model, I get the following error: targets[3] is out of range My code can be accessed through my github account: https://github.com/isaac-altair/Titanic-Dataset/blob/master/Titanic%2BProject.ipynb Thank you
type: UnansweredQuestion

http://stackoverflow.com/comment/132142905
type: QuestionComment
has text: See my answer below.
score: 0
comment on: http://stackoverflow.com/q/50190990
type: Comment

http://stackoverflow.com/q/50124954
tagged with: python
has answer: http://stackoverflow.com/a/50139828
answer count: 3
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50125258
upvote count: 1
has answer: http://stackoverflow.com/a/50125224
has comment: http://stackoverflow.com/comment/87268322
has body: The story is simple. I want to import class under different names twice. The rationale for this is good looking api. # This class enhances other classes with convinience methods # I own this class class CssMixin: def add_css_class(self, name: str): # Code to add css style to self In another file: # import class twice as Mixing and as Helper class from breaffy.helper import CssMixin as Helper, CssMixin # Enrich class with convinience methods # ExternalClass is class from some third-party library # And is not under my control class MyClass(ExternalClass, CssMixin): def __init__(self): self.add_css_class("button-class") # another instance of ExternalClass # often used in GUI libraries self.child = ExternalClass() # Here not to duplicate all GUI class hierarchy # to use method as a helper and pass original ExternalClass as self Helper.add_css_class(self.child, "label-class") Is this correct and standard approach in Python? What other solutions to do the same? Is it possible to monkey-patch original class, so that all classes derived from ExternalClass will automatically have add_css_class method (without adding mixins)? Is this approach better?
has comment: http://stackoverflow.com/comment/87268095
favorite count: 0
type: Question
has title: Import class twice under different names
has comment: http://stackoverflow.com/comment/87297893
type: UnansweredQuestion

http://stackoverflow.com/comment/87403113
score: 0
type: Comment
type: QuestionComment
has text: Which of the two scores? Please provide an example of what you would want to do.
comment on: http://stackoverflow.com/q/50192485

http://stackoverflow.com/a/50120294
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50116836
type: Answer
has body: For me, using mock/patch is a painful exercise. On the other hand, it was trivial to accomplish by setting (and restoring) the global for the tests: import mock_module class TestSomeClass(unittest2.TestCase): def setUp(self): self._original = mock_module.DATA_PATH mock_module.DATA_PATH = 'data_path_here' def tearDown(self): mock_module.DATA_PATH = self._original def test_constructor(self): obj = mock_module.SomeClass() self.assertEqual(r"data_path_here\ABC.txt", obj.filename) Note that for my os path join, the separator is \ but your usage may differ. Ran 1 test in 0.005s OK
answers question: http://stackoverflow.com/q/50116836
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87416717
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50200023
has text: @Aiven (1, 10, 0, u'final', 1)

http://stackoverflow.com/comment/87260310
has text: Use Numpy and its respective functions for dealing with saving and loading arrays.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50121277
score: 0

http://stackoverflow.com/comment/87373839
score: 0
has text: @Kevin it should also give 70 percent
type: QuestionComment
comment on: http://stackoverflow.com/q/50177941
type: Comment

dataframe
tags question: http://stackoverflow.com/q/50077922
tags question: http://stackoverflow.com/q/50229561
tags question: http://stackoverflow.com/q/50100370
tags question: http://stackoverflow.com/q/50149552
tags question: http://stackoverflow.com/q/50134687
tags question: http://stackoverflow.com/q/50190809
tags question: http://stackoverflow.com/q/50209425
tags question: http://stackoverflow.com/q/50187932
tags question: http://stackoverflow.com/q/50182568
tags question: http://stackoverflow.com/q/50102808
tags question: http://stackoverflow.com/q/50189828
tags question: http://stackoverflow.com/q/50206431
tags question: http://stackoverflow.com/q/50189738
tags question: http://stackoverflow.com/q/50210555
tags question: http://stackoverflow.com/q/50098113
tags question: http://stackoverflow.com/q/50183920
tags question: http://stackoverflow.com/q/50136944
tags question: http://stackoverflow.com/q/50098025
tags question: http://stackoverflow.com/q/50100941
tags question: http://stackoverflow.com/q/50163319
tags question: http://stackoverflow.com/q/50181366
tags question: http://stackoverflow.com/q/50189394
tags question: http://stackoverflow.com/q/50157251
tags question: http://stackoverflow.com/q/50149499
tags question: http://stackoverflow.com/q/50165614
tags question: http://stackoverflow.com/q/50176189
tags question: http://stackoverflow.com/q/50084989
tags question: http://stackoverflow.com/q/50082846
tags question: http://stackoverflow.com/q/50178925
tags question: http://stackoverflow.com/q/50111745
tags question: http://stackoverflow.com/q/50148731
tags question: http://stackoverflow.com/q/50205684
tags question: http://stackoverflow.com/q/50106170
tags question: http://stackoverflow.com/q/50154147
tags question: http://stackoverflow.com/q/50120247
tags question: http://stackoverflow.com/q/50098753
tags question: http://stackoverflow.com/q/50199917
tags question: http://stackoverflow.com/q/50082441
tags question: http://stackoverflow.com/q/50191215
tags question: http://stackoverflow.com/q/50162722
tags question: http://stackoverflow.com/q/50153319
tags question: http://stackoverflow.com/q/50122930
tags question: http://stackoverflow.com/q/50212175
tags question: http://stackoverflow.com/q/50177258
tags question: http://stackoverflow.com/q/50115074
tags question: http://stackoverflow.com/q/50119162
tags question: http://stackoverflow.com/q/50194261
tags question: http://stackoverflow.com/q/50228213
tags question: http://stackoverflow.com/q/50107182
tags question: http://stackoverflow.com/q/50172357
tags question: http://stackoverflow.com/q/50197052
tags question: http://stackoverflow.com/q/50123883
tags question: http://stackoverflow.com/q/50178072
tags question: http://stackoverflow.com/q/50120823
tags question: http://stackoverflow.com/q/50183789
tags question: http://stackoverflow.com/q/50074981
tags question: http://stackoverflow.com/q/50191861
tags question: http://stackoverflow.com/q/50214155
tags question: http://stackoverflow.com/q/50185547
tags question: http://stackoverflow.com/q/50123833
tags question: http://stackoverflow.com/q/50220770
tags question: http://stackoverflow.com/q/50106021
tags question: http://stackoverflow.com/q/50127167
tags question: http://stackoverflow.com/q/50106611
tags question: http://stackoverflow.com/q/50216267
tags question: http://stackoverflow.com/q/50088085
tags question: http://stackoverflow.com/q/50140640
tags question: http://stackoverflow.com/q/50101964
tags question: http://stackoverflow.com/q/50136587
tags question: http://stackoverflow.com/q/50141802
tags question: http://stackoverflow.com/q/50100635
tags question: http://stackoverflow.com/q/50228673
tags question: http://stackoverflow.com/q/50085655
tags question: http://stackoverflow.com/q/50078784
tags question: http://stackoverflow.com/q/50168448
tags question: http://stackoverflow.com/q/50218179
tags question: http://stackoverflow.com/q/50137024
tags question: http://stackoverflow.com/q/50079247
tags question: http://stackoverflow.com/q/50118268
tags question: http://stackoverflow.com/q/50093130

python-3.x
tags question: http://stackoverflow.com/q/50188475
tags question: http://stackoverflow.com/q/50110868
tags question: http://stackoverflow.com/q/50164224
tags question: http://stackoverflow.com/q/50133693
tags question: http://stackoverflow.com/q/50076903
tags question: http://stackoverflow.com/q/50145412
tags question: http://stackoverflow.com/q/50106662
tags question: http://stackoverflow.com/q/50075379
tags question: http://stackoverflow.com/q/50175793
tags question: http://stackoverflow.com/q/50219763
tags question: http://stackoverflow.com/q/50149291
tags question: http://stackoverflow.com/q/50180735
tags question: http://stackoverflow.com/q/50082447
tags question: http://stackoverflow.com/q/50190677
tags question: http://stackoverflow.com/q/50194711
tags question: http://stackoverflow.com/q/50089668
tags question: http://stackoverflow.com/q/50194562
tags question: http://stackoverflow.com/q/50173776
tags question: http://stackoverflow.com/q/50091793
tags question: http://stackoverflow.com/q/50224346
tags question: http://stackoverflow.com/q/50154693
tags question: http://stackoverflow.com/q/50207157
tags question: http://stackoverflow.com/q/50185795
tags question: http://stackoverflow.com/q/50144072
tags question: http://stackoverflow.com/q/50088193
tags question: http://stackoverflow.com/q/50205482
tags question: http://stackoverflow.com/q/50200611
tags question: http://stackoverflow.com/q/50181787
tags question: http://stackoverflow.com/q/50127633
tags question: http://stackoverflow.com/q/50108003
tags question: http://stackoverflow.com/q/50202741
tags question: http://stackoverflow.com/q/50204828
tags question: http://stackoverflow.com/q/50220147
tags question: http://stackoverflow.com/q/50147410
tags question: http://stackoverflow.com/q/50151197
tags question: http://stackoverflow.com/q/50210458
tags question: http://stackoverflow.com/q/50109549
tags question: http://stackoverflow.com/q/50087479
tags question: http://stackoverflow.com/q/50143697
tags question: http://stackoverflow.com/q/50164550
tags question: http://stackoverflow.com/q/50194821
tags question: http://stackoverflow.com/q/50138988
tags question: http://stackoverflow.com/q/50224808
tags question: http://stackoverflow.com/q/50158962
tags question: http://stackoverflow.com/q/50113130
tags question: http://stackoverflow.com/q/50090072
tags question: http://stackoverflow.com/q/50127785
tags question: http://stackoverflow.com/q/50190974
tags question: http://stackoverflow.com/q/50217971
tags question: http://stackoverflow.com/q/50089849
tags question: http://stackoverflow.com/q/50091968
tags question: http://stackoverflow.com/q/50206349
tags question: http://stackoverflow.com/q/50210634
tags question: http://stackoverflow.com/q/50114709
tags question: http://stackoverflow.com/q/50217834
tags question: http://stackoverflow.com/q/50204998
tags question: http://stackoverflow.com/q/50138795
tags question: http://stackoverflow.com/q/50162838
tags question: http://stackoverflow.com/q/50194786
tags question: http://stackoverflow.com/q/50166133
tags question: http://stackoverflow.com/q/50074811
tags question: http://stackoverflow.com/q/50202606
tags question: http://stackoverflow.com/q/50102174
tags question: http://stackoverflow.com/q/50080878
tags question: http://stackoverflow.com/q/50159235
tags question: http://stackoverflow.com/q/50202268
tags question: http://stackoverflow.com/q/50127304
tags question: http://stackoverflow.com/q/50206190
tags question: http://stackoverflow.com/q/50146706
tags question: http://stackoverflow.com/q/50152249
tags question: http://stackoverflow.com/q/50179311
tags question: http://stackoverflow.com/q/50085112
tags question: http://stackoverflow.com/q/50151036
tags question: http://stackoverflow.com/q/50168670
tags question: http://stackoverflow.com/q/50216175
tags question: http://stackoverflow.com/q/50134790
tags question: http://stackoverflow.com/q/50095233
tags question: http://stackoverflow.com/q/50184021
tags question: http://stackoverflow.com/q/50171754
tags question: http://stackoverflow.com/q/50212975

coding-style
type: Tag
tag name: coding-style
tags question: http://stackoverflow.com/q/50229777

http://stackoverflow.com/comment/87362970
score: 0
has text: Thanks, that makes things a lot clearer!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50172671

http://stackoverflow.com/comment/121071742
type: Comment
has text: But why convert it to `frozenset` instead of just using `__annotations__.keys()`?
score: 2
comment on: http://stackoverflow.com/a/63658478
type: AnswerComment

http://stackoverflow.com/comment/87333222
type: Comment
has text: This is why you have to initialize all the instance attributes in `__init__` method.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50157631

http://stackoverflow.com/comment/87201722
type: QuestionComment
has text: 'are you asking how to turn "a" and "b" and then put them together and making them "ab"?' Yes I am. If you don't know how to do that, that shows that you need to spend more time on basic tutorials like [this](https://www.tutorialspoint.com/python/python_strings.htm). The answer is in there. If you can't find it, try and think of words to google to express that operation. If you do `for letter in decrypt_msg` the `letter` is already a string, not an index, so you wouldn't do `List1[letter]`. Printing the letters is not going to help you, you need to store them and the combined result.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50078807

http://stackoverflow.com/comment/87239342
comment on: http://stackoverflow.com/q/50110646
score: 0
has text: For questions about code, StackOverflow's scope is limited to asking about specific problems, and does not extend to review for general comment or suggestion. See [A Guide to Code Review for StackOverflow Users](https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users) for guidance on which questions are appropriate on each site (if either).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50092512
accepted answer of: http://stackoverflow.com/q/50091331
has comment: http://stackoverflow.com/comment/87201893
has body: The custom is to instantiate the trasformer/estimator first and then to fit and transform. Here is what the output is with a couple of minor changes: import pandas as pd from sklearn.preprocessing import StandardScaler df = pd.DataFrame([(1,2,3), (2,3,4), (3,4,5)], columns=['a','b','c']) scaler = StandardScaler() scaler.fit(df['c'].values.reshape(-1,1)) df['d'] = scaler.transform(df['c'].values.reshape(-1,1)) df Out[84]: a b c d 0 1 2 3 -1.224745 1 2 3 4 0.000000 2 3 4 5 1.224745
answers question: http://stackoverflow.com/q/50091331
has comment: http://stackoverflow.com/comment/87201908
has comment: http://stackoverflow.com/comment/87201853
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87201923

http://stackoverflow.com/comment/87517944
type: Comment
has text: @JacquesGaudin hey, I added source with data set and values.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50141228

http://stackoverflow.com/comment/87317693
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50102789
has text: Thanks Tianyun, it worked well. Now i saw that in some files i have the word that i want to extract appears several times. But with my function it just extract the first one it finds and exit. How can i fix it ? Thanks in advance
score: 0

http://stackoverflow.com/a/50324740
upvote count: 1
score: 1
has body: I suggest taking a look at PyQt5 from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets app = QtWidgets.QApplication([]) view = QtWebEngineWidgets.QWebEngineView() view.setHtml(' Hello World! ') view.show()
type: Answer
answers question: http://stackoverflow.com/q/50092072
downvote count: 0

http://stackoverflow.com/a/50202763
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50202701
has body: What happens if the class code is not 1,2 or 3. If all class code do the same thing you can make the filename dynamic, instead of repeating the code several times. class_file=open("class{}.csv".format(classCode),"w") class_file.write("name, correct\n" + name + "," + str(correct) + "\n") class_file.close()
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50202701
score: 1

http://stackoverflow.com/a/50100082
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87216925
has body: Python's map doesn't just work for lists; it works for any iterable. Rather than add separate map methods to disparate classes (or adding a do-nothing map method to object and overriding it multiple times), Python uses the iterable protocol; any class that implements __iter__ (providing an object the implements __next__) can be used with map.
has comment: http://stackoverflow.com/comment/87219976
answers question: http://stackoverflow.com/q/50099765
downvote count: 0

http://stackoverflow.com/comment/87331173
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50156547
has text: `x.reshape(3,3)` converts an np.array x with 9 entries into a 3*3 np.array

http://stackoverflow.com/comment/87185277
type: QuestionComment
comment on: http://stackoverflow.com/q/50080951
has text: More details have been added to the question. Also, I do not know in advance how many times the script can be run before it fails.
score: 0
type: Comment

http://stackoverflow.com/q/50178120
tagged with: django-fixtures
has body: GOAL: Run the DJANGO development server, using the TestCase database. Case: DJANGO produces this database when running a TestCase. Now I'm filling the database using DJANGO-autofixture. It would be really nice to start the DJANGO testserver using this database, so I can checkout how the website presents it. Unfortunately, I can't find anywhere how to do this. Writing the test database to sqlite would make sense, but I don't see an options for this. Any hints are appreciated! Thanks!
answer count: 1
downvote count: 0
tagged with: django-tests
has answer: http://stackoverflow.com/a/50180648
favorite count: 0
type: Question
upvote count: 4
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 4
has title: DJANGO development server using TestCase database

python-2.6
type: Tag
tag name: python-2.6
tags question: http://stackoverflow.com/q/50115102
tags question: http://stackoverflow.com/q/50186714

http://stackoverflow.com/comment/87225369
comment on: http://stackoverflow.com/a/50103981
type: AnswerComment
has text: There is no difference, just don't see why you would use pd.wide_to_long. The "New" column or "dropme" column isn't used anyway, so the single _ vs __ is an issue. Just use a single _ as the seperator and you are fine.
score: 1
type: Comment

http://stackoverflow.com/comment/87397082
type: Comment
score: 0
type: QuestionComment
has text: @YOLO The plan is to do the following: 1. Ask user for input. 2. WHILE user hasn't typed in "quit", extract data they need from dataframe and ask them what their input is again.
comment on: http://stackoverflow.com/q/50189866

http://stackoverflow.com/a/50178080
accepted answer of: http://stackoverflow.com/q/50177846
has body: It's not possible because virtual environments contain libraries which might be specific for different versions of Python. As to testing your code in different versions, you can use Tox Regarding PyCharm, it has a feature of compatibility inspection (Settings->Editor->Inspections->Code compatibility inspection) where you can specify Python versions that must be supported by your code
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/50177846
type: Answer

http://stackoverflow.com/comment/126706644
type: AnswerComment
comment on: http://stackoverflow.com/a/50104628
has text: How can I set git secret here ?
type: Comment
score: 0

http://stackoverflow.com/q/50159567
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87336882
has comment: http://stackoverflow.com/comment/87338133
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29213106
downvote count: 0
tagged with: command-line-arguments
has comment: http://stackoverflow.com/comment/87336975
tagged with: python
has comment: http://stackoverflow.com/comment/87338383
has comment: http://stackoverflow.com/comment/87339176
has comment: http://stackoverflow.com/comment/87337621
score: 2
duplicate of: http://stackoverflow.com/q/29213106
has comment: http://stackoverflow.com/comment/87338294
answer count: 0
has comment: http://stackoverflow.com/comment/87338573
tagged with: windows
tagged with: http://stackoverflow.com/tag/json
has body: I have a script that is called from another process that receives an input that is a json string. import sys import json script_name, json_in = sys.argv my json in looks something like: '{"key1":"val1", "key2":[val2, val3], "key3":"val4"}' when i print what is received by python and stored in json_in it looks like: {key1:val1, key2:[val2, val3], key:val4} stepping through the pdb when i get to json_in it's value is: "'{key:val1, key2:[val2, vale3], key:val4}'" i wasn't having this problem on Ubuntu, but when i use the same script on Windows it no longer works. The script does work if you copy and paste the exact same input that is being passed to argv. So the only conclusion i've been able to come to is that argv is somehow stripping the double quotes? I haven't found any documentation that might describe why this is happening (especially when it works on Ubuntu). Does anyone know why its being stripped? The python function is being called by javascript function, but even if i just call the python scipt from the terminal using &gt;&gt;&gt; python file_name.py '{"key1":"val1", "key2":[val2, val3], "key3":"val4"}' I get the same error. If you set the json_in variable to the same value, or call it in the exact same way in the Ubuntu terminal, then there is no problem.
has title: How can I pass a JSON string to a Python program's command line on Windows?
has comment: http://stackoverflow.com/comment/87339239
has comment: http://stackoverflow.com/comment/87336930
has comment: http://stackoverflow.com/comment/87338203
has comment: http://stackoverflow.com/comment/133319139
has comment: http://stackoverflow.com/comment/87337375

http://stackoverflow.com/q/50131705
type: UnansweredQuestion
has body: I have a file lets say "Mrinq_Parts_Available.txt" which looks like this. Source Date Category SubCategory Present Description Value Units Vendor Part No Package Box Name Location Quantity Ordered Used MOQ=1 MOQ=100 MOQ=1000 Comments Link Digikey 29-May-15 RF Amplifier No 0.5 W RFMD RFPA3807 SOIC8 10 0 3.4 5V http://www.digikey.com/product-detail/en/RFPA3807TR13/689-1073-1-ND/2567207 I have a python code which does split of those lines. def removeEmptyLines(inputFile): with open(inputFile, 'rb') as f: d = f.readlines() k = [] for i in d: k.append(i.split()) print (k) if __name__=="__main__": parts_database_file = "Mrinq_Parts_Available.txt" removeEmptyLines(parts_database_file) But the output is shown like this: [b'Source', b'Date', b'Category', b'SubCategory', b'Present', b'Description', b'Value', b'Units', b'Vendor', b'Part', b'No', b'Package', b'Box', b'Name', b'Location', b'Quantity', b'Ordered', b'Used', b'MOQ=1', b'MOQ=100', b'MOQ=1000', b'Comments', b'Link'] [b'Digikey', b'29-May-15', b'RF', b'Amplifier', b'No', b'0.5', b'W', b'RFMD', b'RFPA3807', b'SOIC8', b'10', b'0', b'3.4', b'5V', b'http://www.digikey.com/product-detail/en/RFPA3807TR13/689-1073-1-ND/2567207'] How do I remove the 'b' preceding each parsed data?
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/87281386
tagged with: python
tagged with: string
has comment: http://stackoverflow.com/comment/87281374
has title: How to remove character outside a string from a tab delimited text
duplicate of: http://stackoverflow.com/q/41918836
has answer: http://stackoverflow.com/a/50131808
linked to: http://stackoverflow.com/q/6269765
answer count: 1
linked to: http://stackoverflow.com/q/41918836
favorite count: 0
type: Question
tagged with: split
upvote count: 0

http://stackoverflow.com/comment/87367994
has text: Actually my filenames consist of pairs: `[[image1, image2], [image2, image3],...]` and I need to pass into function `filename1` and `filename2`. So, I should create 2 filename_queue and can pass it like this? `tf.py_func(my_preprocessing_from_filename, [key1, key2], tf.int64)`
comment on: http://stackoverflow.com/a/50172229
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50194900
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/87416021
has comment: http://stackoverflow.com/comment/87406861
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/50196963
has title: I have a web page link that consists few data that needs to be scraped but those data have different id and are considerably to long also
has answer: http://stackoverflow.com/a/50195496
has body: How do I scrape those data as they are different from each other? Wheat Rice Barleyt Milk . . . XYZ I need all those data at once. Help me, prefered language is python.

http://stackoverflow.com/a/50147208
upvote count: 1
answers question: http://stackoverflow.com/q/50145309
score: 1
type: Answer
has body: The following version would only add those axes you need for your df-columns and share their y-scales: import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.arange(50).reshape((5,10))).transpose() fig = plt.figure(tight_layout=True) ref_ax = None for i in range(len(df.columns)): ax = fig.add_subplot(2, 3, i+1, sharey=ref_ax) ref_ax=ax iC = df.iloc[:, i] iC.plot(ax=ax) plt.show() The grid-layout Parameters, which are explicitly given as ...add_subplot(2, 3, ... here can of course be calculated with respect to len(df.columns).
downvote count: 0

http://stackoverflow.com/q/50136593
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
score: 0
answer count: 1
tagged with: queue
has answer: http://stackoverflow.com/a/50137011
type: Question
has title: processing limited threads at a time in a thread list
has body: I have a thread list in python code which is quiet big threadlist = [thread1, thread2, thread3..........threadn] where n is greater than 200 and I need to process 10 threads at a time using python queue, how do I do that. Suggestions deeply appreciated.

http://stackoverflow.com/comment/87304306
type: Comment
comment on: http://stackoverflow.com/a/50142522
score: 0
type: AnswerComment
has text: For recursive functions, so far I've just been tracking the recursion depth, so you actually have `_g_0`, `_g_1`, etc., and the recursion limit can be explicitly capped (and should be a really low cap). Pretty sure generator functions are impossible to inline syntactically, so I've taken a "you better know what you're doing" approach and treated a call to a generator function `f(x)` to be equivalent to `list(f(x))`, which makes it inlinable.

http://stackoverflow.com/a/50097683
downvote count: 1
has body: It searches for the sequence of characters(the first is a capital letter) followed at least by a low-capital character('+') that starts with a space and ends with a dot(since dot is a special character, it uses \ before it)
type: Answer
accepted answer of: http://stackoverflow.com/q/50097500
score: 0
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/50097500

http://stackoverflow.com/a/50093425
has body: You can use, combine_first, where and ffill: dfweekly.combine_first(dfdaily)\ .where(dfweekly.notnull())\ .ffill() Ouptut: open high low close volume date 2017-10-30 44.66 44.75 42.19 42.93 3500.0 2017-11-01 44.66 44.75 42.19 42.93 3500.0 2017-11-03 44.66 44.75 42.19 42.93 3500.0 2017-11-06 43.15 43.75 40.60 41.02 9200.0 2017-11-07 43.15 43.75 40.60 41.02 9200.0 2017-11-08 43.15 43.75 40.60 41.02 9200.0 2017-11-09 43.15 43.75 40.60 41.02 9200.0 2017-11-10 43.15 43.75 40.60 41.02 9200.0 2017-11-13 41.60 43.21 40.03 42.36 3575.0 2017-11-14 41.60 43.21 40.03 42.36 3575.0 2017-11-16 41.60 43.21 40.03 42.36 3575.0 2017-11-17 41.60 43.21 40.03 42.36 3575.0 2017-11-20 42.70 43.10 40.35 40.37 3100.0 2017-11-21 42.70 43.10 40.35 40.37 3100.0 2017-11-22 42.70 43.10 40.35 40.37 3100.0 2017-11-23 42.70 43.10 40.35 40.37 3100.0 2017-11-24 42.70 43.10 40.35 40.37 3100.0 2017-11-27 40.28 40.40 39.10 40.04 3500.0 2017-11-28 40.28 40.40 39.10 40.04 3500.0 Update: dfweekly.combine_first(dfdaily)\ .where(dfweekly.notnull())\ .ffill().reindex(dfdaily.index)
answers question: http://stackoverflow.com/q/50093299
upvote count: 3
score: 3
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87203853
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50093299
has comment: http://stackoverflow.com/comment/87203903

http://stackoverflow.com/comment/87322176
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50152188
score: 1
has text: This should help. `print(df["mycol"].apply(lambda x: x.replace("[", "").replace("]", "").split()))`

http://stackoverflow.com/a/50136003
has comment: http://stackoverflow.com/comment/87295243
answers question: http://stackoverflow.com/q/50134620
score: 1
accepted answer of: http://stackoverflow.com/q/50134620
type: Answer
has comment: http://stackoverflow.com/comment/87294728
has comment: http://stackoverflow.com/comment/87295342
has comment: http://stackoverflow.com/comment/87297815
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87295238
has body: You may want to use the option 'norm' in your FFT : swh_f = np.fft.fft(swh, norm = "ortho") You can find more informations about NumPy's implementation of FFT here : https://docs.scipy.org/doc/numpy/reference/routines.fft.html#module-numpy.fft
has comment: http://stackoverflow.com/comment/87296641

http://stackoverflow.com/a/50201549
has body: Cleaner more concise code would probably have gotten a quicker answer. One issue I can see is for the 3 situations where you're adding a where term based on a number (Number_Participants, Total_Assets, Net_Assets), you include '%" ... "%' either side which is not applicable when using BETWEEN. I rewrote your basic code below to condense it, apply some common SQL style and hopefully make it more readable, but skipped parameterization for now. See if that solves your problem. string selectTerm = @"SELECT CONCAT(dbo.[5500].plan_name, dbo.[5500_SF_NEW].SF_PLAN_NAME) [Plan_NAME] , CONCAT(dbo.[5500].ADMIN_CARE_OF_NAME, dbo.[5500_SF_NEW].SF_ADMIN_CARE_OF_NAME) [Admin_Name] , CONCAT(dbo.[5500].SPONS_DFE_EIN, dbo.[5500_SF_NEW].SF_SPONS_EIN) [EIN_Number] , CONCAT(dbo.[5500].SPONS_DFE_PN, dbo.[5500_SF_NEW].SF_PLAN_NUM) [Plan_Number] , CONCAT(dbo.[5500].TOT_ACT_RTD_SEP_BENEF_CNT, dbo.[5500_SF_NEW].SF_TOT_ACT_PARTCP_EOY_CNT) [Number_Participants] , CONCAT(dbo.[5500].SPONS_DFE_MAIL_US_ADDRESS1, dbo.[5500].SPONS_DFE_MAIL_US_ADDRESS2, dbo.[5500_SF_NEW].[SF_SPONS_US_ADDRESS1], dbo.[5500_SF_NEW].[SF_SPONS_US_ADDRESS2]) [Address] , CONCAT(dbo.[5500].SPONS_DFE_MAIL_US_CITY, dbo.[5500_SF_NEW].[SF_SPONS_US_CITY]) [City] , CONCAT(dbo.[5500].SPONS_DFE_MAIL_US_STATE, dbo.[5500_SF_NEW].[SF_SPONS_US_STATE]) [State] , CONCAT(dbo.[5500].SPONS_DFE_MAIL_US_ZIP, dbo.[5500_SF_NEW].[SF_SPONS_US_ZIP]) [ZipCode] , (ISNULL(dbo.SCH_H.TOT_ASSETS_EOY_AMT, 0) + ISNULL(dbo.SCH_I.SMALL_TOT_ASSETS_EOY_AMT, 0) + ISNULL(dbo.[5500_SF_NEW].SF_TOT_ASSETS_EOY_AMT,0)) [Total_Assets] , (ISNULL(dbo.SCH_H.NET_ASSETS_EOY_AMT, 0) + ISNULL(dbo.SCH_I.SMALL_NET_ASSETS_EOY_AMT, 0) + ISNULL(dbo.[5500_SF_NEW].SF_NET_ASSETS_EOY_AMT,0)) [Net_Assets] , (ISNULL(dbo.SCH_H.TOT_LIABILITIES_EOY_AMT, 0) + ISNULL(dbo.SCH_I.SMALL_TOT_LIABILITIES_EOY_AMT, 0) + ISNULL(dbo.[5500_SF_NEW].SF_TOT_LIABILITIES_EOY_AMT,0)) [Total_Liabilities] FROM dbo.[5500] FULL JOIN dbo.sch_h ON dbo.[5500].ack_id = dbo.sch_h.ack_id FULL JOIN dbo.SCH_I ON dbo.[5…
answers question: http://stackoverflow.com/q/50137195
type: Answer
score: 0

http://stackoverflow.com/a/50179649
accepted answer of: http://stackoverflow.com/q/50179485
score: 2
downvote count: 0
has body: You can use numpy.where to align your AutomationStatus values. Then use pd.pivot_table. This is a minimal example: print(df) AutomationStatus TestPriority 0 Done 4 1 Done 4 2 Done 4 3 WillNotAutomate 3 4 Done 4 5 ReviewforAutomation 3 6 ReviewforAutomation 3 7 ReviewforAutomation 3 df['AutomationStatus'] = np.where(df['AutomationStatus'] == 'Done', 'Automated', 'ManualTest') res = df.pivot_table(index='AutomationStatus', columns=['TestPriority'], aggfunc=len, fill_value=0) print(res) TestPriority 3 4 AutomationStatus Automated 0 4 ManualTest 4 0
upvote count: 2
answers question: http://stackoverflow.com/q/50179485
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87207674
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50095511
has text: @IşıkKaplan It does fetch the first one correctly... I checked it
score: 0

http://stackoverflow.com/comment/87386810
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50182965
score: 0
has text: I think scipy uses numpy to save too, as it gives the exact same error

http://stackoverflow.com/q/50119456
type: UnansweredQuestion
has title: Merge two records in pandas on basis of individual column trust
has comment: http://stackoverflow.com/comment/87261304
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87256315
score: 0
has answer: http://stackoverflow.com/a/50120072
tagged with: pandas
has body: I have recently started working with Pandas (Python beginner). I am trying to merge two records from different IDs and create a final record which contains values for each column from the IDs I trust for each column. df1: ID NAME ADDRESS PHONE 1 abc street1 9999 df2: ID NAME ADDRESS PHONE 2 xyz street2 8888 df_col_priority: COLUMN PRIORITY_BY_ID NAME 1 ADDRESS 2 PHONE 2 So here, based on priority for each column for each id, I should get single output record as: df_output: NAME ADDRESS PHONE abc street2 8888 So basically I should get NAME from ID=1 and other 2 fields from ID=2. Likewise, I have thousands of records, for which I will pick pair of two records by a logic and calculate the final output record using above method. I am not able to think of a way to achieve this other than looping over each column for each dataframe, extracting priority and constructing new record column by column by concat. But I think this is pretty inefficient. Any help would be appreciated.
answer count: 1
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87267375
type: Comment
type: QuestionComment
has text: Double-check your code. Your updated example has mismatched parentheses, specifically `totals = pd.read_sql("""select * from #output"""), connection)` has an extra `)`.
comment on: http://stackoverflow.com/q/50109536
score: 0

http://stackoverflow.com/comment/87427284
type: AnswerComment
comment on: http://stackoverflow.com/a/50205120
has text: To do three, do `groupby([a, b, c])` etc.
score: 0
type: Comment

http://stackoverflow.com/q/50225400
answer count: 2
type: Question
tagged with: python
type: UnansweredQuestion
has title: splitting column value in to three with two delimiter in pandas
has comment: http://stackoverflow.com/comment/87468242
tagged with: pandas
has body: I have written an excel file with one column with values of: col1 22125051|2/136|Possible Match nan|3/4|Not Match 22125051|1/26|Match these data are initially in different columns but I want to get the value of the said columns and put the data into one, and I did it by using .apply() and .join() then I added a delimiter | to separate the values now I want to split the column per value then put it in to specific column in an existing .xlsx file. say df3 = pd.read_excel('type_primary_data.xlsx') and .columns[37], .columns[39], .columns[40] Desired ouput svc_no port Result 22125051 2/136 Possible Match nan 3/4 Not Match 22125051 1/26 Match I am not sure what is the best way to do this in pandas. UPDATE turns out that I need to match the adsl column to an existing .xlsx file so, as the adsl matched with the said column I also wanted to get the svc_no and comparison result along with the matched adsl. my ouput should be adsl svc_no port Result 3/4 nan 3/4 Not Match 1/26 22125051 1/26 Match 2/136 22125051 2/136 Possible Match
has answer: http://stackoverflow.com/a/50225517
has answer: http://stackoverflow.com/a/50225721
score: 0

http://stackoverflow.com/a/50191936
answers question: http://stackoverflow.com/q/50191861
type: Answer
has comment: http://stackoverflow.com/comment/87400909
upvote count: 2
has comment: http://stackoverflow.com/comment/87400795
has comment: http://stackoverflow.com/comment/87400882
score: 2
has body: I think need lookup df1['New']=df2.set_index('GAME').lookup(df1.GAME,df1.PLAY) df1 Out[26]: GAME PLAY BET New 0 (SWE,FIN) DRAW 10 2.0 1 (DEN,GER) WIN 20 2.0 2 (RUS,CZE) LOSS 30 10.0
downvote count: 0

http://stackoverflow.com/q/50209429
has title: Can't scrape website using Beautiful Soup
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50209655
tagged with: python
has body: i follow tutorial from here about scraping website with Python and BeautifulSoup. I try to scraping website from my goverment (for research purpose) but it give me error like this : Traceback (most recent call last): File "C:/Python27/scrap web.py", line 8, in &lt;module&gt; name = name_box.text.strip() AttributeError: 'NoneType' object has no attribute 'text' i try another website like this and it work. And when i look into my goverment website and i use "View Page Source", i dont see code like &lt;table id="tableLeftBottom"&gt;. So, how i can scrap data from this website ? import urllib2 from bs4 import BeautifulSoup quote_page = "https://bps.go.id/linkTableDinamis/view/id/1116" page = urllib2.urlopen(quote_page) soup = BeautifulSoup(page, "html.parser") name_box = soup.find("table", attrs={"id": "tableRightBottom"}) name = name_box.text.strip() print name
has comment: http://stackoverflow.com/comment/87436039
has answer: http://stackoverflow.com/a/50209612
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/87435857
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50209744
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/comment/87236719
type: QuestionComment
comment on: http://stackoverflow.com/q/50109404
score: 0
has text: If someone uses `pickle.loads` before you patch it then they can do evil things with it, yes. There isn't really anything you can do about that, except maybe search every imported module's globals for a reference to `pickle.loads`... but that sounds like overkill. Better just find a way to run your patch before anything can happen.
type: Comment

http://stackoverflow.com/q/50078091
tagged with: python
tagged with: cryptography
type: Question
has title: Is there a way to offline sign transaction hex with python?
tagged with: cryptocurrency
answer count: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50513320
has comment: http://stackoverflow.com/comment/87177710
downvote count: 1
favorite count: 0
has body: I have been searching for a function that takes raw transaction hex, private key and gives signed transaction hex as a result.
tagged with: bitcoin
score: 1
has answer: http://stackoverflow.com/a/50078157
has comment: http://stackoverflow.com/comment/87208197

http://stackoverflow.com/comment/87196431
has text: @YazMajeed. Because you passed `self` to `win2` when you created it.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50083035

pyqt4
tags question: http://stackoverflow.com/q/50162090
tags question: http://stackoverflow.com/q/50116038
tags question: http://stackoverflow.com/q/50104099
tags question: http://stackoverflow.com/q/50086893
tags question: http://stackoverflow.com/q/50218411
tags question: http://stackoverflow.com/q/50124556
tags question: http://stackoverflow.com/q/50133693
type: Tag
tags question: http://stackoverflow.com/q/50196579
tag name: pyqt4

http://stackoverflow.com/q/50153403
has comment: http://stackoverflow.com/comment/87324769
has body: i am trying to get the last value of the id from the SQL table, but it returns tuple and i am struggling to concatenate to an int in order to pass the value to the other methods, Example of the method: def generateId(myConnection): with myConnection: cur = myConnection.cursor() cur.execute(" select max(id) from images") id = cur.fetchall() myConnection print id # returns ((43L,),) newId = int(id) + 1 return newId The error: &lt;ipython-input-1-9955a4d0f492&gt; in generateId(myConnection) 30 myConnection 31 print id ---&gt; 32 newId = int(id) + 1 33 34 TypeError: int() argument must be a string or a number, not 'tuple' If you have any further questions regarding my database or method, please let me know, Thank you in advance
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50153459
tagged with: sql
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50153459
has answer: http://stackoverflow.com/a/50153929
upvote count: 1
possible better answer: http://stackoverflow.com/a/50153468
has title: Tuple returned from sql can't be converted to int
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50153468
type: Question
tagged with: python

http://stackoverflow.com/comment/87463135
has text: Can you show the JSON data?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50222720

http://stackoverflow.com/comment/87445208
has text: Also, why are you defining `row` in your lambda and never using it? You're always passing the hard-coded value of `1` to `update_count`.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50209416

atdd
tags question: http://stackoverflow.com/q/50227900
tag name: atdd
type: Tag

http://stackoverflow.com/comment/87375827
comment on: http://stackoverflow.com/a/50119842
has text: Thanks. I found a way to load 9.8million records. I have usedpart of your code and psycopg2 package to load the data. Data is loaded in 30mins
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/50180644
has comment: http://stackoverflow.com/comment/87378567
upvote count: 1
has body: Say I want the index of a list, with sublists, of the sublist with the first item as 3: therefore I want index of 2. Ideally I could use index: mylist = [[1,3],[2,2],[3,7]] # Sadly this is not possible: i = mylist.index(3, key = lambda x: x[0]) &gt;&gt;&gt; 2 But sadly index method does not support a key parameter. Are there any pythonic functions which can do the same job?
tagged with: nested
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87378756
answer count: 0
duplicate of: http://stackoverflow.com/q/1701211
has title: Indexing a list with nested lists
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87378909
tagged with: python
has comment: http://stackoverflow.com/comment/87378830
linked to: http://stackoverflow.com/q/1701211
tagged with: indexing
linked to: http://stackoverflow.com/q/2361426
tagged with: list
score: 0

http://stackoverflow.com/q/50107860
linked to: http://stackoverflow.com/q/35312334
favorite count: 0
has title: Viewing queries history in django
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50109544
linked to: http://stackoverflow.com/q/24209655
linked to: http://stackoverflow.com/q/50029714
type: Question
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/50109544
has comment: http://stackoverflow.com/comment/87236510
score: -2
answer count: 1
has body: I need something to view the queries happened ( creating or updating or deleting ) in DB tables in Django, I want it to be able to be used by the user, not at the admin panel
tagged with: django
tagged with: python

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

http://stackoverflow.com/a/50108975
type: Answer
has body: I can't vouch for the efficiency of this, but: [(x,y) for (i,x) in enumerate(arr) for (j,y) in enumerate(arr) if i &lt; j and x+y == k] Just loop over all pairs, keeping only those whose first element comes before the second so as to avoid duplicates.
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50108911

http://stackoverflow.com/comment/87167017
type: Comment
comment on: http://stackoverflow.com/q/50075379
type: QuestionComment
has text: start with what does "not working" mean? What's in your file?
score: 0

http://stackoverflow.com/comment/87230351
type: QuestionComment
has text: Yes i just updated it. Thank you
score: 0
comment on: http://stackoverflow.com/q/50104357
type: Comment

http://stackoverflow.com/comment/87409930
type: QuestionComment
has text: Please show us the URL config for the view. Also how do you know in your `CreateView` which `Client` you're working with?
score: 0
comment on: http://stackoverflow.com/q/50196294
type: Comment

http://stackoverflow.com/comment/87435462
comment on: http://stackoverflow.com/a/50204991
score: 0
type: AnswerComment
has text: Yes, it is still necessary. I only included the code that had to be added, and importing Axes3D must be in your original code. I hope everything is clear and I have not missed anything from the question
type: Comment

http://stackoverflow.com/q/50080049
tagged with: python-3.x
has title: Python list vector matrix decimals 0s 1s
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/87176028
has comment: http://stackoverflow.com/comment/87176030
has answer: http://stackoverflow.com/a/50081193
tagged with: python
linked to: http://stackoverflow.com/q/588004
tagged with: list
answer count: 2
tagged with: vector
tagged with: matrix
downvote count: 3
linked to: http://stackoverflow.com/q/10825926
has answer: http://stackoverflow.com/a/50080454
upvote count: 1
has comment: http://stackoverflow.com/comment/87176927
has body: I have a list in python l=[[0.1,0.2,0.9],[0.3,0.4,0.6],[0.8,0.2,0.8]] if element &lt;=0.5, return 0, if element &gt; 0.5, return 1 Hence resulting l should look like: l=[[0,0,1],[0,0,1],[1,0,1]] Thanks in advance!
favorite count: 0
type: Question

http://stackoverflow.com/comment/87396161
has text: DId you try doing `window.configure(bg="blue")` on the text widget?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50187281
score: 0

http://stackoverflow.com/q/50085431
has answer: http://stackoverflow.com/a/50085443
answer count: 1
has body: I want to display a single string connected to values from a list displayed using a for loop For example I have this: nums = [1,2,3,4,5] print("Numbers: ") for i in nums: print(i) but I would like it to be displayed with the 1 starting after "Numbers:" e.g Numbers: 1 2 3 ... How would I format the code to enable this to happen?
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/493386
tagged with: format
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87186662
type: UnansweredQuestion
score: -2
linked to: http://stackoverflow.com/q/493386
tagged with: python
has title: Formatting string connected to for loop from a list (python)
tagged with: list
downvote count: 3
upvote count: 1

http://stackoverflow.com/q/50215285
duplicate of: http://stackoverflow.com/q/4140437
has body: Now this may sound confusing, but here is what I have to say. I have a simple Tkinter calculator which runs smoothly, but say for example when you enter something into the entry and the first entry is a 0 you can continue typing and clog your entry up with instances like 05 + 2, etc., which are incorrect on a math level. How can you stop this so 0 can only be followed by a decimal point or replaced by other numbers being pressed? So far just theory and need ideas to get this into code.
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87447969
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87448032
has comment: http://stackoverflow.com/comment/87467312
tagged with: python
tagged with: python-3.6
has title: Tkinter calculator: How to make 0 disappear when it's your first entry or if a decimal point does not follow
linked to: http://stackoverflow.com/q/4140437
score: 0
has comment: http://stackoverflow.com/comment/87447533
answer count: 0

http://stackoverflow.com/comment/87371866
type: QuestionComment
score: 0
has text: What is the expected output?
comment on: http://stackoverflow.com/q/50177211
type: Comment

strftime
tags question: http://stackoverflow.com/q/50134014
type: Tag
tag name: strftime

http://stackoverflow.com/comment/87306408
type: QuestionComment
type: Comment
score: 0
has text: I think you mean `sum(f,'w','z')`?
comment on: http://stackoverflow.com/q/50144023

http://stackoverflow.com/comment/87284661
has text: @AlexanderReynolds I am using histogram backprojection so I don't think there's much more I can do for preprocessing?
comment on: http://stackoverflow.com/q/50110903
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87458482
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50220617
has text: Just tried this on my machine. It removed 15 from `BITES` and added it to `BITES_DONE`. Is that not what it was supposed to do? Doesn't seem like it's ignoring the condition for me.
type: Comment

http://stackoverflow.com/q/50114898
tagged with: python-2.7
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87247264
has comment: http://stackoverflow.com/comment/87247021
upvote count: 1
accepted answer: http://stackoverflow.com/a/50115052
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50115052
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87246909
has title: why the zip function did not give the expected result in python
tagged with: python
has comment: http://stackoverflow.com/comment/87246922
has body: a = enumerate('abcdef') b = enumerate('ghi') for i, j in zip(a, b): print(i, j) if i[0] == 0: next(itertools.islice(zip(a, b), 1, 1), None) For the above code, I expect the following result as I advance zip(a, b) by 1: ((0, 'a'), (0, 'g')) ((2, 'c'), (2, 'i')) However, it still gives the same result as the following code: iter1 = enumerate('abcdef') iter2 = enumerate('ghi') for i, j in zip(a, b): print(i, j) output: ((0, 'a'), (0, 'g')) ((1, 'b'), (1, 'h')) ((2, 'c'), (2, 'i')) why the statement next(itertools.islice(zip(a, b), 1, 1), None) does not advance zip(a, b)?
type: AnsweredQuestion

http://stackoverflow.com/comment/87422256
type: Comment
type: QuestionComment
score: 0
has text: I have added an answer.
comment on: http://stackoverflow.com/q/50202262

http://stackoverflow.com/a/50148481
has comment: http://stackoverflow.com/comment/87317078
score: 1
downvote count: 1
has body: In your code, you will stuck into endless while loop because the condition never fulfilled.Here, you need to change the condition to check whether $ is remaining to you or not. x=0 y=1000 while y&gt;0: x=(83.5*y)/86.8 y=int(x) print x, y
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50148148

http://stackoverflow.com/comment/87187922
comment on: http://stackoverflow.com/q/50080459
type: Comment
type: QuestionComment
score: 0
has text: Nope, same error but when I go into my programes, I see its installed @Kubuntuer82

http://stackoverflow.com/comment/87210299
comment on: http://stackoverflow.com/a/50096549
score: 0
type: AnswerComment
has text: bboumend Its not a single list
type: Comment

http://stackoverflow.com/q/50074981
tagged with: python
has body: Say I have the following dataset : df = pd.DataFrame({'a' : [1, 1, 3], 'b' : [4, 5, 6], 'c' : [7, 8, 9], 'cat' : ['a', 'a', 'b']}) df cat = df.groupby('cat') ag = cat.agg({ "a" : ["sum", "mean"], "b" : "count", "c" : "mean"}) print(ag) a b c sum mean count mean cat a 2 1 2 7.50 b 3 3 1 9.00 I'd like to return a DataFrame containing (a,sum) and (b,count) for (cat==a). How would I do that without flattening the headers a b sum count cat a 2 2
downvote count: 0
answer count: 1
has title: Pandas - Select multiple columns from a nested header after groupby
score: 1
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50075087
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50075087
tagged with: pandas-groupby
tagged with: pandas
tagged with: dataframe

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

http://stackoverflow.com/comment/87412492
type: QuestionComment
comment on: http://stackoverflow.com/q/50197397
score: 0
type: Comment
has text: Could you explain the train/test split int he Option 1? I assume `variables` is the column number that is supposed to be predicted. However, I don't understand what `:trimestres * variables` is supposed to do.

http://stackoverflow.com/comment/87227461
type: QuestionComment
comment on: http://stackoverflow.com/q/50104938
score: 0
type: Comment
has text: Thanks all, Now it's clear to me where is the problem.

http://stackoverflow.com/q/50138015
has title: Need help parsing manga images using BeautifulSoup/requests
has body: I am beginner in Python and I have learned most of the basics of the program. So I decided to create my first project in order to test my skills and understanding. My project involves parsing images for a certain manga chapter from a website called https://bato.to/. Upon looking at the html code, I notice the image code is hidden and is put in a format I never seen before. &lt;/script&gt; &lt;script&gt; var seriesId = 69462; var chapterId = 1204541; var images = {"1":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/57a04a3ce55bd48debf0a486a4c1a48f6380ef9b_1066291_800_1138.png","2":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/a0f75d10919430e6ef25a86c3dcc65f343d8e319_518773_800_1138.png","3":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/575d00ff9ef6873ee9ecfb418e360fe72cc1c594_418309_800_1138.png","4":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/cf839d2425379267218aa666d655e78bd0ee4e4a_425299_800_1138.png","5":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/99e371b684dafca9a91b0a7ad447f51582640bfa_480515_800_1138.png","6":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/7780852155c02e4e6b5059beb97131788274c561_614212_800_1138.png","7":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/569b810f952dd3146c7f120d23b24ee7c9707486_548081_800_1138.png","8":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/53d251f743b61863d6d7557844b34ff5152e1609_484778_800_1138.png","9":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/7800fbe47802269e499b2f70fe53b41a52b0594b_410873_800_1138.png","10":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/3583ca41d7ff56641fae4a717e9b612c1ac365f2_436785_800_1138.png","11":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/81eac44fa63bdbdf2e0d29163ff56d79bc71c820_389040_800_1138.png","12":"https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/b2a0b8…
has answer: http://stackoverflow.com/a/50139514
tagged with: urllib
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/50138987
accepted answer: http://stackoverflow.com/a/50138987
answer count: 2
tagged with: web-scraping
tagged with: python
tagged with: request
possible better answer: http://stackoverflow.com/a/50139514
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87329643
has text: Please report back what option was best and I can highlight this in my answer here for future visitors.
type: Comment
comment on: http://stackoverflow.com/a/50155584
score: 0
type: AnswerComment

http://stackoverflow.com/q/50158035
answer count: 1
has body: I have two dataframes. One is a Pivot table containing three columns, an identifier, a date and a value. It looks like this: The identifier is the CUSIP code. My other dataframe contains over 50 columns but shares the identifier with the first dataframe. It looks like this: The CUSIP code is present in this dataframe as the common identifier. There are multiple entries for each identifier, and they all have different starting and end dates. What I would like to do is merge my 3-column dataframe with my large dateframe by matching the identifier (CUSIP) and using the closest match of the datetime column between the two. I tried using the merge_asof tool, but that is only possible if the dates are sorted (which is not possible given that I have multiple entries for each date - several identifiers have values on each date). Any ideas how to handle this?
has answer: http://stackoverflow.com/a/50158638
accepted answer: http://stackoverflow.com/a/50158638
has comment: http://stackoverflow.com/comment/87334362
type: Question
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87334399
tagged with: python
has title: Matching pivot and dataframe by nearest date
has comment: http://stackoverflow.com/comment/87334434

http://stackoverflow.com/a/50114871
answers question: http://stackoverflow.com/q/50114709
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87248703
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87247312
has body: Your mistake is to assume size equivalence. An integer in a pickle is little more than the bytes needed. But an integer in memory is (some exceptions for small numbers non-withstanding) about 28 bytes. This is the reason why normally one would use numpy to hold the data, as it’s compact arrays of fixed sized numeric types.
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87246832
has comment: http://stackoverflow.com/comment/87248177
has comment: http://stackoverflow.com/comment/87247129
accepted answer of: http://stackoverflow.com/q/50114709
has comment: http://stackoverflow.com/comment/87250600
has comment: http://stackoverflow.com/comment/87248857

http://stackoverflow.com/a/50182008
type: AcceptedAnswer
has body: What you're describing is what's usually called a plugin system. For Python 3.4 and later, there's a standard recipe for importing a source file. The only things left to do are (a) enumerating all the source files in a specified directory, and (b) calling some factory/register/whatever function on each module after you've loaded it. So: def load_module(path): name = os.path.split(path)[-1] spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module plugins = [] for fname in os.listdir(PLUGIN_DIR): if not fname.startswith('.') and fname.endswith('.py'): try: module = load_module(os.path.join(PLUGIN_DIR, fname) plugins.append(module.plugin_factory()) The plugin_factory is just a function or class that "creates an object" for each module. You can call it whatever you want. Often, either every plugin provides a class that's a subclass of (or duck-types as) some type that you defined, or provides a function that returns an instance of some class that you defined. But in really simple cases, you can just use the module itself as the plugin object. In that case, of course, the last line just becomes plugins.append(module). And obviously, if you want to access the plugins by name rather than just iterating over them (and they don't have some name attribute), you'll want to store them in a dict rather than a list. And of course you can add them to sys.modules, as in the recipe in the docs, but usually you don't need that.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50181878
score: 3
accepted answer of: http://stackoverflow.com/q/50181878
upvote count: 3

http://stackoverflow.com/q/50193898
tagged with: python
tagged with: dictionary
downvote count: 1
tagged with: tuples
has answer: http://stackoverflow.com/a/50193922
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50193917
has title: Adding new key to all keys in python dictionary
tagged with: key
possible better answer: http://stackoverflow.com/a/50193922
has answer: http://stackoverflow.com/a/50193917
favorite count: 0
score: -1
type: Question
upvote count: 0
has body: I currently have this dict: initial_dict = {'val_1': 2, 'val_2': 4} And I`m looking for the more efficient way to add a new 'foo' key to all keys to get: final_dict = {('foo' ,'val_1'): 2, ('foo' ,'val_2'): 4}
answer count: 2

http://stackoverflow.com/a/50206043
accepted answer of: http://stackoverflow.com/q/50205938
downvote count: 0
type: Answer
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/87430620
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87454818
has body: Try to change the printer settings: openpyxl.worksheet.worksheet.Worksheet.set_printer_settings(worksheetObject, paper_size = &lt;someInt&gt;, orientation='landscape')
has comment: http://stackoverflow.com/comment/87429442
answers question: http://stackoverflow.com/q/50205938

http://stackoverflow.com/comment/87210133
comment on: http://stackoverflow.com/q/50096846
type: QuestionComment
has text: Can you modify the file format using yaml or json ?
score: 0
type: Comment

http://stackoverflow.com/comment/87347936
has text: You're mixing up different things here. If you want to use `shell=True`, you have to build a single command-line string, including the `nohup ` at the start. If you don't want to use `shell=True`, you have to build a list of all of the separate arguments. If you do something halfway between, like `['nohup', cmd]`, you're passing that entire `cmd` string as one giant argument, the name of the program you want `nohup` to run, and of course there is no such program./
comment on: http://stackoverflow.com/q/50164514
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87377125
type: QuestionComment
comment on: http://stackoverflow.com/q/50179976
has text: What does "it doesn't work" mean? If you need help fixing your code, you have to post a [mcve]. Or if you _aren't_ asking for help debugging your code, then I'm afraid this is a duplicate, because "how do I delete files" has been asked innumerable times in the past.
score: 0
type: Comment

http://stackoverflow.com/a/77127699
type: Answer
answers question: http://stackoverflow.com/q/50181484
score: 0
has body: There are many reasons to did not connect s3 file. Check your region Verify your bucket policy Check IAM user region and your s3 bucket region. it will help you

http://stackoverflow.com/q/50186758
answer count: 2
has body: I have a string of str = '\+234', from which I would like to create another string of '\\+'. And the statement '\' + str[1] gives the following error: SyntaxError: EOL while scanning string literal But the str[1] is '+'. Why the two characters cannot be joined?
upvote count: 1
tagged with: python-3.5
downvote count: 1
tagged with: string
favorite count: 0
type: Question
tagged with: string-literals
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50186833
accepted answer: http://stackoverflow.com/a/50186833
tagged with: python
has title: how to extract '\+' in string of '\+234' in python3
has answer: http://stackoverflow.com/a/50186808
possible better answer: http://stackoverflow.com/a/50186808
score: 0

http://stackoverflow.com/q/50205704
tagged with: python
has answer: http://stackoverflow.com/a/55937661
favorite count: 0
tagged with: postgresql
score: 3
has title: Performance issue with psycopg2 named cursor in python
tagged with: data-migration
type: Question
has body: After some research done, I found out the nameless cursor in python using psycopg2 will try to load all the result set into my computer memory, this is a big issue for me as the Postgresql table that I am querying is about 1.4 TB in size. I found out that giving a name to my cursor will create a server-side cursor that will only load the number of rows I will ask it to, using 'fetchmany' but it has become significantly slower to perform a query. Is there a way for me to speed up the server side cursor? *I try and only load about 2,000 rows as that is about the size that I need the batches to be in.
upvote count: 3
type: UnansweredQuestion
tagged with: database-migration
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50107438
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87253720
answers question: http://stackoverflow.com/q/50106611
has comment: http://stackoverflow.com/comment/87255090
upvote count: 4
has body: This is one solution. df = pd.DataFrame(insights) parts = [pd.DataFrame({d['action_type']: d['value'] for d in x}, index=[0]) if x == x else pd.DataFrame({'add_to_cart': [np.nan], 'purchase': [np.nan]}) for x in df['actions']] df = df.drop('actions', 1)\ .join(pd.concat(parts, axis=0, ignore_index=True)) print(df) account_id cust_id cust_name add_to_cart purchase 0 1234 xyz123 xyz 8 2 1 1234 pqr123 pqr NaN NaN 2 1234 abc123 abc NaN 45 Explanation Utilise pandas to read the outer list of dictionaries into a dataframe. For the inner dictionaries, use a list comprehension together with a dictionary comprehension. Account for nan values by testing for equality within the list comprehension. Concatenate and join the parts to the original dataframe. Explanation - detail This details the construction and use of parts: Take each entry in df['actions']; each entry will be a list of dictionaries. Iterate them one by one, i.e. by row, in a for loop. The else part says "if it is np.nan [i.e. null] then return a dataframe of nans". The if part takes the list of dictionaries and creates a mini-dataframe for each row. We then use the next part to concatenate these mini-dictionaries, one for each row, and join them to the original dataframe.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87256437
score: 4
accepted answer of: http://stackoverflow.com/q/50106611

http://stackoverflow.com/q/50082440
downvote count: 1
has body: I have a Pandas dataframe (1800 obs) that looks something like this: A B C D 1 CL0 CL1 CL2 CL0 2 CL2 CL1 CL1 CL3 3 CL3 CL2 CL0 CL1 . ... ... ... ... . ... ... ... ... n CL2 CL1 CL0 CL3 I want to create a stacked bar chart that will have columns 'A', 'B', 'C', 'D' on the x axis, and the percentage of each level in that feature on the y axis. Something like the picture below. I'm guessing I need to tabulate the data somehow? But I don't know how to do this.
accepted answer: http://stackoverflow.com/a/50082560
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50082560
upvote count: 2
tagged with: python
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: matplotlib
answer count: 1
has title: python stacked bar chart using categorical data

http://stackoverflow.com/q/50197686
answer count: 1
has comment: http://stackoverflow.com/comment/87412460
has comment: http://stackoverflow.com/comment/87412574
accepted answer: http://stackoverflow.com/a/50197869
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87412614
tagged with: python
has comment: http://stackoverflow.com/comment/87412589
has comment: http://stackoverflow.com/comment/87412328
has answer: http://stackoverflow.com/a/50197869
has body: I have an m by n matrix A, implemented as a numpy array. import numpy as np m = 10 n = 7 A = np.random.rand(m, n) I want to compute the m by m matrix B whose entries are B[i, j] = sum_{k=1,...,n} sum_{l=1,...,n} A[i, k] * A[j, l] What is the easiest way to do this without making explicit for loops?
has comment: http://stackoverflow.com/comment/87412439
tagged with: numpy
has title: Compute a sum in numpy array

http://stackoverflow.com/a/50222355
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/113836852
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50213196
has comment: http://stackoverflow.com/comment/113812825
type: AcceptedAnswer
score: 6
answers question: http://stackoverflow.com/q/50213196
has comment: http://stackoverflow.com/comment/113843600
has body: The sorted set requires elements be hashable. Your elements are lists which don't support hashing. Change the elements to tuples and it will work: &gt;&gt;&gt; from sortedcontainers import SortedSet &gt;&gt;&gt; ss = SortedSet([(4, 'last'), (1, 'first')], key=lambda value: value[0]) &gt;&gt;&gt; ss SortedSet([(1, 'first'), (4, 'last')], key=&lt;function &lt;lambda&gt; at 0x10fff4848&gt;) This sorted set will order elements by the first index in the pair. The benefit of tuples is that they're hashable, the drawback is they're immutable. Consider using a sortedcontainers.SortedDict instead: &gt;&gt;&gt; sd = SortedDict({4: 'last', 1: 'first'}) &gt;&gt;&gt; sd SortedDict({1: 'first', 4: 'last'}) &gt;&gt;&gt; sd[2] = 'second' &gt;&gt;&gt; sd.pop(4) 'last' The sorted dict will keep keys in sorted order and let you update the values to anything you like.
has comment: http://stackoverflow.com/comment/113816406

http://stackoverflow.com/q/50165767
tagged with: python
tagged with: tweepy
type: Question
has body: Using the library: from multiprocessing.dummy import Pool as ThreadPool I am streaming tweets and then processing them as follows: class StreamListener(tweepy.StreamListener): httpsCheck = 'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+' httpCheck = 'http?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+' def on_status(self, status): if status.retweeted: return tweetText = status.text.encode('utf8') created_at = status.created_at id = status.id if (re.findall(self.httpCheck, tweetText) or re.findall(self.httpsCheck, tweetText)): return if (re.search('[a-zA-Z]', tweetText)): response = natural_language_understanding.analyze( text=tweetText, features=Features( entities=EntitiesOptions( emotion=True, sentiment=True, limit=2), keywords=KeywordsOptions( emotion=True, sentiment=True, limit=2)), language='en' ) response["tweet"] = tweetText response["id"] = id response["created_at"] = created_at with open('#LFCROMA-SF2.csv', 'a') as csv_file: writer = csv.writer(csv_file) for key, value in response.items(): writer.writerow([key, value]) def on_error(self, status_code): if status_code == 420: return False Now, I want to use multi-threading in order to increase my speed using pool auth = tweepy.OAuthHandler(settingsTwitter.TWITTER_APP_KEY, settingsTwitter.TWITTER_APP_SECRET) auth.set_access_token(settingsTwitter.TWITTER_KEY, settingsTwitter.TWITTER_SECRET) api = tweepy.API(auth) stream_listener = StreamListener() stream = tweepy.Stream(auth=api.auth, listener=stream_listener) pool = ThreadPool(4) pool.map(stream.filter, languages=["en"], track=["#LFC"]) By doing so, I am getting an error: Traceback (most recent call last): File "atomic.py", line 66, in pool.map(stream.filter, languages=["en"], track=["#LFC"]) TypeError: map() got an unexpected keyword argument 'languages' I am unable to figure out a way to call this function in pool.map() The purpose is to stream tweets, apply some heavy processing and then save the results. There is a bottleneck as streaming >> processing in terms of speed. Which…
score: 0
has answer: http://stackoverflow.com/a/50165916
possible better answer: http://stackoverflow.com/a/50165916
answer count: 2
has comment: http://stackoverflow.com/comment/87349836
has title: How do I map the stream filter function of tweepy with the thread pool?
has comment: http://stackoverflow.com/comment/87349594
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50211029
accepted answer: http://stackoverflow.com/a/50211029

http://stackoverflow.com/q/50211546
possible better answer: http://stackoverflow.com/a/73244663
has comment: http://stackoverflow.com/comment/87440996
answer count: 2
has answer: http://stackoverflow.com/a/73244663
downvote count: 0
score: 13
favorite count: 0
has comment: http://stackoverflow.com/comment/87440358
accepted answer: http://stackoverflow.com/a/50214281
type: Question
tagged with: type-conversion
linked to: http://stackoverflow.com/q/7585435
linked to: http://stackoverflow.com/q/14453152
has comment: http://stackoverflow.com/comment/87440403
has answer: http://stackoverflow.com/a/50214281
tagged with: byte
has comment: http://stackoverflow.com/comment/87441859
tagged with: python
has title: Converting Byte to String and Back Properly in Python3?
has body: Given a random byte (i.e. not only numbers/characters!), I need to convert it to a string and then back to the inital byte without loosing information. This seems like a basic task, but I ran in to the following problems: Assuming: rnd_bytes = b'w\x12\x96\xb8' len(rnd_bytes) prints: 4 Now, converting it to a string. Note: I need to set backslashreplace as it otherwise returns a 'UnicodeDecodeError' or would loose information setting it to another flag value. my_str = rnd_bytes.decode('utf-8' , 'backslashreplace') Now, I have the string. I want to convert it back to exactly the original byte (size 4!): According to python ressources and this answer, there are different possibilities: conv_bytes = bytes(my_str, 'utf-8') conv_bytes = my_str.encode('utf-8') But len(conv_bytes) returns 10. I tried to analyse the outcome: &gt;&gt;&gt; repr(rnd_bytes) "b'w\\x12\\x96\\xb8'" &gt;&gt;&gt; repr(my_str) "'w\\x12\\\\x96\\\\xb8'" &gt;&gt;&gt; repr(conv_bytes) "b'w\\x12\\\\x96\\\\xb8'" It would make sense to replace '\\\\'. my_str.replace('\\\\','\\') doesn't change anything. Probably, because four backslashes represent only two. So, my_str.replace('\\','\') would find the '\\\\', but leads to SyntaxError: EOL while scanning string literal due to the last argument '\'. This had been discussed here, where the following suggestion came up: &gt;&gt;&gt; my_str2=my_str.encode('utf_8').decode('unicode_escape') &gt;&gt;&gt; repr(my_str2) "'w\\x12\\x96¸'" This replaces the '\\\\' but seems to add / change some other characters: &gt;&gt;&gt; conv_bytes2 = my_str2.encode('utf8') &gt;&gt;&gt; len(conv_bytes2) 6 &gt;&gt;&gt; repr(conv_bytes2) "b'w\\x12\\xc2\\x96\\xc2\\xb8'" There must be a prober way to convert a (complex) byte to a string and back. How can I achieve that?
has comment: http://stackoverflow.com/comment/87440183
upvote count: 13
type: AnsweredQuestion

http://stackoverflow.com/q/50185657
downvote count: 0
tagged with: web-scraping
favorite count: 0
has body: I'm working on a scraper running through many pages built from the same template. Each page holds some information regarding a specific item. In the optimistic case, I want to get all available data, for simplicity let's say it means name, price, and description. Pages are structured as follows: Product name Manufacturer Some-Mark Full description of the product Conditions that apply to this case: Tags are nested so that I need to test for existence of each level, Some pages will miss some data - empty column in a table is just as possible as missing table, Some pages will have no content at all, Empty text in tag is a valid value, but missing tag must be logged, Missing data is not an exceptional situation. In effect, I test check the presence of each piece of information, which leads to pretty hardly readable code: content = soup.select_one("#content") if content: product_name_tag = content.select_one("h1") if product_name_tag: name = product_name_tag.text else: log("Product name tag not found") table = content.select_one("table") if table: manufacturer_tag = table.select_one("#manufacturer-row > td") if manufacturer_tag: manufacturer = manufacturer_tag.text else: log("Manufacturer tag not found") else: log("Table not found") else: log("Tag '#content' not found") return ( name if name in locals() else None, manufacturer if manufacturer in locals() else None ) In actual application the code is harder to read as properties I'm looking for are often more nested and I need to check existence of each tag before extracting its text. I was wondering if there is any neat way to handle this problem in terms of code readability and conciseness? My ideas: Creating a function to extract tag's text if tag exists - would save few lines, but in real application I must use regexes to extract some phrases from text, so a single function would not be enough. Creating a wrapper to log missing pieces if None was returned rather than under 'else' code - for improved readability. Putti…
tagged with: beautifulsoup
type: Question
has title: Multi-level tag existence check in web scraping - improving readability in python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51486842
tagged with: python
upvote count: 2
score: 2
answer count: 1
tagged with: error-handling

http://stackoverflow.com/q/50074778
has comment: http://stackoverflow.com/comment/87166809
has comment: http://stackoverflow.com/comment/87165875
downvote count: 2
has answer: http://stackoverflow.com/a/50074849
has body: how can i make this calendar in two lines (horizontal) # List of tuples for Months and date ranges # + 1 added to avoid confusion of max day range calender = [('January', range(1, 31 + 1)), ('Feburary', range(1, 28 + 1)), ('March', range(1, 31 + 1)), ('April', range(1, 30 + 1)), ('May', range(1, 31 + 1)), ('June', range(1, 30 + 1)), ('July', range(1, 31 + 1)), ('August', range(1, 31 + 1)), ('September', range(1, 30 + 1)), ('October', range(1, 31 + 1)), ('November', range(1, 30 + 1)), ('December', range(1, 31 + 1))] week = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] def make_calendar(year, start_day): """ make_calendar(int, str) --&gt; None """ # Determine current starting position on calendar start_pos = week.index(start_day) # if True, adjust Feburary date range for leap year | 29 days if is_leap(year): calender[1] = ('Feburary', range(1, 29 + 1)) for month, days in calender: # Print month title print('{0} {1}'.format(month, year).center(20, ' ')) # Print Day headings print(''.join(['{0:&lt;3}'.format(w) for w in week])) # Add spacing for non-zero starting position print('{0:&lt;3}'.format('')*start_pos, end='') for day in days: # Print day print('{0:&lt;3}'.format(day), end='') start_pos += 1 if start_pos == 7: # If start_pos == 7 (Sunday) start new line print() start_pos = 0 # Reset counter print('\n') def is_leap(year): """Checks if year is a leap year""" if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False yr=int(input('Enter Year')) strtday=input('Enter start day of the year Mo,Tu,We,Th,Fr,Sa,Su') make_calendar(yr,strtday)
favorite count: 0
type: Question
upvote count: 0
has title: how can i make this calendar in two lines(python)
type: UnansweredQuestion
score: -2
answer count: 1
tagged with: python

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

methods
tags question: http://stackoverflow.com/q/50110340
tags question: http://stackoverflow.com/q/50080530
tags question: http://stackoverflow.com/q/50191174
tag name: methods
type: Tag

http://stackoverflow.com/q/50125844
has answer: http://stackoverflow.com/a/50134698
has answer: http://stackoverflow.com/a/75386880
upvote count: 31
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/66650120
tagged with: machine-learning
tagged with: scikit-learn
tagged with: keras
has answer: http://stackoverflow.com/a/68435794
favorite count: 0
has answer: http://stackoverflow.com/a/53231071
score: 31
type: AnsweredQuestion
answer count: 9
has answer: http://stackoverflow.com/a/76559665
possible better answer: http://stackoverflow.com/a/59601298
has title: How to standard scale a 3D matrix?
has body: I am working on a signal classification problem and would like to scale the dataset matrix first, but my data is in a 3D format (batch, length, channels). I tried to use Scikit-learn Standard Scaler: from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) But I've got this error message: Found array with dim 3. StandardScaler expected &lt;= 2 I think one solution would be to split the matrix by each channel in multiples 2D matrices, scale them separately and then put back in 3D format, but I wonder if there is a better solution. Thank you very much.
has answer: http://stackoverflow.com/a/54431114
has answer: http://stackoverflow.com/a/59601298
tagged with: python
has answer: http://stackoverflow.com/a/61617645
accepted answer: http://stackoverflow.com/a/50134698
type: Question

http://stackoverflow.com/a/50079356
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50079311
score: 3
type: Answer
has body: you can import the future package from future import .... nested_scopes 2.1.0b1 2.2 PEP 227: Statically Nested Scopes generators 2.2.0a1 2.3 PEP 255: Simple Generators division 2.2.0a2 3.0 PEP 238: Changing the Division Operator absolute_import 2.5.0a1 3.0 PEP 328: Imports: Multi-Line and Absolute/Relative with_statement 2.5.0a1 2.6 PEP 343: The “with” Statement print_function 2.6.0a2 3.0 PEP 3105: Make print a function unicode_literals 2.6.0a2 3.0 PEP 3112: Bytes literals in Python 3000

http://stackoverflow.com/a/50145713
type: Answer
accepted answer of: http://stackoverflow.com/q/50145115
type: AcceptedAnswer
has body: I didn't take a look at the source code of Django GenericView, variables that you point out are variables that we can call class Variables, these are variables of the class ListView. Basically, they are class variables shared by all instances. Whereas inside __init__ they're called instance variable Unique to each instance A small example (Not good enough): class MyView: template_name = 'default_name.html' # class variable shared by all instances def __init__(self,name): self.name = name # instance variable unique to each instance def get_template_name(self): return self.name
answers question: http://stackoverflow.com/q/50145115
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/50196758
upvote count: 1
has comment: http://stackoverflow.com/comment/87410643
type: Answer
has body: May not be a very elegant solution but you could use locals() for retrieving the variables and then convert them into a dictionary. fruit = 'apple' vegetable = 'potato' dic = {key:value for key, value in locals().items() if not key.startswith('__')} This results in {'vegetable': 'potato', 'fruit': 'apple'} However, I believe a better option would be to pass the variable names and create a dictionary as provided in this answer: def create_dict(*args): return dict({i:eval(i) for i in args}) dic = create_dict('fruit', 'vegetable') Edit: Using eval() is dangerous. Please refer to this answer for more information.
answers question: http://stackoverflow.com/q/50196712
has comment: http://stackoverflow.com/comment/87410690
downvote count: 0
score: 1

http://stackoverflow.com/comment/87204871
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50094179
has text: That does not look like the full traceback.
score: 1

http://stackoverflow.com/comment/89086589
comment on: http://stackoverflow.com/a/50174182
has text: Where would one add these headers in a GAE project running on flex env?
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/50078816
type: UnansweredQuestion
score: -2
duplicate of: http://stackoverflow.com/q/533905
has comment: http://stackoverflow.com/comment/87181499
has comment: http://stackoverflow.com/comment/87173918
has body: Suppose I have two lists. noun=["Whispers", "Loners", "Gamblers"] adj=["Shining", " Moaning"] And I want to print: The Shining Whispers The Shining Loners The Shining Gamblers The Moaning Whispers The Moaning Loners The Moaning Gamblers What should be my code to do this? These ones are small lists. I have bigger lists. So what code should I write to accomplish this?
tagged with: python
has comment: http://stackoverflow.com/comment/87173642
has title: How to generate an entire combination of two lists?
downvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/12935194
upvote count: 1
has comment: http://stackoverflow.com/comment/87173826
linked to: http://stackoverflow.com/q/533905
has answer: http://stackoverflow.com/a/50078872
favorite count: 0
type: Question

http://stackoverflow.com/q/50216039
has answer: http://stackoverflow.com/a/50216359
accepted answer: http://stackoverflow.com/a/50216359
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9510474
score: 0
has comment: http://stackoverflow.com/comment/87449455
answer count: 1
tagged with: pip
has comment: http://stackoverflow.com/comment/87448953
type: Question
has body: I'm trying to use pytaglib. If I install it through the root account in the system-wide directory (/usr/lib64/python2.7/site-packages), it installs pytaglib-1.43.dist-info and a binary taglib.so. If I create a virtual environment for a user account, it installs version pytaglib-1.43.dist-info and a binary taglib.so in the appropriate virtual-env directory. But the contents of pytaglib-1.43.dist-info are different (there are a few missing files), and the binary is of a different size. What accounts for this difference? I do not use pip very much, and neither the root account nor the user account has a .pip directory. I haven't explicitly changed any pip settings for either.
has title: Why is pip installing different binaries for the same version of the same package?

http://stackoverflow.com/a/50136406
type: Answer
accepted answer of: http://stackoverflow.com/q/50136310
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87312768
has comment: http://stackoverflow.com/comment/87312814
answers question: http://stackoverflow.com/q/50136310
score: 0
has body: By don't having it as an inner class, but as a separate class and then an instant attribute: class child_class: def __init__(self): self.some_variable = None class test: def __init__(self): self.child = child_class() t = test() t.child.some_variable = "123" t = test() print(t.child.some_variable) # prints None Or alternative you can have a inner class, but still you have to create an instance attribute: class test: class child_class: def __init__(self): self.some_variable = None def __init__(self): self.child = self.child_class() t = test() t.child.some_variable = "123" t = test() print(t.child.some_variable) # also prints None

http://stackoverflow.com/a/50152310
has body: In native Python: a = [-1,-1,0,2] bools = [x &gt; 1 for x in a] &gt;&gt;&gt; [False, False, False, True] In numpy you can use the simpler syntax like in your example though (this will also be noticeably faster if you have millions of values rather than just four): import numpy as np a = np.array([-1,-1,0,2]) bools = a &gt; 1 &gt;&gt;&gt; array([False, False, False, True])
answers question: http://stackoverflow.com/q/50152243
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50152243
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/53009123
upvote count: 3
downvote count: 0
has body: try running this command %gui tk at the console before running your code. The alternative is it go to Tools &gt; Preferences &gt; IPython Console &gt; Graphics &gt; Graphics backend and select tkinter there. This worked for me :) The answer was found here https://groups.google.com/forum/#!topic/spyderlib/rFJhJZgjZTE
answers question: http://stackoverflow.com/q/50158218
type: Answer
has comment: http://stackoverflow.com/comment/100118271
score: 3

http://stackoverflow.com/comment/87401147
has text: This: `year >= 1965 <= 1968` doesn't work the way you want it to.
comment on: http://stackoverflow.com/q/50192120
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50204679
score: 4
has title: Python-pptx formatting datalabels after adding text
has body: As I needed to add custom text to a chart data labels in python-pptx I used for point in plot.series[1].points: frame = point.data_label.text_frame frame.text = "Test " for run in frame.paragraphs[0].runs: run.font.size = Pt(10) run.font.color.rgb = RGBColor(0x0A, 0x42, 0x80) This allowed me to change the font to the labels but I would need to rotate them. I saw the solution from This other thread but it does not work. Any ideas?
has answer: http://stackoverflow.com/a/72044449
tagged with: python-pptx
has comment: http://stackoverflow.com/comment/87427222
tagged with: python
upvote count: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/124046276
linked to: http://stackoverflow.com/q/44544701
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87435866
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68758482

http://stackoverflow.com/q/50097852
type: UnansweredQuestion
has title: Check every Minute if there was an *.odb file generated or not. If yes --> Get Data
answer count: 1
has body: I would like to check every minute if there was a file like "RESULTS.ODB" generated and if this file is bigger than 1.5 Gigabyte there starts another subprocess to get the Data from this file. How can i make sure that the file isn´t in progress to be written and everything is included? I hope you know what i mean. Any ideas how to handle that? Thank you very much. :)
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87212254
linked to: http://stackoverflow.com/q/21126108
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50099004
tagged with: subprocess
upvote count: 2

http://stackoverflow.com/q/50198977
answer count: 1
tagged with: python
type: Question
tagged with: spectrum
accepted answer: http://stackoverflow.com/a/50199533
type: AnsweredQuestion
tagged with: audio
score: 0
has answer: http://stackoverflow.com/a/50199533
tagged with: matplotlib
has title: How to get an x-axis adapted to audio/acoustics with pyplot?
has body: When plotting frequency response curves: import numpy as np from scipy import signal import matplotlib.pyplot as plt w, h = signal.freqz([1, -1]) x = w * 44100 * 1.0 / (2 * np.pi) y = 20 * np.log10(abs(h)) then plt.plot(x, y) and plt.semilogx(x, y) give: but none of them have the "standard x-axis used in audio". Question: how to have the x-axis usually used in audio applications? It includes: some sort of logarithmic axis, but not sure: is it really a normal logarithmic axis (see examples after)? axis from 20 to 20Khz, and ticks ["20", "50", "100", "200", "500", "1K", "2K", "5K", "10K", "20K"] Here are a few examples of what I mean:

http://stackoverflow.com/q/50075979
accepted answer: http://stackoverflow.com/a/50076049
tagged with: python
has answer: http://stackoverflow.com/a/50076049
tagged with: watermark
has comment: http://stackoverflow.com/comment/87168189
tagged with: python-2.7
tagged with: pypdf
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 0
answer count: 1
favorite count: 0
has body: I have two pdf files of the same length, let's say pdf1.pdf and pdf2.pdf. I'm trying to watermark each page of pdf1.pdf with pdf2.pdf (i.e., page 1 of pdf1.pdf with page 1 of pdf2.pdf, page 2 of pdf1.pdf with page 2 of pdf2.pdf ...). However, I'm really struggling with how to loop them around (I'm new to programming). For example, I tried this: import PyPDF2 from PyPDF2 import PdfFileMerger from PyPDF2 import PdfFileReader, PdfFileWriter output = PdfFileWriter() ipdf = PdfFileReader(open('pdf1.pdf', 'rb')) wpdf = PdfFileReader(open('pdf2.pdf', 'rb')) for i in xrange(wpdf.getNumPages()): watermark = wpdf.getPage(i) for i in xrange(ipdf.getNumPages()): page = ipdf.getPage(i) for i in watermark: page.mergePage(watermark) output.addPage(page) with open('newfile.pdf', 'wb') as f: output.write(f) Any help would be appreciated :) :)
type: Question
has title: Watermark two pdfs - Each page of the first with each page of the second

http://stackoverflow.com/a/50272859
upvote count: 1
answers question: http://stackoverflow.com/q/50218050
score: 1
downvote count: 0
has body: Try the following method: (it works fine in NUKE 10.5v7 on macOS 10.11) import nuke import math def doThat(a,b): c = a + b print(c) nuke.menu('Nuke').addCommand('self', 'doThat(5,7)', 'alt+u') # Result: &lt;MenuItem object at 0x11eb54d50&gt; # doThat(5,7) # 12 or this one: nuke.menu('Nuke').addCommand('', 'doThat(5,7)', 'alt+u') # Result: &lt;MenuItem object at 0x11eb54d38&gt; # doThat(5,7) # 12
type: Answer

http://stackoverflow.com/comment/87271580
type: QuestionComment
has text: Parsing the result is (a) very expensive compared to retrieving it and (b) not related to testing the performance of the server since it happens on the client. You will put more load on the test client than on the server.
type: Comment
comment on: http://stackoverflow.com/q/50126725
score: 0

http://stackoverflow.com/comment/87449847
type: QuestionComment
comment on: http://stackoverflow.com/q/50214502
score: 0
has text: Sounds like an interesting problem! Any chance that you can create a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve)? That would make it much easier for someone to help you. Without code, the best anyone can do is guess (but you might get some very informed guesses).
type: Comment

http://stackoverflow.com/comment/87441315
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50211607
type: AnswerComment
has text: @MihaiAlexandru-Ionut reason for `word[::-1]` being faster?

http://stackoverflow.com/q/50123435
type: AnsweredQuestion
answer count: 2
downvote count: 0
has body: I have two different dataframes with two different lengths of rows. I want df1 to match df2 but I don't want to create a new dataframe in the process (no merge). df1 0 Alameda 1 Alpine 2 Amador 3 Butte 4 Calaveras 5 Colusa 6 Contra Costa 7 Del Norte 8 El Dorado 9 Fresno 10 Glenn 11 Humboldt 12 Imperial 13 Inyo 14 Kern 15 Kings 16 Lake 17 Lassen 18 Los Angeles 19 Madera 20 Marin 21 Mariposa 22 Mendocino 23 Merced 24 Modoc 25 Mono 26 Monterey 27 Napa 28 Nevada 29 Orange 30 Placer 31 Plumas 32 Riverside 33 Sacramento 34 San Benito 35 San Bernardino 36 San Diego 37 San Francisco 38 San Joaquin 39 San Luis Obispo 40 San Mateo 41 Santa Barbara 42 Santa Clara 43 Santa Cruz 44 Shasta 45 Sierra 46 Siskiyou 47 Solano 48 Sonoma 49 Stanislaus 50 Sutter 51 Tehama 52 Trinity 53 Tulare 54 Tuolumne 55 Ventura 56 Yolo 57 Yuba df2 0 Alameda 1 Amador 2 Butte 3 Calaveras 4 Colusa 5 Contra Costa 6 Del Norte 7 El Dorado 8 Fresno 9 Glenn 10 Humboldt 11 Imperial 12 Inyo 13 Kern 14 Kings 15 Lake 16 Lassen 17 Los Angeles 18 Madera 19 Marin 20 Mariposa 21 Mendocino 22 Merced 23 Mono 24 Monterey 25 Napa 26 Nevada 27 Orange 28 Placer 29 Plumas 30 Riverside 31 Sacramento 32 San Benito 33 San Bernardino 34 San Diego 35 San Francisco 36 San Joaquin 37 San Luis Obispo 38 San Mateo 39 Santa Barbara 40 Santa Clara 41 Santa Cruz 42 Shasta 43 Siskiyou 44 Solano 45 Sonoma 46 Stanislaus 47 Sutter 48 Tehama 49 Tulare 50 Ventura 51 Yolo 52 Yuba Is there a way to modify a column's rows in a dataframe using a column's rows from a different dataframe? Again I want to keep the dataframes separate, but the goal is to get the dataframes to have the same number of rows containing the same values.
has comment: http://stackoverflow.com/comment/87265207
favorite count: 0
has comment: http://stackoverflow.com/comment/87265052
type: Question
has comment: http://stackoverflow.com/comment/87265199
has answer: http://stackoverflow.com/a/50123639
has answer: http://stackoverflow.com/a/50123569
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50123569
has title: Removing rows from one DataFrame based on rows from another DataFrame
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/50123639
score: 2
upvote count: 2

http://stackoverflow.com/q/50111681
score: 0
answer count: 2
has title: Filtering a very large list of domains using slice
accepted answer: http://stackoverflow.com/a/50111876
tagged with: string
has answer: http://stackoverflow.com/a/50111876
type: Question
possible better answer: http://stackoverflow.com/a/50111900
has answer: http://stackoverflow.com/a/50111900
tagged with: python
has body: I'm filtering a very large list of subdomains and I'm trying to create a variable slice. The list is extremely large so I want to approach this in the most "pythonic" method that would be performance optimised. The method works like the following: Assuming a list of domains taking a variety of formats: a.b.c.domain.com d.e.domain.com f.domain.com If the user wants to filter by a depth of one, only domains that are formatted like f.domain.com would be displayed. If the user selects a depth of two, domains formatted like both f.domain.com and d.e.domain.com would be shown. I believe this could be accomplished with something like s.join(a.split(".")[len(a.split(".")) - 4:]) however it seems overly complicated and I was wondering if there's a way of using slice that I'm missing which is ideal for this kind of use case?
tagged with: slice
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87240766

http://stackoverflow.com/q/50181895
upvote count: 0
has title: Pandas - Numbers turn to months
answer count: 1
has body: When i convert my pandas dataframe to csv, some numbers turn to months. Screenshot It only happens when it converts to csv. This is my code: import requests my_url = requests.get('http://www.vivoelfutbol.com.mx/futbolmexicano.php') from bs4 import BeautifulSoup as soup page_soup = soup(my_url.text, "html.parser") containers = page_soup.findAll("div", {"class":"bordermitad"})[0].findAll("div", {"class":"det"}) #dates = page_soup.findAll("div", {"class":"bordermitad"})[0].findAll("div", {"class":"tif"}) #for result in dates: #date = result.text.strip() #print(date + "\n") calendario = [] for result2 in containers: time = result2.find('div', {'class':'hor'}).text hometeam = result2.find('a').text score = result2.find('a', {'title':'Analisis y Antecedentes'}).text awayteam = result2.find('div', {'class':'eqvc'}).text calendario.append((time, hometeam, score, awayteam)) #print("\n" + time + " " + hometeam + " " + score + " " + awayteam + "\n") import os import pandas as pd df = pd.DataFrame(calendario, columns=['Hora', 'Equipo_1', 'Marcador', 'Equipo 2']) if not os.path.isfile('Marcadores_futbol_mexico.csv'): df.to_csv('Marcadores_futbol_mexico.csv', index=True) else: df.to_csv('Marcadores_futbol_mexico.csv', mode ='a') EDIT: Printing df i get this: Hora Equipo_1 Marcador Equipo 2 0 19:30 UNAM 1-4 America 1 21:30 Tijuana 1-1 Monterrey 2 19:30 Tigres 2-0 Santos 3 21:30 Morelia 2-2 Toluca 4 19:00 America --- UNAM 5 21:00 Monterrey --- Tijuana 6 12:00 Toluca --- Morelia 7 18:00 Santos --- Tigres In the csv, it shows this: Hora Equipo_1 Marcador Equipo 2 0 19:30 UNAM 4-Jan America 1 21:30 Tijuana 1-Jan Monterrey 2 19:30 Tigres Feb-00 Santos 3 21:30 Morelia 2-Feb Toluca 4 19:00 America --- UNAM 5 21:00 Monterrey --- Tijuana 6 12:00 Toluca --- Morelia 7 18:00 Santos --- Tigres EDIT 2: Solved, it was excel messing with me :P
downvote count: 1
has answer: http://stackoverflow.com/a/50182094
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50182094
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87381423
tagged with: pandas

http://stackoverflow.com/q/50158459
has comment: http://stackoverflow.com/comment/87350648
has body: I'm a beginner of Python and Flask. I was going through Flask tutorial up to "Define and Access the Database" section. Wrote up all codes, saved, and did below on Windows command prompt. flask init-db However, got received the error on the command prompt as follows. AttributeError: 'ellipsis' object has no attribute 'teardown_appcontext' I doublechecked the codes to confirm it's written exactly in a way that tutorial specifies and it actually worked fine until the previous section. Searched through Stackoverflows if there is any similar questions, but ended up not finding out a clear cause. Any advises? Thank you very much for your support. --Additions-- Thanks Joost. Here is what I did. Files layout image link __init__.py import os from flask import Flask def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # Load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # Load the test config if passed in app.config.from_mapping(test_config) # ensure the instance floder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' def create_app(): app = ... # existing code omitted from . import db db.init_app(app) return app db.py import sqlite3 import click from flask import current_app, g from flask.cli import with_appcontext def get_db(): if 'db' not in g: g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row return g.db def close_db(e=None): db = g.pop('db', None) if db is not None: db.close() def init_db(): db = get_db() with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf8')) @click.command('init-db') @with_appcontext def in…
has answer: http://stackoverflow.com/a/70135440
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54611811
score: 5
has comment: http://stackoverflow.com/comment/87346128
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52017175
upvote count: 6
tagged with: python
tagged with: flask
answer count: 3
has title: Flask tutorial: AttributeError teardown_appcontext
downvote count: 1

http://stackoverflow.com/a/51023001
has comment: http://stackoverflow.com/comment/117530554
has body: After some research this is what i came up with final_score = np.squeeze(scores) count = 0 for i in range(100): if scores is None or final_score[i] &gt; 0.5: count = count + 1 print('cpunt',count) printcount =0; for i in classes[0]: printcount = printcount +1 print(category_index[i]['name']) if(printcount == count): break this will print all the detected objects , if you want to return it u can add it to some variable and return. if you only want to print the detected objects add print(class_name) in the visualization_utils.py file inside the util folder if not agnostic_mode: if classes[i] in category_index.keys(): class_name = category_index[classes[i]]['name'] **print(class_name)** --&gt; this line else:
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50077353
score: 3
type: Answer

http://stackoverflow.com/q/50175821
answer count: 1
type: Question
has body: I have the following use case In my project- Python. We have a prediction system in place for every user request through API (We are using IIS, need to look at flask capabilities). The size of a pickle file is huge, like 700MB, I don't want to load it for every request (since it is consuming more RAM for every request). Can we load the pickle file into flask cache and use it for all the requests? (or) Can we share the data among all the requests, so that we don't need to load it again and again? Please help with the sample implementation of sharing pickle data across all the requests
tagged with: urllib3
tagged with: python
type: UnansweredQuestion
tagged with: flask-restful
tagged with: python-3.x
score: 0
has answer: http://stackoverflow.com/a/50176786
has title: How to use sklearn pickle object created in first request across all other requests
tagged with: flask

http://stackoverflow.com/q/50144018
type: Question
has answer: http://stackoverflow.com/a/50144110
possible better answer: http://stackoverflow.com/a/50144110
tagged with: python
has answer: http://stackoverflow.com/a/50144062
accepted answer: http://stackoverflow.com/a/50144062
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50144159
has title: Create sublists with duplicate list elements
answer count: 3
upvote count: 2
downvote count: 0
has body: I'm new to Python and I'm trying to create sublists for list elements sharing the same base: listRaw = ['AKS/STB', 'SBHS/AME', 'SBJ/OAK', 'SBJ/ALS', 'AKS/OSMX', 'SBHS/ABNX', 'AKS/AKX'] desiredOutput = [['AKS/STB', 'AKS/OSMX', 'AKS/AKX'], ['SBHS/AME', 'SBHS/ABNX'], ['SBJ/OAK', 'SBJ/ALS']] I've tried to first isolate the base from each list element using: def commonNumerator(self): checkPosition = self.find('/') commonNumerator = self[:checkPosition] return commonNumerator listRawModified = [commonNumerator(x) for x in listRaw] print(listRawModified) which gets me: ['AKS', 'SBHS', 'SBJ', 'SBJ', 'AKS', 'SBHS', 'AKS'] but from then I don't know how to proceed to get to the desired ouput. Can someone explain to me how to do it?
favorite count: 0

http://stackoverflow.com/q/50197326
has title: How do I evaluate whether the mean squared error (MSE) is reasonable or not?
upvote count: 3
tagged with: regression
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87414116
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50197472
has answer: http://stackoverflow.com/a/50197472
tagged with: python
downvote count: 1
has body: I'm creating regression models using scikit learn. Now I'm wondering how I can evaluate whether the mean squared error is reasonable or bad? For example, when I do cross validation, the testing data's MSE for model of train data is 0.70. Is it reasonable or bad score? Also is it meaningful to calculate the whole data's MSE for a model and compare them and see if the scores are similar? It's not programming question but I want to know how to evaluate the value. I'm not sure if my way is correct or not.
tagged with: statistics
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/50084532
has comment: http://stackoverflow.com/comment/87193297
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87191557
downvote count: 0
tagged with: python
score: 3
has body: I am creating a bot to scrape images from a discord channel. The images can come in two ways: 1) A link such as: https://cdn.discordapp.com/attachments/XXXXXXXX In this case I download the image directly from the URL and there is no problem. 2) In the second case, there is no URL and the images simply come directly as an attachment. I am using the Python API, is there a simple way of downloading any attachments that are sent in a channel? The code I am using for part 1 is: if(string[0:26] == "https://cnd.discordapp.com"): r = requests.get(string, stream = True) with open("image1.png",'wb') as out_file: shutil.copyfileobj(r.raw, out_file) Is there any way to like extract a URL from an attachment where the URL isn't listed in chat so I can plug it into the first method? If not, what commands do I use to iterate through message attachments/ downloading them?
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/87192507
has answer: http://stackoverflow.com/a/69791747
tagged with: discord
has title: Downloading attachments with Discord API in python
favorite count: 0
type: Question

http://stackoverflow.com/q/50138814
has comment: http://stackoverflow.com/comment/87295988
type: Question
tagged with: python-datetime
tagged with: python
has comment: http://stackoverflow.com/comment/87296108
has comment: http://stackoverflow.com/comment/87296379
score: 0
has comment: http://stackoverflow.com/comment/87296139
has comment: http://stackoverflow.com/comment/87296305
answer count: 0
has comment: http://stackoverflow.com/comment/87296369
type: UnansweredQuestion
has body: I have to extract start date, start time and end date, end time in desired format from a string in python. For that I wrote a code: from datetime import * #date_time = 'Sun Apr 22 2018 at 02:00 pm to Sun May 13 2018 at 02:00 pm' #date_time = 'Sun Apr 22 2018 at 02:00 pm' #date_time = 'Sat Apr 28 2018 at 05:00 pm to 07:00 am' #date_time = 'Fri Oct 15 2021' date_time = 'Sat Aug 01 2020' #date_time = 'Wed Jan 22 2020 at 01:30 pm' #date_time = 'Wed Jan 01 2020 to Thu Jan 02 2020' delim = 'to' if delim in date_time: start_date_time = date_time.split(delim, 2)[0] start_date_time = start_date_time.partition(' ')[2] #remove the first word of the string end_date_time = date_time.split(delim, 2)[1] end_date_time = end_date_time.strip() #remove the first space in the string #end_date_time = end_date_time.partition(' ')[2] #remove the first word of the string delim = 'at' start_date = start_date_time.split(delim, 2)[0] start_date = start_date.rstrip() #remove the space at the end of the string start_date = datetime.strptime(start_date, "%b %d %Y") start_time = start_date_time.split(delim, 2)[1] start_time = start_time.strip() start_time = datetime.strptime(start_time, "%I:%M %p") start_time = datetime.strftime(start_time, "%H:%M:%S") if delim in end_date_time: end_date_time = end_date_time.partition(' ')[2] #remove the first word of the string end_date = end_date_time.split(delim, 2)[0] #print(end_date) end_date = end_date.rstrip() end_date = datetime.strptime(end_date, "%b %d %Y") #print(end_date) end_time = end_date_time.split(delim, 2)[1] end_time = end_time.strip() end_time = datetime.strptime(end_time, "%I:%M %p") end_time = datetime.strftime(end_time, "%H:%M:%S") else: end_date = start_date end_time = end_date_time end_time = end_time.strip() end_time = end_time.rstrip() end_time = datetime.strptime(end_time, "%I:%M %p") end_time = datetime.strftime(end_time, "%H:%M:%S") else: delim = 'at' if delim in date_time: start_date_time = date_time.partition(' ')[2] #end_date_time…
has title: Strange behaviour of Python script

http://stackoverflow.com/q/50087319
tagged with: sdn
has body: I've got an assignment in SDN course to create a Load Balancer using mininet and pox controller. I have the topology file, which I've created using Python and mininet, and the controller file, which I've created using Python and POX. The topology is as follow: Hosts h1-h4 are the client hosts, Hosts h5-h8 are the servers. I have one switch that acts as the load balancer. The clients send a requests to the switch, which forwards the request to a randomly selected server. The server is then sends the request back to the switch, and the switch is then direct it back to the client. I've managed to complete this task, but now i have to show that the load balancer is acting as expected (meaning, it balance the requests among all servers). The way i need to show it, is by generate at least 10,000 requests from the clients to the switch. My question is: how do i make a script like that and run it from the mininet shell? I thought about making a script that runs a loop (10K iterations) and pick a random client which ping the switch. The problem is i don't know how to do it.
answer count: 1
tagged with: shell
tagged with: pox
has answer: http://stackoverflow.com/a/50094021
type: Question
has title: How to run script from mininet shell?
tagged with: mininet
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/50172557
has body: Following the canonical advice of this post, I am trying to cast my dict_keys object to a list. It works in the python 3.6.5 interpreter just fine. However, when I do it in pdb, it does not work. E.g. &gt;&gt;&gt; import pdb; pdb.set_trace() --Return-- &lt;function save_history at 0x100369e18&gt; &gt; &lt;stdin&gt;(1)&lt;module&gt;()-&gt;None (Pdb) newdict = dict() (Pdb) newdict["pig"] = "pink" (Pdb) newdict["finch"] = "yellow" (Pdb) newdict.keys() dict_keys(['pig', 'finch']) (Pdb) list(newdict.keys()) *** Error in argument: '(newdict.keys())' How do I get this to work in pdb?
linked to: http://stackoverflow.com/q/10319147
has comment: http://stackoverflow.com/comment/87362912
tagged with: python
type: UnansweredQuestion
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87362625
duplicate of: http://stackoverflow.com/q/10319147
has comment: http://stackoverflow.com/comment/87362667
upvote count: 2
linked to: http://stackoverflow.com/q/17322668
score: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: pdb
linked to: http://stackoverflow.com/q/16819222
tagged with: python-3.x
has title: Why does casting dict_keys as a list not work in pdb?
type: Question
has answer: http://stackoverflow.com/a/50173042

http://stackoverflow.com/a/50109061
has comment: http://stackoverflow.com/comment/87236967
score: 1
downvote count: 0
upvote count: 1
has body: Even though you specified the expected_shape, the tf.Variable will take the shape of initial_value (0 for your case here) as its shape. It seems that the expected_shape argument has been deprecated since v1.0.0. I'm not sure why it is still documented with tf.Variable. I just filed an issue on Github.
has comment: http://stackoverflow.com/comment/87236826
answers question: http://stackoverflow.com/q/50103262
type: Answer

http://stackoverflow.com/q/50179334
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Python extract json strings from large textfile
has comment: http://stackoverflow.com/comment/87376050
tagged with: python
tagged with: regex
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50179476
accepted answer: http://stackoverflow.com/a/50179476
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87375955
has body: I am working on a project that requires a large data set. I found a sufficiently large data set ( editions dump at https://openlibrary.org/developers/dumps, about 5GB) which is formatted /type/edition /books/OL10000135M 4 2010-04-24T17:54:01.503315 {"publishers": ["Bernan Press"], "physical_format": "Hardcover", "subtitle": "9th November - 3rd December, 1992", "key": "/books/OL10000135M", "title": "Parliamentary Debates, House of Lords, Bound Volumes, 1992-93", "identifiers": {"goodreads": ["6850240"]}, "isbn_13": ["9780107805401"], "languages": [{"key": "/languages/eng"}], "number_of_pages": 64, "isbn_10": ["0107805405"], "publish_date": "December 1993", "last_modified": {"type": "/type/datetime", "value": "2010-04-24T17:54:01.503315"}, "authors": [{"key": "/authors/OL2645777A"}], "latest_revision": 4, "works": [{"key": "/works/OL7925046W"}], "type": {"key": "/type/edition"}, "subjects": ["Government - Comparative", "Politics / Current Events"], "revision": 4} /type/edition /books/OL10000179M 4 2010-04-24T17:54:01.503315 {"publishers": ["Stationery Office"], "physical_format": "Hardcover", "subtitle": "26 January - 4 February 1998", "title": "Parliamentary Debates, House of Lords, 1997-98", "isbn_10": ["0107805855"], "identifiers": {"goodreads": ["2862283"]}, "isbn_13": ["9780107805852"], "edition_name": "5th edition", "languages": [{"key": "/languages/eng"}], "number_of_pages": 124, "last_modified": {"type": "/type/datetime", "value": "2010-04-24T17:54:01.503315"}, "latest_revision": 4, "key": "/books/OL10000179M", "authors": [{"key": "/authors/OL2645811A"}], "publish_date": "January 1999", "works": [{"key": "/works/OL7925994W"}], "type": {"key": "/type/edition"}, "subjects": ["Bibliographies, catalogues, discographies", "POLITICS &amp; GOVERNMENT", "Reference works", "Bibliographies &amp; Indexes", "Reference"], "revision": 4} etc... and I wan to extract the JSON part (the fifth field). I am trying to use str.replace() (on a 50 line subset of the big file) but it…

http://stackoverflow.com/comment/87448632
type: AnswerComment
comment on: http://stackoverflow.com/a/50205445
score: 0
type: Comment
has text: Something like the one on the right..https://joonuryuscienceresearch.files.wordpress.com/2015/06/color-qr-code-vs-regular-qr-code-size-difference.png Where could I begin to get a colour scheme like this?

http://stackoverflow.com/a/50143784
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50143672
type: Answer
answers question: http://stackoverflow.com/q/50143672
has body: You need to use ajax to power a dynamic page. First, create the search page, with ajax in the script section and another snippet of HTML in its own file with templating to display the results: search.html: Search results.html: {%for result in results%} {{result.val}} {%endfor%} Then, in app.py, create the route to render search.html and another route, /search_result to receive the query: from collections import namedtuple @app.route('/search', methods=['GET']) def search(): return flask.render_template('search.html') @app.route('/search_result') def search_for(): query = flask.request.args.get('search') result = namedtuple('result', ['val', 'btn']) vals = [("Article1", 60), ("Article2", 50), ("Article 3", 40)] #below is a very simple search algorithm to filter vals based on user input: html = flask.render_template('results.html', results=[result(a, b) for a, b in vals if query.lower() in a.lower()]) return flask.jsonify({'results':html})

http://stackoverflow.com/comment/87219185
has text: Yes, the cell. My biggest problem now is that the figure is shown, but the data is not. I would like to know if I am referring something i the wrong way, maybe
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50100580

http://stackoverflow.com/q/50113417
has title: Struggling to iter over attributes in Django 2.0
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87244164
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87243920
tagged with: django
tagged with: django-models
tagged with: python
has body: Here is my code: class Product(models.Model) : name = models.CharField(max_length=150) price = models.DecimalField(max_digits=15, decimal_places=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField(auto_now=True, auto_now_add=False) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=100) is_featured = models.BooleanField(default=False) descripition = models.TextField() is_published = models.BooleanField(default=True) attributes = models.ManyToManyField('Attribute') def __str__(self) : return self.name class Meta : ordering = ("-date",) class ProductVariant(models.Model) : sku = models.CharField(max_length=120, unique=True) name = models.CharField(max_length=120, blank=False, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) for attri in product.attributes : attri.name = models.ForeignKey(AttributeVariant, on_delete=models.CASCADE, limit_choices_to={'attribute.name': attri.name}) class Meta : ordering = ("name",) def __str__(self) : return self.product.name + self.name class Attribute(models.Model) : name = models.CharField(max_length=120) def __str__(self) : return self.name class Meta : ordering = ("name",) class AttributeVariant(models.Model) : name = models.CharField(max_length=120) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE, related_name='values') class Meta : ordering = ("name",) def __str__(self) : return self.name What I'm trying to do : In the ProductVariant Class, I'm trying to iter through the product attributes and to assign to each of them a field ForeignKey to AttributeVariants to get the values of this specific attribute. It corresponds to the code below: for attri in product.attributes : attri.name = models.ForeignKey(AttributeVariant, on_delete=models.CASCADE, limit_choices_to={'attribute.name': attri.name}) However, when I try to run python manage.py makemigrations,…
score: 0
answer count: 0

http://stackoverflow.com/q/50206520
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50208573
tagged with: split
has title: Split large dataframes (pandas) into chunks (but after grouping)
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: dask
tagged with: pandas
has body: I have a large tabular data, which needs to be merged and splitted by group. The easy method is to use pandas, but the only problem is memory. I have this code to merge dataframes: import pandas as pd; from functools import reduce; large_df = pd.read_table('large_file.csv', sep=',') This, basically load the whole data in memory th # Then I could group the pandas dataframe by some column value (say "block" ) df_by_block = large_df.groupby("block") # and then write the data by blocks as for block_id, block_val in df_by_block: pd.Dataframe.to_csv(df_by_block, "df_" + str(block_id), sep="\t", index=False) The only problem with above code is memory allocation, which freezes my desktop. I tried to transfer this code to dask but dask doesn't have a neat groupby implementation. Note: I could have just sorted the file, then read the data line by line and split as the "block" value changes. But, the only problem is that "large_df.txt" is created in the pipeline upstream by merging several dataframes. Any suggestions? Thanks, Update: I tried the following approach but, it still seems to be memory heavy: # find unique values in the column of interest (which is to be "grouped by") large_df_contig = large_df['contig'] contig_list = list(large_df_contig.unique().compute()) # groupby the dataframe large_df_grouped = large_df.set_index('contig') # now, split dataframes for items in contig_list: my_df = large_df_grouped.loc[items].compute().reset_index() pd.DataFrame.to_csv(my_df, 'dask_output/my_df_' + str(items), sep='\t', index=False) Everything is fine, but the code my_df = large_df_grouped.loc[items].compute().reset_index() seems to be pulling everything into the memory again. Any way to improve this code??

http://stackoverflow.com/comment/87602639
type: QuestionComment
comment on: http://stackoverflow.com/q/50202268
type: Comment
score: 0
has text: Did one of the solutions below help? Feel free to accept one if it did (green tick on left), or ask for clarification.

http://stackoverflow.com/q/50100368
has comment: http://stackoverflow.com/comment/87311551
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87222654
tagged with: arduino
has title: Stop getting data from arduino when python get data from it
has comment: http://stackoverflow.com/comment/87217490
has comment: http://stackoverflow.com/comment/87236737
has comment: http://stackoverflow.com/comment/87217562
type: Question
has comment: http://stackoverflow.com/comment/87224012
score: 0
has comment: http://stackoverflow.com/comment/87222697
has comment: http://stackoverflow.com/comment/87218100
tagged with: python
has body: I am doing Python and Arduino serial communication. This is part of my code. while True: data = arduino.readline() str = data[:-2].decode() print(str) # to check the str if str: # if str gets 1 from arduino some logics here.............. but the problem is when python code is running that while clause, Arduino is still sending data to Python. I think if it keep send it to python, I don't think that code goes well. So the question is how to stop sending data when while clause is started? Thank you in advance. The whole codes are here just right here! python code import serial import time import MySQLdb from datetime import datetime import cv2 import boto3 now = datetime.today().strftime("%Y-%m-%d-%H-%M-%S") station="hansung-" type=".jpg" filename=station+now+type st=filename.split('-')[0] ye=filename.split('-')[1] mo=filename.split('-')[2] da=filename.split('-')[3] #the picture is just uploaded in to s3 bucket port ="COM15" #I am testing this on my windows laptop brate = 9600 arduino =serial.Serial(port, baudrate = brate, timeout=None) while True: #keep receive data from arduino data= arduino.readline() # delete \n\r from arduino str = data[:-2].decode() # if person exists str = 1 or str = 0 print(str) if str: #if picture is taken cap = cv2.VideoCapture(0) ret, frame = cap.read() cv2.imwrite(filename, frame) cap.release() print('picture is taken') #upload in to s3 s3 = boto3.resource('s3') bucketname = 'dongyeon2' bucket = s3.Bucket(bucketname) bucket.upload_file(filename, filename, ExtraArgs={'ACL': 'public- read'}) bucketurl = "https://s3-ap-northeast-1.amazonaws.com/dongyeon2/" + filename db = MySQLdb.connect(host='localhost', user='root',passwd='', db='pythonprogramming') cur = db.cursor() #insert into sql sql = "insert into image(station,year,month,day,img_url) values(%s,%s,%s,%s,%s)" cur.execute(sql, (st, ye, mo, da, bucketurl)) db.commit() db.close() else: print("no body") This is Arduino code int IR_sensor = A0; int value; void setup() { Serial.begin(9600); p…
has comment: http://stackoverflow.com/comment/87218445
answer count: 0
tagged with: pyserial

http://stackoverflow.com/q/50106387
has comment: http://stackoverflow.com/comment/87230168
tagged with: python
accepted answer: http://stackoverflow.com/a/50106542
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50106542
has title: Python: Printing grid of varying sizes
score: 0
tagged with: function
answer count: 1
tagged with: grid
has comment: http://stackoverflow.com/comment/87238382
has body: I am working on a function to get a grid to print out depending on user-input. So far I was able to get it to print a simple version where it changed sizes for example: print_grid(15) #prints a larger grid: + - - - - - - - + - - - - - - - + | | | | | | | | | | | | | | | | | | | | | + - - - - - - - + - - - - - - - + | | | | | | | | | | | | | | | | | | | | | + - - - - - - - + - - - - - - - + But now I am trying to do something so that it can accept two input variables (x, y) where x is the number of rows/columns (area) and y is the size of the individual, smaller grids within the larger whole. For example, print_grid2(3,4) results in: + - - - - + - - - - + - - - - + | | | | | | | | | | | | | | | | + - - - - + - - - - + - - - - + | | | | | | | | | | | | | | | | + - - - - + - - - - + - - - - + | | | | | | | | | | | | | | | | + - - - - + - - - - + - - - - + I reused some of my code from the first grid example and then changed it to try to accommodate this specific task, but I don't get any output this time and am not sure what is going on if I am getting nothing as output... Any help is appreciated. (I haven't updated my comments yet, so I realize that they are not making sense anymore since they relate to the previous iteration). Current Code: def grid_print(area, units): print_Area = (area * area) grid_rows = units + (units + 1) + 2 grid_cols = units + 2 if units % 2 == 0: # If grid entry is even (it will end up making grid_rows += 1 # the square uneven, so increase number of rows by 1 # now grid is technically uneven for i in range(print_Area): for row in range(grid_rows): # for each item in number of items(rows) for col in range(grid_cols): # for each item in number of items(columns) if row == 0 or row == int(grid_rows/2) or row == grid_rows -1: # if item is beginning, middle or end # -- Formatting beam structure -- # if col == 0: # beginning, print '+' no '\n' print('+', end='') elif col == grid_cols -1: # end, print '+' print('+') elif int(grid_cols/2) == col: # mi…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87230124

http://stackoverflow.com/q/50100235
has comment: http://stackoverflow.com/comment/87217599
has comment: http://stackoverflow.com/comment/87221253
tagged with: generator
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50100411
has comment: http://stackoverflow.com/comment/87219788
answer count: 2
has comment: http://stackoverflow.com/comment/87217331
score: 1
has body: I want to get "next asset" with an iterator-like object, but (instead of __next__() method) there are two algorithms loading next asset (next1 and next2 below), which can be implemented as a "quasi-iterator" like: class AssetLoader(object): def __init___(self): pass def next1(self): # ... def next2(self): # ... To be clear, what is the next retrieved object may depends on the "history" of calling next1 and next2, like: next1(); next1(); next2(); next1(); next2() My question: May this (two kinds of "next" step in an iterator) be implemented as a generator function? I guess this can be done with a global variable to which the function refers. But can it be done without using global variables, but with some local variable? If it is hard or impossible with current Python, can we discuss how to add new semantics to Python to make it possible?
has comment: http://stackoverflow.com/comment/87217192
has title: "Double" iterator and a generator function
has comment: http://stackoverflow.com/comment/87218227
has comment: http://stackoverflow.com/comment/87216987
has comment: http://stackoverflow.com/comment/87218316
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50102958
has comment: http://stackoverflow.com/comment/87218502
type: Question
has comment: http://stackoverflow.com/comment/87222827
tagged with: iterator
upvote count: 2
has answer: http://stackoverflow.com/a/50100411
has comment: http://stackoverflow.com/comment/87217621
has comment: http://stackoverflow.com/comment/87217662
accepted answer: http://stackoverflow.com/a/50102958
has comment: http://stackoverflow.com/comment/87218403
tagged with: python
has comment: http://stackoverflow.com/comment/87223968

http://stackoverflow.com/comment/87308192
type: QuestionComment
comment on: http://stackoverflow.com/q/50145032
score: 0
has text: Replace all pictures with text please.
type: Comment

http://stackoverflow.com/comment/87265664
comment on: http://stackoverflow.com/a/50123708
score: 0
has text: No problem! I'm sure I've been in the same place before. The quotes are easy to glide your eyes over.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50169850
has comment: http://stackoverflow.com/comment/87676501
has body: I'm trying to use the tesseract ocr tool to extract ocr text from video games(I'm pre processing screenshots and passing them to command line tool tsv output and parsing that). I'd like to use it for test automation not unlike selenium web testing. That is I'd like to be able to wait for elements to appear instead of sleeping and clicking on buttons(mostly menus). To be able to do that I need to be able to consistently find the same button text and find as much text as possible against a range of video games. For the sake of abstraction I'd prefer the pre processing/tesseract options to be the same for every game. I can probably add a dictionary of each word encountered in each game but I'd prefer not to. I've got a setup where I can test a number of different combinations of pre-processing/tesseract options and see the resulting words. I'm already tried blowing up the screenshot (which is 70-90 dpi) 5x times, and making it greyscale before passing it to tesarect. What other techniques can I use to improve the number and accuracy of my results? Which tesseract knobs should I be looking at? Is there any other useful pre-processing I can add? P.S. I'm finding that if I enlarge the picture to be twice as long/wide tesseract blows up seemingly because it runs out of memory for the image. Is there a static limit? Can I find it so I can blow up the image near max size? Can I adjust it?
tagged with: tesseract
score: 19
answer count: 4
downvote count: 4
has comment: http://stackoverflow.com/comment/87617647
tagged with: automated-tests
has answer: http://stackoverflow.com/a/55555258
tagged with: ui-automation
tagged with: ocr
has comment: http://stackoverflow.com/comment/87649415
favorite count: 0
has answer: http://stackoverflow.com/a/50344543
type: Question
has title: What's the best way to ocr as much text as possible from video game screenshots?
tagged with: python
has comment: http://stackoverflow.com/comment/87484208
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50318156
has answer: http://stackoverflow.com/a/50328393
has comment: http://stackoverflow.com/comment/87646804
upvote count: 23

http://stackoverflow.com/comment/87426718
score: 0
type: Comment
type: QuestionComment
has text: As an aside, `.startswith` is a little easier to use as you don't have to know the length of the string. E.g, `ok.startswith("adv.")`.
comment on: http://stackoverflow.com/q/50204783

http://stackoverflow.com/comment/87253319
comment on: http://stackoverflow.com/q/50117209
score: 0
type: Comment
type: QuestionComment
has text: @anishtain4 I need the coordinates for tow circles separated at a small distance. The second loop is for generating the second circle (at a small distance from first circle).

http://stackoverflow.com/q/50140853
type: Question
score: 2
has answer: http://stackoverflow.com/a/76449297
answer count: 2
upvote count: 2
has body: when I use PIL, I got a error. Read a img and convert to 'P' mode. Then I use img.putpalette(palette),len(palette) equals 768.And the range of pattle was 0~255. png = Image.fromarray(labelMap).convert('P') png.putpalette(cmap) png.save(pngPath, format='PNG') And I got a raise ValueError: invalid palette size, So I want know why and how to solve this problem. edit.. I found a problem, when length of palette smaller than 192, this code works well, and... I don't know why. Thanks much.
has comment: http://stackoverflow.com/comment/87398569
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87301347
downvote count: 0
tagged with: image-processing
favorite count: 0
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/53032408
has title: PIL putpalette error
tagged with: python
has comment: http://stackoverflow.com/comment/87311657
tagged with: image

http://stackoverflow.com/q/50091265
has comment: http://stackoverflow.com/comment/87199316
type: UnansweredQuestion
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/87199358
tagged with: flask
has comment: http://stackoverflow.com/comment/87199186
tagged with: node.js
score: 0
has comment: http://stackoverflow.com/comment/87199411
has body: I'm doing a Node.js exercise (from Nodeschool.io) which reads: # LEARN YOU THE NODE.JS FOR MUCH WIN! ## JUGGLING ASYNC (Exercise 9 of 13) This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get(). However, this time you will be provided with three URLs as the first three command-line arguments. You must collect the complete content provided to you by each of the URLs and print it to the console (stdout). You don't need to print out the length, just the data as a String; one line per URL. The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments. In order to test my implementation, I made a little Flask app like so: from flask import Flask import time app = Flask(__name__) @app.route("/1") def hello1(): time.sleep(1) return "Hello 1! " @app.route("/2") def hello2(): time.sleep(0.5) return "Hello 2!" @app.route("/3") def hello3(): return "Hello 3!" To get me started on the Nodeschool exercise, I wrote the following Javascript code (jugglingAsync.js): var http = require('http'); var bl = require('bl'); var handler = (response) =&gt; { response.pipe(bl(function (err, data) { if (err) { return console.error(err) } console.log(data.toString()) })) } http.get(process.argv[2], handler) http.get(process.argv[3], handler) http.get(process.argv[4], handler) However, If I run this script, I see the responses 1-3 printed in that order, instead of the reverse order: Kurts-MacBook-Pro:learnyounode kurtpeek$ node jugglingAsync.js http://localhost:5000/1 http://localhost:5000/2 http://localhost:5000/3 Hello 1! Hello 2! Hello 3! If these commands are run asynchronously, however, I would actually expect the results to be printed in reverse order. Can someone explain why this is not the case?
answer count: 1
linked to: http://stackoverflow.com/q/14672753
has comment: http://stackoverflow.com/comment/87199616
has answer: http://stackoverflow.com/a/50092378
duplicate of: http://stackoverflow.com/q/14672753
has title: Node.js script appears to be synchronous even though I would expect it to be asynchronous?
type: Question

http://stackoverflow.com/comment/87199316
comment on: http://stackoverflow.com/q/50091265
score: 0
has text: I started the Flask server using `FLASK_APP=hello.py flask run` and it would appear that unlike Django, the development server doesn't immediately adapt to changes you make in the source code; after stopping and re-running it I did experience the expected wait times. (I had added the `time.sleep` statements later). So it would appear that the issue is the Javascript code after all; I've updated my question to reflect this.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50215456
type: Answer
has comment: http://stackoverflow.com/comment/87466725
has body: Original answer below, here I address the added code you've uploaded. in your combine_nets functions you needlessly try to remove and set the attribute, when you can simply copy your required value like this: def combine_nets(net_train, net_no_train, net_place_holder): ''' Combine nets in a way train net is trainable ''' params_train = net_no_train.named_parameters() dict_params_place_holder = dict(net_place_holder.named_parameters()) dict_params_no_train = dict(net_train.named_parameters()) for name, param_train in params_train: if name in dict_params_place_holder: param_no_train = dict_params_no_train[name] W_new = param_train + param_no_train dict_params_no_train[name].data.copy_(W_new.data) return net_place_holder Due to other errors in the code you've supplied I couldn't make it run without further changes so I attach below an updated version of the code I've given you earlier: import torch from torch import nn from torch.autograd import Variable import torch.optim as optim # toy feed-forward net class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 5) self.fc3 = nn.Linear(5, 1) def forward(self, x): x = self.fc1(x) x = self.fc2(x) x = self.fc3(x) return x def combine_nets(net_train, net_no_train, net_place_holder): ''' Combine nets in a way train net is trainable ''' params_train = net_no_train.named_parameters() dict_params_place_holder = dict(net_place_holder.named_parameters()) dict_params_no_train = dict(net_train.named_parameters()) for name, param_train in params_train: if name in dict_params_place_holder: param_no_train = dict_params_no_train[name] W_new = param_train + param_no_train dict_params_no_train[name].data.copy_(W_new.data) return net_place_holder # define random data random_input1 = Variable(torch.randn(10,)) random_target1 = Variable(torch.randn(1,)) random_input2 = Variable(torch.rand(10,)) random_target2 = Variable(torch.rand(1,)) random_input3 = Variable(torch.randn(10,))…
score: 5
has comment: http://stackoverflow.com/comment/87475702
downvote count: 0
has comment: http://stackoverflow.com/comment/87463888
answers question: http://stackoverflow.com/q/50144597
has comment: http://stackoverflow.com/comment/87619781
has comment: http://stackoverflow.com/comment/87466561
upvote count: 5
has comment: http://stackoverflow.com/comment/87493680
has comment: http://stackoverflow.com/comment/87566057

http://stackoverflow.com/comment/87244698
type: Comment
type: QuestionComment
has text: @PM2Ring True, a safety level could be decide. However same issue as the one I describe in the comment above. Second, I didn't actually code the multithreading in the program. I'm just running several .py files of the same program with different inputs at the same time. i.e. no interaction between the threads, and I can't modify much on that part yet.
score: 0
comment on: http://stackoverflow.com/q/50113282

http://stackoverflow.com/comment/87340066
type: QuestionComment
has text: Possible duplicate of [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space)
score: 3
comment on: http://stackoverflow.com/q/50161012
type: Comment

http://stackoverflow.com/comment/126004807
comment on: http://stackoverflow.com/q/50173642
score: 0
type: Comment
has text: This problem may be solved after the PR for this issue is merged. https://github.com/matplotlib/matplotlib/issues/18883
type: QuestionComment

http://stackoverflow.com/comment/87236324
comment on: http://stackoverflow.com/q/50109396
score: 0
type: Comment
has text: Why do you need to import requests?
type: QuestionComment

http://stackoverflow.com/q/50117513
tagged with: hdf5
has body: Is there a way / plugin to view hdf5 files in pycharm so that you don't have to install HDFVIEW to manually check a file?
favorite count: 0
type: AnsweredQuestion
tagged with: h5py
has title: Can you view hdf5 files in pycharm?
tagged with: python
has answer: http://stackoverflow.com/a/51287058
accepted answer: http://stackoverflow.com/a/51287058
type: Question
upvote count: 5
score: 5
tagged with: pycharm
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50226923
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50163198
has body: In my case,I have updated visual studio 2015 to update3, and I found version is 14.0.25431 ,not v19.0.24210.0.So I changed \dlib\cmake_utils\set_compiler_specific_options.cmake file , and edited elseif(MSVC AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.24210.0 ) to elseif(MSVC AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14.0.24210.0 ) then everything is OK.
downvote count: 0

http://stackoverflow.com/comment/87367198
has text: I think solvepnp takes one set of points, so maybe something like objpointsL[0] and imgpointsL[0] will work.
comment on: http://stackoverflow.com/q/50137181
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/50162870
downvote count: 0
has body: Borrowing Wen's df pandas.Series.str.zfill df.time.str.zfill(4) 0 0001 1 0012 2 0123 3 1234 Name: time, dtype: object Python 3.6 f-string [f'{int(i):04d}' for i in df.time] ['0001', '0012', '0123', '1234']
score: 2
answers question: http://stackoverflow.com/q/50162326
type: Answer
upvote count: 2

http://stackoverflow.com/q/50174965
downvote count: 3
has comment: http://stackoverflow.com/comment/87366933
has comment: http://stackoverflow.com/comment/87366874
has comment: http://stackoverflow.com/comment/87367109
has body: I wrote a function which gets two numbers and an operation (string) and returns the result of the two numbers with the given operation. For example calculate_matehamatical_expression(5,6,'+') should return 11. I divide the the assignment to little functions, but when I call these little function it always returns None. Can someone explain to me why that happens? This is the Code I wrote: def mathematical_sum(num1,num2): return num1 + num2 def mathematical_difference(num1,num2): return num1 - num2 def mathematical_product(num1,num2): return num1 * num2 def mathematical_division(num1,num2): if num2 != 0: return num1 / num2 else: return None def operation_error(operation): if operation != "+" or operation != "-" or operation != "*" or operation != "/": return None def calculate_mathematical_expression(num1,num2,operation): if operation == "+": mathematical_sum(num1,num2) elif operation == "-": mathematical_difference(num1,num2) elif operation == "*": mathematical_product(num1,num2) elif operation == "/": mathematical_division(num1,num2) else: operation_error(operation)
favorite count: 0
has answer: http://stackoverflow.com/a/50175063
type: Question
tagged with: python-3.x
tagged with: return
has title: python - return returns None
possible better answer: http://stackoverflow.com/a/50175055
accepted answer: http://stackoverflow.com/a/50175004
score: -3
has answer: http://stackoverflow.com/a/50175004
has answer: http://stackoverflow.com/a/50175055
tagged with: python
type: AnsweredQuestion
answer count: 3
upvote count: 0

http://stackoverflow.com/comment/110629109
comment on: http://stackoverflow.com/a/62556094
type: Comment
type: AnswerComment
score: 5
has text: This would be a better answer if you explained how the code you provided answers the question.

http://stackoverflow.com/q/50087252
has answer: http://stackoverflow.com/a/50090809
upvote count: 18
favorite count: 0
type: Question
tagged with: numpy
tagged with: pytorch
has title: How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0?
answer count: 1
downvote count: 0
tagged with: python
score: 18
has body: Pytorch 0.4.0 introduced the merging on the Tensor and Variable classes. Before this version, when I wanted to create a Variable with autograd from a numpy array I would do the following (where x is a numpy array): x = Variable(torch.from_numpy(x).float(), requires_grad=True) With PyTorch version 0.4.0, the migration guide shows how we can create Tensors with autograd enabled, examples show you can do things such as x = torch.ones(3, 4, requires_grad=True) and also set requires_grad to existing tensors existing_tensor.requires_grad_() I have tried the following three things to try and create a Tensor with requires_grad=True which give errors (where x is a numpy array): The first is x = FloatTensor(x, requires_grad=True) which gives the error TypeError: new() received an invalid combination of arguments - got (numpy.ndarray, requires_grad=bool), but expected one of: * (torch.device device) * (tuple of ints size, torch.device device) didn't match because some of the keywords were incorrect: requires_grad * (torch.Storage storage) * (Tensor other) * (object data, torch.device device) didn't match because some of the keywords were incorrect: requires_grad The second is to do x = FloatTensor(x) x.requires_grad() And the third is x = torch.from_numpy(x).single() x.requires_grad() Which both throw the following error on the second line: TypeError: 'bool' object is not callable These errors give me little hint at what I'm doing wrong, and since the latest version is so new its hard to find content online to help. How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0, preferably in a single line?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50090809

http://stackoverflow.com/comment/87369967
has text: it's not a message. the client will send the position of the snake every time the snake moves
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50175387

http://stackoverflow.com/comment/87346958
type: Comment
has text: It seems like you already parsed the result, i.e. you have a `dict` instead of just a JSON string. Now all you have to do is access the values, e.g. `result['command']`.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50164461

http://stackoverflow.com/comment/135421287
score: 0
has text: Confirmed this works; `python` will be python2 and `python3` will be python3.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50225399

http://stackoverflow.com/comment/87412662
type: Comment
type: QuestionComment
has text: I'd recommend you visualise this with something like http://pythontutor.com/visualize.html#mode=edit if you can't figure out what it does. This isn't a good question for SO.
comment on: http://stackoverflow.com/q/50197930
score: 0

http://stackoverflow.com/comment/87170363
comment on: http://stackoverflow.com/a/50077027
has text: User said they always have 10 values per country and I guess that's why you hard coded the average calculation. By using ```statistics.mean()``` you simplify the code and remove the number of items limitation.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50088313
favorite count: 0
type: Question
tagged with: vtk
has comment: http://stackoverflow.com/comment/87211878
type: UnansweredQuestion
has body: I'm new in vtk, I'm trying to learn and for this I ask for help. I looked for a similar problem but I didn't find anything about it. In my project (python 2.7 and VTK 6.3) I visualize several actors (from STL files) that are loaded one at a time(self.renderer.AddActor (self.Actor)) I also insert them in arrays (self.pieces) and display them in a wx.ListBox (self.workplateList) for list, selection, file name ... So far so good I'm able to manage selections, changes, additions, actor operations but the problem is when I try to remove an actor: From button I would like to delete the actor selected in the ListBox from the scene with the function: def onRemoveModel(self, event): actor = self.pieces[self.workplateList.GetSelection()] self.renderer.RemoveActor[actor] but returns the error: Traceback (most recent call last): File ".\main.py", line 276, in onRemoveModel self.renderer.RemoveActor[actor] TypeError: 'builtin_function_or_method' object has no attribute 'getitem' Can you tell me where I'm wrong? Thanks.
tagged with: python
has title: Python VTK: remove an actor from a scene with multiple actors
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87210341
has comment: http://stackoverflow.com/comment/87198545

http://stackoverflow.com/q/50096286
type: Question
has answer: http://stackoverflow.com/a/50096568
has comment: http://stackoverflow.com/comment/87209277
linked to: http://stackoverflow.com/q/31528812
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87208844
has comment: http://stackoverflow.com/comment/87208983
score: 1
has body: so i want to make auto download when i got some link, let say the link is : http://test.com/somefile.avi import os import sys from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QWidgetAction from PyQt5.QtCore import QUrl, QEventLoop from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEngineDownloadItem, QWebEnginePage class WebPage(QWebEngineView): def __init__(self): QWebEngineView.__init__(self) self.load(QUrl("http://test.com")) self.loadFinished.connect(self._on_load_finished) self.n = 0 def _on_load_finished(self): print("Finished Loading") self.page().toHtml(self.Callable) def Callable(self, html_str): self.html = html_str self.load(QUrl(userInput)) if __name__ == "__main__": userInput = input() app = QApplication(sys.argv) web = WebPage() except i only have the page 'test.com', but i cant get the file 'somefile.avi', is it possible to make it autodownload after i input the 'http://test.com/somefile.avi' in console? Thanks
has comment: http://stackoverflow.com/comment/87208932
answer count: 1
downvote count: 0
tagged with: pyqt5
upvote count: 1
accepted answer: http://stackoverflow.com/a/50096568
has title: How can I download file using pyQt 5 webengine with python script code?
has comment: http://stackoverflow.com/comment/87208749
favorite count: 0

http://stackoverflow.com/comment/87300678
type: QuestionComment
has text: @CharlesDuffy Got your point. But what should I return in else condition as I want to end the program if it reaches there
type: Comment
comment on: http://stackoverflow.com/q/50141123
score: 0

http://stackoverflow.com/comment/87371300
type: QuestionComment
has text: Odd behavior. It seems to be intentional (see https://github.com/numpy/numpy/issues/6104), but I can't understand why.
type: Comment
comment on: http://stackoverflow.com/q/50175227
score: 0

http://stackoverflow.com/a/50217555
has body: You if you want to move back one folder/directory you use the .. in your file path. os.chdir('../other_scripts/') will work. You may fine it helpful to view this or the wiki. If you want to move from where you currently are you can use './new_dir/'. If you want to automate how to find other files you may want to read here which says to use os.walk. This may be the same question.
answers question: http://stackoverflow.com/q/50216508
downvote count: 0
upvote count: 1
type: Answer
score: 1

http://stackoverflow.com/q/50219672
has title: How to combine output in single line in a key-logger program?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87456424
tagged with: python
has body: from pynput.keyboard import Key, Listener import logging log_dir = "C:/Users/noswear/Desktop/Mail/" logging.basicConfig(filename = (log_dir + "key_log.txt"),level = logging.DEBUG, format = '%(asctime)s:%(message)s') def on_press(key): logging.info(str(key)) with Listener(on_press = on_press) as listener: listener.join() The above program gives output like this: 2018-05-07 20:54:56,020:'m' 2018-05-07 20:54:57,010:Key.backspace 2018-05-07 20:55:00,192:'p' 2018-05-07 20:55:00,366:'a' 2018-05-07 20:55:00,485:'s' 2018-05-07 20:55:00,695:'s' 2018-05-07 20:55:01,432:'w' 2018-05-07 20:55:01,653:'o' 2018-05-07 20:55:01,857:'r' 2018-05-07 20:55:02,056:'d' How can I club together by minutes, where all stroke in a minute is stored in a single line? Something like this 2018-05-07 20:54:mKey.backspace 2018-05-17 20:55:password
has answer: http://stackoverflow.com/a/50220504
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: pynput
tagged with: keystroke
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87457845
tagged with: keylogger

http://stackoverflow.com/comment/87255279
type: QuestionComment
has text: Sure, just need to sanitise some hostnames etc and I'll edit it into the question, thanks
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50118909

http://stackoverflow.com/comment/87189392
type: Comment
comment on: http://stackoverflow.com/q/50086769
score: 3
has text: Are your functions _really_ named `call_1`, `call_2`, etc? Why don't you put them into a list?
type: QuestionComment

http://stackoverflow.com/a/50221795
has body: You can also try following: for val in new.num: print('This is ', val) Result: This is 11 This is 14 This is 25 This is 39
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50221412
score: 2
upvote count: 2

http://stackoverflow.com/comment/87174553
score: 0
type: AnswerComment
has text: @Mr.Robot Do not access the GUI from another thread, in your case I think you should get the data just before starting the thread, and pass it through args, see my updated answer.
comment on: http://stackoverflow.com/a/50078592
type: Comment

http://stackoverflow.com/a/50209047
upvote count: 1
answers question: http://stackoverflow.com/q/50208867
type: Answer
has body: You would need to use the same color normalization for all scatter plots. This normalization would need to span over the complete range of possible color values. Otherwise the first scatter doesn't know about the second scatter's range etc. import matplotlib.pyplot as plt x = [1,2,3,4,5,6,7,8,9,10] y = [1,2,3,4,5,6,7,8,9,10] colors = [0,1,1,0,1,4,1,3,2,4] sizes = [500,500,300,300,300,500,500,300,300,300] map1 = plt.cm.get_cmap("jet", 5) norm = plt.Normalize(min(colors),max(colors)) kw = dict(cmap=map1, norm=norm) plt.scatter(x[0:3], y[0:3], c=colors[0:3] ,s=sizes[0:3],marker="*",**kw) plt.scatter(x[3:6], y[3:6], c=colors[3:6] ,s=sizes[3:6],marker="&lt;",**kw) plt.scatter(x[6:10], y[6:10], c=colors[6:10], s=sizes[6:10],marker="D",**kw) plt.colorbar(ticks=range(5)) plt.clim(-0.5, 4.5) plt.show()
has comment: http://stackoverflow.com/comment/87435801
accepted answer of: http://stackoverflow.com/q/50208867
score: 1
type: AcceptedAnswer
downvote count: 0

tk-toolkit
tags question: http://stackoverflow.com/q/50135108
tags question: http://stackoverflow.com/q/50164738
tag name: tk-toolkit
tags question: http://stackoverflow.com/q/50203538
type: Tag

http://stackoverflow.com/a/50118147
has comment: http://stackoverflow.com/comment/87254923
has body: I think you should replace: Sound.objects.get(pk=self.fields['master_sound']) with: Sound.objects.get(pk=cleaned_data['master_sound']) When the Form is valid, cleaned_data will include a key and value for all its fields and you can see that in your question as well (The local vars paragraph). In general speaking you should do validation in the individual clean_&lt;fieldname&gt; methods. So: def clean_master_sound(self): master_sound_key = self.cleaned_data.get('master_sound') try: master_sound=Sound.objects.get(pk=master_sound_key) except Sound.DoesNotExist: raise forms.ValidationError("Sound with id: %s does not exist", master_sound_key) return master_sound
has comment: http://stackoverflow.com/comment/87289038
type: Answer
accepted answer of: http://stackoverflow.com/q/50118015
has comment: http://stackoverflow.com/comment/87255386
has comment: http://stackoverflow.com/comment/87288843
has comment: http://stackoverflow.com/comment/87254522
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87255220
score: 3
answers question: http://stackoverflow.com/q/50118015

http://stackoverflow.com/comment/135877697
comment on: http://stackoverflow.com/a/63662786
type: Comment
has text: doesnt work. use keys.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50143448
has comment: http://stackoverflow.com/comment/87305218
type: Answer
has comment: http://stackoverflow.com/comment/87305151
answers question: http://stackoverflow.com/q/50143138
score: 0
has body: I like the @P.Camilleri answer. This one just for the sake of diversity... &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x,y = np.random.random(5), np.random.random(3) &gt;&gt;&gt; x array([0.5538738 , 0.31099761, 0.42709952, 0.28999541, 0.76811293]) &gt;&gt;&gt; y array([0.80281963, 0.31063054, 0.20141215]) &gt;&gt;&gt; np.array([x])*np.array([y]).T array([[0.44466076, 0.24967499, 0.34288388, 0.23281401, 0.61665614], [0.17205012, 0.09660536, 0.13267015, 0.09008143, 0.23859933], [0.11155691, 0.0626387 , 0.08602303, 0.0584086 , 0.15470727]])
has comment: http://stackoverflow.com/comment/87305125

http://stackoverflow.com/a/50205864
has comment: http://stackoverflow.com/comment/87429127
answers question: http://stackoverflow.com/q/50205822
score: 0
has body: This is one way using pd.DataFrame.apply / str.join followed by pd.Series.replace to account for instances where no names exist: import pandas as pd df = pd.DataFrame({'Artist_1': ['A', 'B', '?', 'D', '?', 'E'], 'Artist_2': ['?', '?', '?', 'G', '?', 'I'], 'Artist_3': ['J', '?', '?', '?', 'M', 'N']}) df['Artist_All'] = df.apply(lambda x: ', '.join([i for i in x if i != '?']), axis=1)\ .replace('', '?') print(df) Artist_1 Artist_2 Artist_3 Artist_All 0 A ? J A, J 1 B ? ? B 2 ? ? ? ? 3 D G ? D, G 4 ? ? M M 5 E I N E, I, N Alternatively, you can use a list comprehension: df['Artist_All'] = [', '.join([i for i in x if i != '?']) for x in df.values] df['Artist_All'] = df['Artist_All'].replace('', '?')
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50205822
type: Answer
has comment: http://stackoverflow.com/comment/87429146

http://stackoverflow.com/q/50101760
has comment: http://stackoverflow.com/comment/114835556
has answer: http://stackoverflow.com/a/50102740
has comment: http://stackoverflow.com/comment/87220810
has comment: http://stackoverflow.com/comment/87221325
favorite count: 0
type: Question
has body: The text file (itemsList) that i work on it have this format: id "item 1" str "item 1 description" id "item 2" str "item 2 description" and tried to read this file in Python like this: import re itemList= open('itemsList.txt', encoding="utf8") items='' pattern = re.compile('(id\s)(\"(.*)\")|(str\s)(\"(.*)\")',re.IGNORECASE) for item in itemList: Result = re.search(pattern,item) if Result: items+= Result.group(3) else: items+= "\n" I got this error: TypeError: must be str, not NoneType Editing Result.group(3) to str(Result.group(3)) giving this None with the group: item 1None item 2None the expected result should be like: item 1, item 1 description item 2, item 2 description
has comment: http://stackoverflow.com/comment/87220724
has title: Return None using re group () in python
downvote count: 2
answer count: 1
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87220245
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50102740
score: 1
upvote count: 3

http://stackoverflow.com/a/50144383
has comment: http://stackoverflow.com/comment/87309952
has body: Here is the canonical way of doing it: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; src = np.random.rand(4, 3) &gt;&gt;&gt; src array([[0.0309325 , 0.72261479, 0.98373595], [0.06357406, 0.44763809, 0.45116039], [0.63992938, 0.6445605 , 0.01267776], [0.76084312, 0.61888759, 0.2138713 ]]) &gt;&gt;&gt; &gt;&gt;&gt; idx = np.indices(src.shape).reshape(2, -1) &gt;&gt;&gt; np.random.shuffle(idx.T) &gt;&gt;&gt; idx array([[3, 3, 0, 1, 0, 3, 1, 1, 2, 2, 2, 0], [1, 2, 2, 0, 1, 0, 1, 2, 2, 1, 0, 0]]) &gt;&gt;&gt; &gt;&gt;&gt; dst = np.empty_like(src) &gt;&gt;&gt; dst[tuple(idx)] = src.ravel() &gt;&gt;&gt; dst array([[0.2138713 , 0.44763809, 0.98373595], [0.06357406, 0.63992938, 0.6445605 ], [0.61888759, 0.76084312, 0.01267776], [0.45116039, 0.0309325 , 0.72261479]]) If you can't be sure that idx is a proper shuffle it's a bit safer to use np.full with a fill value that does not appear in src instead of np.empty. &gt;&gt;&gt; dst = np.full_like(src, np.nan) &gt;&gt;&gt; dst[tuple(idx)] = src.ravel() &gt;&gt;&gt; &gt;&gt;&gt; dst array([[0.27020869, 0.71216066, nan], [0.63812283, 0.69151451, 0.65843901], [ nan, 0.02406174, 0.47543061], [0.05650845, nan, nan]]) If you spot the fill value in dst, something is wrong with idx.
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/87310401
type: Answer
answers question: http://stackoverflow.com/q/50144283
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50144283
type: AcceptedAnswer

http://stackoverflow.com/a/50081390
type: Answer
downvote count: 0
score: 7
upvote count: 7
has body: I managed to fix it: You get this error message if your keys don't match.
answers question: http://stackoverflow.com/q/50081261

http://stackoverflow.com/comment/87285611
type: AnswerComment
score: 3
type: Comment
has text: You beat me to it! This is what I came up with! Just for future visitors, you can use 'H' for hour, 'T' for minute and 'M' for month time bins.
comment on: http://stackoverflow.com/a/50133646

http://stackoverflow.com/comment/87345830
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50163903
has text: This will also work with the OP's input, if it is slightly modified: `product(*[[a], [a, b], [c, d, e]])`

http://stackoverflow.com/comment/87429168
type: QuestionComment
comment on: http://stackoverflow.com/q/50205997
score: 0
has text: Would enumerate work for you? Like: '''for c in enumerate(stock)'''
type: Comment

http://stackoverflow.com/a/50210709
answers question: http://stackoverflow.com/q/50210555
downvote count: 0
type: AcceptedAnswer
has body: what about df1[df1.frame.isin(df2.frame)] Out: frame 1 2 2 3 df2[df2.frame.isin(df1.frame)] Out: frame 0 2 1 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50210555
score: 2
upvote count: 2

http://stackoverflow.com/a/50142167
upvote count: 1
answers question: http://stackoverflow.com/q/50138891
accepted answer of: http://stackoverflow.com/q/50138891
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87303917
type: AcceptedAnswer
downvote count: 0
has body: As you know, LSTM input should be have ndim=3, which in your case becomes (None, None, 100). I'm not sure about your input. But your noise and model_input is 2D with shape (None, 100) based on the code. This didn't match the requirement and thus triggered the error. Maybe you want to reshape your input as noise = Input(shape=(None, latent_dim))?

http://stackoverflow.com/comment/87391462
has text: @deceze "The queries can't do the same?" Not that I'm aware of.
score: 0
comment on: http://stackoverflow.com/q/50187126
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50194637
type: AnsweredQuestion
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87406483
linked to: http://stackoverflow.com/q/48879495
has comment: http://stackoverflow.com/comment/100443490
linked to: http://stackoverflow.com/q/41553806
upvote count: 30
favorite count: 0
score: 30
type: Question
has answer: http://stackoverflow.com/a/50842328
has comment: http://stackoverflow.com/comment/87406433
accepted answer: http://stackoverflow.com/a/50842328
has title: Colaboratory: How to install and use on local machine?
has answer: http://stackoverflow.com/a/50194820
tagged with: productivity-power-tools
has body: Google Colab is awesome to work with, but I wish I can run Colab Notebooks completely locally and offline, just like Jupyter notebooks served from the local? How do I do this? Is there a Colab package which I can install? EDIT: Some previous answers to the question seem to give methods to access Colab hosted by Google. But that's not what I'm looking for. My question is how do I pip install colab so I can run it locally like jupyter after pip install jupyter. Colab package doesn't seem to exist, so if I want it, what do I do to install it from the source?
tagged with: pip
tagged with: python
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/50563569
possible better answer: http://stackoverflow.com/a/50563569

http://stackoverflow.com/comment/87386394
type: QuestionComment
comment on: http://stackoverflow.com/q/50184575
has text: Please post the entire exception, not a loose description of it.
score: 1
type: Comment

http://stackoverflow.com/a/50152700
upvote count: 3
downvote count: 0
has body: Use select_related In your view, get the Child objects like this: children = Child.objects.select_related('parent').all()
answers question: http://stackoverflow.com/q/50152598
type: Answer
score: 3

http://stackoverflow.com/q/50103637
has answer: http://stackoverflow.com/a/50103949
answer count: 1
downvote count: 1
has body: On my Windows 10 machine open() throws FileNotFoundError for a file that does exist. The same file on a Windows 7 machine is found. What's going on?
type: AnsweredQuestion
score: 0
tagged with: windows-10
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: file-not-found
accepted answer: http://stackoverflow.com/a/50103949
has title: Python - FileNotFoundError for existing file
upvote count: 1
tagged with: python

http://stackoverflow.com/q/50153230
tagged with: python
tagged with: data-structures
has title: Python list vs. array: reason for the unexpected performance difference
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87324012
accepted answer: http://stackoverflow.com/a/50153480
tagged with: instructions
upvote count: 1
has answer: http://stackoverflow.com/a/50153480
favorite count: 0
type: Question
has body: I'm studying algorithms and data structures at the moment. I thought I would run a quick timeit.timeit test for iterating through a list of 2**30 random integers in a list() comparing to the same for the array.array format. I was expecting the array to finish first as one of the few muted benefits I have seen on other posts with a Python array is performance (I was initially wrongly under the impression that the list was implemented as a linked list: thank you for the correction Duncan) Surely an array should be at least as quick as a list? import os import array l = list(os.urandom(2**30)) a = array.array('I', l) def test_list(): for i in l: pass def test_array(): for i in a: pass &gt;&gt;&gt; timeit.timeit(test_array, number=5) 50.08525877200009 &gt;&gt;&gt; timeit.timeit(test_list, number=5) 37.00491460799958 Here's my platform information: Python 3.6.5, [GCC 7.3.0] on linux x86_64 (Intel i5 4660)
tagged with: python-3.x

http://stackoverflow.com/a/50186218
has body: Running shell script from jenkins required proper execution permissions. In your python script before executing your script.sh run following command: sh "chmod 755 script.sh"
answers question: http://stackoverflow.com/q/50186133
type: Answer
has comment: http://stackoverflow.com/comment/87399930
has comment: http://stackoverflow.com/comment/87399040
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87399113

http://stackoverflow.com/comment/87306693
type: AnswerComment
has text: thanks, i had indeed this first output when i tried and i was confused. thank you for the "post treatment"
comment on: http://stackoverflow.com/a/50144198
type: Comment
score: 0

http://stackoverflow.com/a/50099167
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50091573
has body: The error comes from applying Keras backend functions on regular integers instead of Tensor objects. i = K.int_shape(y_true)[0] This line produces an int, and can therefore not be used in a K.update_sub call. You can, however, just use normal python integer calculations on it.

http://stackoverflow.com/q/50214180
has title: Response opencv (numpy) images with flask
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51724213
type: Question
tagged with: video-streaming
tagged with: opencv
type: UnansweredQuestion
tagged with: python
tagged with: flask
tagged with: image
has body: Since I heard about problems, caused by writing to SD-Cards many times, I want to serve my Images on a flask app (running on raspberry pi) directly using a file like object. In my application I process Images every few seconds and need to display them on a web interface using flask. I'm actually trying something like this: @app.route('/image') def image(): img = cv2.imread('raw.png') img_str = cv.imencode('.png', img)[1].tostring() f = io.BytesIO() f.write(img_str) f.seek(0) #return Response(bytes, mimetype='image/jpeg') return send_file(f, mimetype='image/png') My goal is to call this function from the web interface using ajax a few times per second, to update the image. Maybe also longterm polls can be used instead of fixed frequency. For now I want to serve the image without writing it to the sdcard. The code example returns in an "Image can not be displayed since it contains errors.." I'm new to flask, and also to opencv so any advice would help. Also let me know if there is an easy or better way to serve frequently updating images using builtin stream objects, socketio or whatever. Thanks

http://stackoverflow.com/comment/87287448
type: QuestionComment
score: 0
has text: dataset.head() Out[116]: carry_dt carry_rate sedol 0 1/2/2018 0.15 BP41ZD1 2 1/2/2018 0.15 2371823 3 1/2/2018 0.15 2369389 4 1/2/2018 0.15 2502139
comment on: http://stackoverflow.com/q/50134181
type: Comment

http://stackoverflow.com/comment/87292849
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50137283
has text: Can you tell us what you have tried in Python so far?

http://stackoverflow.com/q/50210397
has comment: http://stackoverflow.com/comment/87437850
has answer: http://stackoverflow.com/a/50210734
tagged with: ryu
has body: How can I get the /8 subnet containing a given ip address. e.g., subnet 10.0.0.0/8 for ip 10.1.1.1 I tried it so for wit netaddr lib, but it doesn't do what it should network = netaddr.IPNetwork(ip) network.prefixlen=8 ip_subnet=network.cidr ip is the given ip adress
score: 0
tagged with: sdn
has title: Python how get /8 subnet for an IP addres
type: Question
tagged with: inetaddress
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50210541
tagged with: python

http://stackoverflow.com/a/50213604
has body: run pip install ModuleName on your CMD pip install JayDeBeApi Resultat : Collecting JayDeBeApi Using cached https://files.pythonhosted.org/packages/87/e2/a84253efa32c104256d 44731513b8d8b7e47a890b6e44fb42c54688a5dc2/JayDeBeApi-1.1.1-py2-none-any.whl Collecting JPype1 (from JayDeBeApi) Using cached https://files.pythonhosted.org/packages/c4/4b/60a3e63d51714d4d7ef 1b1efdf84315d118a0a80a5b085bb52a7e2428cdc/JPype1-0.6.3.tar.gz Installing collected packages: JPype1, JayDeBeApi Running setup.py install for JPype1 ... done Successfully installed JPype1-0.6.3 JayDeBeApi-1.1.1 Done: &gt;&gt;&gt; import jaydebeapi &gt;&gt;&gt;
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50207793
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50207793
type: Answer
score: 2

http://stackoverflow.com/comment/121421386
type: AnswerComment
has text: This answer is addressed as a comment in response to @oya163 under the accepted answer.
type: Comment
comment on: http://stackoverflow.com/a/68591023
score: 0

http://stackoverflow.com/q/50209741
has body: I am new to Tensorflow and I hope I get some help here, I'm trying to make a neural network which gets four inputs and one output, it looks like a simple task in Tensorflow but I'm still get this error: InvalidArgumentError: assertion failed: [Label IDs must >= 0] [Condition x >= 0 did not hold element-wise:] [x (dnn/head/ToFloat:0) = ] [[0][0][0]...] [[Node: dnn/head/assert_range/assert_non_negative/assert_less_equal/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_STRING, DT_FLOAT], summarize=3, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dnn/head/assert_range/assert_non_negative/assert_less_equal/Assert/AssertGuard/Assert/Switch, dnn/head/assert_range/assert_non_negative/assert_less_equal/Assert/AssertGuard/Assert/data_0, dnn/head/assert_range/assert_non_negative/assert_less_equal/Assert/AssertGuard/Assert/data_1, dnn/head/assert_range/assert_non_negative/assert_less_equal/Assert/AssertGuard/Assert/data_2, dnn/head/assert_range/assert_non_negative/assert_less_equal/Assert/AssertGuard/Assert/Switch_1)]] This is my code, thanks in advance. F1 = tf.feature_column.numeric_column('F1') F2 = tf.feature_column.numeric_column('F2') F3 =tf.feature_column.numeric_column('F3') F4 = tf.feature_column.numeric_column('F4') F5 =tf.feature_column.numeric_column('F5') F6 = tf.feature_column.numeric_column('F6') F7 = tf.feature_column.numeric_column('F7') F8 = tf.feature_column.numeric_column('F8') F9 = tf.feature_column.numeric_column('F9') F10 = tf.feature_column.numeric_column('F10') F11 = tf.feature_column.numeric_column('F11') F12 = tf.feature_column.numeric_column('F12') F13 = tf.feature_column.numeric_column('F13') deep_columns = [F2, F6, F11,F5] COLUMNS = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"] df_train = pd.read_csv("C:/data_4.csv", names=COLUMNS, sep = "\t",skiprows=1,skipinitialspace=True) df_train = df_train.fillna(0) Xtrain = df_train.drop("F7", axis=1) y_train = pd.DataFrame(df_train.F7) ytrain['F7'] = df_…
tagged with: network-programming
type: UnansweredQuestion
downvote count: 0
tagged with: input
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87436471
has title: Error with labels in the training step: InvalidArgumentError: assertion failed: [Label IDs must >= 0]
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50162326
tagged with: pandas
score: 1
possible better answer: http://stackoverflow.com/a/50162398
favorite count: 0
accepted answer: http://stackoverflow.com/a/50162485
type: Question
has answer: http://stackoverflow.com/a/50162398
has comment: http://stackoverflow.com/comment/87342659
has answer: http://stackoverflow.com/a/50162870
downvote count: 0
has body: I have some time data that I need to convert to a proper datetime with data['dep_time'] = pd.to_datetime(data['dep_time'], format='%H:%M').dt.time The problem is in each cell I have an inconsistent number of digits I might have '1714' or '714' or just '6'. I want to use format to change each str to the format 00:00, but I have to start from the back of the str and assume that if I just have '6' it means '00:06' year month day dep_time dep_delay arr_time arr_delay cancelled \ 103992 2014 5 11 1013 -2 1247 -13 0 103993 2014 5 11 1929 -1 2215 -24 0 103994 2014 5 11 1117 5 1355 9 0 103995 2014 5 11 736 -10 924 -18 0 103996 2014 5 11 1340 0 1647 10 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87342598
has answer: http://stackoverflow.com/a/50162641
answer count: 4
has title: Format time str with slicing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87342585
has comment: http://stackoverflow.com/comment/87342559
has answer: http://stackoverflow.com/a/50162485

http://stackoverflow.com/q/50149552
type: UnansweredQuestion
has body: import random import re import pandas as pd df1 = pd.DataFrame({"Greetings": ["Greetings to you too", "hi", "hello", "hey", "greetings", "sup", "what's up", "yo"]}) df2 = pd.DataFrame({"Farewell": ["GoodBye", "see you", "bye", "laters"]}) frames = [df1, df2] df3=pd.concat(frames, axis=1, join='outer', copy=True) def check_for_greet(): while True: try: sentence = input("Start chatting: ") wordList = re.sub("[^\w]", " ", sentence).split() if sentence == "$$$": return "END" for word in wordList: for col in df3.columns: if word.lower() in df3[col].values: print (df3[col][0]) break The above works perfectly now between columns (thank you @R.yan), only issue however is when I type "hi hi', it prints it twice: Start chatting: hi hi Greetings to you too Greetings to you too Why is it doing that, I am breaking the for loop with continue to return to the while loop?!
tagged with: dataframe
tagged with: python
tagged with: slice
has title: Python DataFrame loop and slice issue
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50150008
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: loops
favorite count: 0
type: Question

http://stackoverflow.com/comment/87422744
has text: @hpaulj Sure yeh I guess being written in `C` thats about as fast as it can go. Thanks
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50198393

http://stackoverflow.com/comment/87174436
score: 2
has text: That is a confusing error, but `multiprocessing` in Windows should be shielded within `if __name__ == '__main__'` anyway
comment on: http://stackoverflow.com/q/50079165
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87693826
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50256576
has text: @YoonSangpill Your final model is a combination of all trees so there is not really an efficient way to visualize them all. If your model was created with 1000 trees, you would need to look at all 1000 trees seperatly to see the 'final' model. If you're looking for like feature importance or just more insight on what's going on, I recommend using [SHAP](https://github.com/slundberg/shap). Take a look at the force plots and dependence plots to see how features effect the model.
score: 1

http://stackoverflow.com/a/50228748
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50227974
type: Answer
downvote count: 0
has body: Turn off use_scientific: fig = figure() x = np.linspace(0, 100) fig.line(x, x**4) yaxis = fig.yaxis[0] yaxis.formatter.use_scientific = False show(fig)

http://stackoverflow.com/a/50101462
has comment: http://stackoverflow.com/comment/87220518
has comment: http://stackoverflow.com/comment/87220474
type: Answer
has body: df['date'] = pd.to_datetime(df['date']) #Create 3 additional columns df['day'] = df['date'].dt.day df['month'] = df['date'].dt.month df['year'] = df['date'].dt.year Ideally, you can do this without having to create 3 additional columns, you can just pass the Series to your function. In [2]: pd.to_datetime('01/31/2010').day Out[2]: 31 In [3]: pd.to_datetime('01/31/2010').month Out[3]: 1 In [4]: pd.to_datetime('01/31/2010').year Out[4]: 2010
has comment: http://stackoverflow.com/comment/87220196
has comment: http://stackoverflow.com/comment/87219692
has comment: http://stackoverflow.com/comment/87220582
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50101384
score: 3

http://stackoverflow.com/q/50103615
score: -1
has comment: http://stackoverflow.com/comment/87228276
has comment: http://stackoverflow.com/comment/87225187
has comment: http://stackoverflow.com/comment/87225320
has comment: http://stackoverflow.com/comment/87225559
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/50122209
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/87262113
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87224856
has title: Python - How to set conditions for key bindings
has answer: http://stackoverflow.com/a/50122209
tagged with: tkinter
linked to: http://stackoverflow.com/q/47996285
has body: recently I've found this piece of code here (How to draw a line following your mouse coordinates with tkinter?): import tkinter as tk def draw(event): x, y = event.x, event.y if canvas.old_coords: x1, y1 = canvas.old_coords canvas.create_line(x, y, x1, y1) canvas.old_coords = x, y def draw_line(event): if str(event.type) == 'ButtonPress': canvas.old_coords = event.x, event.y elif str(event.type) == 'ButtonRelease': x, y = event.x, event.y x1, y1 = canvas.old_coords canvas.create_line(x, y, x1, y1) def reset_coords(event): canvas.old_coords = None root = tk.Tk() canvas = tk.Canvas(root, width=400, height=400) canvas.pack() canvas.old_coords = None root.bind('&lt;ButtonPress-1&gt;', draw_line) root.bind('&lt;ButtonRelease-1&gt;', draw_line) #root.bind('&lt;B1-Motion&gt;', draw) #root.bind('&lt;ButtonRelease-1&gt;', reset_coords) root.mainloop() and I'm really curious how to make those functions working accordingly to e.g. selected option. Let's say, I'd want select when draw free-hand and when draw lines. I've tried using one integer for comparison and then define conditions for binds, like this: if c==1: root.bind('&lt;ButtonPress-1&gt;', draw_line) root.bind('&lt;ButtonRelease-1&gt;', draw_line) elif c==2: root.bind('&lt;B1-Motion&gt;', draw) root.bind('&lt;ButtonRelease-1&gt;', reset_coords) but it doesn't seem to work. Have You got any ideas how to make conditions for binding?
tagged with: python

http://stackoverflow.com/comment/87362652
comment on: http://stackoverflow.com/a/50172043
has text: Note that `dieX - dieY` will only work on numerics, not on strings.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50181242
has answer: http://stackoverflow.com/a/50181318
answer count: 1
tagged with: python
downvote count: 1
tagged with: primes
has body: at the moment I try to implement a generate_random_prime()-function from the algorithm shown in FIPS186-4 from NIST (Appendix B3.2.1), see here. But there seems a big problem with step 4.4 (if p &lt; sqrt(2)*(2**((nlen/2)-1)), because of the precision in Python. to show the relevant part and problem of my code, see this example: import os from decimal import Decimal import math for i in range(100): nlen = 2048 #my key-size should be 2048bit p = int.from_bytes(os.urandom(int(2048/2/8)), byteorder = "little") #see Ann1 and Ann2 print(p &lt; Decimal(math.sqrt(2))*(Decimal(2**(int(2048/2))) - 1) Ann1: 2048/2/8 because of bytes Ann2: I know that os.urandom is not the best generator - I will later use an approved one... for the testing phase it should be acceptable I think... The result is always "True" - so the algorithm will never leave step 4.4. I think the problem is Decimal(math.sqrt(2))*(Decimal(2**(int(2048/2))) - 1), because the result of this is Decimal('2.542322012307292741109308792E+308'). Convert to int via int(Decimal(math.sqrt(2))*(Decimal(2**(int(2048/2))) - 1)), the result will be 254232201230729274110930879200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 It is rounded up! - Is this the reason for the always True result? I think in this case it will never be possible to get a p less than Decimal(math.sqrt(2))*(Decimal(2**(int(2048/2))) - 1) How can I solve this problem? __ edit: found a mistake: Decimal(math.sqrt(2))*(Decimal(2**(int(2048/2))) - 1) should be Decimal(math.sqrt(2))*(Decimal(2**(int(2048/2-1)))), so the result of this should be Decimal('1.271161006153646370554654396E+308') instead of Decimal('2.542322012307292741109308791E+308')
favorite count: 0
tagged with: int
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87380353
has comment: http://stackoverflow.com/comment/87386016
tagged with: math
has comment: http://stackoverflow.com/comment/87379775
score: -1
type: Question
tagged with: decimal
accepted answer: http://stackoverflow.com/a/50181318
upvote count: 0
has title: Python: Solution for high int-precision needed (generate primes)

http://stackoverflow.com/q/50148321
has title: How to use ODBC to link SQL database and do SQL queries in Python
tagged with: sql
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/49247884
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87316235
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50155975
has body: I usually use R to do SQL queries by using ODBC to link to a SQL database. The code generally looks like this: library(RODBC) ch&lt;-odbcConnect('B1P HANA',uid='****',pwd='****') myOffice &lt;- c(0) office_clause = "" if (myOffice != 0) { office_clause = paste( 'AND "_all"."/BIC/ZSALE_OFF" IN (',paste(myOffice, collapse=", "),')' ) } a &lt;- sqlQuery(ch,paste(' SELECT "_all"."CALDAY" AS "ReturnDate FROM "SAPB1P"."/BIC/AZ_RT_A212" "_all" WHERE "_all"."CALDAY"=20180101 ',office_clause,' GROUP BY "_all"."CALDAY ')) The workflow is: odbcConnect is to link R and SQL using ODBC. myOffice is an array for achieving data from R. Those data will be used as filter conditions in WHERE clause in SQL. a stores the query result from SQL database. So, how to do all of these in Python, i.e., do SQL queries in Python by using ODBC to link SQL database and Python? I am new to Python. All I know is like: import pyodbc conn = pyodbc.connect(r'DSN=B1P HANA;UID=****;PWD=****') Then I do not know how to continue. And I cannot find an overall example online. Could anyone help by providing a comprehensive example? From link SQL database in Python unitl retrieving the result?
accepted answer: http://stackoverflow.com/a/50155975
tagged with: python
tagged with: odbc
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion

http://stackoverflow.com/comment/87188343
comment on: http://stackoverflow.com/q/50086338
type: Comment
type: QuestionComment
score: 0
has text: I have no clue what the sequencematcher does. What is your "cleanup-criteria" ? Some kind of unique tweet-id? Or do you compare tweet-texts and if they match more then 73% you discard them? How does your csv file look - post a few line into your question (edit it, format it as code)? If you do semantik analysis over the tweeds texts, it will take time, its a difficult topic with lots of calculations/ datastore behind it....

http://stackoverflow.com/comment/87271589
has text: I recently read more on setuptools, I'm going to try to use a combination of setuptools.commands.install and the setup_requires package options to resolve my issue.
comment on: http://stackoverflow.com/q/50082055
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50075770
has body: As the problems stated above, I need to use a nonlibrary sorting function, specifically a mergesort function I implemented in a previous assignment. I have my assignment working really well using activity_arr.sort(key=operator.itemgetter(2)). However, the requirements are asking that I use this function: def merge_sort(array): ''' Sorts an array using merge sort algorithm.''' if len(array) &gt; 1: # '//' is for "floor division", used in case array is filled with floats mid = len(array) // 2 left = array[:mid] right = array[mid:] # Recursion to sort left and right half of array merge_sort(left) merge_sort(right) i = 0 j = 0 k = 0 while i &lt; len(left) and j &lt; len(right): if left[i] &lt; right[j]: array[k] = left[i] i += 1 else: array[k] = right[j] j += 1 k += 1 # Fill the rest of the array with remaining numbers in each array while i &lt; len(left): array[k] = left[i] i += 1 k += 1 while j &lt; len(right): array[k] = right[j] j += 1 k += 1 I assume, I will have to modify it so that I can sort my list of tuples. An example of my list to sort is example_list = [(1, 3, 4), (7, 2, 5), (1, 2, 1)]. I want to sort in ascending order by the third element of the tuple. SO it should result in the following: sorted_list = [(1, 2, 1), (1, 3, 4), (7, 2, 5)]. I am still just learning python and still have much to learn in CS in general. I have no idea how to make this change despite lots of research I mostly find people saying to use .sort(). If I left out anything important please let me know! Any help or information for me to look up will be very much appreciated. Thank you!
has answer: http://stackoverflow.com/a/50075829
type: AnsweredQuestion
score: 0
has title: Sort a list of tuples, using nonlibrary sorting function (Python)
answer count: 1
accepted answer: http://stackoverflow.com/a/50075829
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python
tagged with: sorting

http://stackoverflow.com/comment/87353953
has text: That did the trick! Thank you very much for your help.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50163249

http://stackoverflow.com/comment/87168603
has text: There is a syntax error in your code.
comment on: http://stackoverflow.com/q/50076241
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50194610
has comment: http://stackoverflow.com/comment/87406306
has comment: http://stackoverflow.com/comment/87406312
answers question: http://stackoverflow.com/q/50194576
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50194576
has body: Assignment is a statement, not an expression. It has no value. So you can't return the value of an assignment. Across languages that do allow this kind of thing, it's ambiguous what exactly the return value should be, but most of them—including C and the many languages derived from or inspired by C—would give you the new value of lista[2]1. So presumably you want this: def replace_spy(lista): lista[2]=lista[2]+1 return lista[2] If you're looking to shorten things, this is fewer keystrokes, and probably more readable: def replace_spy(lista): lista[2] += 1 return lista[2] 1. As an "lvalue", but that isn't a meaningful thing in Python.
score: 5
type: AcceptedAnswer
downvote count: 0

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

http://stackoverflow.com/comment/87193413
comment on: http://stackoverflow.com/q/50088734
type: Comment
type: QuestionComment
has text: Faster than what?
score: 2

http://stackoverflow.com/q/50115190
tagged with: python
has comment: http://stackoverflow.com/comment/87248048
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50115578
answer count: 2
has comment: http://stackoverflow.com/comment/87247732
type: UnansweredQuestion
has title: Beautiful Soup parsing an XML file
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50119391
score: 2
downvote count: 0
has body: I am writing a simple Python using Beautiful Soup to parse the data I need out of an xml file. It's working how I need it to, but I have one ask of you guys as I have tried to Google this but can't seem to find what I am looking for. Sample of XML string: Clamp-On I am needing the AttributeID within the ProductAttribute. When I write, the below I am able to grab the value "Clamp-On" but I need AttributeID to tell me what Clamp-On is referencing. attributes[part.find('PartNumber').get_text()] = [x.get_text() for x in part.find_all('ProductAttribute')] for key, value in attributes.items(): for v in value: print(v) Any guidance is appreciated before negative feedback. Thanks!
has comment: http://stackoverflow.com/comment/87247702

http://stackoverflow.com/q/50118813
downvote count: 1
has title: python for loop if statement issue
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50119088
accepted answer: http://stackoverflow.com/a/50119088
tagged with: python
favorite count: 0
type: Question
tagged with: for-loop
has body: When we run the following foor loop, it outputs the same pair multiple times (see further below), although keptPairs contains only distinct tuples. Has anyone a quick fix on that? processedPairs = [] bestCorrPairs = [] corrCoefs = [] for pair in keptPairs: if pair not in processedPairs: processedPairs.append(pair) bestCorrCoef = 0 targetx = pair[0] t_y = [] for p in keptPairs: if targetx in p: if (p[0]!=targetx): t_y.append(p[0]) else: t_y.append(p[1]) else: continue for targety in t_y: corr = calcCorr(final_t,targetx, targety) if (np.abs(corr) &gt; np.abs(bestCorrCoef) and not (corr==0 or corr==1)): bestCorrCoef = corr bestPair = tuple([targetx, targety]) else: continue bestCorrPairs.append(bestPair) corrCoefs.append(bestCorrCoef) else: continue for i in range(0,len(bestCorrPairs)): print(bestCorrPairs[i], ': ', corrCoefs[i]) out: ('9.4', '15.4') : 0.9906385237419475 ('9.4', '15.4') : 0.9906385237419475 ('9.4', '15.4') : 0.9906385237419475 ('9.4', '15.4') : 0.9906385237419475 ('9.4', '15.4') : 0.9906385237419475 ('9.4', '15.4') : 0.9906385237419475 ('9.4', '15.4') : 0.9906385237419475 ('3.1', '15.1') : -0.9815967899407816 ('3.1', '15.1') : -0.9815967899407816 ('17.8', '6.2') : -0.9982604771744984 ('6.2', '17.8') : -0.9982604771744984 ('10.c', '7.2') : -0.8082515774139288 ('17.3', '15.1') : 0.9810874111013809 etc. We would like to process each pair only once. Printing the pairs after the first for-loop actually only prints them once, however, the output seems like these pairs have been processed multiple times. Thank you!
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/87306765
score: 0
comment on: http://stackoverflow.com/q/50144214
type: Comment
type: QuestionComment
has text: The value of `sensors` is a array, whose first element is an array, and whose second element is `"mailInfo": …`. But that can't go inside a array, only inside an object.

http://stackoverflow.com/q/50177431
has title: in Jupyter, pip reports different version of python module than is imported
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87376405
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/87373970
has comment: http://stackoverflow.com/comment/87372130
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87372212
downvote count: 0
upvote count: 1
has body: I have upgraded a module as follows !pip install py2neo==3.1.2 --user --upgrade pip confirms that the right version is installed. That is, running this: !pip show py2neo gives this: Name: py2neo Version: 3.1.2 Summary: Python client library and toolkit for Neo4j Home-page: http://py2neo.org/ Author: Nigel Small &lt;nigel@py2neo.org&gt; Author-email: nigel@py2neo.org License: Apache License, Version 2.0 Location: c:\users\db15237\appdata\roaming\python\python36\site-packages Requires: Required-by: neo4j-doc-manager But if I import the module, it imports an older version. This code: import py2neo print(py2neo.__version__) returns 2.0.8 How do I import version 3.1.2, which pip says is installed?
favorite count: 0
tagged with: jupyter-notebook
type: Question

http://stackoverflow.com/q/50202870
has comment: http://stackoverflow.com/comment/87422478
has answer: http://stackoverflow.com/a/50202983
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/87422687
upvote count: 2
accepted answer: http://stackoverflow.com/a/50202890
downvote count: 0
has answer: http://stackoverflow.com/a/50202890
has comment: http://stackoverflow.com/comment/87422577
favorite count: 0
possible better answer: http://stackoverflow.com/a/50202983
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87424459
tagged with: algorithm
has comment: http://stackoverflow.com/comment/87423292
tagged with: python
has title: How to iterate over two lists without using nested for loops?
has body: If a and b are two lists then how can we get c without using nested for loops in python? a=[1,2,3] b=[4,5,6] c=[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)] Let's assume I have to find the sum of all nth term of fibonacci sequence formed by these pairs as the first two numbers, where n is any positive number. In this case for n=3 answer in 63. &gt; 1 4 5 nth term in 5 1 5 6 nth term in 6 . . . 3 6 9 nth term in 9 &gt; &gt; Sum of all nth term in 63.
has comment: http://stackoverflow.com/comment/87424011
score: 2

http://stackoverflow.com/comment/87481803
comment on: http://stackoverflow.com/a/50219064
type: AnswerComment
has text: Welcome on SO! Don't forget to accept the answer it it worked for you.
score: 0
type: Comment

http://stackoverflow.com/comment/87231046
comment on: http://stackoverflow.com/a/50106442
score: 0
type: Comment
type: AnswerComment
has text: so, for this case, I just need to use im.save(png_file_name) without the the option of transparency, is that right?

http://stackoverflow.com/comment/87173402
comment on: http://stackoverflow.com/a/50077940
score: 0
type: Comment
has text: Perfect!. I think I understand it much better now. Very helpful explaination.
type: AnswerComment

http://stackoverflow.com/q/50101740
upvote count: 8
has body: I have a header-only C++ library that I use in my Python extensions. I would like to be able to install them to Python's include path, such that I can compile extensions very easily with python3 setup.py build. I'm partly able, but there are two things that I cannot get working (see below): How can I use python3 setup.py install to install the header files? Currently I only get some *.egg file, but not the headers installed. How can I retain the module's file structure? Currently the file structure is erroneously flattened. What works With the following setup.py from setuptools import setup setup( name = 'so', description = 'Example', headers = [ 'so.h', ], ) I can upload the module to PyPi: python3 setup.py bdist_wheel --universal twine upload dist/* and then install it using pip: pip3 install so On my system then I then find the header here /usr/local/include/python3.6m/so/so.h which is available when I compile the extensions with Python. How can I use 'python3 setup.py install'? Using this strategy I cannot simply run python3 setup.py install In that case some so*.egg is installed, but the headers are not stored somewhere where they are available to the compiler. How to retain a file structure? When the module is a bit more complicated, and there is some directory hierarchy I also run to problems. For the following setup.py from setuptools import setup setup( name = 'so', description = 'Example', headers = [ 'so.h', 'so/implementation.h', ], ) The problem is that the headers are installed to /usr/local/include/python3.6m/so/so.h /usr/local/include/python3.6m/so/implementation.h thus flattening the original file structure. How can I fix both issues?
tagged with: python
score: 8
type: Question
accepted answer: http://stackoverflow.com/a/50114715
has answer: http://stackoverflow.com/a/50114715
tagged with: setup.py
tagged with: setuptools
answer count: 1
downvote count: 0
has title: Install header-only library with Python
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
tagged with: header-only

http://stackoverflow.com/comment/87483212
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50221801
has text: Yes, @tdelaney your notice is coorect, with **a few exceptions :** (1) O/P explicitly stated Windows O/S, where all ***forking* is not supported** ( so far, 2018/Q2 ) (2) Unix / Linux O/S forking-tricks seem as **not supported in py2.7.x** (3) using additional process-to-process communication methods ( as you have proposed to use **`.Array()` will add immense add-on SER/DES overhead costs** `pickle.{dumps|loads}()`. Sure, the above proposed algorithm was not polished for HPC-grade ultimate processing efficiency ( which was not merit of the post ), **yet, no reason to add even more overheads**

http://stackoverflow.com/q/50183044
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I am learning pyqt 5 and python and wanted to make a simple application that would show a layout with tabs a webpage and a matplotlib graph. When I change a combobox I wanted to show the shape file for a country in the matplotlib graph, however, I can only show the first shapefile. `Below is the code simplified that shows the layout and problem, rather than the shapefile for an example I just have some slightly different functions that should change when the combobox is changed. However, only the very first graph is shown, and although the variables are passed from the combobox, the new function is not plotted. Basically, at this point, all I want to do is to be able to pull the combobox down select the other country and see the new graph appear. Other suggestions are also appreciated. The code sample below. import numpy as np import sys from PyQt5.QtCore import QUrl,QRect,QSize from PyQt5.QtWebEngineWidgets import QWebEngineSettings, QWebEngineView, QWebEnginePage from PyQt5.QtWidgets import (QApplication, QMainWindow,QMenu,QHBoxLayout,QVBoxLayout,QFrame,QLabel, QSizePolicy, QMessageBox, QWidget, QPushButton,QRadioButton, QTextBrowser,QDialog,QGroupBox,QTabWidget,QComboBox,QListWidget) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import shapefile as shp import matplotlib.pyplot as plt import random data_square=[(0,0),(1,0),(1,1),(0,1),(0,0),(1,1)] data_rectangle=[(0,0),(2,0),(2,1),(0,1),(0,0),(1,1)] class MyBrowser(QWebEnginePage): def userAgentForUrl(self, url): return "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" class Web(QWebEngineView): def load(self, url): self.setUrl(QUrl(url)) def adjustTitle(self): self.setWindowTitle(self.title()) def disableJS(self): settings = QWebEngineSettings.globalSettings() settings.setAttribute(QWebEngineSettings.JavascriptEnabled, False) class App(QDialog): def __init__(self): super().__init__() self.t…
has answer: http://stackoverflow.com/a/50187356
score: 0
has comment: http://stackoverflow.com/comment/87396600
tagged with: matplotlib
tagged with: pyqt5
has title: Not clearing graph before plotting another graph using matplotlib in pyqt5 inside tabWidget
has comment: http://stackoverflow.com/comment/87383661
type: Question

http://stackoverflow.com/comment/87218308
has text: Maybe [TensorBorad](https://github.com/tensorflow/tensorboard)?
score: 0
comment on: http://stackoverflow.com/q/50100766
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87452782
comment on: http://stackoverflow.com/q/50217553
score: 0
type: Comment
type: QuestionComment
has text: So you have no python code at all?

http://stackoverflow.com/a/50075594
has comment: http://stackoverflow.com/comment/87168582
accepted answer of: http://stackoverflow.com/q/50075118
type: Answer
answers question: http://stackoverflow.com/q/50075118
has comment: http://stackoverflow.com/comment/87168723
has body: Well .. there are characters that do not show up when printed (whitespace) and after your last "normal" character: ' ', '\r' '\t' '\n' and others. Check if len(aa) != len(a): print "Invisible characters - length different" print "'{}' vs '{}'".format(aa,a) Using rstrip() (doku-link) to remove unwanted whitespace if aa.rstrip()==a.rstrip(): # avoid "a" vs "a " comparing to not equal print "same" else: print "Not same" helps. Following this also helps: How to debug small programs (#1) Demo: a = "ff " # 'invisible' difference aa = "ff" print type(a) print a print type(aa) print aa if len(aa) != len(a): print "Invisible characters - length different" print "'{}' vs '{}'".format(aa,a) if aa.rstrip()==a.rstrip(): print "same" else: print "Not same" Output: &lt;type 'str'&gt; ff &lt;type 'str'&gt; ff Invisible characters - length different 'ff' vs 'ff ' same
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50142019
tagged with: python-2.7
linked to: http://stackoverflow.com/q/19068269
tagged with: python
has body: How can i convert date from this formt "Tue May 15 2018 00:00:00 GMT-0400 (EDT)" to date in the format yyyy-mm-dd?
linked to: http://stackoverflow.com/q/10854874
has comment: http://stackoverflow.com/comment/87302448
has answer: http://stackoverflow.com/a/50142109
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/50142055
score: 0
has title: How to get date from this format "Tue May 15 2018 00:00:00 GMT-0400 (EDT)" in python
answer count: 2
upvote count: 1
tagged with: django
type: UnansweredQuestion
downvote count: 1
linked to: http://stackoverflow.com/q/466345

http://stackoverflow.com/q/50104364
type: AnsweredQuestion
score: 2
answer count: 2
tagged with: maya-api
upvote count: 2
has title: How to abort the loading of a file in Maya started via cmds.file in python
tagged with: maya
downvote count: 0
has body: I have code that runs a batch operation on files in Maya. The actual implementation isn't important, just know that it gets fed a list of filepaths, maya opens the files, then an operation is performed on each file in turn. In cases where a reference isn't valid for whatever reason (like an invalid path) I want to abort loading of that whole scene and skip to the next in the batch list. Looking at other questions on this site and elsewhere I've only been able to see users asking how to query references. I already have a reasonable function for doing so, it's what to do after that function returns an invalid reference path that stumps me. Resolving invalid reference paths has historically been done manually via the popup, however in large batches constantly babysitting the maya instance isn't feasible. Nor is suppressing the popup window itself, as I believe that will still open the file, and run the batch operation on the scene while it's in an invalid state. I have been through the maya cmds python module to try and not load references, however when using the loadReferenceDepth flag along with cmds.file I'm still getting a popup: cmds.file(r'c:\path\to\file.ma', o=1, f=1, lrd='none') #invalid ref popup during file cmd The second approach was to look into the maya open api and register a callback on the before open event. The code below is functionally the same as how the batch is set up: import maya.OpenMaya as OpenM batchFileList = [r"c:\path\to\file.ma", r"c:\path\to\file2.ma"] def _test_raise_exception(arg0, arg1, arg2): #pretending that a file ref failed below. Ref path validation code would go here. print '\n'*5+'Test Logging'+'\n'*5 return False cId = OpenM.MSceneMessage.addCheckFileCallback(OpenM.MSceneMessage.kBeforeOpenCheck, _test_raise_exception) for file_ in batchFileList: try: rv = cmds.file(file_, o=1) #do stuff to the maya scene here except: #something didn't validate on load, except and skip, logging the occurrence. print 'load cancelled' OpenM.MSce…
possible better answer: http://stackoverflow.com/a/50182472
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87300192
accepted answer: http://stackoverflow.com/a/51131957
has comment: http://stackoverflow.com/comment/87474010
has answer: http://stackoverflow.com/a/50182472
has answer: http://stackoverflow.com/a/51131957

http://stackoverflow.com/comment/87197939
comment on: http://stackoverflow.com/q/50090793
type: QuestionComment
score: 0
has text: This question is very confusing. If your program doesn't even start because of a syntax error, why are you asking about "ending" it? Are you asking how to finish writing the `main` function?
type: Comment

http://stackoverflow.com/q/50084497
has comment: http://stackoverflow.com/comment/87185168
has comment: http://stackoverflow.com/comment/87184661
has comment: http://stackoverflow.com/comment/87184888
has comment: http://stackoverflow.com/comment/87184845
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87184672
has comment: http://stackoverflow.com/comment/87184826
has comment: http://stackoverflow.com/comment/87184818
has comment: http://stackoverflow.com/comment/87184792
tagged with: python
has comment: http://stackoverflow.com/comment/87184767
has comment: http://stackoverflow.com/comment/87184709
has body: I have 340,000 line file data , when I reading file with Python 3.5 timing is good but when I run it with Python 2.7 reading is very slow , don't have any clue what is going on here, here is code: import codecs as cds INPUT_DATA_DIR = 'some_tsv_file.tsv' ENT = "entities" def train_data_getter(input_dir=INPUT_DATA_DIR): file_h = cds.open(input_dir, encoding='utf-8') data = file_h.read() file_h.close() sentences = data.split("\n\n") parsed_data = parser(sentences[0]) return parsed_data def parser(raw_data): words = [line for line in raw_data.split("\n")] temp_l = [] temp_s = "" for word in words: token, ent = word.split('\t') temp_s += token temp_s += " " temp_l.append(ent) data = [(temp_s), {ENT: temp_l}] return data Edit Thanks to @PM 2Ring , problem was string concatenation inside a for loop but still reason for huge difference between Python2.7 and 3.5 is not clear for me.
linked to: http://stackoverflow.com/q/44503190
tagged with: python-2.7
tagged with: performance
linked to: http://stackoverflow.com/q/25962114
has comment: http://stackoverflow.com/comment/87185092
has comment: http://stackoverflow.com/comment/87184720
has comment: http://stackoverflow.com/comment/87184680
has comment: http://stackoverflow.com/comment/87184773
score: 0
has answer: http://stackoverflow.com/a/50084689
answer count: 1
linked to: http://stackoverflow.com/q/1349311
linked to: http://stackoverflow.com/q/9652832
has comment: http://stackoverflow.com/comment/87184936
upvote count: 1
downvote count: 1
tagged with: append
favorite count: 0
has title: Huge timing difference in string concatenation between Python 3.5 vs 2.7
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87288465
score: 0
has text: what is the app name is urls file
type: QuestionComment
comment on: http://stackoverflow.com/q/50135211
type: Comment

http://stackoverflow.com/comment/87439576
type: Comment
comment on: http://stackoverflow.com/q/50179457
type: QuestionComment
score: 0
has text: Thanks, I didn't realise it was a series so did not realise I'd posted a duplicate question.

http://stackoverflow.com/comment/87420445
score: 0
comment on: http://stackoverflow.com/q/50200678
type: Comment
has text: What about `X := Min(X + Increment, 740);`
type: QuestionComment

http://stackoverflow.com/q/50188520
possible better answer: http://stackoverflow.com/a/50188550
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50188550
has comment: http://stackoverflow.com/comment/87393771
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/87393795
answer count: 2
has comment: http://stackoverflow.com/comment/87393739
upvote count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/87393779
favorite count: 0
type: Question
has body: Given a list, such as [3, 2, 4], how can I generate the following output? [0, 0, 0] [0, 0, 1] [0, 0, 2] [0, 0, 3] [0, 0, 4] [0, 1, 0] [0, 1, 1] [0, 1, 2] [0, 1, 3] [0, 1, 4] [0, 2, 0] [0, 2, 1] [0, 2, 2] [0, 2, 3] [0, 2, 4] [1, 0, 0] ... [1, 2, 4] ... [3, 2, 4] I need to generate every list possible where each element of the list is positive and is not greater than the number given at the relevant index. I know this involves for loops, but I'm looking for the most efficient way (probably using a generator) which can deal with lists of varying sizes.
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50188569
has title: How can I generate this?
has comment: http://stackoverflow.com/comment/87393745
has answer: http://stackoverflow.com/a/50188569

http://stackoverflow.com/comment/87368452
has text: Please post the code that you really start. The code in the question is not runnable.
score: 0
comment on: http://stackoverflow.com/q/50175203
type: QuestionComment
type: Comment

keras
tags question: http://stackoverflow.com/q/50201024
tags question: http://stackoverflow.com/q/50091573
tags question: http://stackoverflow.com/q/50190571
tags question: http://stackoverflow.com/q/50076900
tags question: http://stackoverflow.com/q/50109629
tags question: http://stackoverflow.com/q/50184534
tags question: http://stackoverflow.com/q/50141766
tags question: http://stackoverflow.com/q/50211534
tags question: http://stackoverflow.com/q/50079766
tags question: http://stackoverflow.com/q/50128278
tags question: http://stackoverflow.com/q/50211215
tags question: http://stackoverflow.com/q/50212330
tags question: http://stackoverflow.com/q/50151585
tags question: http://stackoverflow.com/q/50103377
tags question: http://stackoverflow.com/q/50083284
tags question: http://stackoverflow.com/q/50228913
tags question: http://stackoverflow.com/q/50156010
tags question: http://stackoverflow.com/q/50161493
tags question: http://stackoverflow.com/q/50215931
tags question: http://stackoverflow.com/q/50178499
tags question: http://stackoverflow.com/q/50147408
tags question: http://stackoverflow.com/q/50154465
tags question: http://stackoverflow.com/q/50081415
tags question: http://stackoverflow.com/q/50136727
tags question: http://stackoverflow.com/q/50099745
tags question: http://stackoverflow.com/q/50081333
tags question: http://stackoverflow.com/q/50174955
tags question: http://stackoverflow.com/q/50125844
tags question: http://stackoverflow.com/q/50127257
tags question: http://stackoverflow.com/q/50210953
tags question: http://stackoverflow.com/q/50075541
tags question: http://stackoverflow.com/q/50082781
tags question: http://stackoverflow.com/q/50092589
tags question: http://stackoverflow.com/q/50142583
tags question: http://stackoverflow.com/q/50227293
tags question: http://stackoverflow.com/q/50105969
tags question: http://stackoverflow.com/q/50134090
tags question: http://stackoverflow.com/q/50140500
tags question: http://stackoverflow.com/q/50166420
tags question: http://stackoverflow.com/q/50161671
tags question: http://stackoverflow.com/q/50215003
tags question: http://stackoverflow.com/q/50158290
tags question: http://stackoverflow.com/q/50075783
tags question: http://stackoverflow.com/q/50186035
tags question: http://stackoverflow.com/q/50120672
tags question: http://stackoverflow.com/q/50127527
tags question: http://stackoverflow.com/q/50202251
tags question: http://stackoverflow.com/q/50163817
tags question: http://stackoverflow.com/q/50206574
tags question: http://stackoverflow.com/q/50080512
tags question: http://stackoverflow.com/q/50115858
tags question: http://stackoverflow.com/q/50122873
tags question: http://stackoverflow.com/q/50081529
tags question: http://stackoverflow.com/q/50227925
tags question: http://stackoverflow.com/q/50120251
tags question: http://stackoverflow.com/q/50078960
tags question: http://stackoverflow.com/q/50178361
tags question: http://stackoverflow.com/q/50079585
tags question: http://stackoverflow.com/q/50182860
tags question: http://stackoverflow.com/q/50096891
tags question: http://stackoverflow.com/q/50151157
tags question: http://stackoverflow.com/q/50115762
tags question: http://stackoverflow.com/q/50083767
tags question: http://stackoverflow.com/q/50198842
tags question: http://stackoverflow.com/q/50207228
tags question: http://stackoverflow.com/q/50108170
tags question: http://stackoverflow.com/q/50178711
tags question: http://stackoverflow.com/q/50114065
tags question: http://stackoverflow.com/q/50133385
tags question: http://stackoverflow.com/q/50079735
tags question: http://stackoverflow.com/q/50183809
tags question: http://stackoverflow.com/q/50187667
tags question: http://stackoverflow.com/q/50080087
tags question: http://stackoverflow.com/q/50213274
tag name: keras
tags question: http://stackoverflow.com/q/50075175
tags question: http://stackoverflow.com/q/50105143
tags question: http://stackoverflow.com/q/50082388
tags question: http://stackoverflow.com/q/50209452
tags question: http://stackoverflow.com/q/50159859

http://stackoverflow.com/a/63921310
has body: It happened to me using the AWS rekognition sdk for android , the problem was that the region of the S3 bucket is not the same in my request , so I had to put the correct region in the request (same as S3 bucket ) : rekognitionClient.setRegion(Region.getRegion(Regions.US_WEST_1));//replace with your S3 region
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50181484

http://stackoverflow.com/comment/87168615
type: AnswerComment
has text: I think when I merged I will lose the value of customer_id 4:-?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50075197

http://stackoverflow.com/comment/87539492
comment on: http://stackoverflow.com/a/50231030
type: Comment
score: 0
type: AnswerComment
has text: Works perfectly. thank you so much. very smart way of going about it i definitely would not have thought about it that way. still very new to Tkinter and not sure how everything works with each other.

http://stackoverflow.com/a/50197024
downvote count: 0
answers question: http://stackoverflow.com/q/50194797
upvote count: 1
has body: Seems like I found the problem. While it honestly just raises more problems, I'm gonna accept it for now. Looks like Pyinstaller has some serious issues with PyFiglet. Everything compiled fine when I removed the PyFiglet output. I have absolutely zero idea as to why, but oh well. For anyone in the future looking for answers to this, here's the command for compiling. You just need to add the Pyfiglet fonts directory to pyinstaller. pyinstaller --add-data "C:/Python36/Lib/site-packages/pyfiglet";./pyfiglet --onefile myprogram.py
type: Answer
score: 1

http://stackoverflow.com/q/50222699
tagged with: tfrecord
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 0
downvote count: 0
has body: I am following tensorflow's official cifar tutorial to create an input pipeline for my image dataset. After training the model, I decided to use 50000 images for test. However, after testing, I found that many images are tested multiple times, while some images are not tested at all. For example, one image named '1000_left' is tested multiple times, while some images such as '100_left' is not tested at all. Could anyone help me identify what is going on? Thank you! Here is how I load the tfrecord dataset and generated image batches for test: def _generate_image_and_name_batch(image, name, min_queue_examples, batch_size): num_preprocess_threads = 16 images, names = tf.train.batch([image, name], batch_size = batch_size, num_threads = num_preprocess_threads, capacity = min_queue_examples + 3 * batch_size) tf.summary.image('images', images) return images, tf.reshape(names, [batch_size]) def read_test(test_dir, batch_size): #constructs inputs for test if not tf.gfile.Exists(test_dir): raise ValueError("Failed to find file: " + test_dir) #restore features of test record features = {"test/image": tf.FixedLenFeature([], tf.string), "test/name": tf.FixedLenFeature([], tf.string)} with tf.name_scope("test_input"): filename_queue = tf.train.string_input_producer(string_tensor = [test_dir]) reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example(serialized_example, features = features) image = tf.decode_raw(features['test/image'], tf.float32) image = tf.reshape(image, [224,224,3]) name = tf.cast(features['test/name'], tf.string) min_fraction_of_examples_in_queue = 0.4 min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TEST * min_fraction_of_examples_in_queue) return _generate_image_and_name_batch(image, name, min_queue_examples, batch_size) Here is how I load data for test: #start queue runners coord = tf.train.Coordinator() try: threads = [] for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS): threads.extend(qr.c…
tagged with: python
type: UnansweredQuestion
has title: python - tensorflow tfrecord input pipeline duplicate data reading

http://stackoverflow.com/comment/110472022
type: AnswerComment
has text: I've expanded my original answer. My example should run out of the box.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50203979

http://stackoverflow.com/comment/87299578
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50125582
type: QuestionComment
has text: @DanieleCappuccio sys.version says 2.7.5

http://stackoverflow.com/a/50084966
accepted answer of: http://stackoverflow.com/q/50084808
score: 1
type: AcceptedAnswer
has body: My starting assumption is you are able to get a list of strings from your csv file into list phone_imei. For the string format you desire, you need to use string slicing / indexing. Conveniently, this is the same as for lists, so see Understanding Python's slice notation. Here is one example: x = "123456789123456" res = x[:2] + ' ' + x[2:8] + ' ' + x[8:14] + ' ' + x[14] '12 345678 912345 6' You can incorporate this logic in a couple of ways. As you go along... def string_formatter(x): """Format telephone number with spaces.""" return x[:2] + ' ' + x[2:8] + ' ' + x[8:14] + ' ' + x[14] for row in reader: phone_imei.append(string_formatter(row[3])) At the end... phone_imei = list(map(string_formatter, phone_imei)) # equivalently, phone_imei = [string_formatter(i) for i in phone_imei]
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50084808

http://stackoverflow.com/q/50204783
tagged with: file-io
has comment: http://stackoverflow.com/comment/87426718
has comment: http://stackoverflow.com/comment/87427513
has comment: http://stackoverflow.com/comment/87426648
has comment: http://stackoverflow.com/comment/87427102
type: UnansweredQuestion
type: Question
has body: I want to open a file which contains both the Danish æ, ø and å letters. When I've opened the file, I'd like to organize the words and letters in the string that I saved the output of the file to. Unfortunately; when I try to see if either of these letters are part of the string, the output comes out as a no. Here is my program: wordlist = open("_newWordList.txt", "r") print("Opened newwordlist") for lineNo, content in enumerate(wordlist): s_line = content.split(";") print(str(lineNo)+": Checking the content: "+str(s_line)+" on line number: "+str(lineNo)) ok = s_line[1] if ok[:4] == "adj.": adj = adj + s_line[0] elif ok[:10] == "ubøj. adj.": adj = adj + s_line[0] elif ok[:4] == "adv.": adv = adv + s_line[0] elif ok[:5] == "fork.": fork = fork + s_line[0] elif ok[:8] == "præfiks.": præfiks = præfiks + s_line[0] elif ok[:5] == "præp.": praep = praep + s_line[0] elif ok[:5] == "pron.": pron = pron + s_line[0] elif ok[:5] == "prop.": prop = prop + s_line[0] elif ok[:3] == "sb.": sb = sb + s_line[0] elif ok[:7] == "sb. pl.": sb = sb + s_line[0] elif ok[:9] == "udråbsord": uro = uro + s_line[0] elif ok[:3] == "vb.": vb = vb + s_line[0] else: print(" ") print("Error; didn't read any wordclass in the word: "+str(lineNo+1)+" : "+str(content)) print("The wordclass is: "+ok) totalErrors += 1 The letters come out as weird, unreadable symbols.
has comment: http://stackoverflow.com/comment/87432074
answer count: 0
has title: Using æ, ø and å in Python
tagged with: encode
tagged with: python
has comment: http://stackoverflow.com/comment/87426576
has comment: http://stackoverflow.com/comment/87426678
has comment: http://stackoverflow.com/comment/87426688
score: 0
has comment: http://stackoverflow.com/comment/87426610

http://stackoverflow.com/a/50102112
answers question: http://stackoverflow.com/q/50101808
has body: Everyone's trying too hard here. We want each value to be either the original value or 0 -- we want pairs like (1,0), (2,0), and (3,0): &gt;&gt;&gt; from itertools import product, repeat &gt;&gt;&gt; L = [1, 2, 3] &gt;&gt;&gt; zip(L, repeat(0)) &lt;zip object at 0x7f931ad1bf08&gt; &gt;&gt;&gt; list(zip(L, repeat(0))) [(1, 0), (2, 0), (3, 0)] and then we can just pass that into product: &gt;&gt;&gt; list(product(*zip(L, repeat(0)))) [(1, 2, 3), (1, 2, 0), (1, 0, 3), (1, 0, 0), (0, 2, 3), (0, 2, 0), (0, 0, 3), (0, 0, 0)]
downvote count: 0
score: 7
upvote count: 7
type: Answer

http://stackoverflow.com/comment/87354817
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50162628
type: AnswerComment
has text: Looks great! Do you know if it's possible to change the reference category to Sunday and sort the weekdays by day of week?

http://stackoverflow.com/a/50184342
answers question: http://stackoverflow.com/q/50098967
has comment: http://stackoverflow.com/comment/87386041
has comment: http://stackoverflow.com/comment/87438746
has comment: http://stackoverflow.com/comment/87438632
has body: You can hide the verbose output by changing the logging level. Take a look at this line in your code: logging.basicConfig(logging.INFO) Right now, the logging level is INFO which prints everything. You can choose a less verbose logging level such as WARNING, ERROR, or CRITICAL. You can also remove the logging configuration line entirely to disable the verbose logging.
score: 0
type: Answer

http://stackoverflow.com/a/50179125
type: Answer
has body: Answer to question 1, your problem is this line: from multiprocessing.dummy import Pool # This is a thread-based Pool Answer taken from: multiprocessing.dummy in Python is not utilising 100% cpu When you use multiprocessing.dummy, you're using threads, not processes: multiprocessing.dummy replicates the API of multiprocessing but is no more than a wrapper around the threading module. That means you're restricted by the Global Interpreter Lock (GIL), and only one thread can actually execute CPU-bound operations at a time. That's going to keep you from fully utilizing your CPUs. If you want get full parallelism across all available cores, you're going to need to address the pickling issue you're hitting with multiprocessing.Pool.
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87375642
has comment: http://stackoverflow.com/comment/87375476
answers question: http://stackoverflow.com/q/50178900

http://stackoverflow.com/a/50162965
has comment: http://stackoverflow.com/comment/87344039
upvote count: 1
answers question: http://stackoverflow.com/q/50162849
has body: Another method of doing it using from_dict d = { '123' : {'name': 'Joe', 'age': '17'}, '888' : {'name': 'Cheryl', 'hometown': 'Liverpool'}, '432' : {'name': 'Raj'} } df = pd.DataFrame.from_dict(d, orient = 'index').unstack().reset_index() df level_0 level_1 0 0 name 123 Joe 1 name 432 Raj 2 name 888 Cheryl 3 age 123 17 4 age 432 NaN 5 age 888 NaN 6 hometown 123 NaN 7 hometown 432 NaN 8 hometown 888 Liverpool If you want to remove the NaN's, simply add .dropna() to the end of the statement. df = pd.DataFrame.from_dict(d, orient = 'index').unstack().reset_index().dropna() df level_0 level_1 0 0 name 123 Joe 1 name 432 Raj 2 name 888 Cheryl 3 age 123 17 8 hometown 888 Liverpool
has comment: http://stackoverflow.com/comment/87344222
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50162849
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50124877
favorite count: 0
has answer: http://stackoverflow.com/a/55543457
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/77483234
type: UnansweredQuestion
has title: "AttributeError: '_ErrorHolder' object has no attribute '_testMethodName'" error
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87317431
tagged with: python-unittest
tagged with: selenium
has body: I've been having this problem when I run tests and I can't narrow it down because I'm a little new to this and I can't seem to figure it out or find help elsewhere. After the tests execute, if there is an error, I usually get this output: Traceback (most recent call last): File "./src/automated_tests/tests_launcher.py", line 215, in &lt;module&gt; pprint(result.jsonify()) File "./src/automated_tests/tests_launcher.py", line 110, in jsonify json_out = self.json_append(t, ERROR, json_out, k) File "./src/automated_tests/tests_launcher.py", line 93, in json_append {LOGS: logs, STATUS: result, TITLE: test._testMethodName}) AttributeError: '_ErrorHolder' object has no attribute '_testMethodName' The relevant lines referenced are: class JsonTestResult(TextTestResult): def __init__(self, stream, descriptions, verbosity=2): super(JsonTestResult, self).__init__(stream, descriptions, verbosity) self.successes = [] def addSuccess(self, test): super(JsonTestResult, self).addSuccess(test) self.successes.append(test) def json_append(self, test, result, out, logs): suite = test.__class__.__name__ if suite not in out: out[suite] = {TESTCASES: []} if result is PASS: out[suite][TESTCASES].append( {LOGS: logs, STATUS: result, TITLE: test._testMethodName}) elif result is FAIL: out[suite][TESTCASES].append( {LOGS: logs, STATUS: result, TITLE: test._testMethodName}) elif result is ERROR: out[suite][TESTCASES].append( # LINE 93: {LOGS: logs, STATUS: result, TITLE: test._testMethodName}) elif result is SKIP: out[suite][TESTCASES].append( {LOGS: logs, STATUS: result, TITLE: test._testMethodName}) else: raise KeyError("No such result: {}".format(result)) return out def jsonify(self): json_out = dict() for t in self.successes: json_out = self.json_append(t, PASS, json_out, None) for t, k in self.failures: json_out = self.json_append(t, FAIL, json_out, k) for t, k in self.errors: # LINE 110: json_out = self.json_append(t, ERROR, json_out, k) for t, k in self.skipped: json_out = self.json_append…

http://stackoverflow.com/a/50207576
type: Answer
accepted answer of: http://stackoverflow.com/q/50207465
has comment: http://stackoverflow.com/comment/87432628
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87433195
answers question: http://stackoverflow.com/q/50207465
has comment: http://stackoverflow.com/comment/87432694
score: 0
has body: &gt; only has special meaning in a shell, like cmd.exe. Currently, you are passing a very long filename which includes spaces and a &gt; in it to Python. The correct way to redirect a ProcessBuilder’s output is with its redirectOutput method: ProcessBuilder builder = new ProcessBuilder( "C:\\Pythion27\\Python.exe", "H:\\!eGIS.Dev_Workbench\\eGIS.ArcGIS_Workbench\\!eGIS.Network_Build\\Network_Build_Script.v.6.2_2017.12.08\\Script.1-2_Trunk_20170609\\Src\\PY\\ComcastNetworkProcessing\\ComcastNetworkProcessing.py", "H:\\!eGIS.Dev_Workbench\\eGIS.ArcGIS_Workbench\\!eGIS.Network_Build\\eGIS.CoE.Network_Clips\\Network_ETLs\\eGIS.CoE.Network_Clip\\MOUNTAINWEST_AZ.gdb", "H:\\!eGIS.Dev_Workbench\\eGIS.ArcGIS_Workbench\\!eGIS.Network_Build\\Network_DS_ProBuild\\Wp4\\Network_Build_00_00_0000\\WD_Mountainwest_AZ"); builder.redirectOutput(new File( "H:\\!eGIS.Dev_Workbench\\eGIS.ArcGIS_Workbench\\!eGIS.Network_Build\\Network_DS_ProBuild\\Wp4\\Network_Build_00_00_0000\\WD_Mountainwest_AZ\\logs\\BBB2_NB_Script1_AZ.txt"));

http://stackoverflow.com/comment/87320585
type: AnswerComment
has text: Tried and truth!! Thank you! God bless you! You just made my day.
comment on: http://stackoverflow.com/a/50150778
type: Comment
score: 0

http://stackoverflow.com/a/50218405
answers question: http://stackoverflow.com/q/50218274
downvote count: 0
has comment: http://stackoverflow.com/comment/87453985
score: 9
has body: I recommend the "get used to it" option, but if you really want to fiddle with this, you can customize sys.displayhook, the function responsible for setting _: import builtins import sys def displayhook(value): if value is not None: # The built-in displayhook is a bit trickier than it seems, # so we delegate to it instead of inlining equivalent handling. sys.__displayhook__(value) builtins.Ans = value sys.displayhook = displayhook
upvote count: 9
has comment: http://stackoverflow.com/comment/87454604
type: Answer
has comment: http://stackoverflow.com/comment/87454924

http://stackoverflow.com/q/50224053
answer count: 2
has answer: http://stackoverflow.com/a/72866173
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87465780
has answer: http://stackoverflow.com/a/52688605
has body: Unable to install requests using easy_install and python version is 2.7.10 sudo easy_install-2.7 requests Searching for requests Reading https://pypi.org/simple/requests/ Download error on https://pypi.org/simple/requests/: [Errno 101] Network is unreachable -- Some packages may not be found! Couldn't find index page for 'requests' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.org/simple/ Download error on https://pypi.org/simple/: [Errno 101] Network is unreachable -- Some packages may not be found! No local packages or working download links found for requests error: Could not find suitable distribution for Requirement.parse('requests')
tagged with: python
has title: Unable to install requests using easy_install
score: 0

http://stackoverflow.com/a/50152982
has body: try python logging, like this: import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG) logging.debug("print message!!!")
score: 0
answers question: http://stackoverflow.com/q/50147889
type: Answer

http://stackoverflow.com/a/50286977
type: AcceptedAnswer
downvote count: 0
has body: Why are you doing unstack on the input data?. The input to the RNN should be a tensor of shape [batch_size, max_time, n_input] for time_major == False(default) and [max_time, batch_size, n_input] for time_major == True. Just pass the input without the unstack operation should do the trick.
type: Answer
accepted answer of: http://stackoverflow.com/q/50088092
score: 2
answers question: http://stackoverflow.com/q/50088092
upvote count: 2

http://stackoverflow.com/q/50166780
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has title: Why tf.pad return shape [?,?,?]
has comment: http://stackoverflow.com/comment/87353727
tagged with: python
has body: I tried do some customized padding before feeding to a conv1D net as following. x=tf.placeholder("float",[None,50,1]) padding=tf.constant([0,0],[5,0],[0,0]) y=tf.pad(x,padding) However, after the above manipulation, y would be a tensor of shape (?,?,?), thus when feeding to tf.layers.conv1d, I get an error that "The channel dimension of the inputs should be defined. Found 'None'". My question is why does pad result has None shape? It should not be hard to calculate the shape, my guess is this is only calculated in run time, but it is not convenient right? And can I use reshape before passing to conv1d?
has comment: http://stackoverflow.com/comment/88131671
answer count: 0

http://stackoverflow.com/q/50187640
has title: How to list applied migrations from command line?
accepted answer: http://stackoverflow.com/a/50187730
has comment: http://stackoverflow.com/comment/87392064
upvote count: 11
favorite count: 0
has answer: http://stackoverflow.com/a/50187730
type: Question
answer count: 1
tagged with: django
tagged with: python
score: 11
has body: I had run makemigrations and after that migrate to apply the migration python manage.py showmigrations 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 boards [X] 0001_initial contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial How to find out models in boards from command line?
linked to: http://stackoverflow.com/q/8702772
has comment: http://stackoverflow.com/comment/87392026
type: AnsweredQuestion
downvote count: 0
tagged with: django-models

http://stackoverflow.com/q/50124599
has comment: http://stackoverflow.com/comment/87282405
answer count: 1
has answer: http://stackoverflow.com/a/50136689
has body: I am working on simple scanning script, which scan all open ports from the list of the IPs and check their banners. I have a problem, when socket.error occur on one of the port, the script exit and does not continue with banner grabbing on next port and also on next IP from the list. How can I modify my script so that if socket.error occurs it will continue to scan and not exit? print "+" * 40 starting_time = time.time() print " Scanning started at %s" % (time.strftime("%I:%M:%S %p")) print "+" * 40 print "+" * 40 ip_parts1 = host.split('.') h = ip_parts1[0] + '.' + ip_parts1[1] + '.' + ip_parts1[2] + '.' + ip_parts1[3] print "\033[1;31m" lst1 = map_network0() try: for h in lst1[:]: for port in range(1, 1024): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((h, port)) if result == 0: byte = str.encode("Server:\r\n") sock.send(byte) ans = sock.recv(512) socket.setdefaulttimeout(2) print h, ("......port " + '{0}'.format(port) + "/Open/" + '{0}'.format(ans)) sock.close() except KeyboardInterrupt: print ("Scanner aborted") sys.exit() except socket.gaierror: print ('Hostname could not be resolved. Exiting') sys.exit() except socket.error: print ("Couldn't connect to server") sys.exit()
type: Question
has comment: http://stackoverflow.com/comment/87278554
has comment: http://stackoverflow.com/comment/87287131
has title: Python 2.7 (socket) - how to continue on the next port if socket.error occurred on previous port
has comment: http://stackoverflow.com/comment/87267873
type: UnansweredQuestion
tagged with: sockets
tagged with: port
has comment: http://stackoverflow.com/comment/87291555
has comment: http://stackoverflow.com/comment/87278110
tagged with: python
has comment: http://stackoverflow.com/comment/87268776
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87284553
score: 0

http://stackoverflow.com/q/50085163
has comment: http://stackoverflow.com/comment/87186100
has body: class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.append(item) def dequeue(self): if self.items == []: raise IndexError('The queue is empty.') return self.items.pop() def size(self): return len(self.items) def __str__(self): return "Queue: " + (str(self.items)) def enqueue_list(self, list): for i in list: self.items.append(i) return self.items def splice(self, second_queue): for i in second_queue: self.items.enqueue(i) return self.items Hi there, What I am trying to do is at the bottom in the splice method. I want to iterate through a second queue and add it to the end of the original one. I can't find out how I can iterate through a queue without causing an error however. Should I change second_queue into a list somehow first? Original exception was: Traceback (most recent call last): File "prog.python3", line 74, in &lt;module&gt; my_queue.splice(another_queue) File "prog.python3", line 28, in splice for i in second_queue: TypeError: 'Queue' object is not iterable
has comment: http://stackoverflow.com/comment/87186041
has comment: http://stackoverflow.com/comment/87186078
has comment: http://stackoverflow.com/comment/87186052
linked to: http://stackoverflow.com/q/1952464
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: queue
has comment: http://stackoverflow.com/comment/87186024
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87186142
has title: Python - return combination of 2 queues
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50085233
tagged with: python

http://stackoverflow.com/a/50163699
has body: So I guess the obvious workaround is to use matplotlib directly, because it handles multiple widths/heights as expected. import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'value': [3,5,4], 'width': [0.1, 0.5, 1.0]}) fig, ax = plt.subplots(1,3) ax[0].barh(df.index, df.value, height=df.width) ax[1].bar(df.index, df.value, width=df.width) ax[2].barh(df.index, df.value, height=df.width) plt.show()
type: Answer
answers question: http://stackoverflow.com/q/50095188
has comment: http://stackoverflow.com/comment/87363407
score: 0
has comment: http://stackoverflow.com/comment/87350217

http://stackoverflow.com/comment/87211922
type: Comment
has text: Take a look at [`key`](https://docs.python.org/3/howto/sorting.html#key-functions) parameter
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50097704

http://stackoverflow.com/q/50135676
has body: I am trying to deploy an application and it crashes when importing seaborn Here is my config: Python 2.7, pyinstaller 3.3.1, seaborn 0.8.1. Here is the simplest piece of code to reproduce I wrote in installTest.py import seaborn print 'It works now!' Then in console I typed pyinstaller .\installTest I get a long error code terminating with a messagesstream module not found. Do you have any ideas on how to solve this?
type: Question
tagged with: pyinstaller
tagged with: seaborn
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50136359
tagged with: python
has title: Pyinstaller and seaborn
has comment: http://stackoverflow.com/comment/87289477
score: 0
answer count: 1

http://stackoverflow.com/q/50167943
accepted answer: http://stackoverflow.com/a/50169783
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50169783
upvote count: 0
tagged with: python
score: -3
has title: Filter a json by values
type: AnsweredQuestion
has body: I have this code import json,urllib2 def Trade(item): url = json.loads(urllib2.urlopen(urllib2.Request('https://api.warframe.market/v1/items/'+item+'/orders')).read()) primo = url["payload"] secondo = primo["orders"] prezzi = [] for tata in secondo: price = tata["platinum"] prezzi.append(price) print sorted(prezzi,key=int) I get an ordered DESC list, but i need to filter it by "status", in url["payload"]["orders"]["user"]["status"]. I'm kinda new with json parsing, and I need to define sublevels with an integer, but I need to parse the whole json to order "price" DESC by online status of user. What can I do? Here is an example of my JSON data: https://api.warframe.market/v1/items/primed_chamber/orders
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/87353530

http://stackoverflow.com/comment/87274548
type: Comment
has text: Amazing!! Don't think I ever would have got there without you. Great description and walk through your process. I'll be sure to reread multiple times to get a great grasp of the concepts. Appreciate your feedback for future posts as well. Thank you so much again!!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50128113

http://stackoverflow.com/q/50192965
has answer: http://stackoverflow.com/a/50193003
upvote count: 3
score: 3
has title: How to make user input not case sensitive?
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87402891
has answer: http://stackoverflow.com/a/50193354
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71276973
tagged with: python
has body: I want to create a function to filter which files I want to open and which months and day specifically. That way, the users need to input which city (files) they want to analyze on which particular month or day. However, I want the user to be able to input something that is not case sensitive. For example, the user can input 'chicago'/'CHICAGO"/"ChIcAgO" and the it still give you the right output and not the error handling message. Here is the code I use: def get_filters (): city_options = ['Chicago','New York City','Washington'] month_options = ['January','February','March','April','May','June','All'] day_options = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','All'] while True: try: city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n')) month = month_options.index(input('\nInsert month to filter by or "All" to apply no month filter! (January, February, etc.)\n')) day = day_options.index(input('\nInsert day of the week to filter by or "All" to apply no day filter! (Monday, Tuesday, etc.)\n')) return city_options[city].lower(), month_options[month].lower(), day_options[day].lower() except ValueError: print ("Your previous choice is not available. Please try again") def load_data (city,month,day): #load data file into DataFrame df = pd.read_csv(CITY_DATA[city].lower()) #convert start time column (string) to datetime df['Start Time']=pd.to_datetime(df['Start Time']) #create new column to extract month and day of the week from start time df['Month'] = df['Start Time'].dt.month df['Day_of_Week'] = df['Start Time'].dt.weekday_name #filter by month if applicable if month.lower()!= 'All': #use the index of the month list to get corresponding into months = ['January', 'February', 'March', 'April', 'May', 'June'] month = months.index(month) + 1 #filter by month to create new dataframes df = df[df['Month'] == month] if day.lower()!= 'All': #filter by day_of_week to create new DataFrames df =df…
has answer: http://stackoverflow.com/a/50193015
answer count: 4
has comment: http://stackoverflow.com/comment/87403575

http://stackoverflow.com/q/50134882
upvote count: 0
answer count: 1
has title: How to make key binding for history search work in python repl in OSX?
has comment: http://stackoverflow.com/comment/87645234
has body: I was using the below pystartup script in linux to make history and autocompletion on tab available in REPL Python. I have switched to OSX and I have modified the script such that tab completion works. But I am not able to figure out how to make the search work? Search couple of SO questions like Python interactive mode history and arrow keys But I don't want to uninstall the python version that comes with OSX as it may lead to some other dependency breakages. My python version is 2.7.10 Script import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(historyPath=historyPath): import readline readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") readline.set_history_length(1000) atexit.register(readline.write_history_file, historyPath) atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath
has comment: http://stackoverflow.com/comment/87645174
accepted answer: http://stackoverflow.com/a/50290187
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87677642
type: Question
linked to: http://stackoverflow.com/q/3483723
has answer: http://stackoverflow.com/a/50290187
has comment: http://stackoverflow.com/comment/87677597
tagged with: python
score: -1
tagged with: macos
has comment: http://stackoverflow.com/comment/87645165
type: AnsweredQuestion

http://stackoverflow.com/q/50168439
type: Question
has answer: http://stackoverflow.com/a/50177214
has title: Resolve an IP from a specific DNS server in Python
tagged with: python
type: UnansweredQuestion
has body: I want to resolve an IP to a hostname from a specific DNS server. socket.gethostbyaddr() uses default DNS server. I need to resolve ip with specific DNS server. I saw dnspython but do not know how to specify the DNS server to use for reverse lookup.
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/25957249
has comment: http://stackoverflow.com/comment/87354451
downvote count: 0
tagged with: dns
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/3898363
has comment: http://stackoverflow.com/comment/116536737

http://stackoverflow.com/q/50093478
has comment: http://stackoverflow.com/comment/87213146
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50127322
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow
has body: I have a Dataflow job that seems to be failing due to an overly large http_request body sent when attempting to create the job. This is the request header: {'content-length': '107245818', 'content-type': 'application/json', 'accept-encoding': 'gzip, deflate', 'accept': 'application/json', 'user-agent': 'x_xxxxxxxx'} Sending the request gives me: 413. That's an error. Your client issued a request that was too large. What's getting put into the request body that makes it so large? What can I do to reduce its size or get Google's servers to accept the request? I'm using the Apache Beam Python SDK version 2.4.0.
has title: Google Cloud Dataflow how to reduce size of http_request
score: 1

http://stackoverflow.com/comment/87366451
score: 0
comment on: http://stackoverflow.com/q/50174660
type: Comment
has text: stderr is saying:['bash: curl\xa0https://www.facebook.com: No such file or directory\n']
type: QuestionComment

http://stackoverflow.com/q/50108100
tagged with: mongodb
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/466345
answer count: 1
tagged with: python
has body: I am new to MongoDB and Python thus struggling with something that I'm sure is quite simple to do. In my collection (sample below), I have the date and time stored as a string. I need to convert them to Date (ISODate?) and Time data types so I can use built in MongoDB operators. For example, I want to use the $dayofWeek operator to find out whether a date is a weekday or weekend but I can't do that while it is a string. Ideally I would like guidance on how to accomplish this in Python (using Pymongo). If that is too cumbersome, I can do it using the mongo shell. Appreciate any help! { "_id" : ObjectId("xyz"), "Date" : "12/9/17", "Time" : "03:31:40", "Speaker" : "Joe", "Text" : "‎Sample Text" }
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50108202
linked to: http://stackoverflow.com/q/3974985
tagged with: pymongo
duplicate of: http://stackoverflow.com/q/3974985
has title: How do I convert string to ISODate and Time in MongoDB using Python?
favorite count: 0
type: Question

apache-spark
tags question: http://stackoverflow.com/q/50145024
tags question: http://stackoverflow.com/q/50209312
tags question: http://stackoverflow.com/q/50077107
tags question: http://stackoverflow.com/q/50151214
tags question: http://stackoverflow.com/q/50127304
tags question: http://stackoverflow.com/q/50183775
tags question: http://stackoverflow.com/q/50209425
tags question: http://stackoverflow.com/q/50108533
tags question: http://stackoverflow.com/q/50201717
tags question: http://stackoverflow.com/q/50182869
tags question: http://stackoverflow.com/q/50187800
tags question: http://stackoverflow.com/q/50132075
tags question: http://stackoverflow.com/q/50145195
tags question: http://stackoverflow.com/q/50172210
tags question: http://stackoverflow.com/q/50134185
tags question: http://stackoverflow.com/q/50168018
tags question: http://stackoverflow.com/q/50101178
tags question: http://stackoverflow.com/q/50104422
tags question: http://stackoverflow.com/q/50206582
tags question: http://stackoverflow.com/q/50186170
tags question: http://stackoverflow.com/q/50166012
tags question: http://stackoverflow.com/q/50183915
tags question: http://stackoverflow.com/q/50133318
tags question: http://stackoverflow.com/q/50219311
tags question: http://stackoverflow.com/q/50090614
tags question: http://stackoverflow.com/q/50202235
tags question: http://stackoverflow.com/q/50105631
tags question: http://stackoverflow.com/q/50086216
type: Tag
tags question: http://stackoverflow.com/q/50152946
tags question: http://stackoverflow.com/q/50210651
tags question: http://stackoverflow.com/q/50215791
tag name: apache-spark
tags question: http://stackoverflow.com/q/50196447
tags question: http://stackoverflow.com/q/50108601
tags question: http://stackoverflow.com/q/50219200
tags question: http://stackoverflow.com/q/50174227

django-rest-framework
tags question: http://stackoverflow.com/q/50101148
tags question: http://stackoverflow.com/q/50175875
tags question: http://stackoverflow.com/q/50144740
tags question: http://stackoverflow.com/q/50195834
tags question: http://stackoverflow.com/q/50118097
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/50084996
tags question: http://stackoverflow.com/q/50076552
tags question: http://stackoverflow.com/q/50086172
tags question: http://stackoverflow.com/q/50214621
tags question: http://stackoverflow.com/q/50085698
tags question: http://stackoverflow.com/q/50127835
tags question: http://stackoverflow.com/q/50158877
tags question: http://stackoverflow.com/q/50077843
tags question: http://stackoverflow.com/q/50095233
tags question: http://stackoverflow.com/q/50152764
type: Tag
tags question: http://stackoverflow.com/q/50196721
tags question: http://stackoverflow.com/q/50223523
tags question: http://stackoverflow.com/q/50151152
tags question: http://stackoverflow.com/q/50100199
tags question: http://stackoverflow.com/q/50185223
tags question: http://stackoverflow.com/q/50174149
tags question: http://stackoverflow.com/q/50214614
tags question: http://stackoverflow.com/q/50086489
tags question: http://stackoverflow.com/q/50169019
tags question: http://stackoverflow.com/q/50203063
tags question: http://stackoverflow.com/q/50149291
tags question: http://stackoverflow.com/q/50168670
tags question: http://stackoverflow.com/q/50123599

http://stackoverflow.com/comment/87458118
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50214775
score: 0
has text: Possible duplicate of [Not able to install python packages \[SSL: TLSV1\_ALERT\_PROTOCOL\_VERSION\]](https://stackoverflow.com/questions/49768770/not-able-to-install-python-packages-ssl-tlsv1-alert-protocol-version)

http://stackoverflow.com/comment/87381724
type: Comment
score: 0
has text: `Add Comment` is that correct?.... did you mean `comment_new`... because of the text `Add comment` , I thought it might be a typo
type: QuestionComment
comment on: http://stackoverflow.com/q/50182174

http://stackoverflow.com/a/50170722
score: 1
answers question: http://stackoverflow.com/q/50170673
type: Answer
has body: are you looking for &gt;&gt;&gt;a = "fi lou you".split() &gt;&gt;&gt; a ['fi', 'lou', 'you'] &gt;&gt;&gt; a[0] 'fi' &gt;&gt;&gt; a[1] 'lou' &gt;&gt;&gt; a[2] 'you' &gt;&gt;&gt; or there is something more complicated?
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87395295

http://stackoverflow.com/q/50084387
linked to: http://stackoverflow.com/q/11779143
tagged with: user-interface
upvote count: 1
tagged with: python
downvote count: 1
has title: How can i send data to a different language to be executed, then sends the answer back to the original?
score: 0
linked to: http://stackoverflow.com/q/48890238
has comment: http://stackoverflow.com/comment/87184526
tagged with: math
has comment: http://stackoverflow.com/comment/87184475
answer count: 1
favorite count: 0
type: Question
has body: I have a school project in which i need to create a program that derives simple equations and it requires some sort of GUI. I found out that Jupyter(has all Python tools) has the math tools i need to make my program. However, creating a GUI in python isn't as convenient as i thought. So, would it be possible to make a GUI using Visual Studio form design that sends data to a python program to be executed, then send the result back to be displayed in the visual studio GUI. For example, I enter an equation, "3x^3", in Visual Studio GUI program. The equation is then sent to a python program where it is executed and stored. Afterwards, it is sent back to the Visual Studio GUI and displayed as the answer.
has answer: http://stackoverflow.com/a/50084706
type: UnansweredQuestion

http://stackoverflow.com/q/50163249
tagged with: flask
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50168696
has comment: http://stackoverflow.com/comment/87344602
downvote count: 0
has comment: http://stackoverflow.com/comment/87353953
accepted answer: http://stackoverflow.com/a/50168696
tagged with: flask-sqlalchemy
has body: I'm pretty new to database design and web design, so please bear with me. I have a Flask app where I need to search in a database depending on arguments passed in the url, using flask-sqlalschemy, such as: .../index?part_number=123*321$description1=&amp;description2=TestText The asterisk will be interpreted as one or more char and ** as a single char. So I'll replace them with % and _, and terminate any special chars. My question is: In the database some fields will be empty strings and some will be Null. But I need to have them both be interpreted as an empty string, such that they will be returned when the arg is empty or *. I know I can do something along the lines of .like(part_number == None | part_number == '%'). But I only want to do this in the case where the search string is *, but how do I do that in a clever way when I have 10 different args, all and'ed together? Here's a snippet and boiled down version of the relevant code. I'm not quite sure how to make a small program that can run in itself for testing. filter_args = ['part_number', 'description1', 'description2'] # actual code has ~10 args filters = dict() for arg in filter_args: filter_str = request.args.get(arg, type=str, default='*') # get filter arg from url filter_str = '*' if filter_str == '' else filter_str # if the filter string is empty, search for all # Replace * by % and ** by _ and terminate special chars filter_str = filter_str.replace('\\', '\\\\') filter_str = filter_str.replace('%', '\%') filter_str = filter_str.replace('_', '\_') filter_str = filter_str.replace('**', '_') filter_str = filter_str.replace('*', '%') filters[filter_name] = filter_str parts = Part.query.filter( Part.part_number.ilike(filters['part_number']), # and Part.description1.ilike(filters['description1']), # and Part.description2.ilike(filters['description2']) ).order_by(Part.part_number)
tagged with: sqlalchemy
possible better answer: http://stackoverflow.com/a/57973507
favorite count: 0
type: Question
tagged with: postgresql
has answer: http://stackoverflow.com/a/57973507
answer count: 2
has title: Query for empty string or Null using SQLAlchemy
has comment: http://stackoverflow.com/comment/87344918
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/87459720
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50220638
type: QuestionComment
has text: @zython there are no additional code. the hw = linspace(0., 1.0, endpoint=False, Nw) with Nw e.g., 2000; eigv = np.zeros(N_kp, N_bd) with N_kp e.g., 8000, N_bd e.g. 60

http://stackoverflow.com/q/50083878
score: 0
tagged with: django-models
tagged with: python
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/50083915
tagged with: django
has title: How to pass django model field to function and have variables returned to context for use in template
has answer: http://stackoverflow.com/a/50083915
has body: I have some values that I collected from users in a form, which are saved to the DB. I want to take these values, perform an operation on them in function, and then return them so that I can use them in them alongside the other context. Here is my model: #models.py file class MyModel(models.Model): varA = models.PositiveIntegerField() varB = models.PositiveIntegerField() varC = models.PositiveIntegerField() And here is the outside function that I am using: #makecalc.py def MakeCalc(varA, varB, varC): #simplified from what I am actually doing varD = varA*varB**varC varE = varA+varB+varC return varD, varE And here is the views.py file: #views.py file from .makecalcs import MakeCalc class MySummary(DetailView): model = MyModel def get_vars(self): varD, varE = MakeCalc(varA, varB, varC) #Am I passing this correctly? return varD, varE #How do I send these to context? And finally the html: you input: {{ MyModel.varA }} you input:{{ MyModel.varB }} you input:{{ MyModel.varC }} I output:{{ varD }} #how do I call this? you input:{{ varE }} #how do I call this? So, my question is in the view, how do I add varD, varE to context so that I can use it alongside varA, varB, and varC from the model?
type: Question

http://stackoverflow.com/q/50096510
tagged with: django
tagged with: python
has body: I have a DetailView something like in views.py: views.py class CustomView(DetailView): context_object_name = 'content' model = models.AppModel template_name = 'dynamictemplate.html' def get_context_data(self, **kwargs): data = super(CustomView, self).get_context_data(**kwargs) &lt;...snipped...&gt; return data How could I update the model field, an IntegerField when the request from urls.py transfers to views.py. Let's suppose the name of IntegerField is clicks and when a user visits a particular link or passively, a model object from database, then how could I increment the clicks field of that object by 1.
possible better answer: http://stackoverflow.com/a/56230656
has answer: http://stackoverflow.com/a/56230656
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50096543
tagged with: url
has answer: http://stackoverflow.com/a/50096543
has title: Update a Model Field when DetailView encounter. [Django]
type: Question
answer count: 2

http://stackoverflow.com/comment/87355736
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50158877
type: QuestionComment
has text: I will get the postman today. I realise there are ways of getting the data as I want it, however, I am upgrading packages for an extremely large and complex application and if possible I would like to find a way to make request.data behave as before rather then trying to fix every place where it is used.

http://stackoverflow.com/comment/87312221
comment on: http://stackoverflow.com/a/50128014
type: Comment
has text: @supertommy An executor maintains a pool of threads or processes, spawning and destroying them on-demand. If you create an executor for each instance, you will be responsible for calling `close()` on the executor to ensure that its threads are deleted. Also, a new thread will be spawned on each call, which a thread pool is normally designed to prevent to improve efficiency.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87282203
type: Comment
comment on: http://stackoverflow.com/a/50131943
score: 0
type: AnswerComment
has text: (x,TextString,re.M|re.IGNORECASE).... x = user input TextString = the matching word in the file or the string.

http://stackoverflow.com/comment/87335732
type: Comment
comment on: http://stackoverflow.com/q/50158920
has text: @chrisz there can be separators in the title
score: 0
type: QuestionComment

http://stackoverflow.com/a/50169442
score: 0
has body: You've probably missed a very important part of those examples - the lines that follow the "recv()" call while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
type: Answer
answers question: http://stackoverflow.com/q/50168811

http://stackoverflow.com/comment/87378152
score: 2
comment on: http://stackoverflow.com/a/50180446
type: AnswerComment
has text: It may be worth parenthesizing `c1 & c2` for clarity; while Python's precedence puts `&` at higher precedence than `==`, many other languages have it the other way.
type: Comment

http://stackoverflow.com/comment/136678441
score: 0
type: Comment
has text: or you can use file headers in your text files? https://docs.ankiweb.net/importing/text-files.html#file-headers
comment on: http://stackoverflow.com/a/50953014
type: AnswerComment

http://stackoverflow.com/a/50218495
has comment: http://stackoverflow.com/comment/87456033
answers question: http://stackoverflow.com/q/50218054
has comment: http://stackoverflow.com/comment/87456345
has comment: http://stackoverflow.com/comment/87459796
has comment: http://stackoverflow.com/comment/87455572
score: 0
has comment: http://stackoverflow.com/comment/87456727
has body: The syntax in this case would be as follows: print(lst[i][0][0][2][0][0]) That nested structure is more than just a list of lists of tuples though. If that were the case, then the following minimal example list could have the 'a' referenced with a simple lst[0][0][0]: lst = ('a', 'b', 'c'), ('d', 'e', 'f')
type: Answer

http://stackoverflow.com/q/50097661
type: Question
has title: Using python to connect processes stdin/stdout
has body: I have a bash script (fifo1 and fifo2 are created with mkfifo): processor &lt;fifo1 &gt;fifo2 &amp; source &gt;fifo1 &amp; sink &lt;fifo2 &amp; which realizes the graph: source -&gt; processor -&gt; sink How would I go about doing this in a python script ?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87222769
tagged with: python
has answer: http://stackoverflow.com/a/50102810
score: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/87239221
answer count: 1

http://stackoverflow.com/comment/87379237
score: 2
comment on: http://stackoverflow.com/q/50181011
has text: I think you may be looking for [`ITaskBarList`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb774652(v=vs.85).aspx), which you can access via `win32com` from the [`pywin32`](https://github.com/mhammond/pywin32) library.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87189673
has text: Why was this downvoted?
comment on: http://stackoverflow.com/q/50080389
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50119991
upvote count: 2
answers question: http://stackoverflow.com/q/50119123
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50119123
has body: Running the code you show in the question you should get a warning MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. The solution is already given inside the warning, namely to give the axes a unique label, e.g. ax_polar = fig.add_axes(axes_coords, projection='polar', label="ax polar") # ... ax_image = fig.add_axes(axes_coords, label="ax image") The resulting dart board should then look like
has comment: http://stackoverflow.com/comment/87258123
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87257768
score: 2

http://stackoverflow.com/q/50150626
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/50151321
has comment: http://stackoverflow.com/comment/87318960
tagged with: python
has body: I want to remove N/A values in td of same class N/A Wall Street cool to eBay's profit technology Warnings about junk mail deluge technology Web radio takes Spanish rap global sport I want to scrape both category and title but in category want to ignore N/A values for td in parsed_html.body.findAll('td',{"class":lambda class_: class_ in ("category","title")}): print(td) category=td.parent.find("td",attrs={"class":"category"}).text if(not td.parent.find("i")): url=td.parent.find("a")["href"] I have tried matching string to N/A but it dint work
has comment: http://stackoverflow.com/comment/87319208
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50151321
has title: Ignore N/A values in td beautifulsoup
score: 1
answer count: 1
downvote count: 0
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/87319608

http://stackoverflow.com/comment/87350247
type: Comment
comment on: http://stackoverflow.com/a/50165871
type: AnswerComment
has text: Thank you for the response. Your answer is exactly what I need. However when I implement your line of code into the 'body' variable I get error. `ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().` I have even tried setting your line of code into a variable and inputting the variable into the 'body' variable.
score: 0

http://stackoverflow.com/q/50199840
tagged with: string
linked to: http://stackoverflow.com/q/5186839
favorite count: 0
has answer: http://stackoverflow.com/a/50199905
linked to: http://stackoverflow.com/q/16673994
possible better answer: http://stackoverflow.com/a/50199905
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6752485
score: 7
downvote count: 3
has answer: http://stackoverflow.com/a/50199924
tagged with: python
accepted answer: http://stackoverflow.com/a/50199924
upvote count: 10
has comment: http://stackoverflow.com/comment/87416257
has title: python3 replacing double backslash with single backslash
duplicate of: http://stackoverflow.com/q/4020539
tagged with: replace
type: Question
has comment: http://stackoverflow.com/comment/129375919
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87416285
has comment: http://stackoverflow.com/comment/87416343
linked to: http://stackoverflow.com/q/40452956
answer count: 2
has comment: http://stackoverflow.com/comment/87416456
has body: I need to replace \\ with \ in python3 in a complex string. I know that this question had been asked several times, but most of the time for simple strings so that none of the (accepted) answers really works for complex strings. This is also different from this one where the problem could be solved with .decode('unicode_escape') which does not work for this problem. See below. Assuming the string is: my_str = '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z\\x' Straight forward approach would be: my_str.replace('\\','\') which leads to: SyntaxError: EOL while scanning string literal This answer suggests using: my_str.replace('\\\\','\\') Which results in: '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z\\x' So, there is no change. This answer suggests: b = bytes(my_str, encoding='utf-8') b.decode('unicode-escape') But this doesn't work for such a complex string: UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 49-50: truncated \xXX escape Using decode (as suggested here) results in: my_str.decode('unicode_escape') AttributeError: 'my_str' object has no attribute 'decode' A combination of encoding and then decoding using unicode_esacpe returns a totally different string (probably due to using utf-16, but utf-8 results in an error, see above. Also, e.g. latin1 doesn't work): my_str.encode('utf-16').decode('unicode_escape') 'ÿþ\\\x00x\x00a\x005\x00\\\x00x\x00c\x000\x00\\\x00x\x00e\x006\x00a\x00K\x00\\\x00x\x00f\x009\x00\\\x00x\x008\x000\x00\\\x00x\x00b\x001\x00\\\x00x\x00c\x008\x00*\x00\x01\x00\x12\x00$\x00\\\x00x\x00f\x00b\x00p\x00\x1e\x00(\x004\x00\\\x00x\x00d\x006\x00{\x00;\x00Z\x00\\\x00x\x00'

http://stackoverflow.com/comment/87338862
type: Comment
has text: In my python shell, as soon as I enter "conn = ftplib.FTP_TLS...", I get a prompt for entering the passphrase. On entering "cert_password" and hitting enter the connection is established.
type: QuestionComment
comment on: http://stackoverflow.com/q/50160364
score: 0

http://stackoverflow.com/comment/87215419
score: 0
has text: @EnrikShaumann it's true that it can be handy to find the intersection of two nested lists. You can do it in a less optimized way using the `if` condition as @shahaf said in his comment.
type: AnswerComment
comment on: http://stackoverflow.com/a/50075072
type: Comment

http://stackoverflow.com/q/50094162
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50094458
tagged with: if-statement
has answer: http://stackoverflow.com/a/50094458
tagged with: python
tagged with: macos
has title: How to save a file on macos desktop using kml in python?
type: Question
tagged with: simplekml
has body: I have just read some of posts on how to save a kml file on macos desktop in Python but i couldn't find the answer.I try to locate the file path but it doesn't work. my code is: import pathlib import simplekml longitude = input("Enter longitude: ") latitude = input("Enter longitude: ") kml = simplekml.Kml() kml.newpoint(name="Sample", coords=[(longitude, latitude)]) kml.save("~/Desktop/bura/Points.kml") The problem starts with kml.save("~/Desktop/bura/Points.kml") it doesn't find the path and doesn't save the file.
answer count: 1
tagged with: kml

http://stackoverflow.com/a/50178311
upvote count: 2
type: Answer
has body: findwindows is a module name, not an attribute of Application object. This is correct code for the last line: app.window(title="Your Main Window").child_window(auto_id='btQuick').click_input() where "Your Main Window" should be changed to correct text of the top level window.
accepted answer of: http://stackoverflow.com/q/50178161
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50178161

http://stackoverflow.com/q/50093614
answer count: 1
has answer: http://stackoverflow.com/a/50093689
has title: DJANGO MEDIA_URL returns to same page instead of showing image
accepted answer: http://stackoverflow.com/a/50093689
favorite count: 0
type: Question
upvote count: 2
tagged with: django
tagged with: python
has body: There are lots of answer on how to upload media files, what are the correct configuration and how to serve it on our application. But my project seems to work nothing. The aim is simple: User uploads an image. Django displays it on. models.py class UploadImageModel(models.Model): image = models.FileField() title = models.CharField(max_length=100, null=True, blank=True) urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include("Image.urls")), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render from django.views import View from .forms import UploadImageModelForm from .models import UploadImageModel # Create your views here. class UploadImage(View): def get(self, request, *args, **kwargs): form = UploadImageModelForm() context = { "form":form, } return render(request, "index.html", context) def post(self, request, *args, **kwargs): form = UploadImageModelForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.title = str(instance.image) instance.save() context = { "form":form, "instance":instance, } return render(request, "index.html", context) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "Static") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "Media") index.html {% if instance.image %} &lt;img src="{{instance.image.url}}" alt="Image"/&gt; {% endif %} ERROR: After uploading an image named &lt;something&gt;.jpg, if I visit, 127.0.0.1:8000/media/1.jpeg, browser does not displays image, instead it shows index.html page. SO how to serve this media file correctly?
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/87511496
score: 0
comment on: http://stackoverflow.com/q/50204056
type: Comment
has text: In your example you don't pass a value for `post_id`, or `comment_rel`, when creating the comment. It follows that the foreign key is left NULL. Though you've defined `post_id` as NOT NULL (`nullable=False`), has that always been the case? In other words have you added that after creating the tables? If so, you'll have to migrate the DB schema as well. The second argument to `Session.add()` is `_warn`, which defaults to True and is undocumented. Why are you passing a string?
type: QuestionComment

http://stackoverflow.com/comment/87456566
type: Comment
comment on: http://stackoverflow.com/q/50216172
has text: Improved grammar and formatting a bit. Removed irrelevant regex tag.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87259334
type: QuestionComment
comment on: http://stackoverflow.com/q/50120806
has text: Can you _please_ replace those images with actual text? Please see [Why may I not upload images of code on SO when asking a question?](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question)
score: 5
type: Comment

http://stackoverflow.com/q/50200611
score: 4
upvote count: 4
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50201639
tagged with: installation
type: AnsweredQuestion
has body: I followed the steps to install Pyside on my macOS 13.13.4 on Python 3.6.4 on this Github page but after runninng pip install -U PySide, I got the following error message which seems to indicate that Pyside is not compatible to Python 3.6.4 ??: mymacs-MacBook-Pro:~ mymac$ pip install -U PySide Collecting PySide Using cached https://files.pythonhosted.org/packages/36/ac/ca31db6f2225844d37a41b10615c3d371587677efd074db29855e7035de6/PySide-1.2.4.tar.gz Complete output from command python setup.py egg_info: only these python versions are supported: [(2, 6), (2, 7), (3, 2), (3, 3), (3, 4)] ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/jq/yyp9q2fs1z5780k9l1_2ph4r0000gn/T/pip-install-zz9h16bx/PySide/ mymacs-MacBook-Pro:~ mymac$ Is I have anaconda, I looked at this website and this stackoverflow page I tried conda install -c anaconda pyside and conda install -c conda-forge pyside but both of them also threw this same error message: Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - pyqt - pyside Use "conda info &lt;package&gt;" to see the dependencies for each package. Many thanks in advance for your help!
favorite count: 0
downvote count: 0
duplicate of: http://stackoverflow.com/q/47362751
has comment: http://stackoverflow.com/comment/87419746
has comment: http://stackoverflow.com/comment/87419858
answer count: 1
has title: Is Pyside not compatible with python 3.6.4?
linked to: http://stackoverflow.com/q/41708923
type: Question
has answer: http://stackoverflow.com/a/50201639
tagged with: pyside
tagged with: python
linked to: http://stackoverflow.com/q/47362751

http://stackoverflow.com/q/50086452
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50086453
tagged with: grouping
tagged with: python
has title: A recipe to group/aggregate data?
upvote count: 6
has answer: http://stackoverflow.com/a/50097543
answer count: 4
type: Question
has body: I have some data stored in a list that I would like to group based on a value. For example, if my data is data = [(1, 'a'), (2, 'x'), (1, 'b')] and I want to group it by the first value in each tuple to get result = [(1, 'ab'), (2, 'x')] how would I go about it? More generally, what's the recommended way to group data in python? Is there a recipe that can help me?
accepted answer: http://stackoverflow.com/a/50086453
downvote count: 0
score: 6
possible better answer: http://stackoverflow.com/a/50086821
favorite count: 0
has answer: http://stackoverflow.com/a/50086821
has answer: http://stackoverflow.com/a/50656972

http://stackoverflow.com/q/50085847
has comment: http://stackoverflow.com/comment/87189782
has comment: http://stackoverflow.com/comment/87189169
has comment: http://stackoverflow.com/comment/87189560
accepted answer: http://stackoverflow.com/a/50085917
downvote count: 5
has comment: http://stackoverflow.com/comment/87187800
has answer: http://stackoverflow.com/a/50086562
has answer: http://stackoverflow.com/a/50085917
has comment: http://stackoverflow.com/comment/87189826
has comment: http://stackoverflow.com/comment/87189152
has body: Yes there are lots of topic about this. but my question is different. I wrote my code and it is; A = [1,2,3,4,4,4,5,6,6,6,6,6,7,8,8,8,8,8,8,7,7] def countFreq(A): n=len(A) count=[0]*n # Create a new list initialized with '0' for i in range(n): count[A[i]]+= 1 # increase occurrence for value A[i] result = [] for x in count: if x: result.append(x) return result print(countFreq(A)) output is; [1,1,1,3,1,5,3,6] that means, how many numbers there are, that function it counted. there is one "1" and there are five "6" and six "8" etc. but I want to just seeing most frequency number. as that code, just seeing 8. how can I do? Please show a way with my code. not different code. I don't want to built-in function or any ready code. please see a way just in my code. edit: Actually, I want to see from my code's output; A = [1,2,3,4,4,4,5,6,6,6,6,6,7,8,8,8,8,8,8,7,7] Most-frequency number is : 8 or A = [1,2,3,3,3] Most frequency number is : 3 or A = [1,1,1,2,3,4] most frequency number is : 1 I want this.. edit: In my question, teacher give us a hint, this is; "Hint: You may consider recording the number of occurrences of each digit in a new list, whose indices will be mapped to the input digit values." Please anyone that see it, show me a way with my code...
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87189494
answer count: 2
tagged with: frequency
upvote count: 2
possible better answer: http://stackoverflow.com/a/50086562
score: -3
has comment: http://stackoverflow.com/comment/87189069
tagged with: python
has title: Most-frequency number
has comment: http://stackoverflow.com/comment/87189095
has comment: http://stackoverflow.com/comment/87188994
has comment: http://stackoverflow.com/comment/87189744
has comment: http://stackoverflow.com/comment/87189041
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87189187

http://stackoverflow.com/a/50079400
type: Answer
downvote count: 0
has body: There are a few different tools that will help you make sure you are writing python2/3 compatible code. If you are interested in porting python2 code into python3, then the 2to3 program that comes with the standard library will try to convert a python 2 program to python 3. https://docs.python.org/2/library/2to3.html Another great tool is pylint. pylint is a python linter that will describe issues to you without fixing them. If you pip install pylint on a python3 environment, then it will analyze your code based on python 3's rules. If you use python 2 to install pylint, it will do the same but with python 2's rules. There are other popular and similar tools like flake8 or autopep8, but I am not familiar with them enough to advertise them.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50079311

http://stackoverflow.com/comment/87238889
type: Comment
type: QuestionComment
has text: where is your code and data?
comment on: http://stackoverflow.com/q/50110804
score: 0

http://stackoverflow.com/comment/87207111
comment on: http://stackoverflow.com/q/50093215
score: 0
type: Comment
has text: That's way beyond the scope of the question.
type: QuestionComment

http://stackoverflow.com/a/70490762
downvote count: 2
has body: For MacOS I had to set the global version pyenv global 3.10.1 and then exec $SHELL
score: -2
type: Answer
answers question: http://stackoverflow.com/q/50108753
upvote count: 0

http://stackoverflow.com/a/50135032
has body: Never call __init__() directly. This is the constructor method, and is called implicitly when you construct an object. https://docs.python.org/3/reference/datamodel.html#object.__init__ Try: serial.Serial("COM11", 115200, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE) And if that does not work, check the signature of this Serial class. It's possible that the first parameter you give is not supposed to be a str. But that should fix it. The doc to this __init__() is there: https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.__init__ And it feels that your parameters are all tangled up. Try naming them in the constructor.
has comment: http://stackoverflow.com/comment/87319030
answers question: http://stackoverflow.com/q/50134943
type: Answer
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87288627

http://stackoverflow.com/q/50144871
linked to: http://stackoverflow.com/q/48932847
favorite count: 0
has answer: http://stackoverflow.com/a/50144904
type: Question
upvote count: 4
tagged with: yum
tagged with: linux
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51810111
has title: No module named yum
has comment: http://stackoverflow.com/comment/87307880
linked to: http://stackoverflow.com/q/18632016
score: 2
tagged with: rhel
has comment: http://stackoverflow.com/comment/87307932
answer count: 3
has comment: http://stackoverflow.com/comment/87307869
downvote count: 2
has answer: http://stackoverflow.com/a/50145421
has body: I tried the solution @yum---no module named yum and "No module named yum" with Python 2.7 but didn't help,it sounds like the yum module is not a stock Python module and need to build yum against your Python 2.7 install,can anyone provide guidance on how to do this? machine details: [usernames@machine]$ cat /etc/*elease LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch Oracle Linux Server release 6.6 Red Hat Enterprise Linux Server release 6.6 (Santiago) Oracle Linux Server release 6.6 Error:- There was a problem importing one of the Python modules required to run yum. The error leading to this problem was: No module named yum Please install a package which provides this module, or verify that the module is installed correctly. It's possible that the above module doesn't match the current version of Python, which is: 2.7.12 (default, Aug 11 2016, 12:02:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] If you cannot solve this problem yourself, please go to the yum faq at: http://yum.baseurl.org/wiki/Faq
has comment: http://stackoverflow.com/comment/87309129
tagged with: redhat

http://stackoverflow.com/a/50083417
answers question: http://stackoverflow.com/q/50083391
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: When we say "block" we mean an element of code nested inside another syntactical element, like a method or function, or a structure like if or for. The exact definition depends on your language's syntax tree, something that's formally defined.

http://stackoverflow.com/comment/87371396
has text: The path can be in any dimension from 2-150. I'm evaluating a function of the path that isn't single-valued, so if I avoid self-intersections it will appear single-valued. Ideally I'd be able to set a tolerance for intersections in > 2 dimensions.
comment on: http://stackoverflow.com/q/50167737
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50186206
downvote count: 0
answers question: http://stackoverflow.com/q/50186129
upvote count: 18
score: 18
type: Answer
has body: Open .bashrc file nano ~/.bashrc. Type alias python=python3 on to a new line at the top of the file then save and close the file with ctrl+o and ctrl+x.

http://stackoverflow.com/q/50162137
answer count: 0
has body: I am relatively new to Python and spent at least two hours searching both the internet and now StackOverFlow and could not find out what the problem is here. My code was working in Python2, now persistent error message below. I even found this code online for an apparent answer to my question claiming it worked in python3, but it's not for me. Odd. import json, sys with open('2689364.json', 'r', encoding='utf-8') as json_data: d = json.load(json_data) print(d) UnicodeEncodeError: 'ascii' codec can't encode character '\xb6' in position 1938: ordinal not in range(128)
has comment: http://stackoverflow.com/comment/87342224
has title: Python3 now throwing ASCII error loading data from JSON file
has comment: http://stackoverflow.com/comment/87342100
has comment: http://stackoverflow.com/comment/87342204
type: Question
has comment: http://stackoverflow.com/comment/87345268
has comment: http://stackoverflow.com/comment/87342315
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: UnansweredQuestion
tagged with: load
has comment: http://stackoverflow.com/comment/87343970
has comment: http://stackoverflow.com/comment/87344018
linked to: http://stackoverflow.com/q/34837421
has comment: http://stackoverflow.com/comment/87343013
tagged with: ascii
score: 0

http://stackoverflow.com/a/50088480
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50088407
has body: Raspberry Pi's CPU is not fast enough, therefore, you must use the internet connection for the sending voice and take feedback API. In bellow link give implementation how to Using the Web Speech API on Raspberry Pi. https://www.brandoncorlett.com/blog/article/using-the-web-speech-api-on-raspberry-pi

http://stackoverflow.com/a/61804945
has body: # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) message=("is this correct") Print=(message) #store input answer = input("yes/no:") if answer == "yes": print("thank you") if answer == "no": print("hmm, are you sure?") #store input answer = input("yes/no:") if answer == "yes" : print("please call my suppot hotline: +47 476 58 266") if answer == "no" : print("ok goodbye:)") if someone had a solution for line 7 when answerd yes skiped to the end desplaing ok `goodbye:) thank you`
type: Answer
answers question: http://stackoverflow.com/q/50199244
score: 0

http://stackoverflow.com/a/50129574
has comment: http://stackoverflow.com/comment/87285654
answers question: http://stackoverflow.com/q/50125014
downvote count: 0
has comment: http://stackoverflow.com/comment/87286484
upvote count: 1
score: 1
has body: Unfortunately, that is a bug that has never been solved (yes, long time ago already). You can browse the source code of getElementById() function here if you have time. You can circumvent the issue by having to fetch the elements by their tag name, and then filter them using a combination of hasAttribute() and getAttribute() functions as I did in my solution here: Minidom getElementById not working
type: Answer

http://stackoverflow.com/comment/87422345
score: 0
has text: I understand, I already have a page of code written and nothing I type is manipulating the data from a csv file and printing appropriately to console. I did not ask for the whole answer just a push in the right direction and my question is specific to where I am stuck. I posted the assignment so someone with Python experience will know what I am trying to accomplish.
type: Comment
comment on: http://stackoverflow.com/q/50202415
type: QuestionComment

http://stackoverflow.com/q/50104182
tagged with: exponential
has comment: http://stackoverflow.com/comment/87225688
tagged with: python
type: AnsweredQuestion
tagged with: int
score: 0
has answer: http://stackoverflow.com/a/50167539
has body: When I execute this python code: integer = 18243150071292141317265306851 print(int(integer / 1)) The output I receive is: 18243150071292140668971909120 which does not equal to integer. Why does this happen and how can I make the output equal to integer?
answer count: 1
tagged with: floating-point
type: Question
has comment: http://stackoverflow.com/comment/87225523
has title: Converting exponential to integer in python
accepted answer: http://stackoverflow.com/a/50167539
has comment: http://stackoverflow.com/comment/87225602

http://stackoverflow.com/comment/87454913
type: Comment
has text: Not a length of 2, two specific characters. - and :
comment on: http://stackoverflow.com/a/50217979
type: AnswerComment
score: 0

http://stackoverflow.com/a/53833740
has body: Location of the generated cache may be in USER_PROFILE\AppData\Local\Temp\gen_py\PYTHON_VERSION\ . This can be useful if one wants to clear the cache.
answers question: http://stackoverflow.com/q/50127959
downvote count: 1
score: 17
upvote count: 18
type: Answer

http://stackoverflow.com/a/54479389
downvote count: 1
has body: If you don't mind using a third-party library give path a try. Its API is similar to pathlib.Path, but provides some additional methods, including Path.rmtree() to recursively delete a directory tree.
score: 5
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50186904

http://stackoverflow.com/q/50224553
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has body: I am creating an email process in python using smtplib. Got confused what value should I put in In-Reply-To/References Headers as per searching it should be the message id i am replying to, but upon reading the email from webmail I got this on one of the message that has reply: In-Reply-To: mid:3 References: mid:3 What does mid: 3 means? Because right now I am having trouble replying to a message it always sending as new message
favorite count: 0
type: Question
has title: EMAIL: In-Reply-To/References
tagged with: python
tagged with: smtplib
type: UnansweredQuestion

http://stackoverflow.com/q/50146025
tagged with: dictionary
has answer: http://stackoverflow.com/a/50146054
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50146896
answer count: 3
score: 1
possible better answer: http://stackoverflow.com/a/50146078
has title: Proper way to format Dictionary with multiple entries in Python
has body: I am just curious what is the best/most efficient way to structure a Dictionary in Python with multiple entries. It could be a dictionary of students, or employees etc. For sake of argument a 'Name' key/value and a few other key/value pairs per entry. For example, this works great if you have just one student... student_dict = {'name': 'John', 'age': 15, 'grades':[90, 80, 75]} Is this the right way to do it? One variable per dictionary entry? Somehow I don't think it is: student_1 = {'name': 'Fred', 'age': 17, 'grades':[85, 80, 75]} student_2 = {'name': 'Sean', 'age': 16, 'grades':[65, 70, 100]} student_3 = ... I'm sure there is a simple way to structure this where it would be easy to add new entries and search existing entries in one location, I just can't wrap my head around it. Thanks
accepted answer: http://stackoverflow.com/a/50146054
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50146078
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/50103666
has title: Remove not int elements in list
answer count: 2
has comment: http://stackoverflow.com/comment/87224434
duplicate of: http://stackoverflow.com/q/39824683
type: UnansweredQuestion
has body: Hi I have this task in python and I should remove all not int elements, the result of the code down below is [2, 3, 1, [1, 2, 3]] and I have no idea why in the result the list is not moved away. Only tested suggestions please, I mean working ones. # Great! Now use .remove() and/or del to remove the string, # the boolean, and the list from inside of messy_list. # When you're done, messy_list should have only integers in it messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] for ele in messy_list: print('the type of {} is {} '.format(ele,type(ele))) if type(ele) is not int: messy_list.remove(ele) print(messy_list)
score: 0
has comment: http://stackoverflow.com/comment/87224719
has comment: http://stackoverflow.com/comment/87224359
has answer: http://stackoverflow.com/a/50103853
linked to: http://stackoverflow.com/q/1207406
type: Question
has answer: http://stackoverflow.com/a/50103953
has comment: http://stackoverflow.com/comment/87224405
duplicate of: http://stackoverflow.com/q/1207406
linked to: http://stackoverflow.com/q/39824683
tagged with: python
has comment: http://stackoverflow.com/comment/87225544

http://stackoverflow.com/a/50188320
score: 3
accepted answer of: http://stackoverflow.com/q/50188279
upvote count: 3
has body: It's just fix in 1.1.2 update for balebot. try to get new version of balebot by pip. pip install balebot==1.1.2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50188279
type: Answer

http://stackoverflow.com/q/50194495
type: Question
has comment: http://stackoverflow.com/comment/87406217
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87406247
has body: I'm trying to test this code out: https://github.com/shanepm/500px-Bot/blob/master/500px.py Completely new to Phyton, but have programming skills. Running on Windows 10. I get this error msg: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The error is pointed to be at pendingFollowList = json.loads(f.read()) and on the rest of the json.loads...calls Have tried to pass one more argument on the line above: with open('pendingUsers.txt', 'r', **encoding='utf-8'**) as f: This did not help. Have also checked Encoding on .txt files as well. Anybody that knows what to do?? Thanks in advance! Alen
tagged with: python
score: 0
has title: JSON loading from the text file
answer count: 2
has answer: http://stackoverflow.com/a/50196457
has answer: http://stackoverflow.com/a/50197805
has comment: http://stackoverflow.com/comment/87411622
has comment: http://stackoverflow.com/comment/87411706
has comment: http://stackoverflow.com/comment/87406113

http://stackoverflow.com/comment/87443549
comment on: http://stackoverflow.com/q/50212950
has text: Well, if you want to insert the space between any Unicode letter and digit, use `re.sub(r'(?u)([^\W\d_])(\d)', r'\1 \2', s)`. Note that `(?u)` is only needed in Python 2.x. In Python 3.x, the patterns are Unicode-aware by default and you may remove it, `r'([^\W\d_])(\d)'`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87229303
comment on: http://stackoverflow.com/q/50106007
score: 0
has text: Have you tried select_related?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50188940
has body: Your calculation for time remaining is wrong. If it takes execution_time for progress steps. Then how much does it take for 1000 steps ? Simple cross multiply gives you the total time. Subtract it from the time already elapsed and that will give you the time remaining. remaining_time = execution_time * 1000 / progress - execution_time percent_complete = (progress / 1000) * 100 #You can simplify this if you like print("Progress:", percent_complete , "%, Estimated", remaining_time, "time remaining") Also your variable execution_time_1 is never defined
downvote count: 1
answers question: http://stackoverflow.com/q/50188907
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/comment/87374849
type: Comment
comment on: http://stackoverflow.com/a/50178539
has text: @Moia it's easy to transform it though, plus PIL might be a better option for this
type: AnswerComment
score: 1

http://stackoverflow.com/comment/136174913
type: Comment
has text: This however assumes that one column at least has numerical dtype, which OP has not specified.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/77239535

http://stackoverflow.com/q/50083366
tagged with: gaussian
has answer: http://stackoverflow.com/a/50083396
tagged with: python
tagged with: opencv
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39316447
answer count: 1
downvote count: 3
tagged with: image-processing
has body: I am following this course on computer vision: https://in.udacity.com/course/introduction-to-computer-vision--ud810 The instructor explains how gaussian filter causes blurring of image. The instructor uses matlab to demonstrate it but I am using python 3 with opencv. I ran the following code: import cv2 from matplotlib import pyplot as pl image = cv2.imread("Desert.jpg") blur = cv2.GaussianBlur(image,(95,95),5) cv2.imshow("desert", image) pl.imshow(blur) pl.xticks([]), pl.yticks([]) pl.show() This is the original image: And this is is the "blur" image: The image is blurred, no doubt. But how colors have interchanged ? The mountain is blue while the sky is brick red ?
favorite count: 0
has title: Why this color reversal?
duplicate of: http://stackoverflow.com/q/39316447
type: Question
accepted answer: http://stackoverflow.com/a/50083396
upvote count: 0
score: -3

http://stackoverflow.com/comment/87296428
has text: Try `l = [((a, b), c) for [(a, b), c] in l]`
comment on: http://stackoverflow.com/q/50139038
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50104837
has body: My python script takes hours to run since the code is not efficient. Can I make this code faster? texts = pd.read_csv("texts.csv", sep='\t') # has each line (100k total lines) with strings.Eg: ABVDGSVHSJ vectors = pd.read_csv("word_n_vectors.csv", sep='\t') # has unique words (1000) in 1st column and corresponding... # ... 100 dimension vector in next 100 columns vectors_seq = open('output.csv', 'w') # save 100 dimension vector for each line by the following code with vectors_seq: writer = csv.writer(vectors_seq, delimiter="\t") for sequence in texts["text"]: # "text" column contains strings: ABHDJHVD.... vec = np.zeros([1,100]) # to use when "word_n_vectors.csv" doesn't have the selected word. i= 0 data = np.array([sequence[i:i+3] for i in range(0, len(sequence), 3)]) # split the data to 3 letter words for tri in data: a = vectors['0']==tri # get the location word in "vectors" if not any(a): a=np.zeros([1,100]) # if no word present in "vectors" else: a = np.where(a)[0] a = vectors.iloc[a,1:101] # get the 100 D vectors from "vectors" a = np.array(a) vec = np.add(vec,a) # add all the 100 D vectors in each line in loop writer.writerows(vec) # and save new 100 D vectors in each new row print("Writing complete")
has comment: http://stackoverflow.com/comment/87229117
has comment: http://stackoverflow.com/comment/87229016
type: Question
tagged with: performance
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87227428
tagged with: python
tagged with: multicore
tagged with: nlp
has title: How to make python loop faster for getting vectors corresponding to words and writing to a csv?
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87803945

http://stackoverflow.com/comment/129557487
has text: this does not look like it will remove non-empty subdirectories of basedir? The recursive answer from @maf88 looks better.
score: 0
comment on: http://stackoverflow.com/a/60869751
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50111709
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87266902
tagged with: pytest
has comment: http://stackoverflow.com/comment/87240683
score: 1
favorite count: 0
type: Question
has body: I am new to pytest and trying to use fixture. I have the following code: I am trying to convert the following logic to fixture: I have a function called "kubernetes_.fixture" which is a fixture returning me a function fixture. and then I make a list of those and send it to other function. But, when I change the logic to merge to 2 logic in one fixture function I get the following error. pod2 = (kubernetes_.fixture([samelink_pod2], namespace='namespace')) pod3 = (kubernetes_.fixture([difflink_pod3], namespace='namespace')) pod4 = (kubernetes_.fixture([diff_leaf_pod4], namespace='namespace')) pod5 = (kubernetes_.fixture([diff_leaf_pod5], namespace='namespace')) @pytest.fixture def pod_list_fixture(pod2, pod3, pod4, pod5): return [pod2, pod3, pod4, pod5] def test_same_node_traffic(pod_list_fixture): connected_ips = [pod.ip() for pod in pod_list_fixture]&lt;&lt;&lt;&lt; Never get ERRROR HERE ________________________________________________________________ @pytest.fixture def pod_list_fixture(): fixlist = [] for pod in podlist: fixture = (kubernetes_.fixture([pod], namespace='namespace')) fixlist.append(fixture) return fixlist def test_same_node_traffic(pod_list_fixture): connected_ips = [pod.ip() for pod in pod_list_fixture] &lt;&lt;&lt; Get a Error here saying function object doesnt have attribute 'ip' TRACEBACK: pod_list_fixture = [&lt;function fixture.&lt;locals&gt;._fixture at 0x7f9678734268&gt;, &lt;function fixture.&lt;locals&gt;._fixture at 0x7f96787348c8&gt;, &lt;func...&gt;, &lt;function fixture.&lt;locals&gt;._fixture at 0x7f9678734840&gt;, &lt;function fixture.&lt;locals&gt;._fixture at 0x7f9678734d08&gt;, ...] def test_different_uplink(pod_list_fixture): &gt; connected_ips = [pod.ip() for pod in pod_list_fixture] test_remote.py:58: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .0 = &lt;list_iterator object at 0x7f965865c860&gt; &gt; connected_ips = [pod.ip() for pod in pod_list_fixture] E AttributeError: 'function'…
has title: Pytest issue with fixture
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87305165

http://stackoverflow.com/q/50138592
possible better answer: http://stackoverflow.com/a/50139242
type: Question
has comment: http://stackoverflow.com/comment/87295709
answer count: 2
has title: Python3 how to get current and next directory from os.walk?
score: 1
has body: How do I traverse through a directory and print out the current directory and the next directory in the iteration? currentdir = '/tmp/test' for root, dirs, files in os.walk(currentdir): print("Current dir: {}: ".format(root)) print("Next dir: {}: ".format(next(os.walk(root))))
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50138796
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87295917
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87297018
tagged with: python
accepted answer: http://stackoverflow.com/a/50138796
has answer: http://stackoverflow.com/a/50139242

http://stackoverflow.com/a/50161242
has comment: http://stackoverflow.com/comment/87352503
type: Answer
has body: TLDR: Regex capturing groups can be used for the suffix parameter. The suffix parameter tells pandas.wide_to_long which columns it should include in the transformation based on the suffix after the stub. The default behavior of wide to long assumes that your columns are labeled with numbers so for instance columns A1, A2, A3, A4 will work fine without specifying the suffix parameter, while Aone, Atwo, Athree, Afour will fail. As explained, it also has various other uses in the rare cases that your columns may be A1, A2, A3, A4, A100, and you don't want to actually include A100 because it isn't actually related to the other A# columns. Here are some illustrative examples. import pandas as pd df = pd.DataFrame({'id': [1,2], 'A_1': ['a', 'b'], 'A_2': ['aa', 'bb'], 'A_3': ['aaa', 'bbb'], 'A_person': ['Mike', 'Amy']}) pd.wide_to_long(df, stubnames='A_', i='id', j='num') # A_person A_ #id num #1 1 Mike a #2 1 Amy b #1 2 Mike aa #2 2 Amy bb #1 3 Mike aaa #2 3 Amy bbb Because the default behavior is to only consider numbers, 'A_person' was ignored. If you wanted to add that to the conversion, then you would use the suffix parameter. Let's tell it we want either numbers or words. pd.wide_to_long(df, stubnames='A_', i='id', j='suffix', suffix='(\d+|\w+)') # A_ #id suffix #1 1 a #2 1 b #1 2 aa #2 2 bb #1 3 aaa #2 3 bbb #1 person Mike #2 person Amy Now if your df starts without numeric suffixes, you can take care of that with the suffix parameter too. The default call will fail because it expects numbers, but telling it to look for words gives you what you want. df = pd.DataFrame({'id': [1,2], 'A_one': ['a', 'b'], 'A_two': ['aa', 'bb'], 'A_three': ['aaa', 'bbb'], 'A_person': ['Mike', 'Amy']}) pd.wide_to_long(df, stubnames='A_', i='id', j='num') #Empty DataFrame #Columns: [A_three, A_person, A_one, A_two, A_] #Index: [] pd.wide_to_long(df, stubnames='A_', i='id', j='suffix', suffix='\w+') # A_ #id suffix #1 one a #2 one b #1 person Mike #2 person Amy #1 three aaa #2 three bbb #1…
accepted answer of: http://stackoverflow.com/q/50160774
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50160774
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/87352404

http://stackoverflow.com/q/50181366
score: 0
has body: I have a dataframe of the following type df = pd.DataFrame({'Days':[1,2,5,6,7,10,11,12], 'Value':[100.3,150.5,237.0,314.15,188.0,413.0,158.2,268.0]}) Days Value 0 1 100.3 1 2 150.5 2 5 237.0 3 6 314.15 4 7 188.0 5 10 413.0 6 11 158.2 7 12 268.0 and I would like to add a column '+5Ratio' whose date is the ratio betwen Value corresponding to the Days+5 and Days. For example in first row I would have 3.13210368893 = 314.15/100.3, in the second I would have 1.24916943522 = 188.0/150.5 and so on. Days Value +5Ratio 0 1 100.3 3.13210368893 1 2 150.5 1.24916943522 2 5 237.0 ... 3 6 314.15 4 7 188.0 5 10 413.0 6 11 158.2 7 12 268.0 I'm strugling to find a way to do it using lambda function. Could someone give a help to find a way to solve this problem? Thanks in advance. Edit In the case I am interested in the "Days" field can vary sparsly from 1 to 18180 for instance.
tagged with: pandas
has title: Compute a ratio conditional on the value in the column of a panda dataframe
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/88179698
answer count: 2
has answer: http://stackoverflow.com/a/50181599
has comment: http://stackoverflow.com/comment/87380019
has answer: http://stackoverflow.com/a/50181711
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50183045
has comment: http://stackoverflow.com/comment/87396507
tagged with: opencv3.0
favorite count: 0
has comment: http://stackoverflow.com/comment/87398843
tagged with: python
tagged with: image-processing
answer count: 2
downvote count: 0
type: UnansweredQuestion
upvote count: 6
has answer: http://stackoverflow.com/a/55725559
score: 6
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50190203
has title: Finding contours of a two-part letter
type: Question
has body: Suppose that I have an image of letters and I want to find the region of those letters. I have wrote this code: MIN_CONTOUR_AREA = 10 img = cv2.imread("alphabets.png") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blured = cv2.blur(gray, (5,5), 0) img_thresh = cv2.adaptiveThreshold(blured, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2) imgContours, Contours, Hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for contour in Contours: if cv2.contourArea(contour) &gt; MIN_CONTOUR_AREA: [X, Y, W, H] = cv2.boundingRect(contour) cv2.rectangle(img, (X, Y), (X + W, Y + H), (0,0,255), 2) cv2.imshow('contour', img) But the code above has this output: result What can I do to find contour for letters that are not continuous like 'i' or Arabic letters?
tagged with: opencv

http://stackoverflow.com/q/50199175
tagged with: swampy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87415597
has comment: http://stackoverflow.com/comment/87415050
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: turtle-graphics
accepted answer: http://stackoverflow.com/a/50199388
upvote count: 2
answer count: 1
downvote count: 0
has body: I have the following code to play with turtle within turtleworld: &gt;&gt;&gt; from swampy.TurtleWorld import * &gt;&gt;&gt; world = TurtleWorld() &gt;&gt;&gt; bob = Turtle() &gt;&gt;&gt; fd(bob, 100) &gt;&gt;&gt; bob.position() &gt;&gt;&gt; bob.reset() There is no issue with executing the fd(bob, 100) line but when I try to check turtle position it returns AttributeError: Traceback (most recent call last): File "&lt;pyshell#13&gt;", line 1, in &lt;module&gt; bob.position() AttributeError: 'Turtle' object has no attribute 'position' Why is this happening? What am I missing? I have read the documentation and it states that both position() and reset() methods should be available.
has answer: http://stackoverflow.com/a/50199388
has title: Python Turtle AttributeError: 'Turtle' object has no attribute 'position'

http://stackoverflow.com/a/50121073
has body: You can use two delimiters in read_csv such as: pd.read_csv( path_file, sep=':|\t', engine='python') Note the engine='python' to prevent a warning. EDIT: with your input format it seems difficult, but with input like: A one : some data A two : some other data B one : foo B three : bar with a \t as delimiter after A or B, then you get a multiindex by: pd.read_csv(path_file, sep=':|\t', header = None, engine='python', names = ['index_1', 'index_2', 'Value'] ).set_index(['index_1', 'index_2'])
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50116542
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50116542

http://stackoverflow.com/q/50132962
tagged with: python
has title: Does not match name having space in it Django Python
score: 0
has body: try: version_number = request.json['version_number'] name = request.json['dispensary_name'] name = str(name) if version_number == 1.0: if Dispensary.objects.filter(name__iexact=name).exists(): return {SUCCESS: False, MESSAGE: 'Dispensary name already exists.'} Does not match name having space in it.What should I do for this.
has comment: http://stackoverflow.com/comment/87283962
has comment: http://stackoverflow.com/comment/87283992
type: Question
has comment: http://stackoverflow.com/comment/87284511
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50158663
tagged with: pandas
score: 1
has title: Pandas - chaining multiple .loc methods.
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50158886
has comment: http://stackoverflow.com/comment/87495061
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50158886
accepted answer: http://stackoverflow.com/a/50158988
has body: In pandas, is there a way to combine both indexing by label and indexing by boolean mask in a single .loc call? Currently I have this: df.loc[start_date:end_date]np.is_busday(x, holidays=dd.all_holidays) for x in df.index Which works fine but I am curious if there is a better alternative. Thanks.
has answer: http://stackoverflow.com/a/50158988
type: AnsweredQuestion

http://stackoverflow.com/a/50204314
has body: I resolve this issue doing it: First, I Make a RDD using filter to remove unecessary data, acording the number of parameter N. RDDFilter = DadosAgrupadosPorChaveOrdenados.filter(lambda x: n &lt; len(x[1])) After it, I do another RDD mounting data, like I needed: DadosFinal = RDDFilter.map(lambda x: (x[0], [x[1][i][1] for i in range(0,int(n))], x[1][int(n)][1])) Thank you so much, for any help.
type: Answer
answers question: http://stackoverflow.com/q/50193599
score: 0

http://stackoverflow.com/q/50207974
has answer: http://stackoverflow.com/a/50208481
has title: Problems with underscore in the domain name
tagged with: dns
tagged with: django
has comment: http://stackoverflow.com/comment/87433202
tagged with: python
has comment: http://stackoverflow.com/comment/87475336
has comment: http://stackoverflow.com/comment/87487166
has comment: http://stackoverflow.com/comment/87433024
has body: Let me first describe my original problem, and solution: I have several docker-compose files which describe different parts of my application. The parts are developed and deployed independently, so they can not be integrated into a single compose file. But those components need to communicate with each other, and the solution I am using at the moment is to have an external network (bridge) which all services are connecting to. So far so good, and I can indeed connect to my service started with any docker compose file as long as I am connected to the custom bridge network: $ docker run --network=mynet --rm --name ping_test -it xenial-networking bash root@0319469f7951:/# ping -c 1 proj_web_1 PING proj_web_1 (172.30.0.3) 56(84) bytes of data. 64 bytes from 172.30.0.3: icmp_seq=1 ttl=64 time=0.071 ms --- proj_web_1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.071/0.071/0.071/0.000 ms Why am using proj_web_1? Because that is the DNS entry that docker compose is creating. This works fine, and nobody cares that underscores are not that great in domain names. Nobody ... except django it seems: ERROR Invalid HTTP_HOST header: 'proj_web_1:8000'. The domain name provided is not valid according to RFC 1034/1035. 172.30.0.5 - admin [07/May/2018:05:41:53 +0000] "OPTIONS /api/v1/expansions/ HTTP/1.1" 400 58663 "-" "python-requests/2.18.4" It seems that docker-compose does not support using hyphens instead of underscores. It could be that I can workaround this by enabling DEBUG in my django service. Is there a cleaner way of enabling this, without running in django debug mode? Is there a way to tell docker compose to stop using underscores?
tagged with: docker
linked to: http://stackoverflow.com/q/2180465
has comment: http://stackoverflow.com/comment/87433329
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87433577
has comment: http://stackoverflow.com/comment/87484959
tagged with: docker-compose
has comment: http://stackoverflow.com/comment/87433374
has comment: http://stackoverflow.com/comment/87487466
has answer: http://stackoverflow.com/a/50235066
score: 7
has comment: http://stackoverflow.com/comment/87481158
downvote count: 1
has comment: http://stackoverflow.com/comment/87447188
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50208481
accepted answer: http://stackoverflow.com/a/50235066
has comment: http://stackoverflow.com/comment/87433396
has comment: http://stackoverflow.com/comment/87433281
upvote count: 8

http://stackoverflow.com/comment/87276548
score: 0
type: Comment
has text: This means the property acts like a string, not like a dict. And what's the point of converting it to a dict and then throwing the result away at deletion time? Also, `jsons.dump(self.__foo)`?
comment on: http://stackoverflow.com/a/50129255
type: AnswerComment

http://stackoverflow.com/comment/87431609
comment on: http://stackoverflow.com/a/50206830
type: Comment
type: AnswerComment
has text: for my regular / i have an index.html for it. The entire purpose for this is to show a red banner at the top of the index page that says "welcome back, {{user.get_username}}" when they login, but not for people who haven't. Maybe there is a way you can help me with that?
score: 0

wifi
tags question: http://stackoverflow.com/q/50219985
tag name: wifi
type: Tag

http://stackoverflow.com/q/50127226
tagged with: python
has title: Plotting Histogram with conditional bins range
tagged with: pandas
score: 1
answer count: 1
tagged with: histogram
downvote count: 1
has body: I have written following code to plot histogram from given set of values in csv file column : import pandas as pd import matplotlib.pyplot as plt import numpy class createHistogram(): def __init__(self,csv_file): self.csv_file = csv_file def load_csv(self): bin_edge = range(0,100,10) tp_data = pd.read_csv(self.csv_file) dataframe = pd.DataFrame(tp_data)['tp'] dataframe.hist(bins=bin_edge) plt.show() return tp_data Here I am getting histogram if values are less than 10, 20 ... and so on, but i want it should be bin_value&lt;=10 10&lt; bin_value &lt;=20 20 I am new to panda module..
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50128868
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/87233218
comment on: http://stackoverflow.com/a/50107305
type: Comment
has text: @Jean-FrançoisFabre agree, it lost some accentuate
score: 0
type: AnswerComment

http://stackoverflow.com/q/50196887
answer count: 1
tagged with: python
tagged with: dictionary
has title: Python - Parsing Oxford Dictionary API JSON Output
type: Question
has body: I would like to extract the first definition value from the following json output. Additionally, it would also be nice to print all of the definition values line by line. { "metadata": { "provider": "Oxford University Press" }, "results": [ { "id": "ace", "language": "en", "lexicalEntries": [ { "entries": [ { "etymologies": [ "Middle English (denoting the âoneâ on dice): via Old French from Latin as âunity, a unitâ" ], "grammaticalFeatures": [ { "text": "Singular", "type": "Number" } ], "homographNumber": "100", "senses": [ { "definitions": [ "a playing card with a single spot on it, ranked as the highest card in its suit in most card games" ], "domains": [ "Cards" ], "examples": [ { "registers": [ "figurative" ], "text": "life had started dealing him aces again" }, { "text": "the ace of diamonds" } ], "id": "m_en_gbus0005680.006", "short_definitions": [ "playing card with single spot on it, ranked as highest card in its suit in most card games" ] }, { "definitions": [ "a person who excels at a particular sport or other activity" ], "domains": [ "Sport" ], "examples": [ { "text": "a motorcycle ace" } ], "id": "m_en_gbus0005680.010", "registers": [ "informal" ], "short_definitions": [ "person who excels at particular sport or other activity" ], "subsenses": [ { "definitions": [ "a pilot who has shot down many enemy aircraft" ], "domains": [ "Air Force" ], "examples": [ { "text": "a Battle of Britain ace" } ], "id": "m_en_gbus0005680.011", "short_definitions": [ "pilot who has shot down many enemy aircraft" ] } ], "thesaurusLinks": [ { "entry_id": "ace", "sense_id": "t_en_gb0000173.001" } ] }, { "definitions": [ "(in tennis and similar games) a service that an opponent is unable to return and thus wins a point" ], "domains": [ "Tennis" ], "examples": [ { "text": "Nadal banged down eight aces in the set" } ], "id": "m_en_gbus0005680.013", "short_definitions": [ "(in tennis and similar games) service that opponent is unable to return and thus wins point" ], "subsenses":…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50196942
score: 0
has answer: http://stackoverflow.com/a/50196942
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/87452645
has text: Did you write that? did you test it with your example csv's?
comment on: http://stackoverflow.com/q/50217771
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50229767
has body: You can still use the Estimator API. You just need to return a tf.estimator.EstimatorSpec. During training, it would look like this: tf.estimator.EstimatorSpec(mode, predictions, loss, trainOp) where trainOp is typically the result of an optimization step (this is where your error function derivative would be used). You can also use the lower level APIs but you would lose all the advantages of the Estimator API, which, for example, allow you to export your trained model easily for inference serving.
answers question: http://stackoverflow.com/q/50229355
has comment: http://stackoverflow.com/comment/87503658
has comment: http://stackoverflow.com/comment/87480447
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87479302
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50229355
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87513560

http://stackoverflow.com/a/55980935
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50197643
type: Answer
has body: I achieved the same thing using threading library, which is considered a lighter way to spawn new processes. Assumption: Each task will download videos to a different directory. import os import threading import youtube_dl COOKIE_JAR = "path_to_my_cookie_jar" def download_task(videos, output_dir): if not os.path.isdir(output_dir): os.makedirs(output_dir) if not os.path.isfile(COOKIE_JAR): raise FileNotFoundError("Cookie Jar not found\n") ydl_opts = { 'cookiefile': COOKIE_JAR, 'outtmpl': f'{output_dir}/%(title)s.%(ext)s' } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(videos) if __name__ == "__main__": output_dir = "./root_dir" threads = [] for playlist in many_playlists: output_dir = f"{output_dir}/playlist.name" thread = threading.Thread(target=download_task, args=(playlist, output_dir)) threads.append(thread) # Actually start downloading for thread in threads: thread.start() # Wait for all the downloads to complete for thread in threads: thread.join()
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50197643
score: 3
downvote count: 0

http://stackoverflow.com/comment/87256383
type: AnswerComment
comment on: http://stackoverflow.com/a/50119174
has text: Thanks, this is what i want but it takes 32seconds
type: Comment
score: 0

http://stackoverflow.com/q/50139043
has title: How to combine/merge Columns within the same Dataframe in Pandas?
has comment: http://stackoverflow.com/comment/87300691
has answer: http://stackoverflow.com/a/50139138
type: AnsweredQuestion
tagged with: pandas
score: 1
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87303244
has body: I have a data frame similar to this: 0 1 2 3 4 5 0 1001 1 176 REMAINING US SOUTH 1 1002 1 176 REMAINING US SOUTH What I would like to do is to combine columns 3,4, and 5 to create on column that has all of the data in columns 3,4, and 5. Desired output: 0 1 2 3 0 1001 1 176 REMAINING US SOUTH 1 1002 1 176 REMAINING US SOUTH I've already tried hbadef['6'] = hbadef[['3', '4', '5']].apply(lambda x: ''.join(x), axis=1) and that didn't work out. Here is the stacktrace when I implement hbadef['3'] = hbadef['3'] + ' ' + hbadef['4'] + ' ' + hbadef['5'] Stacktrace: TypeError Traceback (most recent call last) pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() TypeError: an integer is required During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 2524 try: -&gt; 2525 return self._engine.get_loc(key) 2526 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() KeyError: '3' During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() TypeError: an integer is required During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-62-2da6c35d6e89&gt; in &lt;module&gt;() ----&gt; 1 hbadef['3'] = hbadef['3'] + ' ' + hbadef['4'] + ' ' + hbadef['5'] 2 # hbadef.drop(['4', '5'], axis=1) 3 # hbadef.columns = ['MKTcode', 'Region'] 4 5 # pd.concat( ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self,…
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50139138
has answer: http://stackoverflow.com/a/50139123
possible better answer: http://stackoverflow.com/a/50139123
answer count: 2
has comment: http://stackoverflow.com/comment/87300724
upvote count: 1
tagged with: python

http://stackoverflow.com/q/50147260
has comment: http://stackoverflow.com/comment/87312739
has comment: http://stackoverflow.com/comment/87312823
has answer: http://stackoverflow.com/a/50147512
answer count: 3
has answer: http://stackoverflow.com/a/50147455
has comment: http://stackoverflow.com/comment/87313059
score: -1
has comment: http://stackoverflow.com/comment/87312995
has title: How to extract variables from boolean logic expression in python
has comment: http://stackoverflow.com/comment/87312748
type: Question
has answer: http://stackoverflow.com/a/50147302
tagged with: extract
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
has body: I want to extract variables from boolean logic expression ex) Input: E= A or B or (C and not D) -&gt; String Output: ['E', 'A', 'B', 'C', 'D'] -&gt; List
tagged with: string
has comment: http://stackoverflow.com/comment/87312965
favorite count: 0
has comment: http://stackoverflow.com/comment/87313133

http://stackoverflow.com/comment/87375749
type: AnswerComment
comment on: http://stackoverflow.com/a/50178390
has text: Thanks for the example!
type: Comment
score: 0

http://stackoverflow.com/comment/87456848
comment on: http://stackoverflow.com/q/50219781
score: 1
has text: z is a scalar; as your comment says, you need an array.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50109284
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89703500
score: -1
has body: I need to solve a system equation using the SymPy library in Python. For example: y = x ** 2 x = 2 Solution: y = 4 How to do this with SymPy?
tagged with: sympy
has comment: http://stackoverflow.com/comment/87237490
upvote count: 0
has answer: http://stackoverflow.com/a/50109355
has title: Solve a system of equations using SymPy
has comment: http://stackoverflow.com/comment/87236383
answer count: 1

http://stackoverflow.com/a/50096558
has comment: http://stackoverflow.com/comment/87210395
has comment: http://stackoverflow.com/comment/87217057
type: Answer
accepted answer of: http://stackoverflow.com/q/50096277
score: 0
answers question: http://stackoverflow.com/q/50096277
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87211329
has comment: http://stackoverflow.com/comment/87211267
has body: This is one approach. Using a check flag. checkFlag Ex: lst=[['*PF4', 'PF6', '#', 'PF2', '\PWD(5D)','PWD(30)'], ['*PF4#', 'PF2', '\PWD(89)','PWD(31)'], ['*PF4', 'PF6', '#', 'PF2', '\PWD(89)','PWD(31)']] def getValue(lst): checkFlag = False res = [] for i in lst: if checkFlag: if i.endswith("#"): res[-1] = res[-1]+i checkFlag = False else: res.append(i) if i.startswith("*") and i.endswith("#"): res.append(i) elif i.startswith("*"): res.append(i) checkFlag = True return res print(getValue(lst[0])) print(getValue(lst[1])) print(getValue(lst[2])) Output: ['*PF4', 'PF6#'] ['*PF4#'] ['*PF4', 'PF6#']

http://stackoverflow.com/comment/87349764
type: Comment
type: QuestionComment
score: 1
has text: Also see https://nedbatchelder.com/text/names.html
comment on: http://stackoverflow.com/q/50165912

http://stackoverflow.com/comment/87447652
has text: Have you tried to open a remote file with Spyder (from context menu of your file manager)? (I have no experience with "connect to server", but that is the first thing I'd try).
comment on: http://stackoverflow.com/q/50214897
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87230168
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50106387
score: 0
has text: Maybe wrong indentation? You indent every thing after `if units % 2 == 0:`

http://stackoverflow.com/q/50209229
score: 0
tagged with: resultset
upvote count: 1
has answer: http://stackoverflow.com/a/50214782
favorite count: 0
type: Question
tagged with: amazon-dynamodb
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50214782
tagged with: amazon-web-services
has title: ResultSet outputted String is refusing to Cast to a Dict with DynamoDB noSQL
downvote count: 1
has body: I am trying to cast a ResultSet to a Dict, however the Python casts do not appear to want to work correctly. Connection to AWS DynamoDB c = boto.dynamodb2.connect_to_region(aws_access_key_id="ACCESSKEYCODE222",aws_secret_access_key="SECRETKEYCODEKFJFJFJF",region_name="us-west-2") table = Table("reko_response",connection=c) # Get the result set from DynamoDB response = table.scan() print(type(response)) # type of the response recieved = &lt;class 'boto.dynamodb2.results.ResultSet'&gt; Test the standard string to dict conversion which works correctly string_of_dict = "{'name':'Frederik'}" dict_of_string = ast.literal_eval(string_of_dict) print(type(dict_of_string)) # Outputs Correction: &lt;class 'dict'&gt; This works correctly and the string is cast to a dict. The ResultSet Casts to a String which Refuses to Cast to a Dict for item in response: string_item = json.dumps(str(dict(item))) print(string_item) print(type(string_item)) # Outputs correctly: &lt;class 'str'&gt; # Cast to Dict Attempt 1 dict_item = json.loads(string_item) print(type(dict_item)) # Expected Output: &lt;class 'dict'&gt; | Actual Output: &lt;class 'str'&gt; # Cast to Dict Attempt 2 dict_item = ast.literal_eval(string_item) print(type(dict_item)) # Expected Output: &lt;class 'dict'&gt; | Actual Output: &lt;class 'str'&gt; sys.exit() Neither of the standard Python casts appear to caste the string of the result set to a dict. What is happening here? The Actual output is &lt;class 'boto.dynamodb2.results.ResultSet'&gt; &lt;class 'dict'&gt; "{'timestamp': 'Time: 2018-05-02 08:42:36.978210', 'ID': '39609c57-6ed5-4fc5-8baa-0007d1aeb7ef', 'Store': 'Coles:Brighton', 'Gender': 'Male', 'Age(high)': Decimal('43'), 'smile': False, 'smile_conf': Decimal('90.57567596435546875'), 'Emotion1': 'HAPPY', 'emo2-conf': Decimal('6.381499767303466796875'), 'Emotion3': 'CALM', 'emo1-conf': Decimal('19.021503448486328125'), 'Age(low)': Decimal('26'), 'emo3-conf': Decimal('5.70695400238037109375'), 'Emotion2': 'SAD'}" &lt;c…
type: AnsweredQuestion

http://stackoverflow.com/comment/87270861
type: AnswerComment
score: 0
has text: Ah ha I did just open terminal this time and the line worked. Currently, waiting for it to download
type: Comment
comment on: http://stackoverflow.com/a/50126006

http://stackoverflow.com/q/50142125
tagged with: shutil
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/18371768
has comment: http://stackoverflow.com/comment/87302502
has comment: http://stackoverflow.com/comment/87302585
has body: I have a large number of .txt files named in the combination of "cb" + number (like cb10, cb13), and I need to filter them out from a source folder that contains all the files named in "cb + number", including the target files. The numbers in the target file names are all random, so I have to list all the file names. import fnmatch import os import shutil os.chdir('/Users/college_board_selection') os.getcwd() source = '/Users/college_board_selection' dest = '/Users/seperated_files' files = os.listdir(source) for f in os.listdir('.'): names = ['cb10.txt','cb11.txt'] if names in f: shutil.move(f,dest)
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50142271
score: 1
duplicate of: http://stackoverflow.com/q/18371768
has answer: http://stackoverflow.com/a/50142271
has title: How can I move files with random names from one folder to another in Python?

http://stackoverflow.com/a/50157471
has comment: http://stackoverflow.com/comment/87355162
has comment: http://stackoverflow.com/comment/87457532
score: 2
has body: If you want to use a specific version of python when creating the virtualenv you should use the --python flag: virtualenv --python=/usr/local/lib/python3.6 &lt;path/to/new/virtualenv/&gt; If you are using pipenv as this is the case just use: pipenv --python 3.6
downvote count: 0
answers question: http://stackoverflow.com/q/50157360
has comment: http://stackoverflow.com/comment/87420139
upvote count: 2
has comment: http://stackoverflow.com/comment/87344708
type: Answer

http://stackoverflow.com/comment/87461662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50222055
has text: Definitely a large array of probabilities, in this case, I generated them randomly, but I will have from data a set of probabilities (values between 0 to 1) which I will use to get a sample.
score: 1

http://stackoverflow.com/comment/87382450
comment on: http://stackoverflow.com/q/50159525
type: QuestionComment
has text: Sorry for that . Will make changes :-)
type: Comment
score: 0

http://stackoverflow.com/comment/87343846
type: Comment
has text: Do I have to convert the column to a separate df for that to work? It doesn't seem to work on just the column because it's a Series object: 'Series' object has no attribute 'time' - so I'm doing data['dep_time'] = pd.to_datetime(data['dep_time'].time.str.pad(4,side='left',fillchar='0'),format='%H%M').dt.time
type: AnswerComment
comment on: http://stackoverflow.com/a/50162485
score: 0

http://stackoverflow.com/a/50097319
upvote count: 1
has body: Here's a much simpler solution: cards.sort(key=lambda x: (x[0], int(x[1:]))) &gt;&gt;&gt; ['b2', 'b5', 'b7', 'b10', 'c3', 'c6', 'c7', 'd10', 's2', 's6'] It works by sorting on a tuple form of the card, whereby the first element of the tuple is the first character of your string, and the second element of the tuple is the integer form of your second (and possibly 3rd in the case of '10') character(s) of your string.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50097227
answers question: http://stackoverflow.com/q/50097227
downvote count: 0
score: 1

http://stackoverflow.com/comment/87356634
has text: The third one should be 001_3.png, right?
comment on: http://stackoverflow.com/q/50169588
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50162849
type: Question
accepted answer: http://stackoverflow.com/a/50162965
has title: Convert a dict to three-column dataframe using ID/key/value
has answer: http://stackoverflow.com/a/50162965
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/50162891
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 0
has body: I'm sure this has been answered somewhere, but querying for it is a bit tricky. I have a dict that's structured with an ID field and then 1-many key-value pairs eg: { '123' : {'name': 'Joe', 'age': '17 }, '888' : {'name': 'Cheryl', 'hometown': 'Liverpool'}, '432' : {'name': 'Raj'} } I want to get this into a SQL table structured as three columns: id | property-name | property-value, eg: 123 | name | Joe 123 | age | 17 888 | name | Cheryl 888 | hometown | Liverpool 432 | name | Raj My plan was to go through a pandas DataFrame, and then to_sql it. The problem is creating a dataframe out of a dict tries to make the IDs column headers and every possible property name a row. Question 1: Is the only way to convert my dict to a 3-col dataframe to loop through it, appending values to three arrays? Question 2: Is it necessary to go through pandas at all? Would it be better to just use sqlalchemy and fill in an INSERT query instead?
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/50162891

http://stackoverflow.com/q/50086571
tagged with: mysql
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: populate dropdown with sql python/tkinter
tagged with: tkinter
has body: i use python 3, tkinter and mysql connector. I want to make an optionMenu object with my sql data i tried to do like that : mongroupe3 = LabelFrame(app, text='nouvelle div 3').pack() Label(mongroupe3, text='groupe3').pack() select_Classes = ("select id,nom from classe") cursor.execute(select_Classes) result = cursor.fetchall() for row in result: id = row[0] nom = row[1] mongroupe3 = Label(app, text=nom).pack() v = StringVar() v.set(nom) om = OptionMenu(mongroupe3, v, nom) om.pack() the code has to show a dropdown menu with a list of the "nom" on my "classe" table but my option menu is in my for loop and is executed as many time as i have records in my classe table . for exemple if i have 3 record i got 3 option menu with 3 different value. o tried to put my optionMenu out of my for loop like that : mongroupe3 = LabelFrame(app, text='nouvelle div 3').pack() Label(mongroupe3, text='groupe3').pack() select_Classes = ("select id,nom from classe") cursor.execute(select_Classes) result = cursor.fetchall() for row in result: id = row[0] nom = row[1] mongroupe3 = Label(app, text=nom).pack() v = StringVar() v.set(nom) om = OptionMenu(mongroupe3, v, nom) om.pack() but i got only the last record i inserted on my table. i cant put my for loop inside my OptionMenu cause of the following shema OptionMenu(parent, default variable, var)
tagged with: sql
has answer: http://stackoverflow.com/a/50087422
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50196759
type: Answer
answers question: http://stackoverflow.com/q/50196511
score: 0
has body: Consider asking for the path from the script, and setting a default if not passed in. This would make your script a lot more flexible than having the path coded in it. You can use the click package which simplifies this a bit. import os import click def write_to_csv(path, journal_list): # .. your normal code file_path = os.path.join(path, '{}.csv'.format(username)) # .. rest of your code here @click.command() @click.option('--output_dir', default='/home/foo/bar/', help='Default path to save files') def main(output_dir): write_to_csv(output_dir) if __name__ == '__main__': main()

http://stackoverflow.com/comment/87238999
type: QuestionComment
score: 0
has text: Skip saving and reloading for each image. Paste each of the images then save.
type: Comment
comment on: http://stackoverflow.com/q/50110798

http://stackoverflow.com/comment/87469957
comment on: http://stackoverflow.com/q/50226219
type: Comment
type: QuestionComment
has text: By splitting my question into tokens and I removed stop words from my question and got the useful words such as what, net income, apple.
score: 0

http://stackoverflow.com/q/50165242
type: Question
has body: I'm starting using Python recently and I'm trying to make a program that manipulates data in Python using pickle, however I would like my file to be kind like this: CODE | PIECE | PRICE line one 1 1 1,00 line two 2 2 2,00 Consider 1 right down CODE, 1 right down PIECE and 1,00 right down PRICE until gets 50. Here's the question: Is there anyway to do this using pickle? Like: columns = int(input('Number of columns : ')) # Which would be 3 (code, piece and price) data = [ ] for i in range(columns): raw = input('Enter data '+str(i)+' : ') data.append(raw) file = open('file.dat', 'wb') pickle.dump(data, file) file.close() Obviously, it cannot be done using input, so is there some way to do this?
type: UnansweredQuestion
tagged with: pickle
tagged with: python
score: 0
answer count: 0
has title: Pickle persistence
has comment: http://stackoverflow.com/comment/87348400
has comment: http://stackoverflow.com/comment/87349283
tagged with: persistence

http://stackoverflow.com/q/50142765
score: 1
accepted answer: http://stackoverflow.com/a/50143079
has comment: http://stackoverflow.com/comment/87303913
has title: NoReverseMatch error in Django tutorial: argument not being picked up
favorite count: 0
has comment: http://stackoverflow.com/comment/87303761
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/36021919
has body: I'm hitting the following error when going through the Django tutorial: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$'] From this answer it seems like the problem is that the argument is not being passed through on line 9 of results.html. This answer suggests that it should be question.id but that's what I have. So I'm not sure where to go next on this. part following error. When I remove line 9 (which includes this link) from the template. Help appreciated. Apologies if this has already been asked before - I feel like I've looked everywhere. Hopefully this is all the relevant code. (After this went wrong a couple of times I copied and pasted everything from the tutorial to guard against typos.) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/results/ Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig'] 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'] Template error: In template C:\Users\User\Dropbox\Personal\Projects\Python\Django\django-tut\mysite\polls\templates\polls\results.html, error at line 8 Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$'] 1 : {{ question.question_text }} 2 : 3 : 4 : {% for choice in question.choice_set.all %} 5 : {{ choice.choice_text }} -- {{ choice.votes }} vote 6 : {% endfor %} 7 : 8 : Vote again? 9 : Trac…
has answer: http://stackoverflow.com/a/50143079
type: Question
type: AnsweredQuestion
tagged with: django-urls
linked to: http://stackoverflow.com/q/38390177

http://stackoverflow.com/a/50128978
downvote count: 0
type: AcceptedAnswer
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50128934
type: Answer
answers question: http://stackoverflow.com/q/50128934
has body: The best here is not use apply(pd.Series) because very slow, but DataFrame contructor with convert NaNs to 0 and then to ints: df = pd.DataFrame({'column1': [{'c681': 1, 'c682': 2, 'c57': 4, 'c680': 5}, {'c681': 2, 'c682': 1, 'c57': 7, 'c680': 6}, {'c681': 4, 'c682': 2, 'c57': 8, 'c680': 2}, {'c681': 2, 'c682': 3, 'c57': 1, 'c680': 4}, {'c683': 3, 'c681': 5, 'c57': 0, 'c680': 3}]}, index=['e1','e2','e3','e4','e5']) print (df) column1 e1 {'c680': 5, 'c682': 2, 'c57': 4, 'c681': 1} e2 {'c680': 6, 'c682': 1, 'c57': 7, 'c681': 2} e3 {'c680': 2, 'c682': 2, 'c57': 8, 'c681': 4} e4 {'c680': 4, 'c682': 3, 'c57': 1, 'c681': 2} e5 {'c683': 3, 'c680': 3, 'c57': 0, 'c681': 5} df = pd.DataFrame(df['column1'].values.tolist(), index=df.index).fillna(0).astype(int) print (df) c57 c680 c681 c682 c683 e1 4 5 1 2 0 e2 7 6 2 1 0 e3 8 2 4 2 0 e4 1 4 2 3 0 e5 0 3 5 0 3 df = pd.concat([df] * 1000, ignore_index=True) In [108]: %timeit (pd.DataFrame(df['column1'].values.tolist(), index=df.index)) 100 loops, best of 3: 10.1 ms per loop In [109]: %timeit (df['column1'].apply(pd.Series)) 1 loop, best of 3: 1.14 s per loop

http://stackoverflow.com/comment/87166545
type: Comment
type: QuestionComment
has text: How did you derive value = 16 for customer_id = 2 & Class = B ?
comment on: http://stackoverflow.com/q/50075154
score: 0

http://stackoverflow.com/comment/87192364
type: AnswerComment
comment on: http://stackoverflow.com/a/50084207
has text: Thank you so much for your help. I've changed the alternatives in matched statement to | return_statement SEMI_COLON | compound_statement SEMI_COLON | simple_statement SEMI_COLON Which seems to fix the things, although I didn't wanted to my code depends on semi-colon.
score: 0
type: Comment

http://stackoverflow.com/a/50163802
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50163319
has comment: http://stackoverflow.com/comment/87345791
has comment: http://stackoverflow.com/comment/87345921
type: Answer
has comment: http://stackoverflow.com/comment/87346156
accepted answer of: http://stackoverflow.com/q/50163319
has comment: http://stackoverflow.com/comment/87345948
downvote count: 0
score: 1
upvote count: 1
has body: So to perform your problem if I understand, you can create a mask_24h to select the data from df1 in the last 24h: h24_ago = (pd.Timestamp.today() - pd.Timedelta(days=1)).date() # time 24h ago mask_24h = df1['datetimecomplete'] &gt;= h24_ago Then to create your df2 you are right to use groupby but I would do this way: df2 = df1[mask_24h ].groupby(['zone','script']).\ count().reset_index().rename(columns = {'datetimecomplete':'totalcount'}) here you select the data from df1 within the last 24h with df1[mask_date] then you groupby() on 'zone' and 'script' and proceed the count(). reset_index() allows to keep the other columns and rename() to rename. Now you are just missing the column 'datetimecomplete' so do: df2['datetimecomplete'] = h24_ago Hope it works

http://stackoverflow.com/q/50123129
has body: I have a Django project in production and when I try to access /calendar endpoint it shows me a 500 error. In local development all the urls work fine, and in production too except this one. Where and how can I check why this endpoint throws an 500 error? views.py def calendar_view(request): if request.user: events = Event.objects.filter(owner=request.user) else: events = Event.objects.filter(author='anonymous') js_data = serialize('json', events) return render(request, 'calendar/calendar.html', {'js_data': js_data, 'events': events}) More information In the admin site, I can't access to Event model. I obtain 500 server error too.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50124253
has title: Django 500 server error only in one URL
has comment: http://stackoverflow.com/comment/87264436
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87265623
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87264619
score: 1
has comment: http://stackoverflow.com/comment/87264719
answer count: 1
has comment: http://stackoverflow.com/comment/87265266
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87301879
comment on: http://stackoverflow.com/a/50141667
has text: yup, makes sense!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87304835
score: 0
has text: I was only testing as my work laptop is at work but the file will contain an x amount of rows and say, 40 columns. The data is from a web scrape/api service that i'm testing and I need to align the data for our databases. (it's for a NFP charity if that makes you feel better about helping :D)
type: Comment
comment on: http://stackoverflow.com/a/50139434
type: AnswerComment

http://stackoverflow.com/q/50091523
tagged with: cython
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87201690
answer count: 1
linked to: http://stackoverflow.com/q/48272969
tagged with: python
favorite count: 0
has title: set cython cdef extension array to zero
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/49058949
has answer: http://stackoverflow.com/a/50095314
accepted answer: http://stackoverflow.com/a/50095314
has body: Is there a cython-ic way to set a cdef array to zeros. I have a function with the following signature: cdef cget_values(double[:] cpc_x, double[:] cpc_y): The function is called as follows: cdef double cpc_x [16] cdef double cpc_y [16] cget_values(cpc_x, cpc_y) Now the first thing I would like to do is set everything in these arrays to zeros. Currently, I am doing that with a for loop as: for i in range(16): cpc_x[i] = 0.0 cpc_y[i] = 0.0 I was wondering if this is a reasonable approach without much overhead. I call this function a lot and was wondering if there is a more elegant/faster way to do this in cython.

http://stackoverflow.com/a/50210708
downvote count: 0
answers question: http://stackoverflow.com/q/50202239
upvote count: 1
has body: You mis-specified the frequencies in the original signal. A sine wave is parameterized according to this equation (from Wikipedia): The factor 2 is missing in the definition of signal = np.cos(5*np.pi*time) + np.cos(7*np.pi*time). Therefore, the actual frequencies are 5*pi*t = 2*pi*t * f f = (5*pi*t) / (2*pi*t) = 5 / 2 7*pi*t = 2*pi*t * f f = (7*pi*t) / (2*pi*t) = 7 / 2 In words, the two frequencies are half of what you think they are. Ironically, that is why it seems to work with fftfreq instead of rfftfreq. The former covers twice the frequency range (positive and negative frequencies), and therefore compensates for the missing factor 2. This is the correct code: signal = np.cos(5 * 2*np.pi * time) + np.cos(7 * 2*np.pi * time) W = rfftfreq(signal.size, d=time[1]-time[0])
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50202239
type: AcceptedAnswer

http://stackoverflow.com/comment/87441859
has text: @legalalien It can be but it doesn't have to be. The string is only for the processing algorithm. Please feel free to write an answer if you know how to use hex to solve the conversion problem.
type: Comment
comment on: http://stackoverflow.com/q/50211546
type: QuestionComment
score: 0

http://stackoverflow.com/q/50120344
answer count: 1
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50129444
has body: On https://www.hltv.org/matches page, matches divided by dates but the classes are same. I mean, This is today's match class 2018-05-01 This is tommorow's match class. 2018-05-02 What i'm trying to do is, I wanna get the links under the "standard-headline" class but only today's matches. Like, getting the only first one. Here is my code. import urllib.request from bs4 import BeautifulSoup headers = {} # Headers gives information about you like your operation system, your browser etc. headers['User-Agent'] = 'Mozilla/5.0' # I defined a user agent because HLTV perceive my connection as bot. hltv = urllib.request.Request('https://www.hltv.org/matches', headers=headers) # Basically connecting to website session = urllib.request.urlopen(hltv) sauce = session.read() # Getting the source of website soup = BeautifulSoup(sauce, 'lxml') matchlinks = [] # Getting the match pages' links. for links in soup.find_all('div', class_='upcoming-matches'): # Looking for "upcoming-matches" class in source. for links in soup.find_all('a'): # Finding "a" tag under "upcoming-matches" class. clearlink = links.get('href') # Getting the value of variable. if clearlink.startswith('/matches/'): # Checking for if our link starts with "/matches/" matchlinks.append('https://hltv.org' + clearlink) # Adding into list.
type: AnsweredQuestion
score: 3
upvote count: 3
has title: How to get only first class' data between two same classes
has answer: http://stackoverflow.com/a/50129444
tagged with: urllib
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50205902
type: Answer
has comment: http://stackoverflow.com/comment/87428940
has body: You can get rid of duplicates in a string by using set() and only iterate through unique strings: s=input("Enter your string: ") s=s.split() for i in set(s): print(i, "=", s.count(i) Alternatively you can use collections.Counter(): from collections import Counter s=input("Enter your string: ") s=s.split() for key, value in Counter(s).items(): print(key, "=", value)
accepted answer of: http://stackoverflow.com/q/50205878
has comment: http://stackoverflow.com/comment/87428963
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50205878
has comment: http://stackoverflow.com/comment/87428931
upvote count: 1
score: 1

http://stackoverflow.com/comment/87242919
type: Comment
comment on: http://stackoverflow.com/a/50112479
type: AnswerComment
score: 0
has text: All these listed elements are variables?

http://stackoverflow.com/comment/87266731
type: Comment
type: QuestionComment
has text: You can override this behavior with `python -i`, but Ctrl+Z will still be broken for `sys.stdin.read()`. A common workaround is to run `winpty python`, which let's Python use a hidden console (conhost.exe) while bridging to mintty.
score: 3
comment on: http://stackoverflow.com/q/50121192

http://stackoverflow.com/q/50214908
has comment: http://stackoverflow.com/comment/87446965
has comment: http://stackoverflow.com/comment/87447200
score: 0
has body: I have a dataframe (df) that I read from an excel file using the code: xls_file = pd.ExcelFile('/Users/Desktop/df_1.xlsx') df = xls_file.parse('Sheet1') A shorter version of the dataframe is transposed and shown below: 0 1 2 3 4 S_Id SB001 SB001 SB001 SB001 SB001 Reg 27548 27548 27548 27548 27548 Visit 1 2 1 2 3 Planned 5 NaN 5 NaN NaN Planned_2 NaN NaN NaN NaN NaN Visit_Date 15-07-22 15-10-01 15-07-22 15-10-01 16-08-01 Weight 69 70 69 70 68.3 Height 170 NaN 170 NaN NaN Consent 1 NaN 1 NaN NaN Filled_Q1 1 1 1 1 1 Filled_Q2 1 1 1 1 1 Other_Id NaN NaN NaN NaN NaN Class1_Taken 1 1 1 1 1 Class1_Date 15-07-22 15-10-01 15-07-22 15-10-01 16-08-01 Class2_Taken 1 1 1 1 1 Class2_Date 15-07-22 15-10-01 15-07-22 15-10-01 16-08-01 Class2_Time 11:05 11:55 11:05 11:55 14:05 Class3_Taken 1 1 1 1 1 Class3_Date 15-07-22 15-10-01 15-07-22 15-10-01 16-08-01 Class3_Time 10:50 10:45 10:50 10:45 13:20 Class4_Taken 1 1 1 1 1 Class5_Taken 1 1 1 1 1 Class6_Taken 1 1 1 1 1 Class7_Taken 1 1 1 1 1 Class8_Taken 0 0 0 0 0 Now if I use the .duplicated() method, it will generate: 0 False 1 False 2 False 3 False 4 False dtype: bool Which is not true since 0, 2 and 1, 3 are the same. Can anybody help here? Thank you in advance!
has comment: http://stackoverflow.com/comment/87447269
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/87448017
has comment: http://stackoverflow.com/comment/87447539
type: Question
has comment: http://stackoverflow.com/comment/87448298
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87448010
has comment: http://stackoverflow.com/comment/87447318
tagged with: duplicates
tagged with: python
has title: pandas .duplicated() unable to find duplicated rows
has comment: http://stackoverflow.com/comment/87447055

http://stackoverflow.com/a/50230064
has comment: http://stackoverflow.com/comment/87478753
upvote count: 0
answers question: http://stackoverflow.com/q/50229634
type: Answer
has body: Add a symlink /usr/bin pointing at your script. Check this question how to do it: How to symlink a file in Linux? Use which command to validate if the system can see it.
has comment: http://stackoverflow.com/comment/87521219
downvote count: 1
score: -1

http://stackoverflow.com/comment/87165970
has text: oh my bad, I forgot to mention that I'm doing it in python's interactive mode.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50074690
score: 0

http://stackoverflow.com/comment/87302942
comment on: http://stackoverflow.com/a/50141806
type: AnswerComment
has text: in PG admin I am only getting the first statement in the list to match, no others are populating. Is there another statement to make it pull them all instead of short circuiting at the first OR match?
score: 0
type: Comment

http://stackoverflow.com/a/50205503
type: Answer
has comment: http://stackoverflow.com/comment/87428218
has comment: http://stackoverflow.com/comment/87428209
score: 0
answers question: http://stackoverflow.com/q/50205482
type: AcceptedAnswer
has body: You need to bring some of your initialization into the loop like: Code: unordered = [18, 13, 44, 12, 19, 27, 2, 31] print(unordered) ordered = [] while unordered: lowest = unordered[0] index_of_lowest = 0 for i, number in enumerate(unordered): if number &lt; lowest: lowest = number index_of_lowest = i del unordered[index_of_lowest] ordered.append(lowest) print(ordered) Results: [18, 13, 44, 12, 19, 27, 2, 31] [2, 12, 13, 18, 19, 27, 31, 44]
accepted answer of: http://stackoverflow.com/q/50205482

http://stackoverflow.com/a/50144507
score: -1
has comment: http://stackoverflow.com/comment/87307250
has comment: http://stackoverflow.com/comment/87307266
answers question: http://stackoverflow.com/q/50144414
has comment: http://stackoverflow.com/comment/87307237
has body: The solution is actually remarkably simple after playing around with a binary calculator a little bit. Just subtract the magnitude of the SIGNED int from 256, to get the value of the UNSIGNED int with the same binary representation. So, -23 signed would be 233 unsigned. Hope this helps anyone else looking for a solution :) EDIT: For those saying answer is 255 - array[0]. In this case I'm looking for a way to go from post NOT'd int to its unsigned counter part. So I've already performed the bitwise NOT on the integer, now I'm just getting it back to a form that can be inputted into the byte-array. So in the end it would look something like this: tmp = ~array[0] array[0] = 256 + tmp or array[0] = 256 - abs(tmp) This gets me the correct answer :)
upvote count: 0
type: Answer
downvote count: 1

http://stackoverflow.com/comment/87434706
type: AnswerComment
has text: Ok now I can see that. Like here: def myfunc(alist): alist.append(2) def testf(alist): myfunc(alist) return(alist) testf([1,2,3]) will return [1,2,3,2]
comment on: http://stackoverflow.com/a/50208910
score: 0
type: Comment

jquery
tags question: http://stackoverflow.com/q/50198172
tags question: http://stackoverflow.com/q/50105364
tags question: http://stackoverflow.com/q/50208182
type: Tag
tag name: jquery
tags question: http://stackoverflow.com/q/50078543
tags question: http://stackoverflow.com/q/50095282
tags question: http://stackoverflow.com/q/50189486

http://stackoverflow.com/q/50076666
has body: I have this code: L = [1, 4, 7, 5, 5, 4, 5, 1, 1, 1] def frequency(L): counter = 0 number = L[0] for i in L: amount_times = L.count(i) if amount_times &gt; counter: counter = amount_times number = i return number print(frequency(L)) But I don't want to use counter function. I want to make code run without any built-in functions. How can I do this?
has answer: http://stackoverflow.com/a/50077531
tagged with: frequency
type: UnansweredQuestion
tagged with: counter
tagged with: python
has answer: http://stackoverflow.com/a/50076736
has comment: http://stackoverflow.com/comment/87169509
score: 0
has comment: http://stackoverflow.com/comment/87169426
answer count: 2
tagged with: function
upvote count: 1
has comment: http://stackoverflow.com/comment/87169589
has comment: http://stackoverflow.com/comment/87169483
has title: Building a custom Counter function without using built-ins
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/54958728
type: Answer
has body: arr = np.array([]) hist = cv2.calcHist([image], [0, 1, 2], mask, self.bins, [0, 180, 0, 256, 0, 256]) hist = cv2.normalize(hist,arr).flatten() works for me
answers question: http://stackoverflow.com/q/50149277
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87311169
score: 2
has text: Your best bet is to keep the previous value in a different variable.
type: Comment
comment on: http://stackoverflow.com/q/50146473
type: QuestionComment

http://stackoverflow.com/q/50164369
tagged with: pandas
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87346769
type: Question
has body: I'm trying to select subset of pandas dataframe and compute some statistics, but it's painfully slow, maybe it can be done faster? column_name1_set = df.column_name1.unique() column_name2_set = df.column_name2.unique() for i, name1 in enumerate(column_name1_set): for name2 in column_name2_set: df_t = df[(df['column_name1']==int(name1)) &amp; (df['column_name2']==name2)] s = df_t.sum(axis=0) s['amount_min'] = df_t['amount'].min() s['amount_max'] = df_t['amount'].max() s['amount_mean'] = df_t['amount'].mean() s['amount_median'] = df_t['amount'].median() #store s ...
type: UnansweredQuestion
tagged with: subset
answer count: 1
has answer: http://stackoverflow.com/a/50164427
has title: Speedup selecting subset
score: 0

http://stackoverflow.com/comment/87300742
score: 0
has text: @TemporalWolfthanks for the help that was a stupid mistake, i dont seem to be getting any syntax errors anymore(i changed the code to `ciphertext += alpha2[ (alpha1[i] + brutekey)% (MAX_KEY_SIZE)]` but now all it prints is 'OPQRSTUVWXYZABCDEFGHIJKLMNLMN' over and over
type: Comment
comment on: http://stackoverflow.com/q/50140985
type: QuestionComment

http://stackoverflow.com/q/50190463
has body: I have the following class: class TfidfEmbeddingVectorizer(object): def __init__(self, word2vec): self.word2vec = word2vec self.word2weight = None self.dim = len(word2vec[next(iter(w2v))]) def fit(self, X, y): tfidf = TfidfVectorizer(analyzer=lambda x: x) tfidf.fit(X) # if a word was never seen - it must be at least as infrequent # as any of the known words - so the default idf is the max of # known idf's max_idf = max(tfidf.idf_) self.word2weight = defaultdict( lambda: max_idf, [(w, tfidf.idf_[i]) for w, i in tfidf.vocabulary_.items()]) return self def transform(self, X): return np.array([ np.mean([self.word2vec[w] * self.word2weight[w] for w in words if w in self.word2vec] or [np.zeros(self.dim)], axis=0) for words in X ]) But when I instantiate it I get the following error: File "&lt;ipython-input-70-dcde03597dd3&gt;", line 23, in &lt;listcomp&gt; for w in words if w in self.word2vec] or TypeError: 'NoneType' object is not subscriptable
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: nonetype
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50190893
has answer: http://stackoverflow.com/a/50190893
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87398933
has title: Don't understand this TypeError: 'NoneType' object is not subscriptable error
answer count: 1

http://stackoverflow.com/q/50220147
has answer: http://stackoverflow.com/a/50221000
tagged with: database
tagged with: python
type: UnansweredQuestion
tagged with: concurrency
has comment: http://stackoverflow.com/comment/87457562
has comment: http://stackoverflow.com/comment/87457379
score: 0
has comment: http://stackoverflow.com/comment/87457328
tagged with: sqlite
has body: I have a scenario where a third party application scans a folder and triggers my python script/generated EXE for the number of times (yes! number of separate processes) for the number of files that are in the folder. My script/application writes the path of the file to a local sqlite database, calls the next application and exits. My script/application takes care that it calls only one instance of the next application. But nothing can be done of the third party application that calls my script. The ISSUE Sometimes more than 1000 instances of my script/application can be called at the same time resulting in almost 1000 concurrent connections to the local sqlite database. Due to the limited number of concurrent connections possible with sqlite, some of the processes are getting a "database is locked" Exception. This results in some of the file names NOT being written to the database We came up with a work around for this. We write in the database in an infinite loop. On encountering the exception, we make the thread sleep for say 50 milliseconds and try again till such time that the write works. I know that this is not a clean approach. Is there a better way of doing this? How do I handle 1000 may be 10000 or may be more concurrent connections and yet each script succeeds?
answer count: 1
tagged with: python-3.x
has title: Python Sqlite Concurrent access
type: Question

http://stackoverflow.com/a/50193865
has comment: http://stackoverflow.com/comment/87404943
type: Answer
accepted answer of: http://stackoverflow.com/q/50193711
has comment: http://stackoverflow.com/comment/87404904
has body: The first problem is that you're not benchmarking properly (you should be using timeit, because it takes care of all the things you didn't think of), and, even more importantly, you're benchmarking the wrong thing. Using %timeit in IPython on my laptop, here are the times for the three parts of your process: b = unhexlify(var): 209ns b[0]: 16.0ns temp = b0: 50.2ns So, you're focusing on the fastest part of the process. Meanwhile, once you've decided to use unhexlify to get a bytes object, of course the fastest way to get the first byte out of that is b[0]. How could anything possibly be any faster than that? But if you take a step back: int(var, 16): 233ns This is nearly as fast as unhexlify(var)[0]—within 4%, and a difference in the single-digit nanos. Which may not even be consistently repeatable across systems, Python versions, or input values. But, even if it were, it's hard to imagine an application where this 8ns makes a difference where you couldn't get a much bigger speedup by stepping back and doing something at a higher level. Sure, it's not impossible this could come up, by immediately jumping to how to micro-optimize this operation is almost always going to be a mistake. Even more importantly, unhexlify(var)[0] only works for single-byte values. Try it with, say, FF22 and you're going to get 255 instead of 65314. The other options—including int—will give you the right answer. And of course using struct and int.from_bytes give you more flexibility—you can read bytes in either endianness, or specify the exact size you expect (or read exactly that many bytes out of an input buffer without consuming the whole buffer). So, the right answer is to use the one that does what you actually want in the most obvious way. Something that's faster but wrong is not helpful, and even something that's faster but not obviously right often isn't helpful. And this means that if what you're actually trying to do is (contrary to what you implied in your question) iterate or in…
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87404913
answers question: http://stackoverflow.com/q/50193711
has comment: http://stackoverflow.com/comment/87404893

constraints
type: Tag
tags question: http://stackoverflow.com/q/50123308
tag name: constraints

http://stackoverflow.com/a/50217671
has comment: http://stackoverflow.com/comment/87452551
type: Answer
has comment: http://stackoverflow.com/comment/87452768
has body: Use subplots with gridspec_kw parmater to setup your grid then use the ax paramter in pandas plot to use those axes defined in your subplots statement: f, ax = plt.subplots(2,2, gridspec_kw={'height_ratios':[1,2]}) df'A','B','C'.plot(subplots=True, sharex=True, ax=[ax[0,0],ax[0,1],ax[1,0]]) ax[1,1].set_visible(False) Output:
score: 2
has comment: http://stackoverflow.com/comment/87452623
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87452321
answers question: http://stackoverflow.com/q/50217206
has comment: http://stackoverflow.com/comment/87452344
accepted answer of: http://stackoverflow.com/q/50217206

http://stackoverflow.com/q/50100730
tagged with: python
tagged with: dictionary
has body: I've been working on a function where I need to take the input from three separate groups of tweets and create three new sets based on the whether the list was longer than 50 characters or not. I'm not really sure how to go about this so I've put my last attempt in the code box below. def filter_short_tweets(tweet): {i for i in tweet if tweet['text'][i] &gt; 50} return tweet filter_short_tweets(k1_tweets) So far no matter what I do the result I always get it is TypeError: list indices must be integers or slices, not str Any help with this would be very much appreciated. Thankyou.
has comment: http://stackoverflow.com/comment/87218278
score: 0
tagged with: typeerror
has comment: http://stackoverflow.com/comment/87217946
has comment: http://stackoverflow.com/comment/87218406
answer count: 1
has answer: http://stackoverflow.com/a/50100951
has comment: http://stackoverflow.com/comment/87218324
tagged with: string
has comment: http://stackoverflow.com/comment/87217981
type: Question
has title: Dividing dictionary into two based on length on string value
type: UnansweredQuestion

http://stackoverflow.com/a/50092529
answers question: http://stackoverflow.com/q/50092497
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: You can do it the following way: d = ['hammer#9.95', 'saw#20.15', 'shovel#35.40'] ## replace hash values = [] items = set() for line in d: line = line.replace('#', '$') values.append(line.split('$')[1]) items.add(line.split('$')[0]) ## sum values sum(map(lambda x: float(x), values)) 65.5 ## count items len(items) 3 Explanation: To count items, we've used a set to get unique count. If you want all, use a list instead. We've calculated sum by extracting the numbers from list by splitting on dollar sign.

http://stackoverflow.com/comment/87410186
has text: Thanks. This is only a minimal example. I do have exclusions like a gitignore and also command line arguments for quality etc. I’m not doing this to good photos but to hundreds of photos shot on cheap cameras surveying construction sites purely for documentary purposes. They take like 90% of our NAS space. Bringing them down to a fraction of their original size without visible loss at a screen when not zoomed is enough in this case. Maybe resizing and compressing a higher quality may be better for some cases. This is nothing professional. I’m just an engineer who likes to code at weekends.
comment on: http://stackoverflow.com/a/50194144
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87235980
has text: I tried both `pipreqs` and `pip freeze`, can't reproduce your issue
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50109155

http://stackoverflow.com/q/50084989
score: 0
has body: I am having trouble to concatenate 2 simple DataFrames. I upload first one .txt file containing the data set, and then another one containing the header of the previous dataset. First I upload the 2 DataFrames: df = pd.read_csv(file_dir + file_name, sep = ',', header = None, encoding = 'latin-1', low_memory = False) df_column_names = pd.read_csv(file_dir + file_name_cols, sep = ',', header = None, encoding = 'latin-1', low_memory = False) Afterwards, I create a list of the header's DataFrame by first transposing the table, and the converting it into a list: list_names = df_column_names.T.values.tolist() Then, I finally create the desired DataFrame: df.columns = list_names But I receive the following error message: ValueError: Length mismatch: Expected axis has 26 elements, new values have 1 elements The dimensions of my objects are: df of size (204,26) and type DataFrame, df_column_names is size (1,26) and type DataFrame, list_names is size 26 and type list. After reading other threads, the most similars were here, and here. Nevertheless, after checking the indexes of my two DataFrames, both seem OK: In [4]: print(df.index) RangeIndex(start=0, stop=205, step=1) In [5]: print(df_column_names.index) RangeIndex(start=0, stop=1, step=1) In [6]: len(list_names) Out[6]: 26 The look of list_names is the following: In [7]: list_names Out[7]: [['symboling'], ['normalized-losses'], ['make'], ['fuel-type'], ['aspiration'], ['num-of-doors'], ['body-style'], ['drive-wheels'], ['engine-location'], ['wheel-base'], ['length'], ['width'], ['height'], ['curb-weight'], ['engine-type'], ['num-of-cylinders'], ['engine-size'], ['fuel-system'], ['bore'], ['stroke'], ['compression-ratio'], ['horsepower'], ['peak-rpm'], ['city-mpg'], ['highway-mpg'], ['price']] Thanks in advance for your help and advice.
tagged with: concatenation
tagged with: pandas
answer count: 1
has title: Concatenating header list to Dataframe in pandas
type: Question
accepted answer: http://stackoverflow.com/a/50085091
has answer: http://stackoverflow.com/a/50085091
linked to: http://stackoverflow.com/q/44876939
tagged with: dataframe
tagged with: python
tagged with: append
linked to: http://stackoverflow.com/q/36608203
type: AnsweredQuestion

http://stackoverflow.com/comment/87170990
type: AnswerComment
comment on: http://stackoverflow.com/a/50077160
score: 0
type: Comment
has text: @ Ok I am a bit confused, I tried to implement the code in different ways but get an error anyways. Could you maybe put the whole code for the last implementation in your answer. :)

http://stackoverflow.com/comment/87272856
type: QuestionComment
comment on: http://stackoverflow.com/q/50127488
type: Comment
has text: Possible duplicate of [Keras Model With CuDNNLSTM Layers Doesn't Work on Production Server](https://stackoverflow.com/questions/48086014/keras-model-with-cudnnlstm-layers-doesnt-work-on-production-server)
score: 0

http://stackoverflow.com/comment/87338573
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50159567
type: QuestionComment
has text: @CharlesDuffy so excaping it with the `^` did not work at all, but using `\\` worked great, so feel free to flag it

http://stackoverflow.com/comment/87302762
has text: @Blu try setting `timeout` keyword argument, e.g.: `r.html.render(timeout=20)` (the default is 8 seconds). To be honest it takes sooo long to render that it pretty much disqualifies this solution on this website. It takes 16 seconds to load even in my browser, so in this case, you should use the regex solution proposed by [Rakesh](https://stackoverflow.com/users/532312/rakesh) if you don't need any other data rendered by JS.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50139514

matplotlib
tags question: http://stackoverflow.com/q/50092460
tags question: http://stackoverflow.com/q/50091591
tags question: http://stackoverflow.com/q/50138291
tags question: http://stackoverflow.com/q/50172905
tags question: http://stackoverflow.com/q/50190900
tags question: http://stackoverflow.com/q/50127979
tags question: http://stackoverflow.com/q/50190132
tags question: http://stackoverflow.com/q/50190718
tags question: http://stackoverflow.com/q/50149562
tags question: http://stackoverflow.com/q/50095188
tags question: http://stackoverflow.com/q/50173642
tags question: http://stackoverflow.com/q/50120633
tags question: http://stackoverflow.com/q/50208867
tags question: http://stackoverflow.com/q/50161915
tags question: http://stackoverflow.com/q/50206120
tags question: http://stackoverflow.com/q/50078277
tags question: http://stackoverflow.com/q/50220922
tags question: http://stackoverflow.com/q/50139712
tags question: http://stackoverflow.com/q/50123534
tags question: http://stackoverflow.com/q/50189919
tags question: http://stackoverflow.com/q/50199904
tags question: http://stackoverflow.com/q/50223388
tags question: http://stackoverflow.com/q/50118660
tags question: http://stackoverflow.com/q/50222011
tags question: http://stackoverflow.com/q/50078060
tags question: http://stackoverflow.com/q/50158333
tags question: http://stackoverflow.com/q/50098388
tags question: http://stackoverflow.com/q/50138862
tags question: http://stackoverflow.com/q/50114827
tags question: http://stackoverflow.com/q/50114891
tags question: http://stackoverflow.com/q/50126307
tags question: http://stackoverflow.com/q/50192121
tags question: http://stackoverflow.com/q/50141983
tags question: http://stackoverflow.com/q/50219454
tags question: http://stackoverflow.com/q/50162556
tags question: http://stackoverflow.com/q/50099081
tags question: http://stackoverflow.com/q/50211658
tags question: http://stackoverflow.com/q/50087868
tags question: http://stackoverflow.com/q/50154976
tags question: http://stackoverflow.com/q/50185275
tags question: http://stackoverflow.com/q/50209585
tags question: http://stackoverflow.com/q/50198977
tags question: http://stackoverflow.com/q/50089485
tags question: http://stackoverflow.com/q/50196837
tags question: http://stackoverflow.com/q/50152628
tags question: http://stackoverflow.com/q/50174336
tags question: http://stackoverflow.com/q/50130445
tags question: http://stackoverflow.com/q/50163565
tags question: http://stackoverflow.com/q/50180981
tags question: http://stackoverflow.com/q/50197712
tags question: http://stackoverflow.com/q/50117875
tags question: http://stackoverflow.com/q/50168860
tags question: http://stackoverflow.com/q/50152057
tags question: http://stackoverflow.com/q/50134783
tags question: http://stackoverflow.com/q/50195331
tag name: matplotlib
tags question: http://stackoverflow.com/q/50093485
tags question: http://stackoverflow.com/q/50222104
tags question: http://stackoverflow.com/q/50181989
tags question: http://stackoverflow.com/q/50145309
tags question: http://stackoverflow.com/q/50119123
tags question: http://stackoverflow.com/q/50175196
tags question: http://stackoverflow.com/q/50224867
tags question: http://stackoverflow.com/q/50106019
tags question: http://stackoverflow.com/q/50215803
tags question: http://stackoverflow.com/q/50109374
tags question: http://stackoverflow.com/q/50213285
tags question: http://stackoverflow.com/q/50159373
tags question: http://stackoverflow.com/q/50119460
tags question: http://stackoverflow.com/q/50103957
tags question: http://stackoverflow.com/q/50144054
tags question: http://stackoverflow.com/q/50097765
tags question: http://stackoverflow.com/q/50087098
tags question: http://stackoverflow.com/q/50139778
tags question: http://stackoverflow.com/q/50194394
tags question: http://stackoverflow.com/q/50098438
tags question: http://stackoverflow.com/q/50183044
tags question: http://stackoverflow.com/q/50107437
tags question: http://stackoverflow.com/q/50196561
tags question: http://stackoverflow.com/q/50080389

http://stackoverflow.com/q/50076467
score: 2
type: AnsweredQuestion
has title: using enhanced model in google cloud speech api
upvote count: 2
has answer: http://stackoverflow.com/a/50099176
answer count: 1
downvote count: 0
has body: I'm trying to use the enhanced models on the Google Speech API like: gcs_uri="gs://mybucket/averylongaudiofile.ogg" client = speech.SpeechClient() audio = types.RecognitionAudio(uri=gcs_uri) config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.OGG_OPUS, language_code='en-US', sample_rate_hertz=48000, use_enhanced=True, model='phone_call', enable_word_time_offsets=True, enable_automatic_punctuation=True) operation = client.long_running_recognize(config, audio) I have enabled data logging, to be able to use the enhanced model, in the 'Cloud Speech API' settings for my project When I run it, it throws the following error: Traceback (most recent call last): File "./transcribe.py", line 126, in &lt;module&gt; enable_automatic_punctuation=True) ValueError: Protocol message RecognitionConfig has no "use_enhanced" field. Any suggestions?
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50099176
tagged with: google-cloud-speech
tagged with: python

http://stackoverflow.com/a/50187968
type: Answer
has body: This works also fine: df_merged['price_new'] = 0 for i, row in df_merged.iterrows(): df_merged.loc[i,'price_new'] = i
answers question: http://stackoverflow.com/q/50187932
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87282507
has text: @APC when you just need to perform some operation you can read directly from DB, or source.
type: QuestionComment
comment on: http://stackoverflow.com/q/50131823
type: Comment
score: 0

http://stackoverflow.com/comment/87312907
comment on: http://stackoverflow.com/q/50146593
type: Comment
has text: I have now edited the code, and i have now put the actual full code in the question.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/94365291
type: QuestionComment
comment on: http://stackoverflow.com/q/50187767
type: Comment
has text: Apparently your _gdbm module got broken or whatever. You should reinstall it.
score: 0

http://stackoverflow.com/a/50189849
type: Answer
answers question: http://stackoverflow.com/q/50189654
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50189654
has body: You can use apply on a series and avoid writing loops. from nltk import word_tokenize from nltk.stem import PorterStemmer ## intialise stemmer class pst = PorterStemmer() ## sample data frame df = pd.DataFrame({'senten': ['I am not dancing','You are playing']}) ## apply here df['senten'] = df['senten'].apply(word_tokenize) df['senten'] = df['senten'].apply(lambda x: ' '.join([pst.stem(y) for y in x])) print(df) senten 0 I am not danc 1 you are play

http://stackoverflow.com/q/50194070
type: Question
has body: My question is similar to another that was asked about Python3 so perhaps the answer is the same one - if so, I´d appreciate it if somebody can clarify this and go the step further of answering the additional questions posted here since there is, really, not a good answer there as to WHY it happens and HOW to avoid it without unintended consequences. Perhaps with 2.7 there is a better one? I don´t understand the following sequence where a virtual environment in my MAC OS ends up with a version of PIP that´s older than the version it created it: dhcp--41:VO$ virtualenv -p /usr/local/Cellar/python@2/2.7.15/bin/python env Running virtualenv with interpreter /usr/local/Cellar/python@2/2.7.15/bin/python New python executable in /Users/jbs/PycharmProjects/VOSW- VWN/env/bin/python2.7 Also creating executable in /Users/jbs/PycharmProjects/VOSW-VWN/env/bin/python Installing setuptools, pip, wheel...done. We´ve made sure the interpreter is 2.7.15 dhcp--41:VO$ source env/bin/activate (env) dhcp--41:VO jbs$ python Python 2.7.15 (default, May 1 2018, 16:44:14) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; exit() This is just a check that the interpreter is 2.7.15 and now we generate the requirements output which is small as expected but which gives this warning (which is what I DON´T understand): (env) dhcp--41:VO$ pip freeze wheel==0.26.0 You are using pip version 8.0.2, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. We´ll now leave the environment and do freeze outside it: (env) dhcp--41:VO$ deactivate dhcp--41:VO$ pip freeze absl-py==0.2.0 No suggestion for upgrade is given here despite the fact that we have the SAME version of python (if I understand correctly) as we check next: dhcp-18--41:VO$ python Python 2.7.15 (default, May 1 2018, 16:44:14) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] o…
tagged with: pycharm
tagged with: installation
has answer: http://stackoverflow.com/a/61656615
has answer: http://stackoverflow.com/a/53492115
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: virtualenv
linked to: http://stackoverflow.com/q/29689514
favorite count: 0
has comment: http://stackoverflow.com/comment/87408218
score: 3
has title: A Python virtual environment ends up with an older version of PIP than the one that created it... why and how can I fix this versioning issue?
has comment: http://stackoverflow.com/comment/87406490
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/93889660
has answer: http://stackoverflow.com/a/50201418
has comment: http://stackoverflow.com/comment/87408289
answer count: 3
has comment: http://stackoverflow.com/comment/93854231
has comment: http://stackoverflow.com/comment/87406960

http://stackoverflow.com/q/50167261
has answer: http://stackoverflow.com/a/50167605
has title: Is it true that "Python never implicitly copies objects"?
possible better answer: http://stackoverflow.com/a/50167605
favorite count: 0
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/87352235
has comment: http://stackoverflow.com/comment/87352181
has comment: http://stackoverflow.com/comment/87352219
has answer: http://stackoverflow.com/a/50167512
accepted answer: http://stackoverflow.com/a/50167512
score: 1
has comment: http://stackoverflow.com/comment/87352637
has comment: http://stackoverflow.com/comment/87357618
linked to: http://stackoverflow.com/q/2465921
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
answer count: 2
has body: I've found this statement in one of the answers to this question. What does it mean? I would have no problem if the statement were "Python never implicitly copies dictionary objects". I believe tuples, lists, sets etc are considered "object" in python but the problem with dictionary as described in the question doesn't arise with them.
has comment: http://stackoverflow.com/comment/87352240
has comment: http://stackoverflow.com/comment/87352194
linked to: http://stackoverflow.com/q/2612802
downvote count: 0
has comment: http://stackoverflow.com/comment/87353632
upvote count: 1

http://stackoverflow.com/q/50209312
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/90283041
has body: I am trying to use spark-tree-plotting package to visualize the decision tree. In the this link https://github.com/julioasotodv/spark-tree-plotting , they have explained two methods to install. By changing the conf file nothing seems to happen. For the installation through second method i am giving the command in cmd- spark-submit --packages julioasotodv:spark-tree-plotting:0.2 %C:\Users\pallaw\PycharmProjects\decision tree\case_1\dt2.py% but i am getting the error: cannot load the main class from JAR file:/C:/spark/bin/%25C:/Users/Pallaw/PycharmProjects/decision. I am new to all this, please if anyone has idea, help me to solve this.
has comment: http://stackoverflow.com/comment/93859089
upvote count: 3
downvote count: 0
tagged with: apache-spark
answer count: 0
has title: Visualizing decision tree using spark_tree_plotting package
tagged with: decision-tree
favorite count: 0
tagged with: apache-spark-ml
type: Question
has comment: http://stackoverflow.com/comment/90296960
score: 3
has comment: http://stackoverflow.com/comment/90220846
type: UnansweredQuestion

http://stackoverflow.com/q/50082549
has comment: http://stackoverflow.com/comment/87858736
has answer: http://stackoverflow.com/a/50422171
downvote count: 2
answer count: 1
upvote count: 1
has title: How to use Constructor to create an object in python
has body: This one has me very stuck. I need to use a class that I have created to create an object in the main module. However in my own experience we are supposed to create the object in main before we can call functions from a class.The name of the object i need to create will be named (Customer1), and the general idea of the program is that it is an ordering program for a Chinese restaurant The code is as follows. def Choose_dish(self): print('Please choose from the following items for a main dish:' 'Sweet and Sour Pork, Sesame Chicken, or Shrimp Fried rice.') choice = input('Press 1 for Sweet and Sour, Press 2 for Sesame Chicken, or press 3 for Shrimp Fried rice.') if choice == 1: self._dish = 'sweet and sour' if choice ==2: self._dish = 'sesame chicken' if choice == 3: self._dish = 'shrimp fried rice' The first method is the protected constructor which is meant to be called so the (Customer1) object can select a choice of main dish. The following is the code I have been trying in main. from Dinner_Combo import Dinner_combo def main(): print('Welcome to the restaurant') choice = input('please select 1 for regular meal, or select 2 for deluxe meal!') if int(choice) == 1: customer1 = Dinner_combo() main() please note that the name of the python class file I have created is "Dinner_Combo", and the name of the class itself is "Dinner_combo"
favorite count: 0
type: Question
tagged with: constructor
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: class

http://stackoverflow.com/comment/87533056
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50210226
type: Comment
has text: @AlexW ok. What/who generates the template? Since no punctuation is allowed in jinja2 fields, it must be told not to put the wrong chars in there.

http://stackoverflow.com/q/50195864
score: 2
linked to: http://stackoverflow.com/q/47755442
answer count: 0
has comment: http://stackoverflow.com/comment/87408894
downvote count: 0
duplicate of: http://stackoverflow.com/q/47755442
has title: Python apply method
favorite count: 0
has comment: http://stackoverflow.com/comment/87417741
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87408834
upvote count: 2
type: UnansweredQuestion
has body: I have a DataFrame which has 5 rows and 5 columns. Created by the statement- df = pd.DataFrame(np.random.randn(25).reshape(5,5), index=list('abcde'), columns=list('vwxyz')) I NEED TO - Define a function call 'Standardizing' which works on a series as: Find the mean and standard deviation of the series Subtract each value of the series with the mean Divide the result with the standard deviation Apply this function to each numerical column (int or float) of the DF. To achieve this, I do - 1) def Standardizing(y): mean = y.mean() sd = y.std() return y.map(lambda x: round(((x-mean)/sd),2)) df.apply(Standardizing) 2) def Standardizing2(y): mean = y.mean() sd = y.std() return round((y-mean)/sd,2) df.apply(Standardizing2) While I understand, 1 should work. y is a Series for me and then I am using map to reach each element of Series. Just of curiosity, I wrote 2 and that also works. I do not understand why it works. I would really appreciate any inputs.
has comment: http://stackoverflow.com/comment/87411942
tagged with: python

http://stackoverflow.com/comment/87407646
type: AnswerComment
comment on: http://stackoverflow.com/a/50194144
has text: This is not correct: " the JPEG "quality" metric is a number from 0-100 where 100 represents lossless and 0 is maximum compression."
type: Comment
score: 1

http://stackoverflow.com/comment/87227929
type: Comment
has text: Might I suggest that you improve your title, making it a little more specific? Perhaps something like "How do I access specific columns and data using Pandas?" It also might be helpful if you provide applicable error message(s).
type: QuestionComment
comment on: http://stackoverflow.com/q/50104357
score: 0

http://stackoverflow.com/q/50138636
type: UnansweredQuestion
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/87295981
upvote count: 1
tagged with: python
has body: I extended standart django user model by one-to-one field. Made news block, and added comments there. In comments i cant display user avatar from UserProfile model, cause dont understand how correctly ask database for it D;. Here my code: main/models.py from django.db import models from django.utils import timezone from django.contrib import auth from django.contrib.auth.forms import User from django.shortcuts import render, redirect from profiles.models import UserProfile # Create your models here. class News(models.Model): news_title = models.CharField(max_length=250) news_body = models.TextField(max_length=2000, blank=True) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) image = models.FileField() published_date = models.DateTimeField(blank=True, null=True) def publish(self, request): self.published_date = timezone.now() self.save() return redirect('index') def __str__(self): return self.news_title class Comment(models.Model): news = models.ForeignKey('main.News', related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text profiles/models.py class UserProfile(models.Model): JEW_CHOICE = ( ('Да', 'Да'), ('Нет', 'Нет'), ) MF_CHOICE = ( ('М', 'М'), ('Ж', 'Ж') ) user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=100, default='', blank=True) city = models.CharField(max_length=100, default='', blank=True) description = models.CharField(max_length=500, default='', blank=True) website = models.URLField(default='', blank=True) avatar = models.ImageField(default='', blank=True) gender = models.CharField(max_length=100, choices = MF_CHOICE, default = 'М', blank=True) jew = models.CharField(max_length=100, choices = JEW_CHOICE, default = 'Да', blank…
score: 1
has answer: http://stackoverflow.com/a/50138756
has answer: http://stackoverflow.com/a/50138860
has comment: http://stackoverflow.com/comment/87295760
favorite count: 0
has title: django, does not display the avatar in the comments
type: Question
answer count: 2

http://stackoverflow.com/a/50161776
has body: tl, dr; I removed auth migrations and ran makemigrations again, that seems to have solved the problem. I had decided to give option 2 a try. I removed the add_to_class patches, created a new class User(AbstractUser) with the new fields, removed all the existing migrations and ran makemigrations again. I got the exact same error, which made no sense because there was no longer any code relating auth.User to Profile, so I decided to investigate auth migrations. I ran $ python migrate --list settings=settings.mysettings and it showed a suspicious migration for auth, with yesterday's date, probably when I first tried to make migrations. Tutorials on "how to reset all migrations" do not mention third-party installed apps, but thanks to this thread I knew where Django stored the auth migrations, so I removed both of them (the initial and the suspicious one) and reordered the INSTALLED_APPS so that access is now before django.contrib.auth. Then ran makemigrations again, and it got through access and auth migrations successfully. I'm now getting other problems with migrations in other apps, but they don't seem to be related with this. It might be nice to have a more intuitive way to reset all existing migrations, not only those from your repo. But then again, I don't think the add_to_class patches are the proper way to do what we wanted.
type: Answer
answers question: http://stackoverflow.com/q/50160551
score: 0

http://stackoverflow.com/comment/87366332
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/50174660
has text: Check `stderr`. Also remove the try except as it's just swallowing errors.

http://stackoverflow.com/a/50087702
has body: Create a dictionary that maps from operand name to the symbol: ops = {'subtract':'-', 'add':'+', 'equal':'=='} You can make it as long as you want, which clearly is an optimisation – adding more operands is extremely easy and does not need any further modification. Loop over your expression using a list comprehension: [x if x.isdigit() else ops[x] for x in re.findall(r'\d+|[a-z]+',expr)] This uses a regex to separate digits and operands, so import re at the start. The regex returns ['9', 'subtract', '5', 'equal', '4'] and the list comprehension replaces not-digit strings with the items from the dictionary. Result: ['9', '-', '5', '==', '4'] so you'd use expr = ''.join([x if x.isdigit() else ops[x] for x in re.findall(r'\d+|[a-z]+',expr)]) to get your output '9-5==4'
score: 2
type: Answer
answers question: http://stackoverflow.com/q/50087588
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/50092883
score: 0
linked to: http://stackoverflow.com/q/1680528
tagged with: python
has comment: http://stackoverflow.com/comment/87201969
has body: I have a list of objects called TerrainTile. Each of these instances have a list called resourceList. resourceList = [] I append an object called obj to this list within this method: def add_resource_object (self, obj): self.resourceList.append(obj) return For some reason, instead of each individual instance having its own list called resourceList, it seems all instances are sharing the same resourceList list and when it is appended to all instances are appended to. Why is the .append() appending to all instances of TerrainTile?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50092918
answer count: 2
has title: Appending an object to the list of an instance, but only in that instance
has comment: http://stackoverflow.com/comment/87202011
has answer: http://stackoverflow.com/a/50092937
possible better answer: http://stackoverflow.com/a/50092937
type: Question
has answer: http://stackoverflow.com/a/50092918
type: AnsweredQuestion

http://stackoverflow.com/q/50109289
downvote count: 0
accepted answer: http://stackoverflow.com/a/50109314
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50109353
has title: Find the max length of list inside another list in a dictionary
tagged with: nested-lists
type: Question
possible better answer: http://stackoverflow.com/a/50109333
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50109333
has answer: http://stackoverflow.com/a/50109314
tagged with: list
has body: I need to get the max lenght of a list INSIDE another list, which in turn is insside a dictionary. Let's say I have: x={ 'a':[[1],[1,2,3],[1],[1]], 'b':[[1],[1,2],[1],[1]], 'c':[[1],[1,2],[1],[1]] } All I need is to get 3 (max lenght according to second list of 'a'). So far I've been searching for similar approaches but I only could find iteration on the first level of lists and I just get 4 (lenght of 'a','b' and 'c' values: 4 lists) which is NOT what I'm looking for. So far I have: x={ 'a':[[1],[1,2,3],[1],[1]], 'b':[[1],[1],[1],[1]], 'c':[[1],[1],[1],[1]] } maxlist=len(x[[k for k in x.keys() if x[k]==max(x.values(),key=len)][0]])
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/50113323
has body: I am using flask sqlalchemy to create db which in turns create a app.db files to store tables and data. Now for the backup it should be simple to just take a copy of app.db somewhere in the server. But suppose while the app is writing data to app.db and we make a copy at that time then we might have inconsistent app.db file. How do we maintain the consistency of the backup. I can implement locks to do so. But I was wondering on standard and good solutions for database backup and how is this implemented in python.
accepted answer: http://stackoverflow.com/a/50114682
upvote count: 6
type: AnsweredQuestion
answer count: 2
tagged with: sqlite
downvote count: 0
has answer: http://stackoverflow.com/a/66586292
possible better answer: http://stackoverflow.com/a/66586292
has answer: http://stackoverflow.com/a/50114682
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
has title: Sqlite database backup and restore in flask sqlalchemy
score: 6
tagged with: python
tagged with: flask

http://stackoverflow.com/comment/87378717
comment on: http://stackoverflow.com/a/50180697
score: 0
type: Comment
has text: Hello David, thank your answer. I was tweaking around with the code and the following seems to work, "with tf.Session() as sess: saver.restore(sess, final_model_path) output= sess.run(tf.argmax(logits,1),feed_dict={X: X_test})". Anyways, since you are the only person to answer here, I will count your answer as correct. Cheers.
type: AnswerComment

http://stackoverflow.com/q/50221512
has comment: http://stackoverflow.com/comment/115668512
has comment: http://stackoverflow.com/comment/87461794
has title: Python multiprocessing performance only improves with the square root of the number of cores used
has comment: http://stackoverflow.com/comment/87467188
upvote count: 13
score: 12
has comment: http://stackoverflow.com/comment/87467270
has comment: http://stackoverflow.com/comment/87483515
answer count: 1
has comment: http://stackoverflow.com/comment/87461021
has body: I am attempting to implement multiprocessing in Python (Windows Server 2012) and am having trouble achieving the degree of performance improvement that I expect. In particular, for a set of tasks which are almost entirely independent, I would expect a linear improvement with additional cores. I understand that--especially on Windows--there is overhead involved in opening new processes [1], and that many quirks of the underlying code can get in the way of a clean trend. But in theory the trend should ultimately still be close to linear for a fully parallelized task [2]; or perhaps logistic if I were dealing with a partially serial task [3]. However, when I run multiprocessing.Pool on a prime-checking test function (code below), I get a nearly perfect square-root relationship up to N_cores=36 (the number of physical cores on my server) before the expected performance hit when I get into the additional logical cores. Here is a plot of my performance test results : ( "Normalized Performance" is [ a run time with 1 CPU-core ] divided by [ a run time with N CPU-cores ] ). Is it normal to have this dramatic diminishing of returns with multiprocessing? Or am I missing something with my implementation? import numpy as np from multiprocessing import Pool, cpu_count, Manager import math as m from functools import partial from time import time def check_prime(num): #Assert positive integer value if num!=m.floor(num) or num&lt;1: print("Input must be a positive integer") return None #Check divisibility for all possible factors prime = True for i in range(2,num): if num%i==0: prime=False return prime def cp_worker(num, L): prime = check_prime(num) L.append((num, prime)) def mp_primes(omag, mp=cpu_count()): with Manager() as manager: np.random.seed(0) numlist = np.random.randint(10**omag, 10**(omag+1), 100) L = manager.list() cp_worker_ptl = partial(cp_worker, L=L) try: pool = Pool(processes=mp) list(pool.imap(cp_worker_ptl, numlist)) except Exception as e: print(e) finally: pool.…
has comment: http://stackoverflow.com/comment/87460936
tagged with: parallelism-amdahl
downvote count: 1
has comment: http://stackoverflow.com/comment/87598309
has comment: http://stackoverflow.com/comment/87461817
favorite count: 0
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/87487934
tagged with: performance
has comment: http://stackoverflow.com/comment/87484939
linked to: http://stackoverflow.com/q/47845
has comment: http://stackoverflow.com/comment/87467173
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50221801
tagged with: windows
has comment: http://stackoverflow.com/comment/87460792
tagged with: python
has comment: http://stackoverflow.com/comment/87487661
linked to: http://stackoverflow.com/q/50183080

http://stackoverflow.com/comment/122971403
score: 0
type: Comment
has text: Oct, 2021. This is still working for me.
type: AnswerComment
comment on: http://stackoverflow.com/a/55943881

http://stackoverflow.com/comment/87349283
has text: Also see the [Wiikipedia article on the CSV (Comma Separated Values)](https://en.wikipedia.org/wiki/Comma-separated_values) file format. They're usually plain-text files and therefore somewhat "human readable".
type: Comment
comment on: http://stackoverflow.com/q/50165242
type: QuestionComment
score: 0

http://stackoverflow.com/q/50197426
has title: Retrieve bulk data from YAML using Python
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50197786
tagged with: python
has answer: http://stackoverflow.com/a/50197786
has answer: http://stackoverflow.com/a/50197737
type: AnsweredQuestion
tagged with: yaml
possible better answer: http://stackoverflow.com/a/50197737
downvote count: 0
upvote count: 1
score: 1
tagged with: pyyaml
favorite count: 0
has body: I have a yaml file of the form below: Solution: - number of solutions: 1 number of solutions displayed: 1 - Gap: None Status: optimal Message: bonmin\x3a Optimal Objective: objective: Value: 0.010981105395 Variable: battery_E[b1,1,1]: Value: 0.25 battery_E[b1,1,2]: Value: 0.259912707017 battery_E[b1,2,1]: Value: 0.120758408109 battery_E[b2,1,1]: Value: 0.0899999972181 battery_E[b2,2,3]: Value: 0.198967393893 windfarm_L[w1,2,3]: Value: 1 windfarm_L[w1,3,1]: Value: 1 windfarm_L[w1,3,2]: Value: 1 Using Python27, I would like to import all battery_E values from this YAML file. I know I can iterate over the keys of battery_E dictionary to retrieve them one by one (I am already doing it using PyYAML) but I would like to avoid iterating and do it in one go!

http://stackoverflow.com/q/50143155
has answer: http://stackoverflow.com/a/50143416
answer count: 1
tagged with: weather
tagged with: groupme
tagged with: bots
type: Question
has body: So in the GroupMe Bot I'm working on - I've gotten the bot to respond by passing messages with an if statement in the webhooks. def webhook(): # 'message' is an object that represents a single GroupMe message. message = request.get_json() speaker = message['name'] # If hypefact! is spoken, return random fact # This code replies once and then calls another function that replies again if 'hypefact!' in message['text'].lower() and not sender_is_bot(message): reply(speaker + ' - Here is your Hype Fact: ') reply(fact_delivery()) Now below is the function for get_weather def get_weather(city): ## Bunch of stuff happens reply(weatherData['currently']['summary'] + ', ' + str( weatherData['currently']['apparentTemperature']) + degree_sign + 'F. ' + weatherData['hourly'][ 'summary'] + '\n\n' + weatherData['daily']['summary']) If a phrase is "in message['text']" it will trigger an action because it is in the message. What if I was trying to get it to parse this message. "Whats the weather in Austin this weekend" The key part of that phrase is "weather in Austin" So I want to take the word after "in" and parse that to get_weather(city) Expected workflow: person in chat says phrase with "weather in {CITY}" in the message bot triggers, filters city out of the string to call get_weather function
has title: Calling function with passing variable from JSON message request in Groupme Bot
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50143416
tagged with: python

http://stackoverflow.com/comment/94326574
type: Comment
type: AnswerComment
has text: @cgnorthcutt Using ⏎ as a newline: ```a,b,c,d = (⏎ long_named_function())``` is valid and identical in meaning. I always break long lines in this style and never use backslashes. PEP 8 recommends this. See [this question](https://stackoverflow.com/questions/48830681/is-line-continuation-with-backslash-dangerous-in-python). It's annoying that Jupyter doesn't support backslashes since they're valid Python but they're almost never necessary.
comment on: http://stackoverflow.com/a/50113127
score: 1

http://stackoverflow.com/a/50190837
score: 0
answers question: http://stackoverflow.com/q/50190720
has body: You could wrap your current data with a class that could provide the specialized update methods you specified, without changing the entire structure of your original data to begin with: class Row: def __init__(self, row): self.row = row def __setitem__(self, _t, _val): self.row[_t] = str(_val) def __getitem__(self, _stat): return int(self.row[_stat]) def __repr__(self): return '{}({})'.format(self.__class__.__name__, str(self.row)) class Players: def __init__(self, data={}): self.data = {i['name']:Row(i) for i in data} def __getitem__(self, name): return self.data[name] def __setitem__(self, _name, _data): self.data[_name] = Row(_data) def __repr__(self): return '{}({})'.format(self.__class__.__name__, str(self.data)) players = [{'points': '27', 'name': 'John', 'Played': '6'}, {'points': '43', 'name': 'Emil', 'Played': '13'}, {'points': '11', 'name': 'Susan', 'Played': '2'}, {'points': '4', 'name': 'Peter', 'Played': '3'}] d = Players(players) d['John']['points'] = 30 d["John"]["Played"] = d["John"]["Played"]+1 print(d['John']) d['Bob'] = {'points': '2', 'Played': '5'} Output: Row({'points': '30', 'name': 'John', 'Played': '7'})
has comment: http://stackoverflow.com/comment/87399932
type: Answer
has comment: http://stackoverflow.com/comment/87399226
has comment: http://stackoverflow.com/comment/87398983
has comment: http://stackoverflow.com/comment/87399910
has comment: http://stackoverflow.com/comment/87399690
has comment: http://stackoverflow.com/comment/87399599
has comment: http://stackoverflow.com/comment/87398848
accepted answer of: http://stackoverflow.com/q/50190720
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87399686
upvote count: 1
has comment: http://stackoverflow.com/comment/87399121
downvote count: 1
has comment: http://stackoverflow.com/comment/87399998
has comment: http://stackoverflow.com/comment/87401600
has comment: http://stackoverflow.com/comment/87399782

http://stackoverflow.com/comment/87463742
comment on: http://stackoverflow.com/q/50222978
type: Comment
type: QuestionComment
score: 0
has text: How do you want the overlap to be if they are 3x3 submatrices? 1 element overlap, or 4 elements overlap?

http://stackoverflow.com/comment/87391763
type: QuestionComment
comment on: http://stackoverflow.com/q/50187519
score: 0
has text: @Nurjan `<cx_Oracle.Connection to something@ip/somethingother>`
type: Comment

http://stackoverflow.com/comment/87301003
score: 0
type: Comment
type: AnswerComment
has text: That is a personal preference. You can have a string format like “User {} passed the year with average grade of {:.2f}”.format(username, marking) and this will print the username and the marking to two decimal places. Is just more readable. In Python 3.6 you can even go a step further with string literals: https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498
comment on: http://stackoverflow.com/a/50124624

http://stackoverflow.com/q/50210802
upvote count: 1
has comment: http://stackoverflow.com/comment/87439136
tagged with: python
linked to: http://stackoverflow.com/q/5055042
has body: I have an input file which looks like =========================== __A= 2.3 __b= 3.26 =========================== __ctx= 4.2 =========================== __itermax= 100 __errmax= 1e-07 Using this inputfile a collection of outputs within a different code( not implemented in python) has been generated. I am now trying to write some Python scripts to read this input file as well as other generated outputs to perform postproccessing analysis. I thus would like to extract the value of each parameter(A, b, ctx, ...) by a python script. Please note that this input file is distinct from the setting file discussed here as I can not perform any modification on the structure of the input file. I have tried import sys try: directory_name=sys.argv[1] print(directory_name) except: print('Please pass directory_name') input_file = directory_name +"input.txt" with open(input_file) as fin: for line in fin: exec(line) The error that I am encountering after running the code is File "code.py", line 14, in &lt;module&gt; exec(line) File "&lt;string&gt;", line 1 =========================== ^ SyntaxError: invalid syntax Any suggestion on improving this code, or with a different outputting method (e.g. as a dictionary), to obtain the values of the parameters is helpful.
type: Question
has comment: http://stackoverflow.com/comment/87471060
has comment: http://stackoverflow.com/comment/87439254
has comment: http://stackoverflow.com/comment/87438667
has comment: http://stackoverflow.com/comment/87438623
downvote count: 3
has comment: http://stackoverflow.com/comment/87471093
possible better answer: http://stackoverflow.com/a/50210935
favorite count: 0
accepted answer: http://stackoverflow.com/a/50211021
has comment: http://stackoverflow.com/comment/87439428
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87439455
has answer: http://stackoverflow.com/a/50210935
has answer: http://stackoverflow.com/a/50211021
has answer: http://stackoverflow.com/a/50210888
has title: Read an input file in python
answer count: 5
score: -2
has answer: http://stackoverflow.com/a/50210924
has answer: http://stackoverflow.com/a/50210964

http://stackoverflow.com/q/50133679
has body: My code below: import random lines = open('/Users/xxx/Desktop/wordlist.text).read().splitlines() words random.choice(lines) guesses = '' turns = 10 while turns &gt; 0: failed = 0 for char in word: if char = " " print (char), elif char in guesses: print(char) else: print("_") failed += 1 if failed == 0 print("You won") Output: Start Guessing _ _ _ _ _ _ guess a character: How do I make it so that the underscores are next to each other like this: _ _ _ _ _ _ I don't understand why they are printing on new lines every time?
has comment: http://stackoverflow.com/comment/87285296
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50133750
score: -5
accepted answer: http://stackoverflow.com/a/50133750
has answer: http://stackoverflow.com/a/50133747
possible better answer: http://stackoverflow.com/a/50133747
has comment: http://stackoverflow.com/comment/87285315
favorite count: 0
type: Question
upvote count: 0
answer count: 2
downvote count: 5
has title: Printing on a new line every time I run?
has comment: http://stackoverflow.com/comment/88587835
tagged with: python

http://stackoverflow.com/comment/87209988
type: Comment
comment on: http://stackoverflow.com/a/50096756
type: AnswerComment
has text: yes, you have to rebuild the dictionary applying the format for each key/value pair
score: 0

http://stackoverflow.com/comment/87188321
comment on: http://stackoverflow.com/q/50085520
has text: Is this http://www.math.udel.edu/~rossi/Math512/2003/br5.pdf the equation or even a source of yours?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/87278225
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50130099
score: 0
has text: also if you are familiar with `pdb` in python, you could put a breakpoint immediately after `aggregated_measurements_objects = AggregatedMeasurement.query.all()` in your view to ensure that a call to the db is being made `aggregated_measurements_objects = AggregatedMeasurement.query.first();` `import pdb; pdb.set_trace()`

http://stackoverflow.com/comment/87378724
has text: `json.loads` should be passed a file object and not the filename. `with open('newfile.json') as f: json.loads(f)`
comment on: http://stackoverflow.com/q/50180707
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/50187792
answers question: http://stackoverflow.com/q/50187667
has comment: http://stackoverflow.com/comment/87438708
score: 0
type: Answer
has body: You just need to wrap you function with a Lambda layer. Here is an example: def complex_tf_fn(x): u, v = tf.nn.moments(x, axes=[1], keep_dims=True) return (x - u) / tf.sqrt(v) with tf.device('/cpu:0'): model = tf.keras.Sequential([ tf.keras.layers.Lambda(complex_tf_fn, input_shape=[784]), tf.keras.layers.Dense(1024, activation='relu'), tf.keras.layers.Lambda(complex_tf_fn), tf.keras.layers.Dense(10, activation='softmax') ])

http://stackoverflow.com/q/50204613
upvote count: 14
tagged with: pre-trained-model
downvote count: 0
has title: Download pretrained ImageNet model of ResNet, VGG, etc. (.PB file)
has body: I have downloaded a pre-trained model on ImageNet of Inception v3 from http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz (found this link while following one of the tutorials on codelabs). This zip file contains .pb file that I can directly import as GraphDef in TensorFlow. I would like to know if there are similar .pb files for other architectures as well, such as ResNet, VGG16, MobileNet, etc. If yes, could you provide the link of those? Thanks in advance. Kind Regards, Ajay
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/69181862
tagged with: python
accepted answer: http://stackoverflow.com/a/50214790
has comment: http://stackoverflow.com/comment/122275099
possible better answer: http://stackoverflow.com/a/69181862
has answer: http://stackoverflow.com/a/50214790
type: AnsweredQuestion
score: 14
answer count: 2

http://stackoverflow.com/a/50198312
has body: Yet another way: import re myText = "sample" result = '.' + '.'.join(list(re.sub('[aeiou]', "", myText, flags=re.I))) print(result) Explanation: re.sub removes the not required letters (case insensitive = re.I) list makes the string an array of characters join places a dot in between '.' + adds the missing dot in front of the first character
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50197726

http://stackoverflow.com/comment/132290673
score: 0
type: Comment
type: AnswerComment
has text: As an extension (since hostname is not in the logging spec), I changed `formatMessage` to return `{fmt_key: host if fmt_key == "host" else record.__dict__[fmt_val] for fmt_key, fmt_val in self.fmt_dict.items()}`, after also adding `import platform` and `host = platform.node()` at the beginning of the file. I find this very handy when sending logs from multiple hosts and consuming centrally, such as filebeat into elastisearch or similar. (I'm no pythonista, there's likely a much better way to do this.) (Add `"host":""` to the instantiation of `jsonFormatter`.)
comment on: http://stackoverflow.com/a/70223539

http://stackoverflow.com/q/50110691
tagged with: python-3.x
has title: Unable to select Python interpreter
tagged with: visual-studio-code
has body: Code on a Mac uses 2.7 version regardless of "python.pythonPath" setting explicitly set to /usr/local/bin/python3. Selecting interpreter interactively via command palette has no effect either. Running python in the terminal launches 3.6 which should be picked up by the Code with default "python.pythonPath" setting, but it is not. No matter what I do Code keeps using 2.7. What am I missing?
has comment: http://stackoverflow.com/comment/87272422
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50142754
tagged with: python
has comment: http://stackoverflow.com/comment/87261658
has comment: http://stackoverflow.com/comment/87272553
has comment: http://stackoverflow.com/comment/87238775
answer count: 3
has comment: http://stackoverflow.com/comment/87262665
downvote count: 0
has comment: http://stackoverflow.com/comment/87261588
upvote count: 1
has comment: http://stackoverflow.com/comment/87238866
score: 1
has answer: http://stackoverflow.com/a/50111958
has comment: http://stackoverflow.com/comment/87266333
favorite count: 0
has answer: http://stackoverflow.com/a/50127373
type: Question

http://stackoverflow.com/a/50165141
downvote count: 0
has comment: http://stackoverflow.com/comment/87348285
answers question: http://stackoverflow.com/q/50164917
score: 3
has comment: http://stackoverflow.com/comment/87348243
type: Answer
has body: I've gone through a lot of this book using Javascript. Part of the fun is translating the ideas into a language you are familiar with. You need to approach it with the understanding that the book is about ideas, not a particular language. However, becoming a little familiar with c will really help you understand the examples. So for example, you are probably unlikely to use linked lists in python the way you would in c, but you can certainly implement them from the examples using classes and object properties that point to other properties. Consider a simple linked list: class ListItem(): def __init__(self, val, next = None): self.next = next self.value = val self.next is essentialy a pointer to the next ListItem. Now you can create a linked list with something like: arr = [5, 7, 2, 1, 9, 0, 10, 23] head = ListItem(10) current = head for n in arr: item = ListItem(n) current.next = item current = item And then traverse the list with: pointer = head while(pointer): print(pointer.value) pointer = pointer.next You can also do a linked-list style insert and it will look a lot like the c code: #insert 'inserted_node' before first list item with value 1 inserted_node = ListItem('inserted') pointer = head while(pointer): if pointer.next.value == 1: inserted_node.next = pointer.next pointer.next = inserted_node break pointer = pointer.next It's a terrific book and worth going through even if you're not doing it in c or some other low level language. And even if you spend time with data structures you normally wouldn't go to in python, doing the translation will make you a better python programmer.
upvote count: 3
has comment: http://stackoverflow.com/comment/87348462
accepted answer of: http://stackoverflow.com/q/50164917
type: AcceptedAnswer

http://stackoverflow.com/comment/87201545
type: QuestionComment
comment on: http://stackoverflow.com/q/50092608
score: 0
has text: @wwii Yes you're right please see my edit.
type: Comment

http://stackoverflow.com/a/64494428
type: Answer
answers question: http://stackoverflow.com/q/50114952
downvote count: 0
upvote count: 1
has body: The cleanest way to do this seems to be as follows: @client.event async def on_message(message): if client.user.mentioned_in(message): await message.channel.send("hello!")
score: 1

http://stackoverflow.com/comment/87265908
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50109822
has text: thanks @jhamman, this works! can you add this as answer so I can accept?

http://stackoverflow.com/comment/87334033
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50157949
has text: Do you want this condition considered for each row individually? There's a very different way to approach this code if that's what you want out.
score: 0

http://stackoverflow.com/q/50200206
tagged with: hmmlearn
score: 0
has body: I am making a project ragrading to sign language recognition by Surface EMG signal. Now, I want to train a GMMHMM model by an array named 'single'. Its shape is (2520, 840). for single in Norm_Feat_Vsplit: # print(shape(single)) # (180, 840) # print(type(single)) # &lt;class 'numpy.ndarray'&gt; clf = hmm.GMMHMM(n_components=7, n_mix=4, covariance_type="diag", n_iter=10) print('Training ' + str(index) + ' model... ') clf1 = clf.fit(single) print('Training finished!') # Save model print('Saving model...') joblib.dump(clf1, "Hmm_model" + str(index) + ".m") print('Saving finished!') But there will be always a ValueError as following: (Sometimes it seems to be able to train the first GMMHMM model successfully, but the second will have an error.) output: Training 1 model... Traceback (most recent call last): File "E:/桌面/手语识别资料/程序/Single_Hand/Single_Hand/One_Hand_Train(注释).py", line 378, in &lt;module&gt; main() File "E:/桌面/手语识别资料/程序/Single_Hand/Single_Hand/One_Hand_Train(注释).py", line 365, in main clf1 = clf.fit(single) File "D:\Anaconda3\lib\site-packages\hmmlearn\base.py", line 436, in fit bwdlattice) File "D:\Anaconda3\lib\site-packages\hmmlearn\hmm.py", line 607, in _accumulate_sufficient_statistics raise ValueError ValueError Process finished with exit code 1 Thank for your help!
answer count: 0
has comment: http://stackoverflow.com/comment/87418162
has title: python GMMHMM fit(X)
type: Question
has comment: http://stackoverflow.com/comment/87418052
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/87266610
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50110916
has text: thank you very much, @dawg ...I wasn't aware about dictionaries aren't sorted, but i will really keep your answer in mind about how to create a new dict with max values only, it would be useful for me in future applications. Once again, thank you very much!

http://stackoverflow.com/q/50217049
tagged with: visual-studio
linked to: http://stackoverflow.com/q/18465793
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50226859
has title: I cannot open Python anymore and get the following error: 'No installed debugger has Just-In-Time debugging enabled. What can I do?
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87596124
favorite count: 0
has body: The full error from the Visual Studio Just-In-Time Debugger is: 'An unhandled win32 exception occurred in python.exe [2976]. Just-In-Time debugging this exception failed with the following error: No installed debugger has Just-In-Time debugging enabled. In Visual Studio, Just-In-Time debugging can be enabled from Tools/Options/Debugging/Just-In-Time.' However, I don't know how to open Visual Studio to enable this debugger (Home > Visual Studio, doesn't give me any results) Error What do I need to do to be able to launch Spyder again?
type: Question
tagged with: debugging
accepted answer: http://stackoverflow.com/a/50226859
tagged with: python
score: -1

http://stackoverflow.com/q/50076076
answer count: 1
tagged with: machine-learning
tagged with: logistic-regression
type: AnsweredQuestion
has title: Building a multi class logistic regression classifier without SKlearn using python
has answer: http://stackoverflow.com/a/50076239
tagged with: python
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/50076239
has body: I am trying to build a multi class logistic regression classifier using python without SKlearn library. My goal is to write a classifier to classify an app's category(e.g. health, social, etc.) with the tf-idf values in the test data. What I have got now is a dataframe where data and labels are matched by appname like the image shows. In the image, the first array 'data' is the tf-idf values from training data and the second array 'labels' is corresponding to the label of the app. What I have known now is that I can use logistic regression to learn the weights and biases for each label and then use these values to predict an app's label in test data. And what I can do now is use sigmoid function p = 1.0 / (1.0 + np.exp(-z)) where z is b+w1x1+w2x2+...+wnxn (b is bias, w is weights and x is the tf-idf value in this case). I am just trying to get weights and bias from the first item. The code is as follows: # the first training item X = train_data[0, 0:13625]#13625 features z = 0.0 for j in range(len(X)): z += W[j] * X[j] z += b p = 1.0 / (1.0 + np.exp(-z)) # sigmoid function y = train_data[1, i] # I don't know if it is right to use the second item's feature as a target. # update all weights after each train item for j in range(0, 13625): # gradient ascent log likelihood W[j] += lr * X[j] * (y - p) # t - o gives an "add" b += lr * (y - p) # update bias I don't know if it is right to train weights and bias in this way, anyone has an idea about how I can get weights and bias for each labels in order to classify an app?

http://stackoverflow.com/a/56208978
type: Answer
has body: I had the same issue with tensorflow-1.8.0. The quickest hack is to create an empty class containing your preprocessing function and pass it to the image_data_generator object of ImageDataGenerator instance : def preprocess_input(im_array): return im_array/255-.5 class foo(object): pass imgen = ImageDataGenerator(preprocessing_function='pass anything') imgen.image_data_generator = foo imgen.image_data_generator.preprocessing_function = preprocess_input flowgen = imgen.flow_from_directory('/tmp/training_folder/') flowgen.__getitem__(0)[0] #check result Another solutoin is to fix the source code in tensorflow/python/keras/_impl/keras/preprocessing/image.py by deleting image_data_generator line 672
answers question: http://stackoverflow.com/q/50114065
score: 0

http://stackoverflow.com/q/50075641
tagged with: debugging
type: Question
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50075722
has body: I'm not sure how to approach this, whether it's a Django, Python, or even Terminal solution that I can tweak. The thing is I'm learning Django following a book (reference here, really like it), and whenever I run the tests, I get really long output in the terminal for debugging matters. Obviously there's many traceback functions that get called after another, but what started bugging me is that the file paths are very long and they all have the same project folder... which is long by itself, and then it adds all the virtualenv stuff like this: Traceback (most recent call last): File "home/user/code/projects/type_of_projects_like_hobby/my_project_application/this_django_version/virtualenv/lib/python3.6/site-packages/django/db/models/base.py", line 808, in save force_update=force_update, update_fields=update_fields) Since the paths take two or more lines, I can't focus on what functions I should be looking at clearly. I have looked at the verbosity option when calling manage.py test but it doesn't help with the paths. If anyone has an idea on how to ~fix~ go about this issue, it'd be cool. Thanks guys.
has answer: http://stackoverflow.com/a/50075722
has title: Configure Django's test debugging to print shorter paths.
answer count: 1

plotly-dash
tags question: http://stackoverflow.com/q/50129149
type: Tag
tags question: http://stackoverflow.com/q/50213761
tags question: http://stackoverflow.com/q/50161471
tag name: plotly-dash
tags question: http://stackoverflow.com/q/50120037
tags question: http://stackoverflow.com/q/50075496

http://stackoverflow.com/q/50165177
has title: Pygame Text: Instead of colour, let the text show an image, or animation
upvote count: 5
answer count: 1
tagged with: pygame
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
accepted answer: http://stackoverflow.com/a/50165749
downvote count: 0
tagged with: python
has body: Something that looks like this but I want the image and text editable. Instead of having something like: title = menuFont.render("COMPUTER INFORMATION!", 1, BLACK) screen.blit(title, Rect(50, 100, 400, 400)) Is it possible for the colour in the text to be an image instead, or an animation? EDIT: For those curious... when I imported the imaged, I had to change the end of the code a bit screen.blit(texture, (50, 50)) screen.fill(BG_COLOR) screen.blit(text_surface, (50, 170)) pg.display.update() clock.tick(30) The screen.fill comes after the texture... just a heads up :)
has answer: http://stackoverflow.com/a/50165749
type: AnsweredQuestion

http://stackoverflow.com/comment/87388219
type: Comment
type: QuestionComment
has text: You could use Selenium for this: https://www.seleniumhq.org/
comment on: http://stackoverflow.com/q/50185605
score: 0

http://stackoverflow.com/comment/87194722
type: QuestionComment
has text: @sacul yeah i tried searching some pandas methods but had no succes, i indeed think pandas is the way to go
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50089228

http://stackoverflow.com/q/50129028
score: -1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
has title: Storing information in a file, Python
tagged with: database
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/87276028
has body: I'm making a car rental console base program in Python where I need to save data about cars I store (such as brand, registration number etc). What would be the ideal type of file for such a thing, and how to iniciate it?
has comment: http://stackoverflow.com/comment/87276098
answer count: 1
tagged with: file
has answer: http://stackoverflow.com/a/50129170

http://stackoverflow.com/comment/87472330
comment on: http://stackoverflow.com/a/50227555
score: 0
type: Comment
type: AnswerComment
has text: As OP intends to use this with findall, you should use a non-capturing group instead of a capturing one.

http://stackoverflow.com/comment/87306416
type: Comment
comment on: http://stackoverflow.com/a/50144045
type: AnswerComment
has text: I did... it did not give me an error. When I removed `axis=0`, I was able to reproduce the error that OP posted. Let me post a code snippet that works.
score: 0

http://stackoverflow.com/comment/87240588
score: 0
has text: It works, but loses legibility. Maybe I should embrace the dict approach.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50111677

http://stackoverflow.com/comment/87819499
comment on: http://stackoverflow.com/q/50184327
has text: I have updated the question following the guideline. I have also tried to use find_element_by_class_name but it didn't help.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87200253
has text: What you've done so far?
comment on: http://stackoverflow.com/q/50091999
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87421696
has text: sorry, but whats wrong with a simple question starting with why!? Im not asking for a discussion neither for a tutorial. Just a straight answer why it works with fftfreq but not with rfftfreq.
type: QuestionComment
comment on: http://stackoverflow.com/q/50202239
type: Comment
score: 1

http://stackoverflow.com/q/50170064
score: 1
has title: Using global variables in unit testing
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51741194
upvote count: 1
favorite count: 0
tagged with: unit-testing
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87357562
accepted answer: http://stackoverflow.com/a/51741194
has body: I'm unit testing a function, e.g. one that checks if the number you've given equals a global const variable. (Simplified situation) def the_special_number = 7 def is_the_special_number(number): if (number == the_special_number): return True else: return False When I'm testing this function, I'd write a test like: import unittest def test_is_special_number_true(self): self.assertTrue(is_the_special_number(the_special_number)) But is this actually a valid unit test, since in the function and the unit test I'm using the same global const? Or does the assertTrue need to be replaced with the following: self.assertTrue(is_the_special_number(7))
tagged with: python
has comment: http://stackoverflow.com/comment/87357476
has comment: http://stackoverflow.com/comment/87357606

http://stackoverflow.com/a/50106766
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50106715
has body: You've got the right idea. Iterate the items in both dicts and compare &gt;&gt;&gt; dict1 = {'Canada' : 2.5, 'UK' : 3.7, 'USA' : 9.0} &gt;&gt;&gt; dict2 = {'a' : 7, 'b' : 2} &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; for kd2, vd2 in dict2.items(): ... for kd1, vd1 in dict1.items(): ... if vd2 &gt; vd1: ... print(kd2, "is larger than", kd1) ... a is larger than Canada a is larger than UK
answers question: http://stackoverflow.com/q/50106715
upvote count: 2

http://stackoverflow.com/a/50163631
accepted answer of: http://stackoverflow.com/q/50160675
answers question: http://stackoverflow.com/q/50160675
downvote count: 0
has body: Figured it out. Here is the solution in case anyone else runs into this issue: textbook_list = [] for item in data: if item not in textbook_list: textbook_list.append(item) with open("./json/bc.json", "w") as writeJSON: json.dump(textbook_list, writeJSON, ensure_ascii=False)
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87405048
has text: @phd it doesn't seem to be the exact issue, although when i create a virtualenv (as one of the solutions to the link), the errors go away and so does the `upgrade pip` problem.
comment on: http://stackoverflow.com/q/50192870
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51348397
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/50151490
upvote count: 1
type: Answer
has body: First of all make sure you have all the dependencies like requests and bs4, if not trying downloading them using pip3 since this code work on Python3 not python2. I have update the repository. The mobilenumber should also be in String format So, instead of q=way2sms.sms(1234567890,'password') #username = 1234567890 use q=way2sms.sms('1234567890','password') #username = 1234567890

http://stackoverflow.com/a/50187397
type: Answer
accepted answer of: http://stackoverflow.com/q/50187234
has comment: http://stackoverflow.com/comment/87395140
has comment: http://stackoverflow.com/comment/87394542
has comment: http://stackoverflow.com/comment/87394136
score: 2
upvote count: 2
has body: The two functions you are missing are those for going from a sequence of bytes to a number, and back: def bytes2num(b): return b[0] + 256 * bytes2num(b[1:]) if b else 0 def num2bytes(n): return bytes([n % 256]) + num2bytes(n // 256) if n else b'' If you want to work with strings you can define the functions: def str2num(s): return bytes2num(s.encode('utf-8')) def num2str(n): return num2bytes(n).decode('utf-8') You should make those implementations iterative if your messages are very long. Test: &gt;&gt;&gt; s = 'Hello, world!' &gt;&gt;&gt; str2num(s) 2645608968347327576478451524936 &gt;&gt;&gt; num2str(2645608968347327576478451524936) 'Hello, world!'
downvote count: 0
has comment: http://stackoverflow.com/comment/87396233
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87394790
has comment: http://stackoverflow.com/comment/87396196
has comment: http://stackoverflow.com/comment/87394361
has comment: http://stackoverflow.com/comment/87394201
has comment: http://stackoverflow.com/comment/87396167
answers question: http://stackoverflow.com/q/50187234
has comment: http://stackoverflow.com/comment/87394209
has comment: http://stackoverflow.com/comment/87396346
has comment: http://stackoverflow.com/comment/87395098
has comment: http://stackoverflow.com/comment/87394082

http://stackoverflow.com/q/50081702
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50082035
has title: Math syntax error in python script
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50081730
has body: Hello Stack Overflow Community! When I try to run this python script (its purpose is to solve for x in a quadratic equation), it returns this message: Traceback (most recent call last): File "/private/var/mobile/Containers/Shared/AppGroup/C692DE78-B0DD-44FF-9815-4675E6956B0A/Pythonista3/Documents/quadratic solver.py", line 13, in &lt;module&gt; root_b_squared_minus_four_a_c = sqrt(b_squared_minus_four_a_c) ValueError: math domain error Here is the code I am running: from math import * # Set up Variables A, B, and C, by asking for input a=int(input("Please enter an a value: ")) b=int(input("Please enter a b value: ")) c=int(input("Please enter a c value: ")) #Set up variables for later use, ac, 4ac, and 2a, in the quadratic formula ac = a*c four_ac = 4 * ac two_a = 2*a b_squared_minus_four_a_c = int(b*b - four_ac) minus_b = -b answer_one_step_one = 0 root_b_squared_minus_four_a_c = sqrt(b_squared_minus_four_a_c) #This section is the solution to the quadratic if a is equal to one, to prevent against printing 1 in front of x if a == 1: print("solving equation x^2+" + str(b) + "x+" + str(c)) answer_one_step_one = minus_b + root_b_squared_minus_four_a_c answer_one = answer_one_step_one / two_a answer_two_step_one = minus_b - root_b_squared_minus_four_a_c answer_two = answer_two_step_one / two_a print("The two solutions for x are:" + str(answer_one) + ",and " + str(answer_two)) else: print("Solving equation" + str(a)+ "x^2+" + str(b) + "x+" + str(c)) answer_one_step_one = minus_b + sqrt(b_squared_minus_four_a_c) answer_one = answer_one_step_one / two_a answer_two_step_one = minus_b - sqrt(b_squared_minus_four_a_c) answer_two = answer_two_step_one / two_a print("The two solutions for x are:" + str(answer_one) + ",and " + str(answer_two)) How do I fix this?? Thanks! Mark
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/50081755

http://stackoverflow.com/comment/87168377
comment on: http://stackoverflow.com/q/50076117
type: QuestionComment
score: 0
has text: I would think this question should be answered in the documentation of the library you want to use ...
type: Comment

http://stackoverflow.com/comment/87239570
comment on: http://stackoverflow.com/q/50108533
has text: You're thinking that you will get row-wise elements by using `toLocalIterator()` but it rather returns partitions. You can use `rdd.foreach(print)`. You can write a function to operate on every row and pass it to foreach.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87283289
has text: lead.partial_save() always returns true so from my code side I cannot tell if it's updated / not
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50131724

http://stackoverflow.com/comment/87288153
has text: That worked, thanks! Didn’t think it would be that simple
comment on: http://stackoverflow.com/a/50134753
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50111072
tagged with: http://stackoverflow.com/tag/html
has title: Django messages.success don't work
answer count: 1
tagged with: django-forms
type: Question
has body: I create a message in my forms.py def clean(self): request = self.request data = self.cleaned_data email = data.get("email") password = data.get("password") qs = User.objects.filter(email=email) if qs.exists(): # user email is registered, check active/ not_active = qs.filter(is_active=False) if not_active.exists(): ## not active, check email activation link = reverse("account:resend-activation") reconfirm_msg = """Go to resend confirmation email. """.format(resend_link = link) confirm_email = EmailActivation.objects.filter(email=email) is_confirmable = confirm_email.confirmable().exists() if is_confirmable: msg1 = "Please check your email to confirm your account or " + reconfirm_msg.lower() raise forms.ValidationError(mark_safe(msg1)) email_confirm_exists = EmailActivation.objects.email_exists(email).exists() if email_confirm_exists: msg2 = "Email not confirmed. " + reconfirm_msg raise forms.ValidationError(mark_safe(msg2)) if not is_confirmable and not email_confirm_exists: raise forms.ValidationError("This user is inactive.") user = authenticate(request, username=email, password=password) if user is None: raise forms.ValidationError("Invalid credentials") login(request, user) self.user = user return data And when I use a simple html it works well and show the message in my screen: {% block content %} Login {% csrf_token %} {{ form }} Submit {% endblock %} But when I use a more 'complex' html the message "Please check your email to confirm your account or " just do not appear: {% load static %} Cadastro {% block content %} {% csrf_token %} Site. Bem vindo de volta! Faça login para continuar. {{ form.email }} {{ form.password }} Entrar Esqueci minha senha Não tem conta? Faça um cadastro {% endblock %} I already debug and see the message is being properly created, But it do not appear. Someone have any idea why?
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87239360
has answer: http://stackoverflow.com/a/50111122
accepted answer: http://stackoverflow.com/a/50111122

http://stackoverflow.com/q/50154976
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87327583
tagged with: seaborn
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I'm creating a set of grouped violin plots with the following: fig = plt.figure(1) ax1 = fig.add_subplot(3,1,1) sns.violinplot(x='x', y='y1', data=df_y1_all, split=True, inner=None, hue="hues_param", palette={"left":"r","right":"b"}) ax1.legend() ax2 = fig.add_subplot(3,1,2) sns.violinplot(x='x', y='y2', data=df_y2_all, split=True, inner=None, hue="hues_param", palette={"left":"r","right":"b"}) ax3 = fig.add_subplot(3,1,3) sns.violinplot(x='x', y='y3', data=df_y3_all, split=True, inner=None, hue="hues_param", palette={"left":"r","right":"b"}) ax3.legend('') plt.show() Which creates something like the following (I've omitted some of the sensitive parameter names as this is pre-published work): I'd like to have a gradient of reds and a gradient of blues as per the argument palette={"left":"r","right":"b"}, but when I try to pass names of color palettes I get an error: ValueError: Could not generate a palette for ['Blues', 'Reds'] or for any other 'named' Seaborn palette. As my data is sensitive I can't share the original dataframe, but it's based on the working example from the docs: import seaborn as sns sns.set(style="whitegrid", palette="pastel", color_codes=True) # Load the example tips dataset tips = sns.load_dataset("tips") # Draw a nested violinplot and split the violins for easier comparison sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True, inner="quart", palette={"Male": "b", "Female": "y"}) sns.despine(left=True) Which produces: Is there anyway to control the palette gradient or call a pre-made gradient within the plot arguments? Thanks!
has title: Using Seaborn split violin plots and palettes
score: 3
answer count: 0
tagged with: pandas
upvote count: 3
tagged with: matplotlib

http://stackoverflow.com/q/50206882
has answer: http://stackoverflow.com/a/50217558
has comment: http://stackoverflow.com/comment/87449475
upvote count: 3
tagged with: tensorboard
tagged with: matplotlib
tagged with: python
has title: How to get smooth mean curves in Pyplot
has comment: http://stackoverflow.com/comment/87430853
has comment: http://stackoverflow.com/comment/87430975
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87430933
answer count: 1
downvote count: 0
has body: So Tensorboard has this nice smoothing feature where you can plot the original curves in shaded colors, and a smooth version on top in solid color: How can I do this with Pyplot? This feature is key to spot the trends with the smoothed curves and the variance with the shaded original curves. Tensorboard is quite limited though, so I'd like to recreate the look in matplot lib. Any ideas? Note I don't want to "interpolate" between the data points, there's too much variance.
accepted answer: http://stackoverflow.com/a/50217558
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/87426026
score: 2
comment on: http://stackoverflow.com/q/50204495
type: Comment
type: QuestionComment
has text: Not really. However decreasing line count shouldn't be the goal of cleaning up code. That looks like good, clear code. It's obvious what each part is doing. If you're worried about speed, your biggest improvement would be to switch `on_sale` from a list to a Set.

http://stackoverflow.com/comment/87318285
score: 0
type: Comment
has text: Please provide a [mcve]
type: QuestionComment
comment on: http://stackoverflow.com/q/50149940

http://stackoverflow.com/comment/87380198
comment on: http://stackoverflow.com/q/50181469
score: 0
type: Comment
type: QuestionComment
has text: There is no way to do this except by adding a "ping_other_server" interface to servers B and C (or adding a "run_arbitrary_code" interface…) that A can call.

http://stackoverflow.com/q/50078807
has comment: http://stackoverflow.com/comment/87199649
has comment: http://stackoverflow.com/comment/87177794
answer count: 1
has comment: http://stackoverflow.com/comment/87201711
has comment: http://stackoverflow.com/comment/87174993
has comment: http://stackoverflow.com/comment/87201722
has comment: http://stackoverflow.com/comment/87175508
favorite count: 0
type: Question
has body: How to make two functions. One to Encrypt and one to Decrypt the message and implement it in the already using code. Sample of encryption: 'My test text is here'.upper() Output: UJ 8ZV8 8Z08 AV DZOZ Decrypt sample: 'V845X6QZO3Y6L AV 4LZV6UZ' Output: 'STACKOVERFLOW IS AWESOME' List1 = ("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",".",1,2,3,4,5,6,7,8,9,0) List2 = (4,"R",5,"G","Z",3,2,"D","A","E","X","Y","U","I",6,"W",7,"O","V",8,"F","Q","L",0,"J",".","H",9,"C","B","N","S","P","M",1,"T","K") while choice != EXIT: display_menu() choice = int(input("Enter a number between 1 and 3.")) if choice == encrypt: encrypt_msg = str(input("Give me a Message to Encrypt Please")) elif choice == decrypt: result = 0 decrypt_msg = str(input("Give me Your message to decrypt please.")) print("Exiting...") else: Print("Error...Invalid Response") That is the two List above, I am New to Programming and still grasping the basics, The program needs to take the message from user and using the two lists provided decrypt and encrypt the message and display it, I have tried searching for similar questions but the soloutions are commands and methods we have not learned in class, Id appreciate any help and explanation on how to program the situation above.
has comment: http://stackoverflow.com/comment/87174916
has comment: http://stackoverflow.com/comment/87199703
has comment: http://stackoverflow.com/comment/87202074
has title: How do I take a User inputted msg, and decrypt or encrypt the msg using 2 Lists
has comment: http://stackoverflow.com/comment/87200992
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87199860
score: -2
tagged with: encryption
has comment: http://stackoverflow.com/comment/87175778
tagged with: python
has answer: http://stackoverflow.com/a/50079073
has comment: http://stackoverflow.com/comment/87201219
has comment: http://stackoverflow.com/comment/87200023
has comment: http://stackoverflow.com/comment/87175358
has comment: http://stackoverflow.com/comment/87201597
has comment: http://stackoverflow.com/comment/87201073
has comment: http://stackoverflow.com/comment/87173897
tagged with: list
has comment: http://stackoverflow.com/comment/87201129
has comment: http://stackoverflow.com/comment/87175160
has comment: http://stackoverflow.com/comment/87201654
downvote count: 3
has comment: http://stackoverflow.com/comment/87201445
has comment: http://stackoverflow.com/comment/87177709
upvote count: 1

http://stackoverflow.com/comment/87267643
comment on: http://stackoverflow.com/q/50109536
type: Comment
type: QuestionComment
has text: The error message you posted has also been butchered. Are you sure you didn't just use `pd.read_sql("""select * from ##output""" ...` instead of `pd.read_sql("""select * from #output""" ...`?
score: 0

http://stackoverflow.com/q/50222314
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50222371
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/50222371
has body: I am trying to reset the csv.reader but the solution posted by others does not work of course because of the presence of strings...what other method could be used instead of csv_reader.seek(0) to reset the csv.reader? I am new to this so I would much appreciate any insights... I also tried turning the column into a list as well which causes additional errors. import os import csv csv_path=os.path.join("..","Resources","budget_data_1.csv") with open(csv_path,newline="") as csvfile: csv_reader=csv.reader(csvfile,delimiter=",") next(csv_reader) count=0 for i in csv_reader: count+=1 print(count) csv_reader.seek(0) total=0 for row in csv_reader: total+=int(row[1]) print(total)
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: .seek does not work for resetting csv.reader containing strings too, what other method could be used?

http://stackoverflow.com/comment/112881420
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/63835056
has text: Remember that you should not delete a whole Folder because Python may not to make a new folder: as a result, it may give you a new error. Stay Safe

http://stackoverflow.com/q/50200367
answer count: 3
has answer: http://stackoverflow.com/a/50200451
has title: Getting all possible combinations from a list with duplicate elements?
has comment: http://stackoverflow.com/comment/87417336
possible better answer: http://stackoverflow.com/a/50200515
has comment: http://stackoverflow.com/comment/87417368
favorite count: 0
type: Question
score: 2
linked to: http://stackoverflow.com/q/464864
upvote count: 2
has comment: http://stackoverflow.com/comment/87417308
downvote count: 0
has body: I have list with repeated elements, for example array = [2,2,2,7]. If I use the solution suggested in this answer (using itertools.combinations()), I get: () (7,) (2,) (2,) (2,) (7, 2) (7, 2) (7, 2) (2, 2) (2, 2) (2, 2) (7, 2, 2) (7, 2, 2) (7, 2, 2) (2, 2, 2) (7, 2, 2, 2) As you can see some of the 'combinations' are repeated, e.g. (7,2,2) appears 3 times. The output I would like is: () (7,) (2,) (7, 2) (2, 2) (7, 2, 2) (2, 2, 2) (7, 2, 2, 2) I could check the output for repeated combinations but I don't feel like that is the best solution to this problem.
tagged with: python
has answer: http://stackoverflow.com/a/50207108
has answer: http://stackoverflow.com/a/50200515
tagged with: combinations
accepted answer: http://stackoverflow.com/a/50200451
type: AnsweredQuestion

http://stackoverflow.com/comment/87396279
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50189683
has text: Actually, I was thinking of a matrix, but you're just doing 10000 queries. What are the limits you're concerned about, then? Is it queries per second?

http://stackoverflow.com/q/50157531
has body: I am using sklearn.metrics.classification_report to evaluate the result of my classification. y_pred = np.argmax(model.predict(X_test), axis=1) y_true = np.argmax(y_test, axis=1) print(classification_report(y_true, y_pred, target_names=list(le.classes_))) And here is my result: precision recall f1-score support Technology 0.00 0.00 0.00 1 Travel 0.00 0.00 0.00 5 Fashion 0.00 0.00 0.00 25 Entertainment 0.72 1.00 0.84 130 Art 0.00 0.00 0.00 7 Politic 0.00 0.00 0.00 12 avg / total 0.52 0.72 0.61 180 The problem is actually I have 7 labels. The order goes Technology, Travel, Fashion, Entertainment, Art, Politic, Sports. Actually I don't have any Art label in my y_true result but the report lists in order so, it lists Art but skips Sports. It writes the result of Politic for Art and the result of Sports goes to Politic's row. Why does not it skip the Art? I have no idea how can I solve this.
favorite count: 0
tagged with: multiclass-classification
type: Question
tagged with: classification
type: UnansweredQuestion
tagged with: scikit-learn
tagged with: python
has title: sklearn.metrics.classification_report support field is showing wrong number for the labels
score: 0
upvote count: 1
downvote count: 1
answer count: 1
tagged with: text-classification
has answer: http://stackoverflow.com/a/50157902

http://stackoverflow.com/a/50147512
answers question: http://stackoverflow.com/q/50147260
upvote count: 0
has body: With re (works with string inputs now): inp = "E= random or andy" #inp = "E= A or B or (C and not D)" logic = ["xor","or","and","not","=",")","(",""," "] outp = re.split(r'(=|\)|\(| )', inp) outp = [x for x in outp if x not in logic ] print(outp)
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/87313204

http://stackoverflow.com/q/50164509
tagged with: image-processing
type: Question
has answer: http://stackoverflow.com/a/50166653
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I have a bunch of skin images with moles. But unfortunately a large part of the set is containing annoying colored circles which I want to detect &amp; remove. I've tried my best with cv2.HoughCircles but the results are completely wrong :( Does anybody have an idea to detect these more efficiently? I've attached some images and my output.
has comment: http://stackoverflow.com/comment/87348277
tagged with: opencv
has title: Detect Colored Circles
score: 0
linked to: http://stackoverflow.com/q/47342025

http://stackoverflow.com/q/50166001
has title: Key Error in Flask Sessions
tagged with: session
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87352091
type: Question
upvote count: 0
type: UnansweredQuestion
has body: So I have been using sessions to pass data from one decorator to another. But now every time I make a new session variable, I get a KeyError from page to page. Meaning, I had a session error from my third to fourth page; but I had the same issue adding a new session variable from my second to third page even though I have four other session variables that give me no error. My code is similar to the one @laila posted below: from flask import Flask, render_template from flask import request, session, url_for,abort,redirect app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' @app.route('/'): def first(): session['this_one']='hello' render('template.html') @app.route('/second') def second(): it=session['this_one'] render('other_page.html') if __name__ == '__main__': app.run(debug=True)
answer count: 1
tagged with: flask
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50167026

http://stackoverflow.com/q/50186467
answer count: 1
has comment: http://stackoverflow.com/comment/87389928
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50186789
has body: I need to calculate moving average using pandas. ser = pd.Series(np.random.randn(100), index=pd.date_range('1/1/2000', periods=100, freq='1min')) ser.rolling(window=20).mean().tail(5) [Out] 2000-01-01 01:35:00 0.390383 2000-01-01 01:36:00 0.279308 2000-01-01 01:37:00 0.173532 2000-01-01 01:38:00 0.194097 2000-01-01 01:39:00 0.194743 Freq: T, dtype: float64 But after appending a new row like this, new_row = pd.Series([1.0], index=[pd.to_datetime("2000-01-01 01:40:00")]) ser = ser.append(new_row) I have to recalcuate all moving data, like this, ser.rolling(window=20).mean().tail(5) [Out] 2000-01-01 01:36:00 0.279308 2000-01-01 01:37:00 0.173532 2000-01-01 01:38:00 0.194097 2000-01-01 01:39:00 0.194743 2000-01-01 01:40:00 0.201918 dtype: float64 I think I just need calculate last 2000-01-01 01:40:00 0.201918 data, but I can't find pandas api that calculate only last appended row value. Pandas rolling().mean() always calculate all series data This is simple example but in my real project, range is more than 1,000,000 series, and each rolling calculation consumes much time Is there way to solve this problem in pandas?
has title: Pandas caculating rolling functions efficiently
tagged with: python
has answer: http://stackoverflow.com/a/50186789
type: AnsweredQuestion
upvote count: 3
score: 3
downvote count: 0
tagged with: pandas

http://stackoverflow.com/q/50170782
has comment: http://stackoverflow.com/comment/87362422
has title: gramex install error: import pip.req ImportError: No module named req
has comment: http://stackoverflow.com/comment/87359246
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50186255
tagged with: installation
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: pip
linked to: http://stackoverflow.com/q/49837301
tagged with: python
tagged with: gramex
has body: My Environment details: Python 3.6.4 :: Anaconda, Inc. anaconda-script.py Command line client (version 1.4.0) pip 10.0.1 I'm getting below error while trying to install with pip install -verbose gramex or pip install -e . (from ) ``` (gramex_34) &lt;src_path&gt;\\gramex&gt;pip install -e . Obtaining file:///&lt;src_path&gt;/gramex 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 "&lt;src_path&gt;\gramex\setup.py", line 7, in &lt;module&gt; from pip.req import parse_requirements ImportError: No module named req ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in &lt;src_path&gt;\gramex\ I could get the below ref on SoF its a usage issue with latest version of pip: pip-git-issue similar-issue-thread
score: 2

http://stackoverflow.com/comment/87348727
type: QuestionComment
type: Comment
has text: might just a permission issue on your cwd
score: 0
comment on: http://stackoverflow.com/q/50165273

http://stackoverflow.com/a/50106357
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50106246
type: AcceptedAnswer
has body: Sounds like it's a simple sequencing of your graphic_pattern() and square() methods. It seems you would want to draw the top right graphic_pattern() first, followed by the middle square, and then followed by the rest of the graphic_pattern() calls: import turtle #Imports the 'turtle module' which allows intricate shapes and pictures to be drawn my_turtle_pos = (10 , 10) def square(my_turtle,x,y,length) : #I set up a function that helps me determine the square my_turtle.penup() #Picks 'up' the turtle pen my_turtle.setposition(x-length/2,y-length/2) #Helps set positon my_turtle.pendown() #Puts 'down' the turtle pen my_turtle.color('black','red') #Allows black outline, with red filling my_turtle.begin_fill() #Starts the filling of red and helps remember the starting point for a filled area my_turtle.forward(length) #Moves the turtle by the specified amount 'length' my_turtle.left(90) #Moves the turtle by given amount '90' my_turtle.forward(length) my_turtle.left(90) my_turtle.forward(length) my_turtle.left(90) my_turtle.forward(length) my_turtle.left(90) my_turtle.end_fill() #Stops filling with red, which will close with the current color def graphic_pattern(my_turtle,x,y,length,times): #recursive function if times &lt;= 0: #This just tells us how many 'times' it needs to repeat till given amount return newSize = length/2.2 #This will grab the new size graphic_pattern(my_turtle,x+length/2,y+length/2,newSize,times-1) square(my_turtle,x,y,length) graphic_pattern(my_turtle,x-length/2,y-length/2,newSize,times-1) graphic_pattern(my_turtle,x-length/2,y+length/2,newSize,times-1) graphic_pattern(my_turtle,x+length/2,y-length/2,newSize,times-1) my_turtle = turtle.Turtle(shape="arrow") #You can use differen't shapes for the turtle, I chose arrow, though the turtle was cool :) my_turtle.speed(100) #I am not sure how fast the turtle can go, I just chose 100 cause it went by quicker. graphic_pattern(my_turtle,3,0,300,4) #Example pattern stated from homework assignment.
accepted answer of: http://stackoverflow.com/q/50106246

http://stackoverflow.com/comment/102606035
comment on: http://stackoverflow.com/a/50195155
has text: @robroc Yeah but think about this: Unless every row for a given code is NaN, the preceeding `GroupBy.ffill` step has filled everything up to and including the last of the group, so the successive `bfill()` step will only fill NaNs in its own group. You get this for free just because of how the previous `ffill` step worked. The caveat, ofc, is "unless every value is NaN inside a group" (then this does not work, hopefully you understand why!).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87349005
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50165445
type: AnswerComment
has text: I used canvas.show() to follow what the tutorial I did. I should not have included plt.show(), I was just blindly following some online examples.ROOT.mainloop() is a blocking method which I'd prefer not to use. I was hoping to be able to call ROOT.update() periodically instead and achieve the same functionality. Thanks for the help, I'll be able to test your fixes tomorrow and hopefully I can implement them in my program

http://stackoverflow.com/q/50141945
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50142002
possible better answer: http://stackoverflow.com/a/50142002
has comment: http://stackoverflow.com/comment/87302407
has comment: http://stackoverflow.com/comment/87302765
tagged with: django
has title: Trouble for rendering a simple checkbox in Django
has comment: http://stackoverflow.com/comment/87303339
type: Question
has comment: http://stackoverflow.com/comment/87303121
has comment: http://stackoverflow.com/comment/87302965
has comment: http://stackoverflow.com/comment/87303615
tagged with: python
tagged with: checkbox
has comment: http://stackoverflow.com/comment/87303697
has answer: http://stackoverflow.com/a/50210535
accepted answer: http://stackoverflow.com/a/50210535
has body: I try to render a simple checkbox (a boolean checkbox) in Django. form.py class Stateform(forms.Form): state = forms.BooleanField() html &lt;form "..." method="post"&gt;{% csrf_token %} &lt;input type="checkbox"&gt; &lt;label&gt;{{ form }}&lt;/label&gt; &lt;/input&gt; &lt;/form&gt; view.py def Defstate(request, *args): if request.method =='POST': form = Stateform(request.POST) if form.is_valid(): ... else : form = Stateform() context = { 'form': Stateform(), } return render(request, 'Page1/Page3.html', context) It display the checkbox correctly but it's impossible for me to check the box...
has comment: http://stackoverflow.com/comment/87302593
type: AnsweredQuestion
tagged with: boolean

http://stackoverflow.com/a/50223639
has comment: http://stackoverflow.com/comment/87475866
has comment: http://stackoverflow.com/comment/87476342
has comment: http://stackoverflow.com/comment/87475797
has comment: http://stackoverflow.com/comment/87477822
has body: Here is another answer, hopefully more efficient. I'll focus on the main point in your question: seeing if the reverse pair in a couple of columns occurred in a previous row. As an example, I'll use df = pd.DataFrame({'a': [1, 1, 4, 5, 2, 5], 'b': [7, 5, 2, 1, 4, 2]}) &gt;&gt;&gt; df a b 0 1 7 1 1 5 2 4 2 3 5 1 4 2 4 5 5 2 Let's find the tuples of each row: this = df'a', 'b'.apply(tuple, axis=1) &gt;&gt;&gt; this 0 (1, 7) 1 (1, 5) 2 (4, 2) 3 (5, 1) 4 (2, 4) 5 (5, 2) dtype: object Here is the cumulative sum of reverse tuples' appearances: cum = pd.get_dummies(df'b', 'a'.apply(tuple, axis=1)).cumsum() &gt;&gt;&gt; cum (1, 5) (2, 4) (2, 5) (4, 2) (5, 1) (7, 1) 0 0.0 0.0 0.0 0.0 1.0 1.0 1 0.0 1.0 0.0 0.0 1.0 1.0 2 1.0 1.0 0.0 0.0 1.0 1.0 3 1.0 1.0 0.0 1.0 1.0 1.0 4 1.0 1.0 1.0 1.0 1.0 1.0 5 NaN NaN NaN NaN NaN NaN To this we need to show that the tuple of the current row, if it didn't exist in reverse, was not found: this_zeros = pd.get_dummies(this) this_zeros[:] = 0 &gt;&gt;&gt; pd.concat([cum, this_zeros[this_zeros.columns.difference(cum.columns)]], axis=1) (1.0, 5.0) (2.0, 4.0) (2.0, 5.0) (4.0, 2.0) (5.0, 1.0) (nan, nan) (1, 7) (2, 2) (5, 2) 0 0.0 0.0 0.0 0.0 1.0 0.0 0 0 0 1 0.0 1.0 0.0 0.0 1.0 0.0 0 0 0 2 1.0 1.0 0.0 0.0 1.0 0.0 0 0 0 3 1.0 1.0 0.0 1.0 1.0 0.0 0 0 0 4 1.0 1.0 1.0 1.0 1.0 0.0 0 0 0 5 1.0 1.0 1.0 1.0 1.0 1.0 0 0 0 6 NaN NaN NaN NaN NaN NaN 0 0 0 Now we can use this DataFrame to look up the current tuple: keep = pd.concat([cum, this_zeros[this_zeros.columns.difference(cum.columns)]], axis=1).lookup(df.index, this) We should keep in the original DataFrame &gt;&gt;&gt; df[keep.astype(bool)] a b 0 1 7 1 1 5 2 4 2 5 5 2
has comment: http://stackoverflow.com/comment/87475276
has comment: http://stackoverflow.com/comment/87480043
answers question: http://stackoverflow.com/q/50198532
type: Answer
has comment: http://stackoverflow.com/comment/87475497
has comment: http://stackoverflow.com/comment/87475616
score: 0
has comment: http://stackoverflow.com/comment/87475034
has comment: http://stackoverflow.com/comment/87475695

http://stackoverflow.com/comment/87349710
type: Comment
has text: i do not know. I do not know, I use ubuntu, python2 and python3
type: AnswerComment
comment on: http://stackoverflow.com/a/50165437
score: 0

http://stackoverflow.com/a/50235876
accepted answer of: http://stackoverflow.com/q/50198678
has body: The appbuilder instance has a bm attribute, which is an instance of the BabelManager class. This class has a get_locale method that returns the current language your app is using. class MyView(BaseView): default_view = 'method1' @expose('/method1/') @has_access def method1(self): return appbuilder.bm.get_locale() You can check the code for the BabelManager class on the project repository.
type: Answer
answers question: http://stackoverflow.com/q/50198678
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87366218
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50174566
has text: @jackotonye what do you mean? interesting question for me. Can't we order by `pk`?

http://stackoverflow.com/comment/87196076
score: 0
has text: Today is 2018.04.29... it looks correct to me :)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50089849

http://stackoverflow.com/q/50198421
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50198446
has body: I want to initialize an empty list of given size. I've found the following on SO: lst = [None] * n What is complexity of this piece of code? Is it constant or linear? If it's linear then what are the constant ways?
answer count: 1
accepted answer: http://stackoverflow.com/a/50198446
favorite count: 0
has title: Complexity of initializing a list
type: Question
upvote count: 2
duplicate of: http://stackoverflow.com/q/27966221
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/27966221
score: 2

http://stackoverflow.com/comment/87188886
score: 0
has text: Problem is, they dont want any predefined functions or classes or changes to their code.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50086562

http://stackoverflow.com/comment/87268649
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50125224
has text: What is the difference and pitfalls from original multiple import?

http://stackoverflow.com/comment/87283642
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50132827
has text: Little shortcut for `if words not in word_count: word_count[words] = 0` --> `word_count.setdefault(words, 0)`
type: Comment

http://stackoverflow.com/comment/87202871
has text: I disagree. The first task is getting the table into a pandas dataframe. Tha's what I need help with, not the rest, as I stated in the question.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50093086

http://stackoverflow.com/q/50074956
tagged with: python
has answer: http://stackoverflow.com/a/50075022
type: AnsweredQuestion
score: 7
has title: How exactly do eval and exec interact with __future__?
answer count: 1
downvote count: 0
upvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87166218
tagged with: eval
has body: I want to know how __future__ imports interact with eval and exec (and compile, I guess). Experimentation (with python 2) shows that module-level __future__ imports do have an effect on code executed by eval and exec: from __future__ import print_function print(1, end='!\n') eval(r"print(2, end='!\n')") exec r"print(3, end='!\n')" Output: 1! 2! 3! But at the same time, code executed with exec can perform its own __future__ imports that only affect the code locally: print 1 exec r"from __future__ import print_function; print(2, end='!\n')" print 3 exec r"print 4" Output: 1 2! 3 4 But experimentation can only get you so far. My questions are: Are these interactions well-defined and documented? Is there a way to disable module-level __future__ imports in eval, exec and compile?
accepted answer: http://stackoverflow.com/a/50075022

http://stackoverflow.com/q/50191174
tagged with: python
has comment: http://stackoverflow.com/comment/87409780
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has body: Here is an sample code, if I create a ListLike class as below class ListLike: def __init__(self): self._items = [] def __getattr__(self, name): return getattr(self._items, name) I can use : &gt;&gt;&gt; a = ListLike() &gt;&gt;&gt; a.append(2) While cannot use : &gt;&gt;&gt; len(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: object of type 'ListLike' has no len() I am wondering what is the difference between append and len in this case , and when I create a class like this , how can I tell which methods/operator needs to be specified by myself in newly created class ?
tagged with: methods
favorite count: 0
linked to: http://stackoverflow.com/q/41471594
tagged with: attributes
type: Question
tagged with: python-3.x
tagged with: operator-overloading
duplicate of: http://stackoverflow.com/q/41471594
has title: Difference between common method VS operator in Python data type as list
type: UnansweredQuestion

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

http://stackoverflow.com/a/51863486
score: 2
downvote count: 0
has body: Previous solutions are limited to short length reg_patterns. The below implementation scales nicely when the normalization pattern has many entries (e.g. spell correction using a custom dictionary). Start by mapping the reg_patterns list to a dictionary: from pyspark.sql.functions import col, udf def parse_string(s, or_delim, target_delim): keys,value = s.rstrip(target_delim).rsplit(target_delim) return {key:value for key in keys.split(or_delim)} reg_patterns=["ADVANCED|ADVANCE/ADV/","ASSOCS|AS|ASSOCIATES/ASSOC/"] normalization_dict = {} for item in reg_patterns: normalization_dict.update(parse_string(item, "|", "/")) Complete the normalization of the DataFrame "Notes" column using a curried function as follows: def my_norm_func(s, ngram_dict, pattern): return pattern.sub(lambda x: ngram_dict[x.group()], s) norm_pattern = re.compile(r'\b(' + '|'.join([re.escape(item)\ for item in normalization_dict.keys()]) + r')\b') my_norm_udf = udf(lambda s: my_norm_func(s, normalization_dict, norm_pattern)) df = df.withColumn("NotesUPD", my_norm_udf(col("Notes"))) yields the following desired result: +----+--------------------+--------------------+ | ID| Notes| NotesUPD| +----+--------------------+--------------------+ |2345| ADVANCED by John| ADV by John| |2398| ADVANCED by ADVANCE| ADV by ADV| |2328|Verified by somer...|Verified by somer...| |3983|Double Checked by...|Double Checked by...| +----+--------------------+--------------------+
answers question: http://stackoverflow.com/q/50151214
type: Answer
upvote count: 2

http://stackoverflow.com/comment/87185601
score: 0
type: Comment
type: QuestionComment
has text: Also, what do you mean by "type hinting"? Python doesn't have type hinting. Python itself has *type annotations*. A specific type checker for Python may or may not have type hinting, which brings me back to my other comment: what type checker and which type system are you using to check your types?
comment on: http://stackoverflow.com/q/50084798

http://stackoverflow.com/a/50117794
answers question: http://stackoverflow.com/q/50115934
has body: Try it: from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QUrl class Main(QObject): def __init__(self): QObject.__init__(self) # signal sending string # necessarily give the name of the argument through arguments=['textLabel'] # otherwise it will not be possible to pick it up in QML textResult = pyqtSignal(str, arguments=['textLabel']) @pyqtSlot(str) def textLabel(self, arg1): # do something with the text and emit a signal arg1 = arg1.upper() self.textResult.emit(arg1) if __name__ == "__main__": import sys app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() main = Main() engine.rootContext().setContextProperty("main", main) engine.load(QUrl('main.qml')) engine.quit.connect(app.quit) sys.exit(app.exec_()) main.qml import QtQuick 2.7 import QtQuick.Controls 2.3 import QtQuick.Window 2.3 ApplicationWindow{ title: qsTr('Quomodo') id: mainWindow width: 480 height: 640 visible: true Column { anchors.horizontalCenter: parent.horizontalCenter spacing: 8 padding: 8 Button { objectName: "myButton" text: qsTr("Work") highlighted: true onClicked: { // call the slot to process the text main.textLabel("Next") } } Label { id: textResult text: qsTr("Time") anchors.horizontalCenter: parent.horizontalCenter } } // Here we take the result of text processing Connections { target: main // Signal Handler onTextResult: { // textLabel - was given through arguments=['textLabel'] textResult.text = textLabel } } }
accepted answer of: http://stackoverflow.com/q/50115934
downvote count: 1
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87260426
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/87324545
score: 0
has text: I'm still getting False with your code. Are you sure you changed it?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50153412

http://stackoverflow.com/q/50219443
tagged with: google-natural-language
type: AnsweredQuestion
tagged with: google-cloud-platform
downvote count: 1
has body: I want to extract emails from a text which I get from the business cards using Google Vision API. How can I do that using Natural Language API? (I'm using Python)
has title: How can I use Google Natural Processing API to extract emails from a text?
favorite count: 0
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/50222330
answer count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50222330

http://stackoverflow.com/comment/87449805
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50216345
has text: @Stack there are a lot of ways to Upgrade the Running time , for mathematiques we use numpy example
score: 0

http://stackoverflow.com/a/50166021
answers question: http://stackoverflow.com/q/50165397
has comment: http://stackoverflow.com/comment/87393130
type: Answer
has comment: http://stackoverflow.com/comment/87350745
has comment: http://stackoverflow.com/comment/87350981
score: 1
has comment: http://stackoverflow.com/comment/87404940
downvote count: 0
upvote count: 1
has body: Since you're working with a csv file, you may want to look at the csv module in Python. That module has many convenient options and forms in which the data is read. Following is an example of csv.DictReader reading and usage, import csv # Read the data with open('data.csv') as f: reader = csv.DictReader(f) data = [row for row in reader] # Print it for row in data: print (' ').join(['Nome:',row['NOME'],'G1:',row['G1'],'G2:',row['G2']]) # Print only names and G2 grades as a table print '- '*10 print 'NOME\t' + 'G2' for row in data: print row['NOME'] + '\t' + row['G2'] # Average of G1 and G2 for each student print '- '*10 print 'NOME\t' + 'Average' for row in data: gpa = (float(row['G1']) + float(row['G2']))/2.0 print row['NOME'] + '\t' + str(gpa) Here the data is read as a list of dictionaries - each element in the list is a dictionary representing a single row of your dataset. The dictionary keys are names of your headers (NOME, G1) and values are the corresponding values for that row. That particular form can be useful in some situations. Here in the first part of the program the data is printed with keys and values, one row per line. The thing to note is that dictionaries are unordered - to ensure printing in some specific order we need to traverse the dictionary "manually". I used join simply to demonstrate an alternative to format (which is actually more powerful) or just typing everything with spaces in between. Second usage example prints names and the second grade as a table with proper headers. Third calculates the average and prints it as a table. For me this approach proved very useful when dealing with datasets with several thousands entries that have many columns - headers - that I want to study separately (thus I don't mind them not being in order). To get an ordered dictionary you can use OrderedDict or consider other available datastructures. I also use Python 2.7, but since you tagged the question as 3.X, the links point to 3.X documentation.

http://stackoverflow.com/a/50190775
has comment: http://stackoverflow.com/comment/87399394
has comment: http://stackoverflow.com/comment/87398705
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/104824283
has comment: http://stackoverflow.com/comment/87400306
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/87398416
answers question: http://stackoverflow.com/q/50189727
has body: I am not expert in raw socket programming too, but I have some knowledge of network. 1st Question: how to know that I read the complete packet not 50% or 1 and half packet? Answer: You can't. It don't have "sequence number" or "acknowledgement number" like TCP. 2nd Question: Is it possible to tell me how can I read one full packet by recvfrom()? Answer: Let try import socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) s.bind(('0.0.0.0', 1337)) while True: packet = s.recvfrom(65535).decode() #decode packet forwared_packet_function(packet) print(packet) #print packet to read

http://stackoverflow.com/comment/87396606
has text: Nope, sorry. As I said, try with test values starting from 10.
comment on: http://stackoverflow.com/a/50189845
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50124738
has comment: http://stackoverflow.com/comment/87267889
favorite count: 0
linked to: http://stackoverflow.com/q/29148462
has body: The problem is that I cannot record the output of my Python script using Tee-Object to both terminal and a file. I have multiple files containing lines of data. I need to verify this data via an HTTP request to a server. There are 8 large files and given I expect this will take a day to run since I don't want to flood the server. Importing file strings and running Python script is producing output to terminal. Completed as follows: $db = Import-Csv C:\Users\xxxx\documents\bunnies\foo.txt foreach ($i in $db.StringName) { &amp; py -2.7 myscript.py -option $i } $db is the file. $i is the string (line) in the file. script prints to terminal. Since the output is going to be over several days, I need to know that it will be recorded. Tee-Object has not created a file after an hour of output. foreach ($i in $db.StringName) { &amp; py -2.7 myscript.py -option $i } &gt; Tee-Object -FilePath .../bunnyrabbit.txt I assume that &gt; Tee-Object -FilePath .../bunnyrabbit.txt appended should create the file immediately and write in an ongoing manner? I need to be able to check the output is okay as the program runs. Additional: filtering output The output per line of the script is simply "x is correct" or "x is incorrect". If I want to filter all the corrects into one file and the incorrects into another how to go about this? My original plan was simply to re-read the output file in python and do it in a language I know.
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50124958
linked to: http://stackoverflow.com/q/48522415
has comment: http://stackoverflow.com/comment/87267650
has title: Using Tee-Object to output the result of a python script to both terminal and file
type: Question
has answer: http://stackoverflow.com/a/50124958
upvote count: 2
downvote count: 0
answer count: 1
tagged with: powershell
tagged with: output
tagged with: python
has comment: http://stackoverflow.com/comment/87267912

http://stackoverflow.com/q/50131848
has title: Problems uploading files to Amazon s3 bucket from a website on heroku
type: Question
tagged with: heroku
tagged with: amazon-s3
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: Im in the process of moving my Django website to Heroku. But I can’t figure out how to use Heroku with Amazon s3 buckets. Previously I used to save all uploaded files in the project, but I can’t do that using Heroku. I have been following the documentation on Heroku: https://devcenter.heroku.com/articles/s3 and https://devcenter.heroku.com/articles/s3-upload-python The bucket is located in Frankfurt. When uploading a file I get the following error: <Code>InvalidArgument a non-empty Access Key (AKID) must be provided in the credential. X-Amz-Credential /20180502/eu-central-1/s3/aws4_request … I have specified the keys in Heroku like this: "heroku config:set AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=yyy" You can go to https://eventcollective.herokuapp.com/accounts/account/ and try to upload an image. from views.py def sign_s3(request): S3_BUCKET = os.environ.get('S3_BUCKET') print(S3_BUCKET) file_name = request.GET.get('file_name') file_type = request.GET.get('file_type') s3 = boto3.client('s3', region_name='eu-central-1') presigned_post = s3.generate_presigned_post( Bucket=S3_BUCKET, Key=file_name, Fields={"acl": "public-read", "Content-Type": file_type}, Conditions=[ {"acl": "public-read"}, {"Content-Type": file_type} ], ExpiresIn=3600 ) return HttpResponse(json.dumps({ 'data': presigned_post, 'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name) })) Do you have any idea on how to resolve this?
score: 0
has answer: http://stackoverflow.com/a/50134693
answer count: 1

http://stackoverflow.com/q/50080859
answer count: 1
tagged with: selenium
tagged with: pyvirtualdisplay
accepted answer: http://stackoverflow.com/a/50087919
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50087919
score: 0
has body: I've had a look around here for multiprocessing, for the most part, I've gotten it narrowed down but the last bit fails for some reason. Context I have a remote webserver that I connect to that I have port forwarded the HTTP page to a local port. I need to connect to the remote host, while I'm connected, I need to open up the HTTP page on my local machine and capture the page. Code from selenium import webdriver from pyvirtualdisplay import Display import paramiko import multiprocessing import time def grabscreendisplay(): time.sleep(10) print('running display code now... ') display = Display(size=(1024, 768), visible=0) display.start() driver=webdriver.Chrome('/usr/local/bin/chromedriver') URL="http://localhost:9012" driver.get(URL) screenshot=driver.save_screenshot('my_screenshot.png') driver.quit() def getserver(): SERV = raw_input('Please enter the server you would like to connect to: ') return SERV def connect_to_server(SERV): print(SERV) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print('Connecting to ' + SERV) ssh.connect(SERV, username='root', key_filename='...') connected = True print('Connected to ' + SERV) time.sleep(30) def main(): SERV = getserver() p1 = multiprocessing.Process(name='p1', target=connect_to_server(SERV)) p2 = multiprocessing.Process(name='p2', target=grabscreendisplay()) p2.start() p1.start() if __name__ == "__main__": main() Problem faced The .png just displays a failed connection to the port ('localhost refused to connect')
tagged with: python
has title: python connect to remote host and capture webpage on local host
type: Question
tagged with: python-multiprocessing
tagged with: subprocess

http://stackoverflow.com/comment/87169459
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50076669
has text: Apart from what's mentioned in the duplicate, with Python 3.6 you can also use [f-strings](https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals): `print(f"NUMBER1 is{num1}")`

graph-theory
tags question: http://stackoverflow.com/q/50178228
tags question: http://stackoverflow.com/q/50146134
tag name: graph-theory
type: Tag
tags question: http://stackoverflow.com/q/50167737
tags question: http://stackoverflow.com/q/50210580

http://stackoverflow.com/q/50181011
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87379237
has comment: http://stackoverflow.com/comment/87379978
has body: I am trying to know if there is a approach in python to read the tabs on the taskbar and get the list of them. Suppose I have a task bar which has outlook,word,Skype minimized. I would like my code to get the list of things which are on taskbar. Example: Here if you notice outlook,slack,chrome,skype and notepad is open. So what is the approach I need to follow to tell my code to return the list of open things on taskbar.
has comment: http://stackoverflow.com/comment/87379805
linked to: http://stackoverflow.com/q/2022219
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has title: Python taskbar tasks
has comment: http://stackoverflow.com/comment/87380071
tagged with: c++
type: Question
tagged with: python-3.x
score: 2
has comment: http://stackoverflow.com/comment/87379283
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/87251786
comment on: http://stackoverflow.com/q/50111612
type: Comment
score: 0
has text: Yes, read it but confused about what means index of leaves? And what they mean -- suppose there are two classes, a specific index means predicted as positive or predicted as negative class?
type: QuestionComment

http://stackoverflow.com/comment/87388892
type: Comment
has text: Traceback (most recent call last): File "C:/Users/cavem/Documents/Python/Personal Python Files/Farmboi Simulator/Farmboi test.py", line 52, in <module> check_harvest() File "C:/Users/cavem/Documents/Python/Personal Python Files/Farmboi Simulator/Farmboi test.py", line 38, in check_harvest print("checker: " + str(growing[grown[item]])) IndexError: list index out of range
type: QuestionComment
comment on: http://stackoverflow.com/q/50185847
score: 0

http://stackoverflow.com/a/50202987
has body: Powershell is used in Scapy under Windows to get the host's network configuration (devices, routes, etc.). It is, however, a bug that it opens windows. This bug is beeing fixed in the current development version. Next release (2.4.1) will include the fix.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50140588
type: Answer

http://stackoverflow.com/q/50150148
has title: Efficient and fastest way to search in a list of strings
has comment: http://stackoverflow.com/comment/87318335
has comment: http://stackoverflow.com/comment/87318220
tagged with: search
type: AnsweredQuestion
upvote count: 3
tagged with: time-complexity
accepted answer: http://stackoverflow.com/a/50150241
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50150241
has comment: http://stackoverflow.com/comment/87318135
favorite count: 0
has comment: http://stackoverflow.com/comment/87318259
has comment: http://stackoverflow.com/comment/87318094
has comment: http://stackoverflow.com/comment/87318324
has body: The following function return the number of words from a list that contain the exact same characters as the word entered. The order of the characters in the words is not important. However, say there is a list that contain millions of words. What is the most efficient and fastest way to perform this search? Example: words_list = ['yek','lion','eky','ekky','kkey','opt']; if we were to match the word "key" with the words in the list, the function only return "yek" and "eky" since they share the same exact characters with "key" regardless of the order. Below is the function I wrote def find_a4(words_list, word): # all possible permutations of the word that we are looking for # it's a set of words word_permutations = set([''.join(p) for p in permutations(word)]) word_size = len(word) count = 0 for word in word_list: # in the case of word "key", # we only accept words that have 3 characters # and they are in the word_permutations if len(word) == word_size and word in word_permutations: count += 1 return count
has comment: http://stackoverflow.com/comment/87318286
tagged with: list
possible better answer: http://stackoverflow.com/a/50150302
type: Question
tagged with: algorithm
score: 3
has comment: http://stackoverflow.com/comment/87318245
has answer: http://stackoverflow.com/a/50150302
tagged with: python

http://stackoverflow.com/a/50181915
has comment: http://stackoverflow.com/comment/87409671
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50181713
has comment: http://stackoverflow.com/comment/87406965
downvote count: 0
has body: Think big, think in terms of tensors. A simple idea would be 1. compute the gray-scale version (poor-man way) 2. subtract gray-scale version from intput 3. L2-distance What about import tensorflow as tf import numpy as np fake_color = np.random.randn(8, 256, 256, 3).astype(np.float32) fake_grayscale = np.random.randn(8, 256, 256, 3).mean(axis=3, keepdims=True).astype(np.float32) def measure_grayscale(x): gray_version = tf.reduce_mean(x, axis=3, keepdims=True) difference = tf.reduce_mean(tf.squared_difference(x, gray_version), axis=[1, 2, 3]) return difference def regions_grayscale(x, tresh=0.1): gray_version = tf.reduce_mean(x, axis=3, keepdims=True) difference = tf.squared_difference(x, gray_version) return tf.greater(difference, tresh * tf.ones_like(difference)) with tf.Session() as sess: data = tf.placeholder(tf.float32) print sess.run(measure_grayscale(data), {data: fake_color}) print sess.run(measure_grayscale(data), {data: fake_grayscale}) This gives here: [0.6701656 0.6660412 0.6667728 0.6642832 0.667957 0.66799116 0.6700557 0.66249603] for the batch of color images [0. 0. 0. 0. 0. 0. 0. 0.] for the batch of only grayscale images Detecting regions which are grayscale according to your heuristic can be done via thresholding in regions_grayscale. You can even apply tf.reduce_mean(.., axis=1) to get your "silly metric" to work. The syntax to NumPy is the same. As you use the tag of TensorFlow the code above is using TensorFlow.
has comment: http://stackoverflow.com/comment/87402602
type: Answer

http://stackoverflow.com/comment/87378114
has text: [`flake8`](http://flake8.pycqa.org/en/latest/) will warn on this.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50180453
type: Comment

http://stackoverflow.com/a/50137987
answers question: http://stackoverflow.com/q/50136628
score: 1
downvote count: 0
has body: A few features I would consider adding: Home and Visitor Superstars. I know you have all stars but superstars are a bit different. Example: Lebron vs. Demar Derozan. Both are super stars but many more people are likely to go see Lebron over Demar. It would, however, be quite a pain to add all of this and also to determine who is a superstar. You may want to consider rivalries. Boston vs Los Angeles (Lakers) is always a sell out crowd due to the history of the teams. The number of season ticket holders may or may not affect the count. I'd be interested to see if that held any weight. Some of these aren't too important. I would consider getting rid of the game score since that is what happens at the end of the game and attendance is related to ticket sales (before the game starts). It looks like you do have a decent amount of data to work with. Obviously its going to be a supervised model. Looks like regression will be something you will want to use for your model.
type: Answer
upvote count: 1

http://stackoverflow.com/q/50176529
has comment: http://stackoverflow.com/comment/87373725
answer count: 2
tagged with: functional-programming
has title: Is there something like the threading macro from Clojure in Python?
has comment: http://stackoverflow.com/comment/87370419
has comment: http://stackoverflow.com/comment/87371087
downvote count: 0
score: 8
has comment: http://stackoverflow.com/comment/87370200
favorite count: 0
has body: In Clojure I can do something like this: (-&gt; path clojure.java.io/resource slurp read-string) instead of doing this: (read-string (slurp (clojure.java.io/resource path))) This is called threading in Clojure terminology and helps getting rid of a lot of parentheses. In Python if I try to use functional constructs like map, any, or filter I have to nest them to each other. Is there a construct in Python with which I can do something similar to threading (or piping) in Clojure? I'm not looking for a fully featured version since there are no macros in Python, I just want to do away with a lot of parentheses when I'm doing functional programming in Python. Edit: I ended up using toolz which supports pipeing.
has comment: http://stackoverflow.com/comment/87370353
type: Question
upvote count: 8
has comment: http://stackoverflow.com/comment/87370310
tagged with: python
accepted answer: http://stackoverflow.com/a/50176857
possible better answer: http://stackoverflow.com/a/50201758
has answer: http://stackoverflow.com/a/50176857
has answer: http://stackoverflow.com/a/50201758
type: AnsweredQuestion

http://stackoverflow.com/comment/87198054
score: 0
comment on: http://stackoverflow.com/q/50090644
type: Comment
type: QuestionComment
has text: What instance type are you running this on? There is the chance that the instance has less capacity than your teammates.

http://stackoverflow.com/q/50153699
has title: How does '%.*g' % (6,k) work in python
has answer: http://stackoverflow.com/a/50154677
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/50154677
has comment: http://stackoverflow.com/comment/87325101
score: 1
has comment: http://stackoverflow.com/comment/87324853
type: Question
accepted answer: http://stackoverflow.com/a/50154826
has comment: http://stackoverflow.com/comment/87325244
answer count: 2
has answer: http://stackoverflow.com/a/50154826
has body: I have the following piece of code: (Python 2.7) k = 4535.65463456 out = '%.*g' % (6,k) print str(out) Output: 4535.65 I am not able to understand the working of '%.*g' % (6,k). Since I not familiar with this syntax and don't know what this is called, I am not even able to google it. Could someone help me with this? Thanks in advance.
tagged with: string-formatting

http://stackoverflow.com/a/50116235
score: 6
upvote count: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/50116204
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50116204
has body: By default, a DetailView for the Question model in the polls app uses the template polls/question_detail.html. You need to use template_name if you want to override that. You have set template, which will have no effect. It should be: class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' ...

http://stackoverflow.com/a/50262589
answers question: http://stackoverflow.com/q/50192934
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: The answer provided by Mikhail is perfectly acceptable, but I realized it wouldn't work for me since the task that is raising the exception is buried deep in some module so trying to retrieve it's exception is kind've difficult. I found that instead if I simply set a custom exception handler for my asyncio loop (loop is created by the discord client): def exception_handler(loop,context): print("Caught the following exception") print(context['message']) client.loop.set_exception_handler(exception_handler) client.run(token)

http://stackoverflow.com/q/50130380
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50130387
downvote count: 0
has title: Python - remove duplicate of dict that contains list of lists
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: list
linked to: http://stackoverflow.com/q/30055830
has answer: http://stackoverflow.com/a/50130601
upvote count: 3
accepted answer: http://stackoverflow.com/a/50130486
possible better answer: http://stackoverflow.com/a/50130484
has body: suppose training_data is a dict that contains a list of lists such as {1: [[1, 2], [1, 3], [1, 2, 5]], 2: [[1], [5], [1, 6]], 3: [[7], [5]]} I want to merge each value in training_data and then flatten it once to a list so that it will become [[1,2,3,5],[1,5,6],[7,5]].
has answer: http://stackoverflow.com/a/50130486
has answer: http://stackoverflow.com/a/50130484

http://stackoverflow.com/a/72370442
has body: On Ubuntu 18.04.6 I solved this issue first taking a look at what was failing with: python -c "import keyring.backends.SecretService as SS; SS.Keyring.priority" (...) RuntimeError: The Secret Service daemon is neither running nor activatable through D-Bus Ref: https://github.com/jaraco/keyring/issues/258 And then these were the steps I followed (most probably you just need to do 3.): [1.] sudo apt-get install -y python-dbus. [2.] pip install secretstorage. 3. sudo apt install gnome-keyring.
type: Answer
answers question: http://stackoverflow.com/q/50094328
score: 0

http://stackoverflow.com/comment/87379049
comment on: http://stackoverflow.com/q/50180886
type: Comment
score: 2
type: QuestionComment
has text: Can you point us to the line of code producing the error and describe the question a bit more please. Posting a large block of code with an error that isn't pinpointed clearly makes the question hard to answer.

iterator
tags question: http://stackoverflow.com/q/50100235
tags question: http://stackoverflow.com/q/50160069
tags question: http://stackoverflow.com/q/50132627
tags question: http://stackoverflow.com/q/50172448
tag name: iterator
type: Tag

http://stackoverflow.com/comment/87229174
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50102651
type: Comment
has text: The first one does the job, but as you said, the plot changes when the graph is resized. The 2nd one generates bars, but I need line graph.

http://stackoverflow.com/a/50214537
has comment: http://stackoverflow.com/comment/87446490
has comment: http://stackoverflow.com/comment/87447980
has comment: http://stackoverflow.com/comment/87447627
type: Answer
answers question: http://stackoverflow.com/q/50214506
score: 0
has comment: http://stackoverflow.com/comment/87446557
has body: responseJSON2 is a list. A list has indexes (0, 1, 2, ...). You need to use an int for your list: ID = str(ID) is wrong, you need to have an int there! try with ID = int(ID) And you can convert back in string: def requestRankedData(ID, APIKey): URL= "https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/"+str(ID)+"?api_key="+APIKey print (URL) response = requests.get(URL) return response.json() You need to find the index matching your ID in your response: responseJSON2 = requestRankedData(ID, APIKey) ID_idx = responseJSON2.index(str(ID)) print (responseJSON2[ID_idx][0]['tier']) print (responseJSON2[ID_idx][0]['entries'][0]['rank']) print (responseJSON2[ID_idx][0]['entries'][0]['leaguePoints'])

http://stackoverflow.com/q/50146855
tagged with: python
type: AnsweredQuestion
score: 0
has title: serial communictation between python and arduino
has answer: http://stackoverflow.com/a/50147415
tagged with: arduino
type: Question
tagged with: pyserial
has body: I send values arduino to python. This is part of my code. #include &lt;nRF24L01.h&gt; #include &lt;RF24.h&gt; #include &lt;RF24_config.h&gt; #include &lt;SPI.h&gt; #include "Timer.h" int IR_sensor = A0; int value; void setup(void) { Serial.begin(9600); pinMode(IR_sensor, INPUT); } void loop() { long IR_value = analogRead(IR_sensor); long IR_range = gp2y0a21yk(IR_value); //Serial.println(IR_value); //Serial.print(IR_range); //Serial.println("cm"); //Serial.println(); if (IR_range &lt; 50) { value = 1; Serial.println(value); } else { value = 0; Serial.println(value); } delay(1000); if (value == 1) { Serial.println("1234"); } } long gp2y0a21yk(long IR_value) { if (IR_value &lt; 10) { IR_value = 10; } return ((67870.0 / (IR_value - 3.0)) - 40.0) / 10; } SO THIS CODE has two options. First value =0 or value = 1 and then 1234 This is my python code import serial import time import MySQLdb from datetime import datetime import cv2 import boto3 port ="COM15" brate = 9600 arduino =serial.Serial(port, baudrate = brate, timeout=None) while True: data= arduino.readline()str = data[:-2].decode() print(str) if str=="0": print("nobody") What I wonder is this part. data=arduino.readline() this code reads the value 0 or 1 and 1234. WHAT I want to do is saving this value to data1 and data2 and I want to use this value! For example, if python gets value=0 I want to save this value to a so a=0 and then use if clause and if python gets value =1 and 1234 I want to save this a=1 and b=1234 and use it to if clause. Do you have any ideas? I really appreciate it!
accepted answer: http://stackoverflow.com/a/50147415
answer count: 1
tagged with: serial-port

http://stackoverflow.com/comment/87385280
score: 0
type: AnswerComment
has text: It says: Requirement already satisfied (use --upgrade to upgrade): scrapy in /usr/local/lib/python2.7/dist-packages Cleaning up...
type: Comment
comment on: http://stackoverflow.com/a/50151204

http://stackoverflow.com/q/50147017
downvote count: 0
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87312862
has title: TCP data sending from python to logstash fails
type: AnsweredQuestion
upvote count: 3
tagged with: tcp
score: 3
accepted answer: http://stackoverflow.com/a/50147884
has answer: http://stackoverflow.com/a/50147884
type: Question
has comment: http://stackoverflow.com/comment/87313684
has body: I am trying to send data from python script over TCP and receive the same in the logstash. But there is no exchange of data happening. logstash.conf input { tcp { port =&gt; 5959 codec =&gt; json } } filter{ } output { stdout {codec =&gt; rubydebug} } python : import json import socket import sys HOST = "127.0.0.1" PORT = 5959 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: sock.connect((HOST, PORT)) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2) msg = {'@message': 'python test message', '@tags': ['python', 'test']} sock.sendall(json.dumps(msg)) sock.send('\n') sock.close() sys.exit(0) After executing both the scripts I am neither getting any error nor data in the logstash so can someone help like what can be causing the issue.
answer count: 1
tagged with: logstash

http://stackoverflow.com/comment/87217620
score: 2
type: Comment
has text: @porton Your question is rather unclear. Why do you need a generator function rather than a different kind of iterator? And for what it's worth, it's quite simple to turn this implementation into a generator function. Please show your attempts, then we may be able to understand your actual problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/50100411

http://stackoverflow.com/a/50123115
type: Answer
answers question: http://stackoverflow.com/q/50107541
score: 0
has body: This was my fix: @property def conversion_number(self): return 'P0{}'.format(self.id) if self.id &lt; 10 else 'P{}'.format(self.id) The issue seemed to be that id is an InstrumentedAttribute (not an int) when sqlalchemy is initializing the model. This behavior is strange because my implementation isn't substantially different from the example in the SQLAlchemy docs.

http://stackoverflow.com/a/50162370
has body: You are comparing the array embedded in your instance (self.array) to the entirety of the other object. This will not work well. You need to compare self.array to other.array and/or convert both objects to the same type before comparing. You probably also need to specify what it means to compare two arrays (i.e., you want a single boolean value that indicates whether all elements are equal, not an array of boolean values for each element). For the code below, I assume you are using a numpy ndarray for self.array. If not, you could write your own array_equal that will convert other to an array, then compare the lengths of the arrays, then return (self.array==other_as_array).all(). If you want to test for strict equality between the objects (same types, same values), you could use this: from numpy import array_equal import numpy as np class List ... def __eq__(self, other): return isinstance(other, List) and array_equal(self.array, other.array) If you just want to check for equality of the items in the list, regardless of the object type, then you could do this: def __eq__(self, other): if isinstance(other, List): return array_equal(array, other.array) else: return array_equal(self.array, other)
answers question: http://stackoverflow.com/q/50158962
score: 0
type: Answer

http://stackoverflow.com/q/50102174
accepted answer: http://stackoverflow.com/a/50102249
has answer: http://stackoverflow.com/a/50102249
score: 1
tagged with: python
has title: Python data fields initialisation
type: AnsweredQuestion
tagged with: python-3.x
answer count: 1
downvote count: 0
upvote count: 1
has body: Seems like an obvious question, but I can't find the answer. In Python, how do I initialise class data (not instance attributes). class MyClass: DATA = MyClass() Doesn't work, because MyClass() isn't defined yet. class MyClass: pass MyClass.DATA = MyClass() Is confusing to the human reader, linter, IDE and autocomplete. Is there a more standard way of doing this?
favorite count: 0
type: Question

http://stackoverflow.com/q/50189626
has answer: http://stackoverflow.com/a/50197228
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87396090
tagged with: search
has comment: http://stackoverflow.com/comment/87396198
score: 1
upvote count: 1
answer count: 1
downvote count: 0
tagged with: bootstrap-4
favorite count: 0
has title: Django - show the query in the search box on the results page
type: Question
has body: I'm trying to show User's search query in the Search Box on the results page. A very basic problem, but for some reason, it doesn't work for me My views.py looks like: def search(request): result_list = [] if request.method == 'POST': query = request.POST['query'].strip() if query: print(query) print(type(query)) # Run our Webhose search function to get the results list! result_list = run_query(query) context_dict = {'result_list': result_list, 'query': query} context_dict = {'result_list': result_list} return render(request, 'rango/search.html', context_dict) my search.html template is below: {% block body_block %} Search with Rango {% csrf_token %} Search {% if result_list %} Results {% for result in result_list %} {{ result.title }} {{ result.summary }} {% endfor %} {% endif %} {% endblock %} Any advice?

http://stackoverflow.com/comment/90781189
score: 0
type: QuestionComment
has text: Related https://stackoverflow.com/questions/19419098/how-to-train-on-and-make-a-serialized-feature-vector-for-a-neural-network
type: Comment
comment on: http://stackoverflow.com/q/50087271

http://stackoverflow.com/a/50230769
score: 6
answers question: http://stackoverflow.com/q/50192121
type: Answer
has comment: http://stackoverflow.com/comment/87487364
downvote count: 0
upvote count: 6
has body: With respect to this documentation here, you could create your own color-dictionary. These dicts have to be of rgb-values, so I wrote a first test function to generate one from Hex_colors and your desired thresholds: def NonLinCdict(steps, hexcol_array): cdict = {'red': (), 'green': (), 'blue': ()} for s, hexcol in zip(steps, hexcol_array): rgb =matplotlib.colors.hex2color(hexcol) cdict['red'] = cdict['red'] + ((s, rgb[0], rgb[0]),) cdict['green'] = cdict['green'] + ((s, rgb[1], rgb[1]),) cdict['blue'] = cdict['blue'] + ((s, rgb[2], rgb[2]),) return cdict hc = ['#e5e5ff', '#acacdf', '#7272bf', '#39399f', '#000080'] th = [0, 0.1, 0.5, 0.9, 1] cdict = NonLinCdict(th, hc) cm = mc.LinearSegmentedColormap('test', cdict) plt.figure() sns.heatmap( vmin=0.0, vmax=1.0, data=data, cmap=cm, linewidths=0.75) which generates: There can be even more done (towards discrete jumps for example, just have a look at the docs...) but this should answer your original question - "custom" included this time... However, I have to add my personal opinion: Colormaps which are stretched like these here might be 'pleasing', but one should pay attention that they are not misleading the eye of the viewer. I hope this helps.

http://stackoverflow.com/comment/87434775
comment on: http://stackoverflow.com/a/50208821
type: Comment
score: 0
type: AnswerComment
has text: Thank you Noor, I will try using Models. But is there anyway to solve this in my way since i never used SqlAlchemy before?

http://stackoverflow.com/comment/87435604
type: Comment
score: 0
type: AnswerComment
has text: Hey Nova, I would like to know more about your issue. First please explain a little bit more about what you meant by this: *"it only Insert the first data on the form"* Secondly what do you mean by this: *Is there anyway i can fix this within a single route?* Do you want to merge both of these routes? Then you can create simple check if its a GET or POST request. For Get just show the data and Post or Update means you are changing something.
comment on: http://stackoverflow.com/a/50208821

http://stackoverflow.com/comment/87337912
score: 0
comment on: http://stackoverflow.com/a/50158632
has text: Yup you did. And I got messed up b/w different keywords I guess. But, thanks a lot Alasdair! Now, all that remains is the issue of creating user accounts for existing users.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87214090
type: Comment
type: AnswerComment
has text: Thanks for your answer! One more question, I have a rather large dataset with over 200 columns is there any shortcut so i dont have to enter all the headings into id_vars?
score: 1
comment on: http://stackoverflow.com/a/50098332

http://stackoverflow.com/comment/87427939
has text: If you own the sites, seems like it would be easier to just export/convert the db content of site 1 into site 2 rather than scraping the pages with Selenium.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50204841
score: 0

http://stackoverflow.com/comment/87311817
has text: If df is my dataframe that has all the input customer ID's as well as purchase data, then how do I map all the customer ID's to their respective clusters in python?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50146570
type: Comment

http://stackoverflow.com/a/50142566
score: 3
has comment: http://stackoverflow.com/comment/87303934
answers question: http://stackoverflow.com/q/50142116
type: Answer
has comment: http://stackoverflow.com/comment/87303909
upvote count: 3
has body: Your code has an obvious "too many loop" issues. It also stores the result as a flat list, you need a list of lists. It has also a more subtle bug: a same index can be added more than once if 2 intervals match in a row. I've registered the added indices in a set to avoid this. The bug doesn't show with your original data (which tripped a lot of experienced users, including me), so I've changed it: pos = [[1,2,3,6,7,8,11,15,16,17,20],[1,5,6,7,8,20]] final_pos = [] for value in pos: sublist = [] added_indexes = set() for i in range(len(value)-1): if value[i+1]-value[i] &gt; 2: if not i in added_indexes: sublist.append(value[i]) ## added_indexes.add(i) # we don't need to add it, we won't go back # no need to test for i+1, it's new sublist.append(value[i+1]) # registering it for later added_indexes.add(i+1) final_pos.append(sublist) print(final_pos) result: [[3, 6, 8, 11, 15, 17, 20], [1, 5, 8, 20]] Storing the indexes in a set, and not the values (which would also work here, with some post-processing sort, see this answer) also would work when objects aren't hashable (like custom objects which have a custom distance implemented between them) or only partially sorted (waves) if it has some interest (ex: pos = [[1,2,3,6,15,16,17,20,1,6,10,11],[1,5,6,7,8,20,1,5,6,7,8,20]])
downvote count: 0
has comment: http://stackoverflow.com/comment/87303826
has comment: http://stackoverflow.com/comment/87303857

http://stackoverflow.com/q/50188485
has answer: http://stackoverflow.com/a/50188804
has title: NoReverseMatch at /post/new Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
has comment: http://stackoverflow.com/comment/87393998
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/87394908
has answer: http://stackoverflow.com/a/62556094
type: Question
has answer: http://stackoverflow.com/a/59000793
tagged with: django-templates
has body: blog/urls.py #from django.contrib import admin from django.urls import path,re_path from . import views app_name='blog' urlpatterns =[ path('about/',views.AboutView.as_view(),name='about'), path('',views.PostListView.as_view(),name='post_list'), path('post/(?P<pk>\d+)/$',views.PostDetailView.as_view(),name='post_detail'), path('post/new',views.CreatePostView.as_view(),name='post_new'), re_path('post/(?P<pk>\d+)/edit/',views.PostUpdateView.as_view(),name='post_edit'), re_path('post/(?P<pk>\d+)/remove/',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.DraftListView.as_view(),name='post_draft_list'), re_path('post/(?P<pk>\d+)/comment/',views.add_comment_to_post,name='add_comment_to_post'), re_path('comment/(?P<pk>\d+)/remove/',views.comment_remove,name='comment_remove'), re_path('post/(?P<pk>\d+)/publish/',views.post_publish,name='post_publish'), re_path('comment/(?P<pk>\d+)/approve/', views.comment_approve, name='comment_approve'), ] views.py from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from blog.models import Comment,Post from blog.forms import CommentForm,PostForm from django.urls import reverse_lazy from django.contrib.auth import authenticate, login from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.views.generic import (TemplateView, ListView,DetailView,CreateView,UpdateView) class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('- published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url='/login/' redirect_field_name='blog/post_detail.html' form_class = PostForm model=Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url='/login/' redirect_field_name='blog/post_detail.html' form_class = P…
type: UnansweredQuestion
tagged with: python

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/50103486
tags question: http://stackoverflow.com/q/50191729
tags question: http://stackoverflow.com/q/50209312
tags question: http://stackoverflow.com/q/50077562
tag name: decision-tree

http://stackoverflow.com/comment/87198601
has text: Can you post your lambda function ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50091109
type: AnswerComment

http://stackoverflow.com/comment/87249082
type: QuestionComment
has text: In Python, doesn't everything under the `def` line need to be indented? I don't write Python though, so...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50115873

http://stackoverflow.com/q/50185839
type: Question
has comment: http://stackoverflow.com/comment/87388628
has comment: http://stackoverflow.com/comment/87390449
type: UnansweredQuestion
has title: Why doesn't my bash read the argument when using Python?
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/87388790
score: 0
answer count: 0
has body: I'm learning Flask following Flask Web Development, when I get Chapter 5, using Flask-Migrate I found that my shell (git bash) doesn't read the arguments at all. When I input python index.py db init It works just like I have not written the argument. Whatever argument I input the shell can't read it and just runs the server. May anyone could tell me what happens? Here is my index.py , but actually when I run the example codes,the shell doesn't read the arguments too. from flask import Flask,render_template,session,redirect,url_for,flash from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from flask_migrate import Migrate from wtforms import StringField,SubmitField from wtforms.validators import DataRequired import os class Nameform(FlaskForm): name = StringField('What is s your name',validators = [DataRequired()]) submit = SubmitField('Submit') basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SECRET_KEY'] = 'tell me why' app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///'+os.path.join(basedir,'data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True bootstrap = Bootstrap(app) #database db = SQLAlchemy(app) class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(64),unique = True) users = db.relationship('User',backref = 'role') def __repr__(self): return '&lt;Role %r&gt;' % self.name class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer,primary_key = True) username = db.Column(db.String(64),unique = True, index = True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return '&lt;User %r&gt;' % self.username #migrate migrate = Migrate(app,db) @app.route('/user/&lt;name&gt;') def user(name): return render_template('user.html',name=name) @app.route('/',methods = ['GET','POST']) def index(): name = None for…
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50126725
has comment: http://stackoverflow.com/comment/87271453
downvote count: 0
tagged with: web-scraping
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87271437
has comment: http://stackoverflow.com/comment/87271580
has title: stress test a website with webscrapig
has answer: http://stackoverflow.com/a/50126867
accepted answer: http://stackoverflow.com/a/50126867
has comment: http://stackoverflow.com/comment/87271523
type: AnsweredQuestion
has body: My friend wrote a website by node.js, and I want to help him to do the stress test just in case it crashed some day. I used beautifulsoup to test it, and it went well. Code: for i in range(0,1000): #i=i+1 l=randint(2008, 2018) first="year=%d" %l k=randint(1600, 2400) second="cc=%d" %k url="http://xx.xxx.xxx.xxx:xxxx/outputData?{0}&amp;{1}&amp;submit=Submit".format(first,second) res = requests.get(url) soup=BeautifulSoup(res.text,'lxml') print(soup) Instead of running 1000 times one by one in order, is there any other way to test it if I want to run it at the same time with 1000 codes by using python? Thanks!
score: 1
has comment: http://stackoverflow.com/comment/87271493
has answer: http://stackoverflow.com/a/50126869
possible better answer: http://stackoverflow.com/a/50126869
favorite count: 0
tagged with: beautifulsoup
type: Question
answer count: 2
tagged with: stress-testing

http://stackoverflow.com/a/50217729
type: Answer
upvote count: 1
score: 1
has body: Why waste time defining a in the first place? You can simply append the correct number of 0s to b instead: &gt;&gt;&gt; b = [1, 2, 3] &gt;&gt;&gt; a = b + [0] * (5 - len(b)) &gt;&gt;&gt; a [1, 2, 3, 0, 0]
answers question: http://stackoverflow.com/q/50217453
downvote count: 0

http://stackoverflow.com/comment/87448297
score: 0
comment on: http://stackoverflow.com/q/50215776
has text: If I'm not mistaken, your `finalScore` seems to be a scalar rather than a list, how are you supposed to iterate through it?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87450068
has text: `print(df)` outside of your loop will tell you if the values have been properly assigned
comment on: http://stackoverflow.com/q/50215831
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/50128934
linked to: http://stackoverflow.com/q/38231591
favorite count: 0
type: Question
upvote count: 4
has body: I have a dataframe like this. index column1 e1 {u'c680': 5, u'c681': 1, u'c682': 2, u'c57... e2 {u'c680': 6, u'c681': 2, u'c682': 1, u'c57... e3 {u'c680': 2, u'c681': 4, u'c682': 2, u'c57... e4 {u'c680': 4, u'c681': 2, u'c682': 3, u'c57... e5 {u'c680': 3, u'c681': 5, u'c683': 3, u'c57... Now I want to expand the dict in column1 to individual columns like below. index c680 c681 c682 c683 e1 5 1 2 0 e2 6 2 1 0 e3 2 4 2 0 e4 4 2 3 0 e5 3 5 0 3 Is there a pandas shortcut that can achieve this?
duplicate of: http://stackoverflow.com/q/38231591
tagged with: python
score: 4
type: AnsweredQuestion
tagged with: pandas
has title: Pandas dict keys to columns
downvote count: 0
accepted answer: http://stackoverflow.com/a/50128978
answer count: 1
has answer: http://stackoverflow.com/a/50128978

http://stackoverflow.com/comment/87459242
comment on: http://stackoverflow.com/q/50220548
has text: thank you very much I definitely have alot to learn!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50142522
has body: The only reasonable way on source level I see, simplified: Parse the source into some AST (or just use the built-in AST). Copy a subtree representing the function's body. Rename the variables in the subtree, e.g. by adding an unique prefix. At the call site, replace all passed arguments with assignments using the function's new variable names. Remove the call and replace it with the function body you've prepared. Serialize the AST back to source. What poses real problems: Generator functions; just don't inline them. Returns from under try/finally that need to run the finally part. Might be pretty hard to rewrite correctly; imho, best left in-unlined. Returns from under context managers that need to run the __exit__ parts. While not impossible, it's also tricky to rewrite preserving the semantics; likely also best left un-inlined. Mid-function returns, especially from within multiple loop constructs. You might need to replace them with an extra variable and thread it into every condition of every while statement, and likely to add a conditional break to for statements. Again, not impossible but likely best left un-inlined.
has comment: http://stackoverflow.com/comment/87304306
has comment: http://stackoverflow.com/comment/87303890
upvote count: 2
has comment: http://stackoverflow.com/comment/87304011
answers question: http://stackoverflow.com/q/50141784
has comment: http://stackoverflow.com/comment/87304388
downvote count: 0
has comment: http://stackoverflow.com/comment/87304436
has comment: http://stackoverflow.com/comment/87303694
type: Answer
score: 2

http://stackoverflow.com/comment/87225418
type: QuestionComment
comment on: http://stackoverflow.com/q/50104095
score: 1
has text: Where is `sentence_stream` defined? Looks like it's missing...
type: Comment

http://stackoverflow.com/comment/87397094
score: 0
comment on: http://stackoverflow.com/q/50189866
has text: @blue-phoenox I didn't think of that possibility, good inference. I'm not sure that's the case though, because print works. It's just that print looks ugly lol, just plain text, nothing like the pandas table.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87208761
has text: Can you please update the question with the code that you've already tried? Also please add the expected output for situations where ranges have intersection or numbers are inside a range.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50096250
type: Comment

http://stackoverflow.com/q/50217481
answer count: 1
has title: Tkinter in virtual environment (PyCharm/Mac OS 10.13.4)
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/87452644
linked to: http://stackoverflow.com/q/50196561
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87453815
has answer: http://stackoverflow.com/a/50965589
type: UnansweredQuestion
score: 1
has body: I have set up a virtual environment and when I try to run matplotlib on it, I get the following error: Traceback (most recent call last): File "/Users/sumeet/PycharmProjects/VISM/test2.py", line 2, in &lt;module&gt; import matplotlib.pyplot as plt File "/Users/sumeet/tensorflow/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/Users/sumeet/tensorflow/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup [backend_name], 0) File "/Users/sumeet/tensorflow/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 4, in &lt;module&gt; from . import tkagg # Paint image to Tk photo blitter extension. File "/Users/sumeet/tensorflow/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 5, in &lt;module&gt; from six.moves import tkinter as Tk File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/six.py", line 203, in load_module mod = mod._resolve() File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/six.py", line 115, in _resolve return _import_module(self.mod) File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/six.py", line 82, in _import_module __import__(name) File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 39, in &lt;module&gt; import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter From what I understand, I need to set the environment variables correctly in the activate script or I can symlink tkinter folder to virtualenv python2.7. I have followed the steps here: TKinter in a Virtualenv, but I am still getting the error. Steps that I followed are: To virtualenv/bin/activate, I added TK_LIBRARY=/usr/lib/python2.7…
tagged with: python
has comment: http://stackoverflow.com/comment/87452084
tagged with: tkinter
linked to: http://stackoverflow.com/q/15884075
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87273513
comment on: http://stackoverflow.com/a/50103961
score: 0
type: Comment
type: AnswerComment
has text: There are a few problems with this answer Only works with integers. What if user actually wanted to enter `-99`? Use of `enumerate()` is unnecessary. Hand written for loop to sum the numbers in a list when `sum()` could be used etc. etc.

http://stackoverflow.com/a/50194994
downvote count: 0
answers question: http://stackoverflow.com/q/50194909
type: Answer
accepted answer of: http://stackoverflow.com/q/50194909
score: 2
upvote count: 2
has body: itemAt(x, y) returns the item that covers the pixel (x, y) in the widget's coordinate system. item(row, col) returns the item at row, col in the widget's grid system.
type: AcceptedAnswer

http://stackoverflow.com/a/50140013
answers question: http://stackoverflow.com/q/50139901
has body: It seems listdir_attr() output also depends on the underlying server implementation. If you already have the printable format you can try splitting the values by \t may be use the last splitted value to be your key and second last would be your value. Also you can load the data in pandas dataframe and can directly access the fields you need with column names.
score: 1
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/50115854
answers question: http://stackoverflow.com/q/50115756
type: AcceptedAnswer
downvote count: 0
has body: this is a duplicate of ... sql transactions needs to be committed, either explicitly or implicitly. either issue a commit command explicitly cursor._get_db().commit() setting the connection to autocommit when opening the connection is also an option.
has comment: http://stackoverflow.com/comment/87248908
score: 3
has comment: http://stackoverflow.com/comment/87248891
type: Answer
accepted answer of: http://stackoverflow.com/q/50115756
has comment: http://stackoverflow.com/comment/87252681
has comment: http://stackoverflow.com/comment/87249576
has comment: http://stackoverflow.com/comment/87252088
upvote count: 3

http://stackoverflow.com/comment/87231425
type: QuestionComment
comment on: http://stackoverflow.com/q/50106983
score: 1
has text: I agree, this question is not a duplicate. On a more helpful note, it looks like you're running into the difference between `__str__` and `__repr__`. Try `print '[%s]' % u', '.join(unicode_list)`.
type: Comment

http://stackoverflow.com/comment/87420393
has text: @AndyK - well, yes, and that was the question I was writing when I saw yours. The problem is that "root" directory is very ambiguous.
score: 1
comment on: http://stackoverflow.com/q/50201842
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50140676
has comment: http://stackoverflow.com/comment/87299828
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87299670
has comment: http://stackoverflow.com/comment/87300023
has comment: http://stackoverflow.com/comment/87299666
has comment: http://stackoverflow.com/comment/87299633
upvote count: 0
has title: How do I accept a function as an input?
has comment: http://stackoverflow.com/comment/87300394
has comment: http://stackoverflow.com/comment/87300052
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/87300002
downvote count: 1
has answer: http://stackoverflow.com/a/50140749
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm trying to write a program that accepts and evaluates a simple function as such: A=[] v = input("Enter Function of x: " o = input("Enter length of range: ") for x in range (1,o+1): f = (v) A.append(f) but this just returns the function text (input string) 'o' times in a list. What am I doing wrong? EDIT: Thanks to @tdelaney for the answer: use f=eval(v)
has comment: http://stackoverflow.com/comment/87300029
type: UnansweredQuestion

http://stackoverflow.com/q/50081793
has answer: http://stackoverflow.com/a/58189041
tagged with: python-requests
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50082112
has body: I am trying to use some Python library to automatically login to a Kerberos account. For example, I found requests_kerberos, and my code is: import requests from requests_kerberos import HTTPKerberosAuth, REQUIRED r = requests.get("https://cas.id.ubc.ca/ubc-cas/login", auth=HTTPKerberosAuth()) However, even before I have a chance to input my username and password, the third line raises requests_kerberos.exceptions.MutualAuthenticationError: Unable to authenticate &lt;Response [200]&gt; Is there something wrong? Does UBC CWL support logging in by Kerberos?
type: UnansweredQuestion
upvote count: 5
score: 5
downvote count: 0
tagged with: python
has title: How to use Kerberos libraries in Python?
tagged with: kerberos

http://stackoverflow.com/comment/87194708
type: QuestionComment
score: 0
has text: The main file in processing is .pyde file. It's not a mistake. It's an ordinary python file that must always contain the setup and draw processing methods - processing rules. Maybe it's the reason it cannot be imported into other modules - only other modules can be imported into it.
comment on: http://stackoverflow.com/q/50089226
type: Comment

http://stackoverflow.com/a/50127194
has body: You can use pandas.melt . Bring your data df2 to long format, i.e. Home and season as columns and Allstars as values and then merge to df1 on 'Home' and 'Season'. import pandas as pd df2['Home'] = df2.index df2 = pd.melt(df2, id_vars = 'Home', value_vars = ['2012-13', '2013-14', '2014-15', '2015-16', '2016-17'], var_name = 'Season', value_name='H_Allstars') df = df1.merge(df2, on=['Home','Season'], how='left')
answers question: http://stackoverflow.com/q/50127062
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87273170
has comment: http://stackoverflow.com/comment/87272711
has comment: http://stackoverflow.com/comment/87272328

http://stackoverflow.com/q/50142583
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/43452353
tagged with: deep-learning
answer count: 1
has body: Is there a way to get the output of a intermediate layer in Keras passing a DirectoryIterator as input? I've already read the documentation of Keras related to this and this question but as far as I undertood, those approaches use single samples as input. I want to do this because it is more simple than read sample by sample and less computationally expensive than put everything on memory. I'm using TensorFlow as backend.
tagged with: keras
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/50142624
has answer: http://stackoverflow.com/a/50142624
tagged with: python
has title: Output of an intermediate layer in keras passing as input a DirectoryIterator

http://stackoverflow.com/comment/87456517
type: Comment
type: QuestionComment
has text: yes, a bzcat query works perfectly fine ...
score: 0
comment on: http://stackoverflow.com/q/50215627

http://stackoverflow.com/q/50083475
has comment: http://stackoverflow.com/comment/87182694
tagged with: tensorflow
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87192235
tagged with: python
has comment: http://stackoverflow.com/comment/87182894
favorite count: 0
type: Question
has body: What is done with this command? What does tf.stack stands for what? tf.stack([tf.range(tf.shape(self.a)[0], dtype=tf.int32), self.a], axis=1)
accepted answer: http://stackoverflow.com/a/50083951
upvote count: 2
has answer: http://stackoverflow.com/a/50083951
has title: what we do wtih tf.stack([tf.range(tf.shape(self.a)[0], dtype=tf.int32), self.a], axis=1)
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/87169483
type: QuestionComment
comment on: http://stackoverflow.com/q/50076666
score: 0
has text: it all std lib functions and language build-in data objects, you can implement `count` in some other ways as you like
type: Comment

http://stackoverflow.com/comment/101057120
score: 4
type: Comment
comment on: http://stackoverflow.com/q/50079735
type: QuestionComment
has text: I think the default settings of ADAM vary between Keras and PyTorch!

http://stackoverflow.com/q/50105373
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: database
downvote count: 0
tagged with: python
has title: Conditional check for strings not giving the behavior I expect
has comment: http://stackoverflow.com/comment/87229097
has comment: http://stackoverflow.com/comment/87227945
score: 2
tagged with: sqlite
answer count: 1
has body: I have an SQLite database which I am reading data from using Python. I connect to the database and then store the whole comment column into a list called output. Each entry in the list is a string, I want to isolate the entries in list which only contain the string '[deleted]'. To do this I am using a loop to index into the list and then for each point I compare the string to at index i to the string '[deleted]', if the string is '[deleted]' it should set a corresponding value of 1 at index i in a vector of zeros called deleted flag. The code I am using is below: deletedFlag = np.zeros((len(output),1)) for i in range(0,len(output)): if (output[i] == "[deleted]"): deletedFlag[i] = 1 The issue is that output[i] == '[deleted]' never returns true and therefore never sets the corresponding deletedFlag[i] = 1 Investigating further and printing output[i] to the console for a value of i I know to contain the '[deleted]' string returns a slightly different string than I expect: &gt;&gt; print(output[3]) &gt;&gt; ('[deleted]',) However even if I change my string comparison to be the same as the printed value I still get the same behavior of the deletedFlag vector remaining at all zeros: deletedFlag = np.zeros((len(output),1)) for i in range(0,len(output)): if (output[i] == "('[deleted]',)"): deletedFlag[i] = 1 Looking at the first four database entries using DB Browser shows the following taken from a screenshot and it is line 4 of the comment column I am trying to identify: I assume I am just doing the string comparison wrong but for the life of me I can't work out what it should be and I have tried most permutation of brackets and inverted commas I can think of. I understand that this is probably a really basic issue but any help would be greatly appreciated!
has answer: http://stackoverflow.com/a/50105678
favorite count: 0
type: Question

http://stackoverflow.com/comment/93380158
comment on: http://stackoverflow.com/a/53208092
score: 0
has text: Thanks for clarifying! That is indeed a bit more interesting, albeit not impossible with signals. I edited the answer, hope it helps!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87769293
has text: Can you please be more specific? i really don't get the trick :(
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50182174
type: Comment

http://stackoverflow.com/q/50098767
has answer: http://stackoverflow.com/a/50098896
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88127201
has comment: http://stackoverflow.com/comment/88129296
tagged with: python
has comment: http://stackoverflow.com/comment/87214276
has body: I have three functions that want to change a global variable and can't combine into one function, the way I know right now is keep define "global" keyword in each functions to be able to access global variable. Is there a better way to do the same thing with out keep redefining the global variable? for example: def fn1(self): global NUM NUM = 1 print "fn1 = ", NUM def fn2(self): global NUM NUM = 2 print "fn2 = ", NUM def fn3(self): global NUM NUM = 3 print "fn3 = ", NUM NUM = 0 fn1(NUM) fn2(NUM) fn3(NUM) Thank you
has answer: http://stackoverflow.com/a/50099862
tagged with: python-2.7
score: 0
has title: python global variable access: keep define in every functions?
answer count: 3
has comment: http://stackoverflow.com/comment/88132602
has comment: http://stackoverflow.com/comment/88127222
type: Question
has answer: http://stackoverflow.com/a/50098875
has comment: http://stackoverflow.com/comment/87213957

http://stackoverflow.com/comment/87199663
has text: No, it's easier to answer _easy_ questions. It's _better_ to answer _good_ questions. keep it up.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50091605
type: Comment

http://stackoverflow.com/comment/87201076
comment on: http://stackoverflow.com/a/50092343
type: Comment
type: AnswerComment
score: 0
has text: Apologize for my formatting but here is what i am trying to achieve and the error i am getting usernumber = input('Enter a number [0-9] to be displayed: ') usernumber = format(usernumber,'#04x') usernumber = str(usernumber) print 'The hex format is:',usernumber.strip() usernnumber = usernumber.strip() writeOneByte(usernumber) def writeOneByte(val): GPIO.output(11, val & (0x01 << 0)) GPIO.output(11, val & (0x01 << 0)) TypeError: unsupported operand type(s) for &: 'str' and 'int'

http://stackoverflow.com/a/50109965
upvote count: 1
has body: I think to ensure your rule nr 1 is never validated you could use assert statement, something like this: b = rand() * b assert a != b
answers question: http://stackoverflow.com/q/50109783
score: 1
has comment: http://stackoverflow.com/comment/87242848
downvote count: 0
type: Answer

http://stackoverflow.com/q/50085252
tagged with: python
has title: How to replace string in different position in sentence by another column
tagged with: pandas
score: 2
upvote count: 2
downvote count: 0
answer count: 1
has body: I have problem how to replace string in another position than 0 in sentence using my function. I want to replace string in col2 from string in col1 (always lowercase) For example I want try replace: input: Hello Aaa1 my very good friend output: Hello NNP my very good friend Now I have only: input: Aaa1 my very good friend output: NNP my very good friend I want to replace string in all position of sentence. I try: ## import libraries from nltk import word_tokenize, pos_tag, pos_tag_sents ## tag the sentece df['col2'] = df['col2'].apply(word_tokenize).apply(pos_tag) ## this function does the magic def get_vals(lst): op = [] for i, v in enumerate(lst): if i == 0: op.append(v[1]) else: op.append(v[0]) return ' '.join(op) ## apply the function df['col2'] = df['col2'].apply(get_vals) print(df) col1 col2 0 aaa1 NNP is a great friend 1 abb2 NN is a very good friend Edit: I have: col1 col2 output aaa1 AAA1 Hello hello NNP Hello hello aaa2 aaa2 hello hello NN hello hello aaa3 Hello AAa3 hello Hello NNP hello I want to replace in each row with specific POS Tag (not only one string for NNP)
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50085311
type: UnansweredQuestion

http://stackoverflow.com/a/50110336
answers question: http://stackoverflow.com/q/50109996
score: 14
upvote count: 14
has body: For tf.constant, the input value must be a static non-tensor type. For example a numpy array. For tf.convert_to_tensor, the value "an object whose type has a registered Tensor conversion function." This means input types like Tensors or tf.Variables can also be provided as inputs. For example, see the tensor conversion function for Variables here: https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/python/ops/variables.py#L762
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/116595251
has comment: http://stackoverflow.com/comment/136065883
has comment: http://stackoverflow.com/comment/87239293
has comment: http://stackoverflow.com/comment/87238505
accepted answer of: http://stackoverflow.com/q/50109996
type: Answer

http://stackoverflow.com/a/50086108
answers question: http://stackoverflow.com/q/50085955
type: Answer
accepted answer of: http://stackoverflow.com/q/50085955
has comment: http://stackoverflow.com/comment/87193631
score: 2
has comment: http://stackoverflow.com/comment/87188084
upvote count: 2
has comment: http://stackoverflow.com/comment/87187916
downvote count: 0
type: AcceptedAnswer
has body: Essentially what reLu is : def relu(vector): vector[vector &lt; 0] = 0 return vector and softmax: def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0) The output of softmax being a one-hot encoded array means there is a problem and that could be many things. You can try reducing the learning_rate for starters, you can use 1e-4 / 1e-3 and check. If it doesn't work, try adding some regularization. I am also skeptical about your weight initialization. Regulatization : This is a form of regression, that constrains/ regularizes or shrinks the coefficient estimates towards zero. In other words, this technique discourages learning a more complex or flexible model, so as to avoid the risk of overfitting. - Regularization in ML Link to : Build a multilayer neural network with L2 regularization in tensorflow

http://stackoverflow.com/comment/87354099
has text: How to get my session variable?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50167544
type: Comment

http://stackoverflow.com/a/50175751
answers question: http://stackoverflow.com/q/50175706
has comment: http://stackoverflow.com/comment/87381549
type: Answer
has body: If you check out this question you can find how to get the index of the last "max" value in a numpy array. then check to see if that is less than the first 1 in B and you are good. import numpy as np reverse_A = A[::-1] i = len(reverse_A) - np.argmax(reverse_A) - 1 i &lt; np.argmax(B)
score: 0

http://stackoverflow.com/q/50202477
answer count: 1
has body: I'm having some problems with getting my Django based blog to display. When running the Django web server in debug mode I'm getting the following error message: The view blog.views.post_list didn't return an HttpResponse object. It returned None instead (Django) It only happens when I'm trying to access my blog application. Other templates are rendering fine. I would be very much grateful for your assistance. Here's the stack trace below: Environment: Request Method: GET Request URL: http://Some_URL Django Version: 2.0.4 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'blog', 'markdown', 'taggit'] 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'] Traceback: File "/usr/local/lib/python3.5/dist- packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.5/dist- packages/django/core/handlers/base.py" in _get_response 139. "returned None instead." % (callback.__module__, view_name) Exception Type: ValueError at / Exception Value: The view blog.views.post_list didn't return an HttpResponse object. It returned None instead. Here's a partial extract from my views.py file of the definition which seems to be causing the problem: def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.ge…
type: Question
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/50203745
tagged with: python
has title: The view blog.views.post_list didn't return an HttpResponse object. It returned None instead (Django)
score: 0
has comment: http://stackoverflow.com/comment/87421777

http://stackoverflow.com/a/50161277
has comment: http://stackoverflow.com/comment/87341690
has body: I've been doing these conversions this way and they performed quite fast: void convert_to_numpy(const mat &amp; input, p::object obj) { PyObject* pobj = obj.ptr(); Py_buffer pybuf; PyObject_GetBuffer(pobj, &amp;pybuf, PyBUF_SIMPLE); void *buf = pybuf.buf; double *p = (double*)buf; Py_XDECREF(pobj); u_int n_rows = input.size(); u_int n_cols = input[0].size(); for (u_int i = 0; i &lt; n_rows; i++) { for (u_int j = 0; j &lt; n_cols; j++) { p[i*n_cols+j] = input[i][j]; } } } Then in python: C = np.empty([10000*10000], dtype=np.float64) timeit(test.convert_to_numpy)(A,C) Timings: 0.557882070541 0.12882900238
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50158131
has comment: http://stackoverflow.com/comment/87342520
answers question: http://stackoverflow.com/q/50158131
type: Answer
score: 2

http://stackoverflow.com/comment/87349390
score: 0
comment on: http://stackoverflow.com/q/50165568
type: Comment
type: QuestionComment
has text: @abarnert Yes that is what I am looking for, but how do I pass that into the course_select function? I tried this but it requires an integer or a slice.

http://stackoverflow.com/comment/87216920
has text: this is for an interview, you may want to stop interviewing until you have a better grasp of the language? make an attempt at least.
type: Comment
comment on: http://stackoverflow.com/q/50100161
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87188739
comment on: http://stackoverflow.com/q/50086404
score: 0
has text: I have solved the transparency using cv2.addWeighted(heatmap , alpha, img, 1 - alpha, 0, output), however another question has occured, i will create another topic for the question not to OT. thanks.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/61959999
type: Answer
has body: You can use linspace to easily shift your graphs to where you want them to start and end. The function also makes it very easy to scale the graph so they would be visually the same width import numpy as np import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt start_offset = 3 end_offset = start_offset y1 = np.random.randint(0, 10, 20) ##y1 has 20 random ints from 0 to 10 y2 = np.random.randint(0, 10, 10) ##y2 has 10 random ints from 0 to 10 x1 = np.linspace(0, 20, y1.size) ##create a number of steps from 0 to 20 equal to y1 array size-1 x2 = np.linspace(0, 20, y2.size) plt.plot(x1, y1) plt.plot(x2, y2) plt.show()
score: 0
answers question: http://stackoverflow.com/q/50195997

http://stackoverflow.com/q/50158745
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87335338
has comment: http://stackoverflow.com/comment/87335323
possible better answer: http://stackoverflow.com/a/50160441
has title: Modifying an xml attribute element with a value of a child element with lxml
has comment: http://stackoverflow.com/comment/87336685
accepted answer: http://stackoverflow.com/a/50159948
type: Question
has answer: http://stackoverflow.com/a/50160441
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50159948
has comment: http://stackoverflow.com/comment/87336212
tagged with: lxml
has comment: http://stackoverflow.com/comment/87336758
tagged with: python
has body: I have an XML snippet like this: [content]I need to get[/content]Other text And I would like to add the [content] of "child1" as an attribute into the parent element. Getting something like this: Other text I have this code, however it does not work as it looks like it only iters in the first child and does not go to the next. pattern = re.compile('[content](.*?)[/content]') xml_parser = et.parse(str(xml_file)) root_xml = xml_parser.getroot() translatable_elements = root_xml.xpath('//parent') for element in translatable_elements: for child_element in element.iterchildren(): if child_element.tag == 'child1': source_content = child_element.text value_str = pattern.match(source_content).group(1) element.attrib['value'] = value_str source_content = pattern.sub(source_content,'') tree = et.ElementTree(root_xml) tree.write(str(xml_file), encoding='utf-8', pretty_print=True)
tagged with: regex
has comment: http://stackoverflow.com/comment/87336641
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/87335297

http://stackoverflow.com/comment/87236945
has text: for floats see https://stackoverflow.com/questions/3477283/what-is-the-maximum-float-in-python
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50109804

http://stackoverflow.com/comment/87220584
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50100765
has text: Ok, so it is just closed and not deleted. So it means that I can give 1up to duplicated closed. ;) Thanks.
score: 0

http://stackoverflow.com/comment/87398047
score: 1
type: Comment
type: QuestionComment
has text: Where is `site/__init__.py`?
comment on: http://stackoverflow.com/q/50190485

http://stackoverflow.com/comment/87397734
comment on: http://stackoverflow.com/q/50190116
type: Comment
type: QuestionComment
score: 0
has text: Did you really do `txt = ''` before the second run?

http://stackoverflow.com/q/50199660
type: Question
tagged with: palindrome
type: UnansweredQuestion
tagged with: python
has title: Python code works in one .py file but not a new one
has comment: http://stackoverflow.com/comment/87417122
has comment: http://stackoverflow.com/comment/87415967
score: 0
has comment: http://stackoverflow.com/comment/87416374
answer count: 0
duplicate of: http://stackoverflow.com/q/21122540
has body: I ran the following code in a .py file (generated by Sublime Text v3126) using Terminal in Ubuntu. Ctrl+B doesn't show any errors in Sublime Text but running in Terminal yields an error. Strangely, this code worked in Terminal when it was in a previous .py file, which had other codes. Anyway, here's the particular code: import math import cmath import datetime import random as RAN from tabulate import tabulate def main(): print ("") print("Key in a word.") while True: try: x = str(input()) x = x.casefold() xr = reversed(x) print("") print("Using iterative and/or recursive functions...") except ValueError: print("Invalid input. Try again") print("") continue if (list(x) != list(xr)) or (x != x[::-1]): print("The input is not a palindrome. Try again.") print("") continue else: print("The input is a palindrome.") break if __name__ == '__main__': main() So, when I run this code in a .py file containing only this code, I get this error in Terminal: Key in a word. example Traceback (most recent call last): File "./Test Pad.py", line 30 in &lt;module&gt; main() File "./Test Pad.py", line 12 in main x = str(input()) File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'example' is not defined Thank you for your consideration.
tagged with: terminal
has comment: http://stackoverflow.com/comment/87416584

http://stackoverflow.com/comment/87302585
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50142125
has text: `if names in f:` isn't going to work as `f` is a filename, not a list. Maybe you want `if f in names:`
type: Comment

http://stackoverflow.com/q/50120823
has comment: http://stackoverflow.com/comment/87262624
has body: I am using a large excel file with four columns, but I only require two: Date and HPCP. The goal of this program is to convert the dates to date objects, remove duplicate dates, and then sum the HPCP of the duplicates. I feel like this code should work, however, the output is very wrong. The code successfully converts the dates to date objects, removes duplicates, but does not sum correctly. Any help would greatly be appreciated. Link to excel file: https://drive.google.com/open?id=1P5-k9Zyz8iFwx6Y-9yhnRozGGSvqpXLz Example some rows from the excel file: STATION STATION_NAME DATE HPCP COOP:305801 NY CITY CENTRAL PARK NY US 20000101 01:00 0 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 15:00 0 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 16:00 0.01 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 17:00 0.03 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 18:00 0.04 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 19:00 0.12 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 20:00 0.17 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 21:00 0.13 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 22:00 0.04 COOP:305801 NY CITY CENTRAL PARK NY US 20000104 23:00 0.09 COOP:305801 NY CITY CENTRAL PARK NY US 20000105 00:00 0.07 COOP:305801 NY CITY CENTRAL PARK NY US 20000105 01:00 0 COOP:305801 NY CITY CENTRAL PARK NY US 20000109 21:00 0.01 COOP:305801 NY CITY CENTRAL PARK NY US 20000109 22:00 0 COOP:305801 NY CITY CENTRAL PARK NY US 20000110 00:00 0.01 COOP:305801 NY CITY CENTRAL PARK NY US 20000110 13:00 0.15 COOP:305801 NY CITY CENTRAL PARK NY US 20000110 14:00 0.29 COOP:305801 NY CITY CENTRAL PARK NY US 20000110 15:00 0.24 COOP:305801 NY CITY CENTRAL PARK NY US 20000110 16:00 0.15 COOP:305801 NY CITY CENTRAL PARK NY US 20000110 17:00 0.01 COOP:305801 NY CITY CENTRAL PARK NY US 20000113 08:00 0 COOP:305801 NY CITY CENTRAL PARK NY US 20000113 09:00 0.01 COOP:305801 NY CITY CENTRAL PARK NY US 20000113 10:00 0.02 COOP:305801 NY CITY CENTRAL PARK NY US 20000113 15:00 0.01 COOP:305…
tagged with: dataframe
has title: Sum function not working correctly with dataframe (Python)
tagged with: date
has comment: http://stackoverflow.com/comment/87259411
has comment: http://stackoverflow.com/comment/87264893
type: Question
has comment: http://stackoverflow.com/comment/87265884
answer count: 2
has answer: http://stackoverflow.com/a/50124036
has comment: http://stackoverflow.com/comment/87264889
has comment: http://stackoverflow.com/comment/87262760
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50124065
has comment: http://stackoverflow.com/comment/87259707
has comment: http://stackoverflow.com/comment/87259234
tagged with: python
has comment: http://stackoverflow.com/comment/87259385
has comment: http://stackoverflow.com/comment/87262220
score: 0
has comment: http://stackoverflow.com/comment/87262281
tagged with: pandas
has comment: http://stackoverflow.com/comment/87262020
tagged with: sum
has comment: http://stackoverflow.com/comment/87262494
has comment: http://stackoverflow.com/comment/87262666

pycharm
tags question: http://stackoverflow.com/q/50088797
tags question: http://stackoverflow.com/q/50139215
tags question: http://stackoverflow.com/q/50147889
tags question: http://stackoverflow.com/q/50196561
tags question: http://stackoverflow.com/q/50154652
tags question: http://stackoverflow.com/q/50117513
tags question: http://stackoverflow.com/q/50218814
tags question: http://stackoverflow.com/q/50080782
tag name: pycharm
tags question: http://stackoverflow.com/q/50184877
tags question: http://stackoverflow.com/q/50116720
tags question: http://stackoverflow.com/q/50156741
tags question: http://stackoverflow.com/q/50189140
type: Tag
tags question: http://stackoverflow.com/q/50111591
tags question: http://stackoverflow.com/q/50113927
tags question: http://stackoverflow.com/q/50113422
tags question: http://stackoverflow.com/q/50113446
tags question: http://stackoverflow.com/q/50169945
tags question: http://stackoverflow.com/q/50194070
tags question: http://stackoverflow.com/q/50093297
tags question: http://stackoverflow.com/q/50171840
tags question: http://stackoverflow.com/q/50222011
tags question: http://stackoverflow.com/q/50129135
tags question: http://stackoverflow.com/q/50110153
tags question: http://stackoverflow.com/q/50197027
tags question: http://stackoverflow.com/q/50150627
tags question: http://stackoverflow.com/q/50177846
tags question: http://stackoverflow.com/q/50181095
tags question: http://stackoverflow.com/q/50186290

http://stackoverflow.com/comment/87426548
has text: What is `groupby`?
score: 0
comment on: http://stackoverflow.com/q/50204697
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87406548
type: Comment
comment on: http://stackoverflow.com/a/50194326
type: AnswerComment
score: 0
has text: FYI: You can set the project directory with the `-p` switch to `mkvirtualenv` too.

http://stackoverflow.com/q/50133876
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50135157
accepted answer: http://stackoverflow.com/a/50135157
has body: I have a list that contains dates that I created using: dates_list = pd.date_range(startdate, num_of_periods, freq = 'MS') ^stored the date range in dates_list This returns my monthly list of dates correctly if I do print(dates_list). What I am trying to do is looking for an index number given a specific date in the range. I tried: dates_list.index(call_date) ^^where call_date is the date I am trying to find the index number of and I get an error message that reads: TypeError: 'DatetimeIndex' object is not callable If I try this same command on a simpler list, ie: simple_list = ['cheese', 'banana', 'mushroom', 'apple' ...] simple_list.index('banana') it returns 1. How do I get the index value from a list of dates? Is there something I have to do differently? Any feedback would be appreciated. Thank you.
downvote count: 1
tagged with: date
favorite count: 0
type: Question
upvote count: 2
has title: Finding the index of a date in a DateTime object python
answer count: 1
tagged with: python
tagged with: indexing
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/a/50168966
has body: First of all, LEARN THE BASICS try break in for loop not sure if while is required for i in range(0, 8): print("Inputting Data for Lane", i) gender = str(input("Is the athlete male or female ")) athlete = str(input("What is the athletes name ")) finishTime = float(input("What was the finishing time ")) dataset = [gender, athlete, finishTime] datasets.append(dataset) decision = input("Would you like to add another lane ") if decision != "yes": break // going by your code and what you have asked import time datasets= [] carry_on = True while carry_on == True: for i in range(0, 8): print("Inputting Data for Lane", i) gender = str(input("Is the athlete male or female ")) athlete = str(input("What is the athletes name ")) finishTime = float(input("What was the finishing time ")) dataset = [gender, athlete, finishTime] datasets.append(dataset) decision = input("Would you like to add another lane ") if decision == "yes": carry_on = True else: carry_on = False break print("") if 3 &lt; i &gt; 9: print("{0:&lt;10}{1:&lt;10}{2:&lt;15}".format("Gender","Athlete","Finish time")) ds = sorted(datasets, key=lambda x:x[2], reverse=False) for s in ds: time.sleep(1) print("{0:&lt;10}{1:&lt;10}{2:&lt;15}".format(s[0], s[1], s[2])) else: print("You have not chosen enough lanes, please choose atleast 4")
answers question: http://stackoverflow.com/q/50168712
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/50168712
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50114356
tagged with: python
tagged with: bottle
tagged with: cherrypy
type: AnsweredQuestion
tagged with: jmeter
has body: We've got an API, written in Python and using Bottle and Cherrypy, which we need to stress test. We've created a JMeter script to do this, but after a couple of minutes of execution, the calls begin to fail with the following exception:- java.net.BindException: Address already in use: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) I can't seem to work out how to tell JMeter not to hang onto the sockets, or how to tell Bottle to drop them. We've tried it with options such as JMeter's KeepAlive on and off but without success. We've pulled almost everything out of the API and this script still has the problem (without any of our functional baggage). """ This script provides a dummy API, which responds to every GET as if it found something. """ import bottle import os import sys import datetime import routes if __name__ == '__main__': HOST = 'localhost' PORT = 5555 @bottle.route('/thing/:id', builtin_function_or_method='GET') def get_thing(id): response_json = { 'data': { 'type': 'thing', 'id': id, 'meta': { 'date_retrieved': datetime.datetime.now().isoformat() } } } bottle.response.headers['Cache-Control'] = 'public,max-age=0' return response_json bottle.run(server='cherrypy', host=HOST, port=PORT) This is Python 3.6.5, Cherrypy 8.9.1 and JMeter 3.3 running on Windows.
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87337769
favorite count: 0
type: Question
tagged with: python-3.x
has title: JMeter and Python bottle - not closing sockets
accepted answer: http://stackoverflow.com/a/50232606
has comment: http://stackoverflow.com/comment/87482347
score: 1
has answer: http://stackoverflow.com/a/50232606

http://stackoverflow.com/a/50109791
score: 4
upvote count: 4
has body: old_df['oldDate'] will return the column containing the dates, which is a series. You can solve this issue by using the .apply function in pandas to apply a function to every row of a dataframe. See here def date_convert(date_to_convert): return datetime.datetime.strptime(date_to_convert, '%b %d, %Y').strftime('%m/%d/%Y') new_df['new_date'] = old_df['oldDate'].apply(date_convert)
downvote count: 0
has comment: http://stackoverflow.com/comment/138203729
answers question: http://stackoverflow.com/q/50109695
type: Answer

http://stackoverflow.com/q/50084998
tagged with: python
has body: from tkinter import * # Create a window spell_window = Tk() # Give the window a title spell_window.title('Spell Table') table_Var = StringVar() ## table = ['T', 'a', 'b', 'l', 'e'] ## I think it needs to move through a list??? def spell_table(): s_table = monty_Var.get() s_table += 'T' #Currently adds a 'T' each time the button is pressed monty_Var.set(s_table) the_label = Label(spell_window, width = 10, textvariable = table_Var, font = ('Arial', 30), bg = 'red') the_button = Button(spell_window, text = 'Next letter', command = spell_table) the_label.pack(padx = 0, pady = 0) the_button.pack(padx = 40, pady = 0) So basically i have created the label and button and need to spell out the word Table by pressing the Next letter button. Just not sure how to make it move through the table list and add them to label.
tagged with: label
type: AnsweredQuestion
tagged with: tkinter
has title: python/tkinter add the individual letters of a word to a label on button press
score: 1
answer count: 1
downvote count: 0
tagged with: button
upvote count: 1
accepted answer: http://stackoverflow.com/a/50085316
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50085316

http://stackoverflow.com/comment/87397384
type: AnswerComment
has text: Is error showing only when you try to update your python packages ? And is it python packages or only python according to your question ? Do you create any virtual environment ?
comment on: http://stackoverflow.com/a/50190086
type: Comment
score: 0

http://stackoverflow.com/comment/87435646
score: 2
type: QuestionComment
type: Comment
has text: well for one, you use the same buffer in the c implementation, but in python you reallocate a new one every time you use `buffer +=`
comment on: http://stackoverflow.com/q/50209291

date
tags question: http://stackoverflow.com/q/50133876
type: Tag
tags question: http://stackoverflow.com/q/50134014
tag name: date
tags question: http://stackoverflow.com/q/50134463
tags question: http://stackoverflow.com/q/50170951
tags question: http://stackoverflow.com/q/50162459
tags question: http://stackoverflow.com/q/50118203
tags question: http://stackoverflow.com/q/50120823
tags question: http://stackoverflow.com/q/50096909
tags question: http://stackoverflow.com/q/50143974
tags question: http://stackoverflow.com/q/50180726
tags question: http://stackoverflow.com/q/50123485
tags question: http://stackoverflow.com/q/50099365
tags question: http://stackoverflow.com/q/50159602

http://stackoverflow.com/a/50295934
type: AcceptedAnswer
type: Answer
upvote count: 1
score: 0
answers question: http://stackoverflow.com/q/50221284
downvote count: 1
has body: The following worked req = requests.request("POST", url=url, data=data, headers=headers)
accepted answer of: http://stackoverflow.com/q/50221284

http://stackoverflow.com/q/50149053
answer count: 0
tagged with: mysql-python
has body: I am using ActivePython version 2.7.13 and install MySQLdb. However the following error occurs when I use 'pip install mysql-python'. Command "/opt/ActivePython-2.7/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-xRB3M9/mysql-python/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-qnksTb/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-xRB3M9/mysql-python/ I have tried a lot approaches, like No module named MySQLdb, but it doesn't work.
type: Question
tagged with: centos
type: UnansweredQuestion
has title: Cannot install MySQLdb (mysql-python) on CentOS
tagged with: python
has comment: http://stackoverflow.com/comment/87316607
linked to: http://stackoverflow.com/q/454854
score: 0
has comment: http://stackoverflow.com/comment/87316223

http://stackoverflow.com/q/50107985
tagged with: loss-function
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: mse
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87239820
answer count: 0
score: 1
has title: Implementing custom mse loss function in tensorflow
has body: I am trying to implement a custom loss function on TensorFlow to calculate circular mean squared error loss. I am taking the difference of true and predicted values, y and yPredict which are both vectors (1D). I am adding another variable 2*j*pi where j ranges from -20 to 20. However, there seems to a problem in computing this line of code. err_matrix = tf.Variable(np.zeros((np.shape(yPredict)[0], np.shape(yPredict)[1], k.shape[0]))) Here is the error message: ValueError: slice index 1 of dimension 1 out of bounds. for 'strided_slice' (op: 'StridedSlice') with input shapes: [100,1,41], [2], [2], [2] and with computed input tensors: input[1] = &lt;0 1&gt;, input[2] = &lt;0 2&gt;, input[3] = &lt;1 1&gt;. This is the full function and the function call and how it is linked to the optimizer. Function: def wmse(yPredict,y): k = tf.constant(np.array(range(-20, 21))) err_matrix = tf.Variable(np.zeros((np.shape(yPredict)[0], np.shape(yPredict)[1], k.shape[0]))) for j in range(1, k.shape[0]): err_matrix[:, j] += tf.subtract(tf.subtract(yPredict,y), tf.constant(2*j*tf.constant(np.pi))) errs = tf.reduce_min(err_matrix, axis=1) std_CNN_errors = tf.sqrt(tf.reduce_mean(tf.square(errs))) return std_CNN_errors Function Call: cost_function = wmse(network_outputs, outputs) optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost_function, var_list=tf.trainable_variables()) Could someone help me with this please? Thanks!
downvote count: 0

http://stackoverflow.com/a/50142745
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50141424
type: AcceptedAnswer
has body: Are you trying to train/run your model and freeze it in one same graph? This could happen if you do both in the same session or script. If so, you may try starting another python script and just do the freeze_graph. freeze_graph will need to restore the model thus add ops into the graph, which already have the same ops (with the same name). That's one cause of the error.
accepted answer of: http://stackoverflow.com/q/50141424
has comment: http://stackoverflow.com/comment/87354839

http://stackoverflow.com/comment/87349278
type: QuestionComment
has text: I can't see how this wouldn't be as simple as iterating over a `range` list, what's the matter doing that?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50165568

http://stackoverflow.com/comment/87471591
comment on: http://stackoverflow.com/q/50225232
type: Comment
type: QuestionComment
score: 0
has text: Did you tried both Length and name? like this `queryset = SwitchesPort.objects.all().order_by(Length('name').asc(), 'name')`

http://stackoverflow.com/q/50216657
answer count: 1
has body: How do I compare if a kivy weakref points to a given object? Setup: &gt;&gt;&gt; my_obj &lt;__main__.Marker object at 0x610054ee8&gt; &gt;&gt;&gt; my_list [&lt;weakref at 0x6100662c8; to 'Marker' at 0x610054ee8&gt;] My list is concretely touch.grab_list comming from a kivy touch event and contains weakrefs to all grabbed widgets. I would like to do something like if my_obj in my_list: and get True but clearly this returns False because the weakref and my_obj are different objects. What would be the correct approach?
upvote count: 1
has answer: http://stackoverflow.com/a/50217290
tagged with: kivy
favorite count: 0
type: Question
has title: kivy compare to weakref
accepted answer: http://stackoverflow.com/a/50217290
downvote count: 0
tagged with: python
tagged with: weak-references
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/50195029
tagged with: tkinter
answer count: 2
linked to: http://stackoverflow.com/q/44398075
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50195030
tagged with: ide
has answer: http://stackoverflow.com/a/50775832
has body: today I have encountered a strange problem where python ide would not scale the font correctly on my 1920*1080 screen. So i fixed it. Kinda I knew that there was an option in windows where one could toggle the "Override high DPI scaling behavior". Problem is that this tab is only available for application e.g ".exe". Windows is a strange beast. By default python ide has font size 9-10. That font on high res display just gets scaled by win 10 My solution is to manually enable DPI Awareness and then set the correct font size in class called run.py As this is not a real question i will post the code and mark it as answered It may not be compatible with displays that have higher resolution then 1920*1080, but hey it works :D
favorite count: 0
tagged with: python-2.7
has title: How to make python ide work on high dpi displays without blurring
downvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/100648928
type: Question
tagged with: python-3.x
upvote count: 0

http://stackoverflow.com/q/50144413
tagged with: deep-learning
type: UnansweredQuestion
tagged with: classification
has answer: http://stackoverflow.com/a/51145879
answer count: 1
tagged with: machine-learning
has body: I have an 3D Convolutional Neural Network in Python with TFLearn. Example code bellow: def model_3d(self): """ This function will build our 3D Convolutional Neural Network """ #Layers net = tflearn.input_data(shape=[None, 40, 80, 80, 3], name='InputLayer') net = tflearn.layers.conv.conv_3d(net, 32, filter_size=(3, 3, 3), activation='relu', name='Conv3D1') net = tflearn.max_pool_3d(net, kernel_size=(1, 2, 2), strides=(1, 2, 2), name='MaxPool3D1') net = tflearn.layers.conv.conv_3d(net, 32, filter_size=(3, 3, 3), activation='relu', name='Conv3D2') net = tflearn.max_pool_3d(net, kernel_size=(2, 2, 2), strides=(2, 2, 2), name='MaxPool3D2') net = tflearn.layers.conv.conv_3d(net, 64, filter_size=(3, 3, 3), activation='relu', name='Conv3D3') net = tflearn.max_pool_3d(net, kernel_size=(2, 2, 2), strides=(2, 2, 2), name='MaxPool3D3') net = tflearn.layers.conv.conv_3d(net, 128, filter_size=(2, 2, 2), activation='relu', name='Conv3D5') net = tflearn.max_pool_3d(net, kernel_size=(2, 2, 2), strides=(2, 2, 2), name='MaxPool3D4') #FC Layers net = tflearn.fully_connected(net, 1024, activation='relu', name='FC1') net = tflearn.dropout(net, 0.5) net = tflearn.fully_connected(net, self.n_classes, activation='softmax', name='FC3') net = tflearn.regression(net, optimizer='adam', loss='categorical_crossentropy', learning_rate=1e-5) return [net] I'll use this model to learn and classify video. For this i wrote an algorithm that extract 40 frames per video and generates a folder with subfolders representing each class, a new dataset, basically. My point is. Which is the best way to load these frames to this model? Should i use mini-batch method with 40 examples (frames) or in case of 3D CNN, the input layer takes 40 images at a time from the dataset and learn from it? I need to know how this model can learn from a set of 40 frames, once each class subfolder have 40 images per video, so, to detail, if i have 50 videos in a class, i have 50*40 frames in that folder. I've searched a lot to sol…
tagged with: tflearn
tagged with: python
type: Question
has title: Loading frames to 3D CNN
score: 0

http://stackoverflow.com/comment/87369988
type: QuestionComment
has text: It is about openvpn config files. They should have the ending .ovpn to be associated with the app, and doesn't have to be renamed manually by the user.
score: 0
comment on: http://stackoverflow.com/q/50088099
type: Comment

http://stackoverflow.com/q/50198750
has body: I have a list in python that might look something like this: list_example = [1,2,20,21,22] As you can see, all the numbers are close to their adjacent list items, except for the jump between 2 and 20. How would I get Python to notice this larger jump and store the list item's index?
downvote count: 3
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50198887
has answer: http://stackoverflow.com/a/50198832
has answer: http://stackoverflow.com/a/50198806
answer count: 4
tagged with: python-2.7
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/87414183
has title: Python test if list items are far apart
has answer: http://stackoverflow.com/a/50198796
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50129589
has comment: http://stackoverflow.com/comment/87279421
tagged with: regex
has answer: http://stackoverflow.com/a/50130506
possible better answer: http://stackoverflow.com/a/50130506
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/87277435
score: 3
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50129993
has title: regex to match age written in textual format
has comment: http://stackoverflow.com/comment/87277119
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87277302
has body: I am trying to extract the age of a person from a sentence; this is a bit simplified, but it's all for a research project. I know that in the sentence the age is always preceded by either a colon followed by 0 or more spaces, or a colon, spaces, a few words, and some spaces (example: "character: a lovely eighty year old grandma", I want a regex that will allow me to extract 'eighty' from one of the groups). I am using python's 're' library and my code hangs on this example (code and example below): regex_age_string = r'([:]*[ ]*)?((([a-z]*)([ -]*))+)([ -]+)(year)' regex_age_string = re.compile(regex_age_string, re.DOTALL) sentence = 'history: four year-old boy was really sad when he found out the toy was broken' age_extract_string = re.search(regex_age_string, sentence) print(age_extract_string.group()) print(age_extract_string.group(2)) However, the works when I shorten the sentence by cutting out a few of the tail words. I read up about regex searches hanging because of catastrophic backtracking but I am not sure how that applies here/how to fix it.
has comment: http://stackoverflow.com/comment/87277700
has answer: http://stackoverflow.com/a/50129993
has comment: http://stackoverflow.com/comment/87277086
has comment: http://stackoverflow.com/comment/87277256
tagged with: python

http://stackoverflow.com/comment/87448953
score: 0
comment on: http://stackoverflow.com/q/50216039
type: Comment
type: QuestionComment
has text: Diffing the output of `pip install -v pytaglib` might help see where the differences come in. Are you using different versions of pip, setuptools and wheel in the system vs. virualenv environments?

http://stackoverflow.com/q/50095511
has title: Django: model object can save value even in not-defined field?
score: 0
has comment: http://stackoverflow.com/comment/87207357
has comment: http://stackoverflow.com/comment/87207596
has comment: http://stackoverflow.com/comment/87207406
has comment: http://stackoverflow.com/comment/87210179
has comment: http://stackoverflow.com/comment/87207674
has comment: http://stackoverflow.com/comment/87210015
has comment: http://stackoverflow.com/comment/87207322
has comment: http://stackoverflow.com/comment/87210060
tagged with: django-models
has comment: http://stackoverflow.com/comment/87209011
type: Question
has body: I have a Symbol model: class Symbol(models.Model): market = models.CharField( max_length=20, null=True, blank=True, ) and generate some Symbol model data. What I was surprised at: &gt;&gt;&gt; s = Symbol.objects.first() &gt;&gt;&gt; s.i_dont_know = 1 &gt;&gt;&gt; s.save() It doesn't occur any error? Why does it not occur any error?
answer count: 2
has comment: http://stackoverflow.com/comment/87207291
has answer: http://stackoverflow.com/a/50095653
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50096527
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87207745

http://stackoverflow.com/comment/122767982
type: AnswerComment
score: 1
type: Comment
has text: Thank for the suggestion. If anyone have an error with `sudo python setup.py install`, please consider method at https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2.md#python-package-installation.
comment on: http://stackoverflow.com/a/55285649

http://stackoverflow.com/q/50137309
downvote count: 0
has body: I have a python module which contains a C++ extension as well a shared library on which the C++ extension depends. The shared library is picked up by setuptools as an extra_object on the extension. After running python setup.py bdist_wheel, the module wheel object gets properly generated has a directory structure as follows: +-pymodule.whl | +-pymodule | +-pymodule-version.dist-info | +-extension.so | +-shared_lib.so To install this wheel, in my python environment I call pip install pymodule.whl which copies the python sources as well as the .so files into the environment's site-packages directory. After installing the module, one can then attempt to import the module by calling import pymodule in a terminal for the environment. This triggers an exception to be thrown: ImportError: shared_lib.so: cannot open shared object file: No such file or directory This exception can be resolved by appending the appropriate site-packages directory to the LD_LIBRARY_PATH variable; however, it seems that this should work out of the box, especially considering that python is clearly able to locate extension.so. Is there a way to force python to locate this shared library without having to explicitly point LD_LIBRARY_PATH at the installation location(i.e. site-packages)? This question works around a similar problem by using package data and explicitly specifying an install location for the shared library. The issue I have with this approach is that the shared object is decoupled from the extension. In my case, the shared library and extension are both targets built by the same cmake build. I had previously attempted to use skbuild to build cmake based extentions; however, as per this issue, there is a similar issue in skbuild with including other libraries generated as part of the extension build.
type: UnansweredQuestion
tagged with: python-extensions
tagged with: python
score: 4
upvote count: 4
tagged with: c++
tagged with: setuptools
has title: Shared library distributed in python wheel not found
tagged with: shared-libraries
has comment: http://stackoverflow.com/comment/112549085
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87299744
has comment: http://stackoverflow.com/comment/87318002
linked to: http://stackoverflow.com/q/9795793
answer count: 0

http://stackoverflow.com/comment/87180262
type: QuestionComment
has text: The stack trace didn't seem to make it into the edit.
comment on: http://stackoverflow.com/q/50081999
score: 0
type: Comment

http://stackoverflow.com/q/50167708
accepted answer: http://stackoverflow.com/a/50167782
has comment: http://stackoverflow.com/comment/87353031
has title: Can anyone help me with the regex for the following example?
tagged with: python
has comment: http://stackoverflow.com/comment/87353005
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87353184
has comment: http://stackoverflow.com/comment/87353067
score: 1
has answer: http://stackoverflow.com/a/50167782
has comment: http://stackoverflow.com/comment/87353032
downvote count: 1
has comment: http://stackoverflow.com/comment/87353099
favorite count: 0
type: Question
tagged with: split
answer count: 2
has comment: http://stackoverflow.com/comment/87353050
upvote count: 2
has answer: http://stackoverflow.com/a/50167876
possible better answer: http://stackoverflow.com/a/50167876
has body: Sample Data: "PlayerId":169193,"PlayerName":"Alexandre Lacazette","PlaysOnHomeTeam":true,"OptaId":"p59966","GoalsConcededInBox":1,"ShotsInsideBox":8,"ShotsWoodwork":1,"TotalPasses":31,"PassSuccess":23,"KeyPasses":5,"DribblesAttempted":3,"DribblesWon":2,"AerialsWon":5,"AerialsLost":2,"TacklesSuccess":3,"TacklesAttempted":3 what i want is a list with data which is inside the quotes i.e PlayerId PlayerName PlaysOnHomeTeam OptaId .. .. .. Can anyone tell me the regex to achieve this
has comment: http://stackoverflow.com/comment/87353047

http://stackoverflow.com/q/50203379
has comment: http://stackoverflow.com/comment/87424005
answer count: 1
has comment: http://stackoverflow.com/comment/87423979
tagged with: virtualenv
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/66240707
linked to: http://stackoverflow.com/q/41573587
has comment: http://stackoverflow.com/comment/87424182
has comment: http://stackoverflow.com/comment/87423872
has comment: http://stackoverflow.com/comment/87423773
has comment: http://stackoverflow.com/comment/87424198
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87426872
tagged with: python
tagged with: cryptography
tagged with: cffi
has comment: http://stackoverflow.com/comment/87423769
has comment: http://stackoverflow.com/comment/87427755
has comment: http://stackoverflow.com/comment/87424112
has comment: http://stackoverflow.com/comment/87427449
has body: Steps I've tried so far: create the virtual environment. python3.4 -m venv [venv_name_here] enter the virtual environment. cd [venv_name_here] activate the virtual environment. source bin/activate install setuptools. pip install --upgrade setuptools install pyparser. pip install --upgrade pyparser Output: Downloading/unpacking pyparser Downloading pyparser-1.0.tar.gz Running setup.py (path:[path-to-venv]/build/pyparser/setup.py) egg_info for package pyparser Downloading/unpacking parse==1.6.5 (from pyparser) Downloading parse-1.6.5.tar.gz Running setup.py (path:[path-to-venv]/build/parse/setup.py) egg_info for package parse Installing collected packages: pyparser, parse Running setup.py install for pyparser Could not find .egg-info directory in install record for pyparser Running setup.py install for parse Could not find .egg-info directory in install record for parse==1.6.5 (from pyparser) Successfully installed pyparser parse Cleaning up.. install cffi. pip install --upgrade cffi Output: Downloading/unpacking cffi Downloading cffi-1.11.5.tar.gz (438kB): 438kB downloaded Running setup.py (path:[path-to-venv]/build/cffi/setup.py) egg_info for package cffi Downloading/unpacking pycparser (from cffi) Downloading pycparser-2.18.tar.gz (245kB): 245kB downloaded Running setup.py (path:[path-to-venv]/build/pycparser/setup.py) egg_info for package pycparser warning: no previously-included files matching 'yacctab.*' found under directory 'tests' warning: no previously-included files matching 'lextab.*' found under directory 'tests' warning: no previously-included files matching 'yacctab.*' found under directory 'examples' warning: no previously-included files matching 'lextab.*' found under directory 'examples' Installing collected packages: cffi, pycparser Running setup.py install for cffi building '_cffi_backend' extension gcc -pthread -Wno-unused-result -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/local/lib/libffi-3…
has comment: http://stackoverflow.com/comment/87423838
has comment: http://stackoverflow.com/comment/87425598
has comment: http://stackoverflow.com/comment/87424662
downvote count: 0
has comment: http://stackoverflow.com/comment/87423763
upvote count: 1
has comment: http://stackoverflow.com/comment/87425340
score: 1
has title: How to install cryptography in Python virtual environment? [ undefined symbol: __syscall_error]

http://stackoverflow.com/comment/87387486
comment on: http://stackoverflow.com/a/50182965
has text: @Setti did you do really try `savemat(your_path, dict(key=key_pressed, window=window))` ?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50154388
downvote count: 0
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50152377
has body: As the documentation for numpy.bincount states each bin gives the number of occurrences of its index value in x (https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.bincount.html). Therefore, since in the expression used by sklearn bincounts is in the denominator, classes that have high frequencies receive low weights and classes with low frequencies receive high weights. Let us see this in action: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns df = pd.DataFrame({'classes': [0, 0, 1, 1, 2, 0, 1, 1, 0, 2, 3]}) n_samples = df.shape[0] classes = df['classes'].unique() bins = np.bincount(df['classes']) n_classes = bins.shape[0] weights = n_samples/(n_classes*bins) sns.barplot(classes, weights) plt.xlabel('class label') plt.ylabel('weight') plt.show()

http://stackoverflow.com/q/50152923
has body: I have this code def run(self): while True: c, a = self.sock.accept() print(c) name = c.recv(1024) people = "" self.name_list.append(str(name, 'utf-8')) num_g = len(self.name_list) c.send(bytes(str(num_g), 'utf-8')) print((str(num_g))) data = str(c.recv(1024), 'utf-8') print(data) if str(data) == "ok": for name in self.name_list: print(name) c.send(bytes(name, 'utf-8')) print(len(self.name_list)) print(strftime("%Y-%m-%d %H:%M:%S", gmtime())+" "+str(name, 'utf-8')+ " is connected") and i get this error File "./server.py", line 51, in run print(strftime("%Y-%m-%d %H:%M:%S", gmtime())+" "+str(name, 'utf-8')+ " is connected") TypeError: decoding str is not supported i don't understand why i get this error. when i receive the bytes from connection, name = c.recv(1024) the name is in bytes, that's why i tried to make it string when i print that line
tagged with: byte
accepted answer: http://stackoverflow.com/a/50153077
tagged with: python
type: Question
upvote count: 2
score: 2
tagged with: decoding
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50153077
has title: TypeError: decoding str is not supported (converting bytes into str)
has comment: http://stackoverflow.com/comment/87323582
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/87172629
comment on: http://stackoverflow.com/q/50077958
type: QuestionComment
score: 0
has text: This is not possible. Usually this is just jupyter making a call out to open the default browser, but as there is no browser *in* the container (only on the host) then there is nothing it can do. You will have to go to the url manually.
type: Comment

http://stackoverflow.com/q/50095327
possible better answer: http://stackoverflow.com/a/50095390
favorite count: 0
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87206921
answer count: 3
has comment: http://stackoverflow.com/comment/87206783
has comment: http://stackoverflow.com/comment/87207083
has title: try block in python
has comment: http://stackoverflow.com/comment/87207563
type: Question
tagged with: try-catch
has answer: http://stackoverflow.com/a/50095390
tagged with: python-3.x
has body: am I using the try block correctly? try: def add(num1, num2): return(float(num1) + float(num2)) except ValueError: return(None) else: return(add(num1, num2)) I am using treehouse and am getting the error that task 1 is no longer passing meaning something has gone wrong with my def add(num1, num2) is my try in the right spot? it says "Add a try block before where you turn your arguments into floats."
accepted answer: http://stackoverflow.com/a/50095350
has answer: http://stackoverflow.com/a/50095350
has answer: http://stackoverflow.com/a/50095428
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/a/50123436
has body: You cannot SELECT with executemany(). DML stands for Data Modification Language, and a SELECT is not regarded as a modfication. What you'll have to do is probably loop over the data: for d in donors: cursor.execute(""" SELECT * FROM Donors WHERE firstname=:First AND lastname=:Last """, d.donor) print(cur.fetchall()) Update: figured out it is, see update below! Edit that I can't figure out yet to make it copy-pastable: You could also use the IN(...) operation, which should be something along the lines of: cur.execute(""" SELECT * FROM Donors WHERE firstname IN ({0})""" .format(', '.join(x.donor for x in donors))) Update for IN clauses: This is a worked example demonstrating how to use placeholders to dynamically construct a query with bound parameters, sparked by @olepinto's comment: import sqlite3 sqlite3.enable_callback_tracebacks(True) con = sqlite3.connect(":memory:") con.set_trace_callback(print) cur = con.execute("CREATE TABLE Donors(firstname, lastname, dob)") data = ( {"First": "Jane", "Last": "Doe", 'Dob': 1957}, {"First": "John", "Last": "Doe", 'Dob': 1972}, {"First": "John", "Last": "Bar", 'Dob': 1980}, {"First": "Jane", "Last": "Foo", 'Dob': 1943}, ) cur.executemany("INSERT INTO Donors VALUES(:First, :Last, :Dob)", data) print("--- setup done ---", end="\n\n") def format_with_in_clause(query, in_vals): # Interpolate the required number of placeholders return query + " IN ({0})".format(",".join(["?"] * len(in_vals))) base_query = "SELECT * FROM Donors WHERE lastname" # The happy path params = ["Bar", "Foo"] print("Happy path, all good:") cur.execute(format_with_in_clause(base_query, params), (*params,)) print(cur.fetchall(), end="\n\n") # DANGER: plain string interpolation is a pool of sharks :( # Assume this is some user-input that is simply parsed into a list by upstream code params = ["'') OR TRUE; --"] print("Oh dear, SQL injection at play:") cur.execute("SELECT * FROM Donors WHERE lastname IN (%s)" % params[0]) print(cur.fetchall(), end="\n\n") # But …
type: Answer
has comment: http://stackoverflow.com/comment/135035219
score: 8
answers question: http://stackoverflow.com/q/50123318
has comment: http://stackoverflow.com/comment/135019560
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50123318
upvote count: 8

http://stackoverflow.com/comment/87204367
has text: @Swan Do you mean web app container? Depends on which you are using. Some communicates through stdio `import sys; sys.stdin.readline()`. It should be configurable within your container.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50093284
type: Comment

http://stackoverflow.com/q/50138622
has answer: http://stackoverflow.com/a/50143620
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87303876
tagged with: pandas
upvote count: 2
tagged with: pivot
tagged with: pivot-table
has comment: http://stackoverflow.com/comment/87302819
has body: My objective in the following dataframe is to count how many cars were sold in a specific location for a given month. You will note that the pivot result are correct BUT the columns (dates) are inconsistent. The reason why it's inconsistent is because I'm aggregating the month as a string (if a car was sold on 9-October and 10-October then I count 2 for October). Question: how should I design the applied get_date in such was that the pivot table would sort the dates correctly? Or, is there a better way to approach this problem to get the desired result. Table pivot table result: The dataframe: df = pd.DataFrame({"LOCATION":["USA","USA","USA","USA","JAPAN","JAPAN"],"CAR":["BMW","BMW","TOYOTA","FORD","BMW","FORD"],"SALE_DATE":pd.to_datetime(["2017-10-09","2017-09-28","2017-10-09","2017-10-12","2017-09-30","2017-09-30"])}) the apply date_str_date (to aggregate by month): def get_date_str(row): doi = row["SALE_DATE"] doi_str = "".join(doi.strftime('%B-%y')) return doi_str the pivot: df.pivot_table(values="CAR", index="LOCATION", columns='SALE_DATE', aggfunc='count')
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87303707
linked to: http://stackoverflow.com/q/25146121
has comment: http://stackoverflow.com/comment/87305422
favorite count: 0
linked to: http://stackoverflow.com/q/37625334
type: Question
has comment: http://stackoverflow.com/comment/87302778
has comment: http://stackoverflow.com/comment/87304066
tagged with: python
accepted answer: http://stackoverflow.com/a/50143620
has title: python pivot table - columns are dates and should be sorted correctly

http://stackoverflow.com/comment/87315155
type: Comment
score: 1
type: QuestionComment
has text: `results= Acetylated Lanolin 5 ` is not even valid code.
comment on: http://stackoverflow.com/q/50147236

http://stackoverflow.com/comment/87419224
comment on: http://stackoverflow.com/a/50187089
has text: Thank you . The new modification for the code works , and i will do some modification again , so all punctuation , except . and - will be not include in TF-IDF calculation
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/87189522
type: Comment
comment on: http://stackoverflow.com/q/50086867
type: QuestionComment
has text: I assume `R` is race. But what is Horse? Couldn't see the why # 1 and 2 would be returned for `R=1` and #1 for `R=2`
score: 1

http://stackoverflow.com/comment/87646804
comment on: http://stackoverflow.com/q/50169850
has text: another approach: rather than trying to recognize the text in the picture, can't you just try to detect if a sample, hardcoded image is present inside the screenshot?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/50226334
tags question: http://stackoverflow.com/q/50114950
tags question: http://stackoverflow.com/q/50206539
tags question: http://stackoverflow.com/q/50200746
tags question: http://stackoverflow.com/q/50096660
tags question: http://stackoverflow.com/q/50139596
tags question: http://stackoverflow.com/q/50205818
tags question: http://stackoverflow.com/q/50204585
tags question: http://stackoverflow.com/q/50180707
tags question: http://stackoverflow.com/q/50222720
tags question: http://stackoverflow.com/q/50221351
tags question: http://stackoverflow.com/q/50196887
tags question: http://stackoverflow.com/q/50151671
tags question: http://stackoverflow.com/q/50081999
tags question: http://stackoverflow.com/q/50105268
tags question: http://stackoverflow.com/q/50109413
tags question: http://stackoverflow.com/q/50159567
tags question: http://stackoverflow.com/q/50122497
tags question: http://stackoverflow.com/q/50092608
tag name: json
tags question: http://stackoverflow.com/q/50162137
tags question: http://stackoverflow.com/q/50217615
tags question: http://stackoverflow.com/q/50116344
tags question: http://stackoverflow.com/q/50100800
tags question: http://stackoverflow.com/q/50081086
tags question: http://stackoverflow.com/q/50092998
tags question: http://stackoverflow.com/q/50092726
tags question: http://stackoverflow.com/q/50166476
tags question: http://stackoverflow.com/q/50167943
tags question: http://stackoverflow.com/q/50224640
tags question: http://stackoverflow.com/q/50141544
tags question: http://stackoverflow.com/q/50199828
tags question: http://stackoverflow.com/q/50206464
tags question: http://stackoverflow.com/q/50195834
tags question: http://stackoverflow.com/q/50183789
tags question: http://stackoverflow.com/q/50223325
tags question: http://stackoverflow.com/q/50199393
tags question: http://stackoverflow.com/q/50123833
tags question: http://stackoverflow.com/q/50144214
tags question: http://stackoverflow.com/q/50227486
tags question: http://stackoverflow.com/q/50077971
tags question: http://stackoverflow.com/q/50172514
tags question: http://stackoverflow.com/q/50108437
tags question: http://stackoverflow.com/q/50113163
tags question: http://stackoverflow.com/q/50189683
tags question: http://stackoverflow.com/q/50197292
tags question: http://stackoverflow.com/q/50141389
tags question: http://stackoverflow.com/q/50216362
tags question: http://stackoverflow.com/q/50137947
tags question: http://stackoverflow.com/q/50075650
tags question: http://stackoverflow.com/q/50176471
tags question: http://stackoverflow.com/q/50091231
tags question: http://stackoverflow.com/q/50167809
type: Tag
tags question: http://stackoverflow.com/q/50188251
tags question: http://stackoverflow.com/q/50207008
tags question: http://stackoverflow.com/q/50085222
tags question: http://stackoverflow.com/q/50162098
tags question: http://stackoverflow.com/q/50186839
tags question: http://stackoverflow.com/q/50079650
tags question: http://stackoverflow.com/q/50160675
tags question: http://stackoverflow.com/q/50100882
tags question: http://stackoverflow.com/q/50204697
tags question: http://stackoverflow.com/q/50105309
tags question: http://stackoverflow.com/q/50075452
tags question: http://stackoverflow.com/q/50199917
tags question: http://stackoverflow.com/q/50119663
tags question: http://stackoverflow.com/q/50154948
tags question: http://stackoverflow.com/q/50110646
tags question: http://stackoverflow.com/q/50106749
tags question: http://stackoverflow.com/q/50166308
tags question: http://stackoverflow.com/q/50177939
tags question: http://stackoverflow.com/q/50214506
tags question: http://stackoverflow.com/q/50082878
tags question: http://stackoverflow.com/q/50083912
tags question: http://stackoverflow.com/q/50219084
tags question: http://stackoverflow.com/q/50101186
tags question: http://stackoverflow.com/q/50219200

http://stackoverflow.com/a/50226992
upvote count: 1
answers question: http://stackoverflow.com/q/50226886
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50226886
has body: You cannot easily do what you want. Tkinter has no way to render html. You would have to parse the HTML and CSS and Javascript yourself, and translate the information for display on a canvas or text widget.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87305054
has text: If you're on that scale and have loads of users then perhaps it does make sense for each user to have their own table but, potentially, a) something could be very wrong with your approach or b) you need a different technology to scale to this.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50143279

http://stackoverflow.com/q/50149228
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has body: Having a few issues with returning documents to a dataframe from a MongoDb collection. The code below establishes a connection to mongodb: from pymongo import MongoClient # Connect to the Mongo client. MongoClient is the connection to the MongoDB instance on port 27017 on host hkgdlvasfj001. client = MongoClient('hkgdlvasfj001', 27017) # Access the bb i.e. access a collection in PyMongo #display(client.database_names()) # all the db's in the db i.e. ['admin', 'config', 'gtm', 'local'] # Assign gtm database db = client.gtm I can succesfully return a single document from the rfq collection: #display(db.collection_names()) # all collections in the d b i.e ['rfqs', 'trades'] # Search for the documents you want display(db.rfqs.find_one({'Data.State': "Done"})) Output: {'Data': {'Action': 'DealerAcceptOrder', 'AllQ': '3.09', 'AutoNegDealerMidValue': '3.09', 'AutoNegDealerSpread': '0', 'AutoNegDealerValue': '3.0846', 'ClearingChannel': '', 'ClearingCode': 'UNKNOWN', 'ClearingHouse': 'UNKNOWN', But when I expand the criteria I can't get any documents from my dataframe df = db.rfqs.find({'Data.State' : "Done",'Data.Ticker': "ACGB 3 3/4 04/21/37"}) display(df) Returns &lt;pymongo.cursor.Cursor at 0x84dc3c8&gt; Is there something different I need to do when assigning documents to a datframe?
favorite count: 0
has title: collection.find not returning any documents to dataframe
type: Question
accepted answer: http://stackoverflow.com/a/50149344
has answer: http://stackoverflow.com/a/50149344
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pymongo

http://stackoverflow.com/comment/87351143
has text: Post the answer separately and will accept it in 9 hours.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50135334

http://stackoverflow.com/comment/87342351
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50162043
score: 0
has text: Infact, the mistake was that in the very first line there was df['Region'] instead of df['Reg_cat']. Thanks so much

http://stackoverflow.com/comment/87213624
comment on: http://stackoverflow.com/a/50096937
type: AnswerComment
has text: can't upvote , so I'm mentioning for whoever reads it , your solution works ! (and thank you) , I can now define a true copy function.
score: 0
type: Comment

http://stackoverflow.com/comment/87262533
has text: I did the print and it returns: "LS8 " "LS7" it seems that find file has a tab after, any idea how i can remove this whitespace?
score: 0
comment on: http://stackoverflow.com/q/50122266
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50155780
favorite count: 0
has answer: http://stackoverflow.com/a/50169214
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/53400205
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50156333
tagged with: python
has title: WebDriverException: Message: unable to set cookie while switching cookies from Session to Selenium's Chrome on Instagram
has body: I'm trying to make a login request to Instagram through an HTTP request (Thanks to Python's "requests" module) and then port the result to Selenium's chromedriver, in order to have the user already logged in. I'm using the "requestium" module to try that. As I successfully manage to login inside the website through Session, it seems that it blocks me in switching to the driver in order to have the already logged in page. This is the error that the console prints me DevTools listening on ws://127.0.0.1:12779/devtools/browser/73b726a1-520f-4d08-8982-a9ada65ead2b Traceback (most recent call last): File "requestiumTest.py", line 124, in <module> s.transfer_session_cookies_to_driver() # You can maintain the session if needed File "C:\Users\gforcell\AppData\Local\Continuum\anaconda3\lib\site-packages\requestium\requestium.py", line 114, in transfer_session_cookies_to_driver 'expiry': c.expires, 'domain': c.domain}) File "C:\Users\gforcell\AppData\Local\Continuum\anaconda3\lib\site-packages\requestium\requestium.py", line 235, in ensure_add_cookie self.add_cookie(cookie) File "C:\Users\gforcell\AppData\Local\Continuum\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 872, in add_cookie self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict}) File "C:\Users\gforcell\AppData\Local\Continuum\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "C:\Users\gforcell\AppData\Local\Continuum\anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unable to set cookie (Session info: chrome=66.0.3359.139) (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.15063 x86_64) While this is the code for reproducing it from requestium import Session, Keys from selenium import webd…
score: 2
tagged with: selenium-chromedriver
tagged with: instagram
answer count: 3
tagged with: cookies
downvote count: 0
tagged with: selenium

http://stackoverflow.com/q/50180298
has title: How to save integer alongside of a np.array
answer count: 2
has comment: http://stackoverflow.com/comment/87387498
possible better answer: http://stackoverflow.com/a/50182965
downvote count: 2
has comment: http://stackoverflow.com/comment/87381560
upvote count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50182965
has comment: http://stackoverflow.com/comment/87377834
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87387549
accepted answer: http://stackoverflow.com/a/50181125
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50181125
has body: I am doing a ConvNet and need to save one image alongside an integer (1 or 0), that indicates if an action was taken or not. How can I do it? I tried this: key_pressed = np.array(key_check(self.key)) # key_check() returns 1 or 0 window = np.array(window) # window is opened with cv2 print(window.shape, key_pressed.shape) # (474, 31) (1,) print(np.concatenate((window, key_pressed))) ^^ ValueError: all the input arrays must have same number of dimensions Is doing what I want even possible with numpy, seeing that the arrays are of different sizes? Any ideas on how to save this data?
type: Question
tagged with: numpy

http://stackoverflow.com/q/50229420
tagged with: caesar-cipher
upvote count: 1
has comment: http://stackoverflow.com/comment/87476175
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87476034
has comment: http://stackoverflow.com/comment/87476305
type: UnansweredQuestion
downvote count: 9
has answer: http://stackoverflow.com/a/50230061
tagged with: python
score: -8
has comment: http://stackoverflow.com/comment/87476091
has body: def encryption(message,skey): encryptedmessage='' for character in message: if character.isalpha()==True: if character==character.lower(): newchar=ord(character)-97 newchar=(newchar+skey)%26 encryptedmessage+= chr(newchar +97) else: newchar=ord(character)-65 newchar=(newchar+skey)%26 encryptedmessage+= chr(newchar +65) else: encryptedmessage+= character return('Your Message is: {:s}'.format(encryptedmessage)) def decryption(message,skey): decryptedmessage='' for character in message: if character.isalpha()==True: if character==character.lower(): newchar=ord(character)-97 newchar=(newchar-skey)%26 decryptedmessage+= chr(newchar +97) else: newchar=ord(character)-65 newchar=(newchar-skey)%26 decryptedmessage+= chr(newchar +65) else: decryptedmessage+= character return('Your Message is: {:s}'.format(decryptedmessage)) while True: u=str(input("To encrypt a messege enter 'E' or 'e',To dycrypt a message enter 'D' or 'd',To stop the program enter'quit': ")) if u=='': print("") elif (u in 'Ee'): Message1=str(input('Please enter your message: ')) key=int(input('Please enter the shifting key: ')) print(encryption(Message1,key)) elif (u in 'Dd'): Message1=str(input('Please enter your message: ')) key=int(input('Please enter the shifting key: ')) print(decryption(Message1,key)) elif u=='quit': print('Program ended.') break;
has title: In line 7: What will happen if i used another number instead of 26 like %28 and why it has to be %26?
answer count: 2
has answer: http://stackoverflow.com/a/50229737

http://stackoverflow.com/q/50123009
accepted answer: http://stackoverflow.com/a/50123220
has comment: http://stackoverflow.com/comment/87264901
answer count: 1
has body: I wrote the following sample code, and I am a bit curious about how will np.frompyfunc work in this case. import numpy as np def test(x): if x&gt;10000: return test(x) else: return x+1 def f(x, y): if y &gt;5: x=test(x) return x/y if x&lt;5: y+=1 return x*y return x*y*2 vf = np.frompyfunc(f,2,1) print(vf(np.arange(10),np.arange(10,0,-1))) I guess it will somehow "flatten" the IF statement in the function and produce vectorized code, but I couldn't find the corresponding code in the numpy code repo.
has title: How does numpy frompyfunc generate ufunc form a python function containing if statements?
type: Question
has comment: http://stackoverflow.com/comment/87267437
tagged with: python
has comment: http://stackoverflow.com/comment/87264420
tagged with: numpy
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50123220

http://stackoverflow.com/a/50150241
has body: A dictionary whose key is the sorted version of the word: word_list = ['yek','lion','eky','ekky','kkey','opt'] from collections import defaultdict word_index = defaultdict(set) for word in word_list: idx = tuple(sorted(word)) word_index[idx].add(word) # word_index = { # ('e', 'k', 'y'): {'yek', 'eky'}, # ('i', 'l', 'n', 'o'): {'lion'}, # ('e', 'k', 'k', 'y'): {'kkey', 'ekky'}, # ('o', 'p', 't'): {'opt'} # } Then for querying you would do: def find_a4(word_index, word): idx = tuple(sorted(word)) return len(word_index[idx]) Or if you need to return the actual words, change it to return word_index[idx]. Efficiency: querying runs in average in O(1) time.
has comment: http://stackoverflow.com/comment/87318522
score: 5
answers question: http://stackoverflow.com/q/50150148
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87318246
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50150148

http://stackoverflow.com/q/50172012
tagged with: tkinter
answer count: 3
accepted answer: http://stackoverflow.com/a/50173013
has answer: http://stackoverflow.com/a/50173013
has body: Hi i'm new to python gui's and have been stumped on this problem for hours. I need to call up a name in an entry box that's inside a def, with another def and keep getting the error: line 15, in callback name = (username.get()) AttributeError: 'str' object has no attribute 'get' Im using the code: from tkinter import * username = str(); e = object(); def getname(): global username e = Entry(root, textvariable=username) e.pack() e.focus_set() b = Button(root, text = "OK", width = 10, command = callback) b.pack() def callback(): name = (username.get()) print(name) root = Tk() getname() mainloop() if i do e.get() it comes up with same error except 'object' instead of 'string' Any help is appreciated, thanks
has comment: http://stackoverflow.com/comment/87361163
type: Question
has answer: http://stackoverflow.com/a/50172158
has title: Need help calling up entry boxes inside defs
has answer: http://stackoverflow.com/a/50172538
tagged with: python
possible better answer: http://stackoverflow.com/a/50172538
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50175074
has comment: http://stackoverflow.com/comment/87367210
upvote count: 1
has body: In your case x_variable and y_variable are numpy arrays as you are using them to plot on matplotlib. So you can use the following function as you requested to extract the variable name and plot it as a label import matplotlib.pyplot as plt import numpy as np def Return_variable_name_as_string(myVar): return [ k for k,v in globals().iteritems() if np.array_equal(v,myVar)][0] x_variable=np.linspace(1,5) y_variable=x_variable**2 plt.plot(x_variable,y_variable) plt.xlabel(Return_variable_name_as_string(x_variable)) plt.ylabel(Return_variable_name_as_string(y_variable)) You may have to change globals with locals, but that will depend on how you use it on your case.
has comment: http://stackoverflow.com/comment/87367862
type: Answer
answers question: http://stackoverflow.com/q/50174336
has comment: http://stackoverflow.com/comment/87367995
score: 1
downvote count: 0

http://stackoverflow.com/q/50156520
has comment: http://stackoverflow.com/comment/87364716
tagged with: sql
downvote count: 0
has answer: http://stackoverflow.com/a/50435657
upvote count: 10
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87369079
has title: Cannot connect to a local mysql db with sqlalchemy on windows machine
has answer: http://stackoverflow.com/a/51216936
type: UnansweredQuestion
has body: I'm trying to connect to a local mysql DB on my windows machine using sqlalchemy. It works using pymysql, but not with sqlalchemy. Code sqlalchemy: engine = create_engine('mysql+mysqldb://root:mypass@localhost/classicmodels') engine.connect() Gives error: OperationalError: (_mysql_exceptions.OperationalError) (1193, "Unknown system variable 'tx_isolation'") Working code, using pymysql: connection = pymysql.connect(host='localhost', user='root', password = 'mypass', db = 'classicmodels') cursor = connection.cursor() cursor.execute('select * from customers') mydata = cursor.fetchall() mydata = pd.DataFrame(list(mydata)) mydata.head(5)
score: 10
tagged with: pymysql
tagged with: python
has comment: http://stackoverflow.com/comment/87332564
answer count: 2
tagged with: database-connection

http://stackoverflow.com/a/50169867
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87359593
has comment: http://stackoverflow.com/comment/87359472
type: Answer
accepted answer of: http://stackoverflow.com/q/50153993
answers question: http://stackoverflow.com/q/50153993
has body: The reason behind your issues You have 18 lists which all are empty, and that is why you do not see any effect on the database after insertion. I am unable to find where I went wrong. Your problems emanate from the misunderstanding on how to use findall(): Element.findall() finds only elements with a tag which are direct children of the current element. So let me take ticker as an example: ticker = dom.findall('TICKER') What is dom? It simply points to the root element of your XML tree which is collection, in your case: &gt;&gt;&gt; dom &lt;Element 'collection' at 0x7f5e24a42e10&gt; Now ask yourself: which are the direct elements of collection? You see there are 6 INFO direct children elements and absolutely no TICKER element. &gt;&gt;&gt; infos = dom.findall('INFO') &gt;&gt;&gt; len(infos) 6 So when you run ticker = dom.findall('TICKER'), you are simply looking for direct children of collection which are called TICKER, and since there is no one, your list ticker is empty. &gt;&gt;&gt; ticker = dom.findall('TICKER') &gt;&gt;&gt; ticker [] So later in your code, when you run this: ticker_list = [t.text for t in ticker] you are simply looping over an empty list, and you got nothing from nothing, I mean: &gt;&gt;&gt; ticker_list = [t.text for t in tickers] &gt;&gt;&gt; ticker_list [] Now apply this reasoning to the 8 remaining first lists with their corresponding 8 lists in the second part of your code. How to fix the problems? How to solve your problem then? Well, if you understood what I explained above, you are already half way to fix your issues. Let us do it: After loading your XML file into dom, initialize the 9 empty lists you need: &gt;&gt;&gt; ticker_list = [] &gt;&gt;&gt; name_list = [] &gt;&gt;&gt; add_list = [] &gt;&gt;&gt; phn_list = [] &gt;&gt;&gt; site_list = [] &gt;&gt;&gt; sec_list = [] &gt;&gt;&gt; ind_list = [] &gt;&gt;&gt; emp_list = [] &gt;&gt;&gt; sum_list = [] Then loop over your data after taking in consideration its hierarchy and how findall() …
downvote count: 0
score: 1

http://stackoverflow.com/a/50091675
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/87200892
upvote count: 1
answers question: http://stackoverflow.com/q/50091548
accepted answer of: http://stackoverflow.com/q/50091548
has comment: http://stackoverflow.com/comment/93166979
has body: The modulus operator should be fine: &gt;&gt;&gt; int(uuid.uuid4()) % 3 2L &gt;&gt;&gt; int(uuid.uuid4()) % 3 1L &gt;&gt;&gt; int(uuid.uuid4()) % 3 2L &gt;&gt;&gt; int(uuid.uuid4()) % 3 1L &gt;&gt;&gt; int(uuid.uuid4()) % 3 1L &gt;&gt;&gt; int(uuid.uuid4()) % 3 0L &gt;&gt;&gt; int(uuid.uuid4()) % 3 1L But for the future-proofing your design I'd suggest you to actually code at least 16 shards, for example with 16 different hostnames pointing to 3 different backend hosts: myhostname00 IN CNAME backend01 myhostname01 IN CNAME backend01 myhostname02 IN CNAME backend01 myhostname03 IN CNAME backend01 myhostname04 IN CNAME backend01 myhostname05 IN CNAME backend01 myhostname06 IN CNAME backend02 myhostname07 IN CNAME backend02 myhostname08 IN CNAME backend02 myhostname09 IN CNAME backend02 myhostname10 IN CNAME backend02 myhostname11 IN CNAME backend03 myhostname12 IN CNAME backend03 myhostname13 IN CNAME backend03 myhostname14 IN CNAME backend03 myhostname15 IN CNAME backend03 This way you'd be able to create more backend servers in the future and move users there without changing you code. You can even have unevenly distributed users if you'd ever have backend servers that are more of less performant than others.
downvote count: 0
score: 1

http://stackoverflow.com/q/50093294
has body: I want to automatically resize the Q-label text size according to window size. In python qt-designer. For example, if window size is max, Q-label text size is big and if window size is min, Q-label text size is small How can I solve?
score: 0
tagged with: qt-designer
has comment: http://stackoverflow.com/comment/87222380
tagged with: python
has comment: http://stackoverflow.com/comment/87202777
favorite count: 0
type: Question
has title: How automatically resize the text size according to window size in pyqt qtdesigner?
answer count: 0
tagged with: pyqt
type: UnansweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87293425
comment on: http://stackoverflow.com/q/50136944
has text: Yes if i use like: `response = bl.query('172.18.164.1') ` I get a json where one of the values is threat score
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87188326
type: Comment
has text: thank you sooo much @Rabbid76. It's working now!!!
type: AnswerComment
comment on: http://stackoverflow.com/a/50084943
score: 0

http://stackoverflow.com/comment/87303207
comment on: http://stackoverflow.com/q/50142275
score: 0
has text: My main goal here is to find the errors in the logs of a application in all 12 servers. If there are no error than my script should pass if not it should fail
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50160791
has comment: http://stackoverflow.com/comment/87347439
tagged with: virtualenv
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87347563
has comment: http://stackoverflow.com/comment/87347542
has body: When running a flask app, Apache2's error.log shows that the flask_bootstrap module cannot be found: [wsgi:warn] mod_wsgi: Compiled for Python/2.7.11. [wsgi:warn] mod_wsgi: Runtime using Python/2.7.12. [mpm_event:notice] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations [core:notice] AH00094: Command line: '/usr/sbin/apache2' [wsgi:error] mod_wsgi (pid=18587): Target WSGI script '/var/www/myapp/myapp.wsgi' cannot be loaded as Python module. [wsgi:error] mod_wsgi (pid=18587): Exception occurred processing WSGI script '/var/www/myapp/myapp.wsgi'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/var/www/myapp/myapp.wsgi", line 7, in &lt;module&gt; [wsgi:error] from myapp import app as application [wsgi:error] File "/var/www/myapp/myapp/__init__.py", line 2, in &lt;module&gt; [wsgi:error] from flask_bootstrap import Bootstrap [wsgi:error] ImportError: No module named flask_bootstrap I have configured the venv as per myapp.conf &lt;VirtualHost *:80&gt; ServerName yourdomain.com ServerAdmin youemail@email.com WSGIProcessGroup myapp WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/myapp/myapp.wsgi WSGIDaemonProcess myapp python-home=/var/www/myapp/myapp/venv &lt;Directory /var/www/myapp/myapp/&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; The module is available both system wide and in the venv: root@host:/var/www/myapp# python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from flask_bootstrap import Bootstrap &gt;&gt;&gt; Bootstrap &lt;class 'flask_bootstrap.Bootstrap'&gt; And... root@host:/var/www/myapp# source myapp/venv/bin/activate (venv) root@host:/var/www/myapp# python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Typ…
tagged with: python
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/50164805
has comment: http://stackoverflow.com/comment/87347096
has comment: http://stackoverflow.com/comment/87346185
answer count: 2
tagged with: mod-wsgi
has title: Why does `flask_bootstrap` fail to import?
has answer: http://stackoverflow.com/a/50164805
score: 0
accepted answer: http://stackoverflow.com/a/50188100
has comment: http://stackoverflow.com/comment/87347519
has comment: http://stackoverflow.com/comment/87346234
tagged with: apache
has answer: http://stackoverflow.com/a/50188100

http://stackoverflow.com/comment/114461661
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/64736819
type: Comment
has text: Code should not be added as image, please edit the answer and add the code in text form formatted as code.

http://stackoverflow.com/comment/87419395
type: Comment
has text: I've upvoted but it wont show as i'm currently still in the first 15 days of my account being created. Will do pal, respect.
type: AnswerComment
comment on: http://stackoverflow.com/a/50120498
score: 0

http://stackoverflow.com/comment/87193844
type: QuestionComment
has text: what have you tried? Also, how can a hexadecimal string contain `|`??
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50088897

http://stackoverflow.com/a/50124625
has body: RabbitMQ actually does support the scenario as-described out of the box, via the Maximum Queue Length feature. From the documentation: The maximum length of a queue can be limited to a set number of messages... In all cases the number of ready messages is used; unacknowledged messages do not count towards the limit. The default behaviour for RabbitMQ when a maximum queue length or size is set and the maximum is reached is to drop or dead-letter messages from the front of the queue (i.e. the oldest messages in the queue).
accepted answer of: http://stackoverflow.com/q/50121287
answers question: http://stackoverflow.com/q/50121287
has comment: http://stackoverflow.com/comment/108365332
has comment: http://stackoverflow.com/comment/108297488
has comment: http://stackoverflow.com/comment/108289325
type: Answer
has comment: http://stackoverflow.com/comment/108322449
has comment: http://stackoverflow.com/comment/108331913
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50315786
has comment: http://stackoverflow.com/comment/89164229
has comment: http://stackoverflow.com/comment/89122732
upvote count: 1
downvote count: 0
has body: I got the solution for this problem! The point is that Python 3.5 works with OpenSSL 0.9.8. The solution is installing Python 3.6.5 with a particular configuration to include 'OpenSSL 1.0.2n 7 Dec 2017'. brew install openssl brew link openssl --force # if you need too brew install python3 --with-brewed-openssl # this brings Python 3.6.5, and not 3.5
score: 1
answers question: http://stackoverflow.com/q/50078384
type: Answer

http://stackoverflow.com/q/50140227
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/87305914
upvote count: 1
has comment: http://stackoverflow.com/comment/87304691
has comment: http://stackoverflow.com/comment/87304769
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87298861
has comment: http://stackoverflow.com/comment/87304861
type: UnansweredQuestion
score: -2
tagged with: arrays
tagged with: numba
has body: I'm using numba and numpy to write a function, and in the course of my function, I will compute these two items: idx, which is a list of coordinates (for example, idx = [3,4,5]), and values, a 3d numpy array (for example, values.shape will yield (100, 100, 100)). Note that the dimension of values can change arbitrarily. Normally, if I do values[3,4,5], it will return a number, which is the value at the coordinate indicated. However, if I do values[idx], I get an array! I know that this works: values[tuple(idx)], but this will throw an error in numba: TypingError: cannot determine Numba type of &lt;class 'type'&gt; I cannot make idx a tuple to start with, because idx is created in a for loop which appends elements to idx, which is defined to be an empty list before the loop. Is there a simple way to extract a value from a 3d numpy array given a list, which has the coordinates in each of the dimensions? This seemingly easy problem is incredibly hard to solve. This is a minimally replicable function: gridMat = (np.linspace(1, 3, 100), np.linspace(0,2,100), np.linspace(5, 6,100)) mGrid = np.meshgrid(*gridMat, indexing = 'ij') values = np.power(mGrid[0], 2) + mGrid[1] / 4.0 + 3.0 + mGrid[2] * 4 @jit(nopython=True) def testFunction(values): idx = [] N = 3 for n in range(N): idx.append(n + 1) idx_res = tuple(idx) print(values[idx_res])
tagged with: python
has comment: http://stackoverflow.com/comment/87304788
has comment: http://stackoverflow.com/comment/87304723
has comment: http://stackoverflow.com/comment/87299137
has comment: http://stackoverflow.com/comment/87304759
has answer: http://stackoverflow.com/a/50140864
has comment: http://stackoverflow.com/comment/87308191
has title: Numba - how can I extract a value from a multidimensional numpy array

http://stackoverflow.com/q/50203283
has comment: http://stackoverflow.com/comment/87423932
downvote count: 1
has title: Python time.sleep command in a loop with if/else condition
favorite count: 0
type: Question
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/50203652
tagged with: python
has comment: http://stackoverflow.com/comment/87423632
linked to: http://stackoverflow.com/q/1931589
has comment: http://stackoverflow.com/comment/87423442
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87423584
has body: I have a question about the time.sleepcommand in a if/elseloop. I make an api request for different places with the latitude and longitude. All in all, I need the request for 5 years. I use two forloops over the latitude and longitude and over the requested five years. The problem is that I can only send 6 requests per minute. Because of that, I use the time.sleepcommand as follow: for lat, lon in zip(lats, lons): for year in years: args = { 'interpolate': False, 'lat': lat, 'lon': lon, 'date_from': year + '-01-01', 'date_to': year + '-12-31', 'capacity': 500, 'height': 44, 'turbine': 'Enercon E40 500', 'format': 'json', 'metadata': False, 'raw': True, } r = s.get(url, params=args) data = pd.read_json(r.text, orient='index') df = df.append(data) time.sleep(61) The function works good and the time.sleepcommand too! But in this form, the function waits 61 seconds after the last passing. I wanna make this a litte bit "smoother" with an if/elseloop in that way, if the loop uses the last latitude/longitude, the time.sleepcommand can be ignored. The years are a normal list and the latitude/longitude are in a seperate excel table. Has someone a idea, how I can write this? The ways I tried it doesn't work and I need some new inspiration...Thank you!
answer count: 1
has answer: http://stackoverflow.com/a/50203652
tagged with: loops
upvote count: 1

http://stackoverflow.com/a/50230158
answers question: http://stackoverflow.com/q/50228781
has body: Did this to work around this issue. However, still unsure why the original isn't working. headers_frame = url_list.copy() H1=[] H2=[] H3=[] for url in headers_frame.url: k = header_agg(url) H1.append(k[0]) H2.append(k[1]) H3.append(k[2]) pd.DataFrame(np.column_stack([headers_frame.url,H1,H2,H3]))
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50228781

http://stackoverflow.com/q/50206724
accepted answer: http://stackoverflow.com/a/50206885
tagged with: python-3.x
tagged with: pack
has body: I am trying to make a network proxy which will forward packets to another IP. I can sniff a packet, unpack it, and view, print, and manipulate its contents. But when I want to pack the bytes to forward it to some other IP, it gives this error: struct.error: required argument is not an integer The error is raised on this line of code: ip_header = struct.pack('!BBHHHBBH4s4s' ,version_IHL, TOS, totalLength, ID,flags, TTL,protocolNR, checksum,sourceAddress,destinationAddress) Here is the code. Bold stuff in code are comments in my code. import socket import sys import struct import re import logging import struct from scapy.all import * import Functions logging.basicConfig(filename='example.log',level=logging.DEBUG) hold = "192.168.0.125" print ("\n\t\t\t**************************") print ("\t\t\t*****SettingUp Server*****") print ("\t\t\t**************************\n\n") print("\t*****Implementing DHKE") print ("\t*****Generating server public &amp; private keypairs now . . .") (e,n), private = Functions.generate_keypair(7, 11) print ("*****Public Key: {} , {} ", e,n) print ("*****Private key: {} ", private) public = (e,n) ip = '192.168.0.125' port = 5001 # the public network interface #HOST = socket.gethostbyname(socket.gethostname()) #.............................................................................................. # create a raw socket and bind it to the public interface s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) s.bind(('192.168.0.117',5001)) # Include IP headers s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) logging.basicConfig(format='%(asctime)s %(message)s') logging.warning('format=%(asctime)s %(message)s') # receive all packages s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) #.............................................................................................. data = Functions.recievedata(s) logging.info('**Packet Recieved') print("Packet Recieved") #function_data = tuple(struct.unpack(data)) unpacked_data =…
tagged with: sockets
has title: struct.pack raises "struct.error: required argument is not an integer"
tagged with: arguments
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50206885
answer count: 1
type: Question

http://stackoverflow.com/q/50211195
tagged with: peewee
has body: I have a silly question. This my code: from peewee import * db = SqliteDatabase(None) class Base(Model): class Meta: database = db class Table(Base): a_date = DateField() url = CharField() def __main()__ parser = argparse.ArgumentParser() parser.add_argument('--db-dir', action='store') args = parser.parse_args() db_path = os.path.join(args.db_dir, 'data.db') try: db.init(db_path) db.connect() query = Table.select().order_by(Table.a_date.desc()).get() except Exception: sys.exit(1) else: print(query.url) sys.exit(0) if __name__ == '__main__': main() This code is working fine, but if the file db not exist db.connect always create it. How I can prevent this ? Another question is , How can query table database for this field without declare the peewee Model? Thanks
tagged with: python
type: AnsweredQuestion
has title: With peewee how connect to existing SQLite db for reading only
score: 1
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50211833
upvote count: 1
has answer: http://stackoverflow.com/a/50211833
favorite count: 0
type: Question

http://stackoverflow.com/a/50212251
score: 0
type: Answer
has body: As Seer.The mentioned above, you can use difflib. import difflib # Read the files f = open('textfile1.txt', 'r').readlines() list1 = [] for n in f: text = n.rstrip().split(" ") list1.append(text) f = open('textfile2.txt', 'r').readlines() list2 = [] for n in f: text = n.rstrip().split(" ") list2.append(text) # Get the output for ii in range(len(list1)): for jj in range(len(list1[0])): output_list = [li[-1] for li in list(difflib.ndiff(list1[ii][jj], list2[ii][jj])) if "-" in li] if output_list == []: output_list = ["no difference"] print "{} {} {}".format(list1[ii][jj], list2[ii][jj], output_list[0]) The output should look like: goerge goergy e hyder hydel r ganesh ganest h singapore singapore no difference
answers question: http://stackoverflow.com/q/50210765

http://stackoverflow.com/a/50241579
score: 0
has body: I've found the answer to my problem. # import libraries (Maya Commands Library and mtoa Core Library) import maya.cmds as cmds import mtoa.core as core Like haggi krey said, you'll find the necessary functions in the arnoldmenu.py file #Copy paste both functions from the arnoldmenu.py Script (filepath: "C:\solidangle\mtoadeploy\2018\scripts\mtoa\ui\arnoldmenu.py") def arnoldOpenMtoARenderView(): core.createOptions() cmds.arnoldRenderView(mode ="open") def arnoldMtoARenderView(): # core.ACTIVE_CAMERA is not set, anything we could do here ? #if core.ACTIVE_CAMERA != None: # cmds.arnoldRenderView(cam=core.ACTIVE_CAMERA) # so instead we're calling it without any argument core.createOptions() cmds.arnoldRenderView() #execute both functions arnoldOpenMtoARenderView() arnoldMtoARenderView() This script opens up the arnoldRenderView in same state as you last closed it.
type: Answer
answers question: http://stackoverflow.com/q/50119503
accepted answer of: http://stackoverflow.com/q/50119503
type: AcceptedAnswer

http://stackoverflow.com/a/50168890
type: Answer
answers question: http://stackoverflow.com/q/50168532
has body: I think one possible solution is rename columns: out = pd.merge_asof(a.rename(columns={'Time':'Time1'}), b.rename(columns={'Time':'Time2'}), left_on='Time1', right_on='Time2', direction='forward', tolerance=pd.Timedelta('30min')) print (out.head()) Time1 Time2 val 0 2010-02-01 00:00:00 2010-02-01 0.0 1 2010-02-01 06:03:00 NaT NaN 2 2010-02-01 12:06:00 NaT NaN 3 2010-02-01 18:09:00 NaT NaN 4 2010-02-02 00:12:00 NaT NaN
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/125251040
score: 24
upvote count: 24
accepted answer of: http://stackoverflow.com/q/50168532

http://stackoverflow.com/comment/123363221
type: AnswerComment
has text: October 2021: plotly is deprecated and should be replaced by chart_studio.
type: Comment
comment on: http://stackoverflow.com/a/52429324
score: 0

http://stackoverflow.com/q/50123140
tagged with: python
score: 1
linked to: http://stackoverflow.com/q/7168508
has title: Run a class function in background and retrieve its status
tagged with: asynchronous
linked to: http://stackoverflow.com/q/42009202
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2829329
linked to: http://stackoverflow.com/q/11533405
tagged with: python-multithreading
has body: import threading from azure.storage.blob import BlockBlobService def do_other_stuff(): print("so much stuff to do") class ABlob: def __init__(self, account_name, account_key, container_name, blob_name, file_path): self.account_name = account_name self.account_key = account_key self.container_name = container_name self.blob_name = blob_name self.file_path = file_path self.blob_service = BlockBlobService(account_name=self.account_name, account_key=self.account_key) def get_blob(self): download_thread = threading.Thread( target=self.blob_service.get_blob_to_path, args=(self.container_name, self.blob_name, self.file_path)) download_thread.start() def get_blob_name(self): print(self.blob_name) first_blob = ABlob(account_name='account_name', account_key='key', container_name='container', blob_name='something.csv', file_path='path') first_blob.get_blob() first_blob.get_blob_name() do_other_stuff() I have Azure Blobs that need to download and upload(not shown). I do not want to wait for them to complete their process as I have other things that should be done. At some point though, I will need to confirm if they have successfully downloaded or uploaded. With my current code, I have used the threading library. If an error happens in the upload or download process, the thread handling the transaction will exit with an error. I have no way to inform the main thread of completion and the status of the completion. What do I need to do to be able to get the status of get_blob? Is there a another library that has a less dangerous way of handling this situation? I have referenced the following threads but cannot figure out how to combine their different approaches. Catch a thread's exception in the caller thread in Python python multiprocessing pool retries How to call a async function contained in a class background function in Python
tagged with: multithreading
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50128014
has answer: http://stackoverflow.com/a/50128014
type: AnsweredQuestion
tagged with: python-asyncio
answer count: 1

http://stackoverflow.com/q/50209037
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
has body: I am trying to add a trend line to the historical values of the S&amp;P500, but when I try to add the trend line it doesn't appear, only the S&amp;P500 values appear in the chart. ("Dato" means "Date" in Norwegian.) Here's my code: ##################### Load the data df = pd.read_csv("SP500.csv", delimiter=r",", names = ["Date","Open", "High", "Low", "Close", "S&amp;P500", "Volume"]) df = df.drop(columns=['Open', 'High', 'Low', 'Close', 'Volume']) df["Dato"] = df["Date"] df2 = pd.read_excel("OSEBX.xlsx", names = ["Date", "OSEBX"]) df.set_index('Date', inplace=True) df2.set_index('Date', inplace=True) df3 = df.join(df2) df["Dato"] = pd.to_datetime(df3["Dato"]) ################################ Graph t = np.array(range(0, len(df["Dato"]))) x = np.array(df3["OSEBX"]) y = np.array(df3["S&amp;P500"]) plt.scatter(t,x, s=1) z = np.polyfit(x, t, 1) p = np.poly1d(z) plt.plot(x,p(x),"bs", linewidth=20) plt.show()
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/87441007
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87435290
has answer: http://stackoverflow.com/a/50213544
has comment: http://stackoverflow.com/comment/87441166
downvote count: 0
has title: Missing trend line

http://stackoverflow.com/comment/87203586
comment on: http://stackoverflow.com/q/50093674
has text: @VivekPabani. Yes I know `[0,1,3]` and `[1,0,3]` are not the same. In my case order deosn't matter.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/87426981
score: 0
has text: *Note*: There is a solution [described by @unutbu](https://stackoverflow.com/a/48600345/9209546) which is more efficient than using `pd.Series.str.contains`. If performance is an issue, then this may be worth investigating.
comment on: http://stackoverflow.com/q/50118786
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50181272
has body: I've tried out Linear Regression using SKLearn. I have data something along the lines of: Calories Eaten | Weight. 150 | 150 300 | 190 350 | 200 Basically made up numbers but I've fit the dataset into the linear regression model. What I'm confused on is, how would I go about predicting with new data, say I got 10 new numbers of Calories Eaten, and I want it to predict Weight? regressor = LinearRegression() regressor.fit(x_train, y_train) y_pred = regressor.predict(x_test) ?? But how would I go about making only my 10 new data numbers of Calories Eaten and make it the Test Set I want the regressor to predict?
has comment: http://stackoverflow.com/comment/87379877
has answer: http://stackoverflow.com/a/50181407
tagged with: scikit-learn
downvote count: 1
has answer: http://stackoverflow.com/a/50181412
favorite count: 0
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/50181411
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87380011
upvote count: 5
tagged with: machine-learning
has title: SKLearn Predicting using new Data
tagged with: python
score: 4

http://stackoverflow.com/a/50187535
accepted answer of: http://stackoverflow.com/q/50186714
type: Answer
answers question: http://stackoverflow.com/q/50186714
score: 0
type: AcceptedAnswer
has body: Instead of subprocess.call("python -m virtualenv " + VIRT_DIR, shell=True) I used subprocess.call("virtualenv " + VIRT_DIR, shell=True) Now , it is working fine. I can able to install python2.7

http://stackoverflow.com/a/50604986
upvote count: 18
has comment: http://stackoverflow.com/comment/95702904
has body: I'm also doing the Google's ML course and ran into the same problem where the describe function does not print to my output window. What worked for me was wrapping describe() in a print() function like below. print(california_housing_dataframe.describe()) That produced the descriptive stats in my output window. Disclaimer: I'm running my python programs from Sublime, and not Atom, and I'm using the following packages below: Sublime Text 3 pandas 0.23.0 tensorflow-gpu 1.8.0 CUDA 9.0.176.2 cudnn 7.1 Hope this helps!
score: 18
type: Answer
answers question: http://stackoverflow.com/q/50169437
downvote count: 0

http://stackoverflow.com/a/50237588
has body: To install pykalman I used: pip install pykalman --user The --user flag installs to my home directory, avoiding having to use sudo to install. I was told that scipy was missing, so I pip installed that as well. On the project github page there is a list of dependent libraries, so you may be asked to install any one of those. You are using single values for each of your readings. Most examples have more than this, for instance position and velocity for each reading. To get something to plot with the transition and observation matrices you supplied, I added a second bogus reading of '1' to each of your measurements. The following Jupyter notebook script will produce a plot, but the output is poor as the matrices values need to be adjusted for your data set. %matplotlib inline from pykalman import KalmanFilter import numpy as np kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]], observation_matrices = [[0.1, 0.5], [-0.3, 0.0]]) # measurements = np.asarray([(250.1),(248.5),(262.3),(265.3), (270.2)]) measurements = np.array([[250.1,1],[248.5,1],[262.3,1],[265.3,1], [270.2,1]]) kf = kf.em(measurements, n_iter=5) filtered_state_estimates = kf.filter(measurements)[0] (smoothed_state_estimates, smoothed_state_covariances)=kf.smooth(measurements) # draw estimates pl.figure() lines_true = pl.plot(measurements, color='b') lines_filt = pl.plot(filtered_state_estimates, color='r') lines_smooth = pl.plot(smoothed_state_estimates, color='g') pl.legend((lines_true[0], lines_filt[0], lines_smooth[0]), ('true', 'filt', 'smooth'), loc='lower right' ) pl.show() For the data set that you propose, a fast and simpler way to produce a filtered output would be to use a one minus alpha filter. Have a look at this link for more details on this type of filter: http://stats.stackexchange.com/questions/44650/a-simpler-way-to-calculate-exponentially-weighted-moving-average
score: 0
answers question: http://stackoverflow.com/q/50217553
type: Answer

http://stackoverflow.com/a/50204207
score: 1
answers question: http://stackoverflow.com/q/50203630
downvote count: 1
upvote count: 2
has body: forbiddenfruit might be able to help you: This project aims to help you reach heaven while writing tests, but it may lead you to hell if used on production code. It basically allows you to patch built-in objects, declared in C through python. Here's an example: from forbiddenfruit import curse def broken_sort(self): print("NOT DOING ANYTHING!") return None curse(list, "sort", broken_sort) some_list = [3, 4, 5, 1, 2] some_list.sort() print(some_list) It outputs: NOT DOING ANYTHING! [3, 4, 5, 1, 2] It doesn't seem to be working reliably on my system though, and it outputs [1, 2, 3, 4, 5] half of the time. Is this due to a race condition? I have no idea. :-/ The project might be worth a small investigation.
type: Answer

http://stackoverflow.com/comment/87396741
score: 0
type: AnswerComment
has text: Yes, I tried that, but no change, actually values changed, but were still wrong!
comment on: http://stackoverflow.com/a/50189936
type: Comment

http://stackoverflow.com/comment/87209331
type: Comment
has text: thank you @martijn the problem was with that library file. pycharm 2018.1 gave an unresolved reference error for the particular library so that i changed it to the google.cloude.speech_v1 earlier. problem solved once changed back to the google.cloud.speech_v1p1beta1.
comment on: http://stackoverflow.com/a/50096365
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87196825
type: QuestionComment
has text: You're printing `len` instead of `leng`.
score: 4
comment on: http://stackoverflow.com/q/50090356
type: Comment

http://stackoverflow.com/a/50107243
has body: Adding turtle.tracer(2,0) seems to make the issue disappear. This may be a temporary solution since I don't know if it just hide the problem behind another one. ... screen = turtle.Screen() screen.setworldcoordinates(0,height,width,0) screen.listen() turtle.tracer(2, 0) # This line turtle.mainloop() ... In the documentation we can read: Turns turtle animation on/off and set delay for update drawings. As @Keven points out, the issue seems to be the implicit update in the callback. This reduce the number of update call by 2. I think it may also remove the recursive call. Note: I don't know why but removing screen.setworldcoordinates(0,height,width,0) removes the glitchy behavior, but the recursive call to update is still present.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50105860
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87501343
type: Comment
type: AnswerComment
has text: Though it turned out to be a different issue (wrongly closed form tag), I really like the zip method so I upvoted it. Thanks
comment on: http://stackoverflow.com/a/50150958
score: 0

http://stackoverflow.com/a/50131515
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50125058
has body: If I remember it correctly, tf.estimator.DNNClassifier expects a dense label (say, [2]), rather than one-hot label (say, [0, 0, 1]). Hence don't use pd.get_dummies, and make sure that your label is 1-dimension data. The misleading information has been corrected in PR: https://github.com/tensorflow/tensorflow/pull/18305.

http://stackoverflow.com/comment/87338751
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50160364
score: 0
has text: What? Manually enter it where?

http://stackoverflow.com/comment/87244865
score: 0
has text: I tried all that (except for moving to a different database engine, which I would hate to do for my own test environment). Nothing unlocks my database, even not restarting the computer. Calling `db.connections.close_all()` from the shell also doesn't work, because the database is not locked when I access it from the shell. I production we use MySQL which does not have this problem, but I really like to use SQLite for my personal testing, and think it should not be a problem.
type: Comment
comment on: http://stackoverflow.com/q/50113817
type: QuestionComment

http://stackoverflow.com/a/63377335
has body: df=pd.DataFrame(np.random.randn(10,2)) print(df) 0 1 0 0.375727 -1.297127 1 -0.676528 0.301175 2 -2.236334 0.154765 3 -0.127439 0.415495 4 1.399427 -1.244539 5 -0.884309 -0.108502 6 -0.884931 2.089305 7 0.075599 0.404521 8 1.836577 -0.762597 9 0.294883 0.540444 #70% of the Dataframe part_70=df.sample(frac=0.7,random_state=10) print(part_70) 0 1 8 1.836577 -0.762597 2 -2.236334 0.154765 5 -0.884309 -0.108502 6 -0.884931 2.089305 3 -0.127439 0.415495 1 -0.676528 0.301175 0 0.375727 -1.297127
downvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50173283
has comment: http://stackoverflow.com/comment/112069932
upvote count: 0
score: -3

http://stackoverflow.com/comment/109114314
score: 0
comment on: http://stackoverflow.com/a/50096576
type: AnswerComment
has text: I hava a similar problem. I want to extract all href that correspond to "tif" from [link](http://www.lanot.unam.mx/goes.php) and save it into a list. I tried with ```by_partial_linked_text("goes-16.rgb.tif")``` and ```by_xpath()``` but in both the list is empty. Using ```by_css_selector("marco_goes.div.div.modal-body.div.div.div.ol.li a")```
type: Comment

http://stackoverflow.com/q/50139853
tagged with: python
tagged with: pygame
type: Question
has answer: http://stackoverflow.com/a/50140263
has body: i searched a lot about this, but no post seems to answere this specific question. So i am making a pygame application and i'm very new to this. For the screen scaling i use the following lines of code to get the user's screen informations: infoObject = pygame.display.Info() ScreenWidth = infoObject.current_w ScreenHeight = infoObject.current_h window = pygame.display.set_mode((ScreenWidth, ScreenHeight), pygame.FULLSCREEN) But my problem here is: I use my current display stats, but another user could obviously have other stats. However, for the placement of text i'm using things like: window.blit(text, (ScreenWidth/2 - text.get_rect().width/2, ScreenHeight*0.6)) to get it to the middle of the screen. If the resolution is changed, the location of the text will be too. Sometimes i am also using things like: window.blit(text, (ScreenWidth/2 - text.get_rect().width/2-500, ScreenHeight*0.6)) to move the text to the left. If the screen has only a width of 720 (for instance), it won't be visible. But since i work with relative positions here, the original layout/design will be no longer present neither. Does somebody know how i can "rescale" my game screen so it "automatically" rescales my text position, if that makes sense :) ?
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has title: Pygame rescaling game-resolution + coordinates
has comment: http://stackoverflow.com/comment/87303670
score: 1

http://stackoverflow.com/comment/87186936
has text: because it is a PYTHON project for school..
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50084990
type: Comment

http://stackoverflow.com/comment/87236888
comment on: http://stackoverflow.com/q/50078170
type: Comment
type: QuestionComment
score: 0
has text: Success Solved thanks to Bryan making me rethink my code structure. https://www.youtube.com/watch?v=BNklD6EJjv0

http://stackoverflow.com/comment/87438708
type: AnswerComment
score: 0
type: Comment
has text: So I tried this using a very simplified example but I am using pure Keras (is that a problem?)... a code snipped would look like this: `inp = Input(shape=(1,24,16))` `x = Conv2D(16, (3,3), activation='relu', padding='same')(inp) x = Lambda(tf.py_func(my_func, [x], tf.float32))(x) model = Model(inp, x)` with `def my_func(x): return 5*x` I get this error message: `target = K.placeholder(ndim=len(shape), TypeError: object of type 'NoneType' has no len()` What am I doing wrong here? I do not get any errors if I just use your `complex_tf_fn`, so this might be due to tf.py_func
comment on: http://stackoverflow.com/a/50187792

http://stackoverflow.com/comment/87475863
has text: This site isn't for people to write stuff for you... This is a Q&A site
comment on: http://stackoverflow.com/q/50229363
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50078741
has body: I am playing around with the similarity function in Spacy and observed something that I dont understand: import spacy nlp = spacy.load('en_core_web_sm') doc1 = nlp("Honda Civic Toyota") doc2 = nlp("Honda Civic Toyota car Christian God") for token in doc1: print (token.text, doc1[0].similarity(token)) for token in doc2: print (token.text, doc2[0].similarity(token)) Output: Honda 1.0 Civic 0.6631208 Toyota 0.4700994 Honda 1.0 Civic 0.6806056 Toyota 0.54713947 car 0.22469836 Christian 0.5016042 God 0.4778438 The word Honda is being compared to all the other words in doc1 and doc2 and it can be observed that when Honda is compared with Civic and Toyota, the similarity is different in doc1 and doc2. My understanding is that the similarity is computed from the consine similarity of the Glove vector of the words, which is loaded from 'en_core_web_sm'. If that is the case, shouldn't the similarity between the same pair of words the same regardless of its context? I think clearly I am misunderstanding something, would appreciate it if someone could clarify on it.
tagged with: spacy
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50088924
favorite count: 0
type: Question
score: 3
upvote count: 3
has title: strange similarity result in spacy
tagged with: python

pipeline
type: Tag
tags question: http://stackoverflow.com/q/50218408
tags question: http://stackoverflow.com/q/50180185
tags question: http://stackoverflow.com/q/50104344
tag name: pipeline

http://stackoverflow.com/q/50093335
has comment: http://stackoverflow.com/comment/87203939
has comment: http://stackoverflow.com/comment/87219894
has answer: http://stackoverflow.com/a/53544612
tagged with: django
tagged with: python
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87229963
has comment: http://stackoverflow.com/comment/87204443
has comment: http://stackoverflow.com/comment/87225409
has title: VSCode Integrated Terminal not loading Django
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87203150
has comment: http://stackoverflow.com/comment/87225377
score: -1
has body: Anaconda:1.8.3 VScode: 1.22.2 Mac: 10.13.4 Just upgraded to Anaconda 1.8.3 and now cannot access Django packages. from the conda python environment prompt I get: Last login: Sun Apr 29 19:21:31 on ttys001 /Users/bill/.anaconda/navigator/a.tool ; exit; Bills-iMac:~ bill$ /Users/bill/.anaconda/navigator/a.tool ; exit; Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (2, 0, 2, 'final', 0) >>> So I know that Django is installed and can be imported from the terminal. From within the VSCode integrated terminal I get: Bills-iMac:Prov bill$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Bills-iMac:Prov bill$ Within the VSCode Settings my python.pythonPath hasn't changed - it is still: { "python.pythonPath": "/anaconda3/envs/py36" } Within the venv the path is: >>> import sys >>> print(sys.path) ['', '/anaconda3/envs/py36/lib/python36.zip', '/anaconda3/envs/py36/lib/python3.6', '/anaconda3/envs/py36/lib/python3.6/lib-dynload', '/anaconda3/envs/py36/lib/python3.6/site-packages'] >>> I've updating the settings in VScode to the sys.path above - but that didn't change anything. I know that the package is installed and I know I can get to in from the prompt, but I can't get VScode to work. If it is a path issue, I'm not sure how to fix it - I'm guessing it is something more - just not sure what. Update I just re…
favorite count: 0
tagged with: visual-studio-code
accepted answer: http://stackoverflow.com/a/53544612
type: Question
has comment: http://stackoverflow.com/comment/87220520
has comment: http://stackoverflow.com/comment/87231910
upvote count: 0

http://stackoverflow.com/comment/87457528
comment on: http://stackoverflow.com/a/50219853
type: AnswerComment
has text: You're definitely right ! I'll take your advice as consideration.
score: 0
type: Comment

http://stackoverflow.com/comment/87310215
comment on: http://stackoverflow.com/q/50145945
type: Comment
score: 0
has text: @Matt.G Using `\w` and `\d+(?:,\d+)*` seems [way too lenient here](https://regex101.com/r/oKjrk3/2).
type: QuestionComment

http://stackoverflow.com/q/50185888
type: Question
accepted answer: http://stackoverflow.com/a/50190929
has title: Tensorflow: how to evaluate test data with persistence session?
has answer: http://stackoverflow.com/a/50190929
tagged with: python
type: AnsweredQuestion
score: 0
has body: Recently, I encountered a tensorflow evaluation question. My demand is that I want to use a trained network to evaluate some dynamic testing data. The dynamic testing data means that I initially just have one testing data, and the second testing data will be generated subsequently according to the evaluation result of the first testing data. A simple solution is I can write a evaluation function to evaluate testing data one by one such as def evaluation(testing_data): input = tf.placeholder(tf.float32, [None, params['height'], params['width'], params['depth']]) logits = inference(input) saver = tf.train.Saver() with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint(checkpoint_dir + '/')) prediction = self.session.run([logits['pred']], feed_dict={input: testing_data}) return prediction However, this solution is extremely slow since I need to initialize the Tensorflow Graph once when I call this function (Obviously, the graph only need to be initialized one time, because I don't change any parameters or something else of the trained network). In order to improve the efficiency, I rewrite the evaluation function as below. def new_evaluation(testing_data, first_initialize): input = tf.placeholder(tf.float32, [None, params['height'], params['width'], params['depth']]) if first_initialize: logits = inference(input) saver = tf.train.Saver() # use a global variable to save session global_session = tf.Session() saver.restore(global_session, tf.train.latest_checkpoint(checkpoint_dir + '/')) prediction = global_session.run([logits['pred']], feed_dict={input: testing_data}) else: prediction = global_session.run([logits['pred']], feed_dict={input: testing_data}) return prediction # I will manually close the global session when I finish all of jobs. The intention of new_evaluation function is obvious: If it is the first time to evaluate, we create tensorflow inference graph and restore trained parameters. If we already have initialized session, we directly use …
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/q/50210036
has body: I'm programming a dashboard with two roles (user &amp; admin). I have a decorator called requires_admin which prevents simple user to access the page. My problem is that I have an index page with all the routes listed and I want to only display the routes that are allowed for this particular user. It means that I want to know which routes have a requires_admin decorator and which haven't. Is that somehow possible?
favorite count: 0
type: Question
has title: Flask - Create index page with only the authorized route for user
has comment: http://stackoverflow.com/comment/87439065
score: 1
has comment: http://stackoverflow.com/comment/87438733
tagged with: python
has answer: http://stackoverflow.com/a/50215844
tagged with: python-decorators
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87439342
tagged with: flask
tagged with: jinja2

apscheduler
tags question: http://stackoverflow.com/q/50146080
tag name: apscheduler
tags question: http://stackoverflow.com/q/50151495
type: Tag

http://stackoverflow.com/comment/87282199
comment on: http://stackoverflow.com/a/50131294
type: Comment
type: AnswerComment
has text: Are you sure that you have more than one event? Can you please check index and event? Use print len(index) and print len(event)
score: 0

http://stackoverflow.com/a/50171889
score: 1
has comment: http://stackoverflow.com/comment/87446515
downvote count: 0
answers question: http://stackoverflow.com/q/50171434
has body: Your use of the function interp1d is wrong. From the docs: This class returns a function whose call method uses interpolation to find the value of new points As you can see from the example on the same page, you should call interp1d only with the x and y values you have. This returns a function to which you can pass new x values and which returns the interpolated y values: x = np.arange(0, 10) y = np.exp(-x/3.0) f = interpolate.interp1d(x, y) xnew = np.arange(0, 9, 0.1) ynew = f(xnew) # use interpolation function returned by `interp1d` So in your case this would be: f = interp1d(X, Y) X_smooth = np.linspace(Xnew.min(), Xnew.max(), 10) Y_smooth = f(X_smooth)
has comment: http://stackoverflow.com/comment/87361860
type: Answer
has comment: http://stackoverflow.com/comment/87393817
upvote count: 1

http://stackoverflow.com/q/50169854
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87357965
answer count: 1
has title: Group users by purchases with ML in Python
tagged with: machine-learning
tagged with: market-basket-analysis
has answer: http://stackoverflow.com/a/50170356
tagged with: python-3.x
has body: I have a dataset of purchases user_id, item_id ================== 1, 1 1, 2 1, 3 2, 2 2, 3 3, 8 3, 9 4, 8 4, 9 From this, I want to create some "clusters". From the data, it seems that user 1 and 2 are very similar and user 3 and 4 are very similar. I don't know how I can create this analysis with machine learning in Python. I guess it, for instance, could be distances with like 1, 2, 3, 4 1, -, ?, ?, ? 2, ?, -, ?, ? 3, ?, ?, -, ? 4, ?, ?, ?, - so I can determine how similar each user is to other users. What I want is to determine if various users belong to certain groups based on their purchases. For instance, if some users buy many baby-related items, they might be new mothers/fathers, while users who buy many software-related books might be IT professionals/students.
tagged with: algorithm
tagged with: python
type: Question
score: 0

http://stackoverflow.com/q/50197292
has answer: http://stackoverflow.com/a/50197308
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/11875770
score: 0
duplicate of: http://stackoverflow.com/q/2150739
tagged with: http://stackoverflow.com/tag/json
has title: How to convert Python datetime in JSON format?
answer count: 1
accepted answer: http://stackoverflow.com/a/50197308
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87411521
has body: How do I convert Python DateTime in JSON format? input from datetime import datetime my_date = datetime.now() output { "start_date": '2020-05-06T09:27:51.386383' }
type: Question
linked to: http://stackoverflow.com/q/2158347
has comment: http://stackoverflow.com/comment/87411517
upvote count: 5
linked to: http://stackoverflow.com/q/11875770
linked to: http://stackoverflow.com/q/2150739
downvote count: 5
duplicate of: http://stackoverflow.com/q/2158347

http://stackoverflow.com/q/50081415
downvote count: 0
tagged with: machine-learning
tagged with: python
has title: Keras model.fit ValueError: Input arrays should have the same number of samples as target arrays
has answer: http://stackoverflow.com/a/50081482
tagged with: keras
answer count: 1
has body: I'm trying to load the bottleneck_features that I obtained from running resnet50 into a top layer model. I ran predict_generator on resnet and saved the resultant bottleneck_features to a npy file. I am unable to fit the model I have created because of the following error: Traceback (most recent call last): File "Labeled_Image_Recognition.py", line 119, in &lt;module&gt; callbacks=[checkpointer]) File "/home/dillon/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/models.py", line 963, in fit validation_steps=validation_steps) File "/home/dillon/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/engine/training.py", line 1630, in fit batch_size=batch_size) File "/home/dillon/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/engine/training.py", line 1490, in _standardize_user_data _check_array_lengths(x, y, sample_weights) File "/home/dillon/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/engine/training.py", line 220, in _check_array_lengths 'and ' + str(list(set_y)[0]) + ' target samples.') ValueError: Input arrays should have the same number of samples as target arrays. Found 940286 input samples and 14951 target samples. I'm not really sure what it means. I have 940286 total images in my train dir and there are 14951 total subdirs that these images are separated into. My two hypotheses are: It is possible that I am not formatting the train_data and train_labels correctly. I set up the model incorrectly Any guidance into the right direction would be much appreciated! Here is the code: # Constants num_train_dirs = 14951 #This is the total amount of classes I have num_valid_dirs = 13168 def load_labels(path): targets = os.listdir(path) labels = np_utils.to_categorical(targets, len(targets)) return labels def create_model(train_data): model = Sequential() model.add(Flatten(input_shape=train_data.shape[1:])) model.add(Dense(num_train_dirs, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(num_train_dirs, activation='…
favorite count: 0
type: Question
score: 2
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50081482

http://stackoverflow.com/a/50131347
answers question: http://stackoverflow.com/q/50131152
has body: You can also use this: &gt;&gt;&gt; a,b,c,d,e,f,g = range(7) &gt;&gt;&gt; a 0 &gt;&gt;&gt; b 1 &gt;&gt;&gt; c 2
type: Answer
has comment: http://stackoverflow.com/comment/87280721
has comment: http://stackoverflow.com/comment/87280838
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87215363
has text: Yes exactly, never thought about it that way. Can a constructor have a return statement ?
comment on: http://stackoverflow.com/q/50099210
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50111472
has comment: http://stackoverflow.com/comment/87240546
tagged with: python
has comment: http://stackoverflow.com/comment/87240458
has answer: http://stackoverflow.com/a/50114826
has comment: http://stackoverflow.com/comment/87246347
score: 0
linked to: http://stackoverflow.com/q/49539265
has answer: http://stackoverflow.com/a/50140409
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/87240518
downvote count: 1
tagged with: maya
linked to: http://stackoverflow.com/q/41742822
has comment: http://stackoverflow.com/comment/87274763
has body: I am trying to use the following sliders for the Colour, Translate, Rotate and Scale for the shapes I have in this code. Is there a way I can control all the shapes with these sliders? I can't seem to figure it out I've tried everything that I could. I would like to do this with maybe a function but any solution is helpful Any help would be appreciated, thank you. #Importing all Maya commands to Python import maya.cmds as cmds from functools import partial class CreateUI(): def __init__(self): windowID = "myWindowID" if cmds.window(windowID, exists=True): cmds.deleteUI(windowID) #-----------------------------------------------Layout of Interface masterWindow = cmds.window(windowID, title="User Interface", w=500, h=800, sizeable=False, resizeToFitChildren=True) ShapeLayout = cmds.rowColumnLayout(parent=masterWindow, numberOfColumns=1, columnOffset=[(2,"left",0)]) #-----------------------------------------------Shape Functions #Functions for creating shapes def mySphere(*args): cmds.polySphere() def myCube(*args): cmds.polyCube() def myCylinder(*args): cmds.polyCylinder() def myCone(*args): cmds.polyCone() def myTorus(*args): cmds.polyTorus() def myPlane(*args): cmds.polyPlane() def myDelete(*args): cmds.select() cmds.delete() #Gets rid of any shapes in the scene so that the user doesn't have to every time the UI is launched or the sript is run ShapeList = cmds.ls("mySphere*", "myCube*", "myCylinder*", "myCone*", "myTorus*", "myPlane*","pSphere*", "pCube*", "pCylinder*", "pCone*", "pTorus*", "pPlane*") if len(ShapeList)&gt;0: cmds.delete(ShapeList) #-----------------------------------------------Shape Buttons #Buttons for creating shapes cmds.button(label="Sphere", command=mySphere) cmds.button(label="Cube", command=myCube) cmds.button(label="Cylinder", command=myCylinder) cmds.button(label="Cone", command=myCone) cmds.button(label="Torus", command=myTorus) cmds.button(label="Plane", command=myPlane) cmds.button(label="Delete", command=myDelete) #COLOUR cmds.separator…
linked to: http://stackoverflow.com/q/43255426
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87242039
linked to: http://stackoverflow.com/q/50110785
has title: Using Sliders in Maya with Python to control Shapes - intSliderGrp
linked to: http://stackoverflow.com/q/43569064
has comment: http://stackoverflow.com/comment/87242077
type: UnansweredQuestion

http://stackoverflow.com/comment/87303913
has text: Sorry - added the whole `polls/views.py` now. I believe (although am not certain) that it does at line 37 `return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50142765

http://stackoverflow.com/q/50174430
downvote count: 0
has body: Haven't found any way to mutate an existing pandas.Timestamp myself, but also have not found any documentation explicitly stating it to be immutable. Anyone knows the answer or has a way to find out?
favorite count: 0
has title: Is pandas.Timestamp immutable?
tagged with: timestamp
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49757871
tagged with: python
accepted answer: http://stackoverflow.com/a/50174963
type: Question
tagged with: immutability
has answer: http://stackoverflow.com/a/50174963
tagged with: pandas
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87367760
answer count: 1

http://stackoverflow.com/comment/87412881
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50128496
has text: @yorkevin can you get the cookie now?
score: 0

http://stackoverflow.com/comment/87304566
type: QuestionComment
comment on: http://stackoverflow.com/q/50143102
has text: Is it OK to use `predict` instead of `evaluate` for your case? You can then get the prediction first and decide whether you win or loss in your own way.
score: 0
type: Comment

http://stackoverflow.com/comment/87429531
comment on: http://stackoverflow.com/q/50206190
type: Comment
type: QuestionComment
score: 0
has text: It's just a matter of indentation

http://stackoverflow.com/comment/87222064
score: 0
comment on: http://stackoverflow.com/q/50101726
type: QuestionComment
has text: @TheImpaler Because you get the LABEL from it (value that I retrieve with a select tag in html)
type: Comment

http://stackoverflow.com/q/50108743
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87235241
possible better answer: http://stackoverflow.com/a/50136146
has body: I am trying to achieve the following: Input = { 'key1':{'key11':'val11', 'key12':'val12'}, 'key2':{'key21':{'key211':'val211', 'key212':'val212'}}, 'key3':'val3', 'key4':{'key41':'val41', 'key42':'val42'} } Output = 1) When value is a dictionary, then create an output string variable = key1 { key11 val11 key12 val12 } key2 { key21 { key211 val211 key212 val212 }} key4 { key41 val41 key42 val42} 2) When value is not a dictionary, then print "just a string element" Below is my code: from collections import defaultdict def stringBuilder(dictionary): stringOption = "" innerString = "" # print dictionary for key, value in dictionary.iteritems(): if isinstance(value, dict): stringBuilder(value) else: innerString = innerString + " " + str(key) + " " + str(value) print innerString stringOption = "{" + innerString + " }" print stringOption return stringOption d = {'key1':{'key11':'val11', 'key12':'val12'}, 'key2':{'key21':{'key211':'val211', 'key212':'val212'}}, 'key3':'val3', 'key4':{'key41':'val41', 'key42':'val42'}} print d stringOption = "" for key, value in d.iteritems(): if isinstance(value, dict): stringOption = stringOption + " " + str(key) + " " + stringBuilder(value) print stringOption else: print "just a string element" print stringOption Here is the output that I get: {'key2': {'key21': {'key211': 'val211', 'key212': 'val212'}}} key211 val211 { key211 val211 } key2 key2
has title: Convert a nested dictionary into a string
has comment: http://stackoverflow.com/comment/87234885
has comment: http://stackoverflow.com/comment/87234982
favorite count: 0
has answer: http://stackoverflow.com/a/50108943
type: Question
tagged with: recursion
has answer: http://stackoverflow.com/a/50136595
has comment: http://stackoverflow.com/comment/87235125
has comment: http://stackoverflow.com/comment/87235235
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50136146
accepted answer: http://stackoverflow.com/a/50108943
has comment: http://stackoverflow.com/comment/87234861
has comment: http://stackoverflow.com/comment/87235141
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/87407536
score: 0
type: Comment
type: AnswerComment
has text: use PythonIDLE。。。。
comment on: http://stackoverflow.com/a/50194820

http://stackoverflow.com/a/50075010
accepted answer of: http://stackoverflow.com/q/50074955
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50074955
type: Answer
has body: You should use groupby.cumsum for this. Using vectorised functionality which comes with pandas is usually more efficient and cleaner than iterating rows. df['result'] = df.groupby('name')['valor'].cumsum() print(df) date name valor result 2 2018-03-01 ACC 75 75 0 2018-03-01 ACE 50 50 0 2018-03-20 ACE 50 100 1 2018-03-01 BBV 20 20 1 2018-03-14 BBV 20 40 5 2018-04-16 BBV 58 98 6 2018-04-20 BBV -58 40

http://stackoverflow.com/a/50156706
has comment: http://stackoverflow.com/comment/122045940
upvote count: 169
has comment: http://stackoverflow.com/comment/135340416
has body: Recommended approach for pytest>=7: use the pythonpath setting Recently, pytest has added a new core plugin that supports sys.path modifications via the pythonpath configuration value. The solution is thus much simpler now and doesn't require any workarounds anymore: pyproject.toml example: [tool.pytest.ini_options] pythonpath = [ "src" ] pytest.ini example: [pytest] pythonpath = src The path entries are calculated relative to the rootdir, thus the src entry adds path/to/project/src directory to sys.path in this case. Multiple path entries are also allowed: for a layout repo/ ├── src/ | └── lib.py ├── src2/ | └── lib2.py └── tests └── test_lib.py the configuration [tool.pytest.ini_options] pythonpath = [ "src", "src2", ] or [pytest] pythonpath = src src2 will add both lib and lib2 modules to sys.path, so import lib import lib2 will both work. Original answer Adjusting the PYTHONPATH (as suggested in the comments) is one possibility to solve the import issue. Another is adding an empty conftest.py file in the src directory: $ touch src/conftest.py and pytest will add src to sys.path. This is a simple way to trick pytest into adding codebase to sys.path. However, the src layout is usually selected when you intend to build a distribution, e.g. providing a setup.py with (in this case) explicitly specifying the root package dir: from setuptools import find_packages, setup setup( ... package_dir={'': 'src'}, packages=find_packages(where='src'), ... ) and installing the package in the development mode (via python setup.py develop or pip install --editable .) while you're still developing it. This way, your package my_package is correctly integrated in the Python's site packages structure and there's no need to fiddle with PYTHONPATH.
type: Answer
has comment: http://stackoverflow.com/comment/87331458
has comment: http://stackoverflow.com/comment/134864670
accepted answer of: http://stackoverflow.com/q/50155464
has comment: http://stackoverflow.com/comment/135699704
has comment: http://stackoverflow.com/comment/87332412
answers question: http://stackoverflow.com/q/50155464
type: AcceptedAnswer
downvote count: 0
score: 169
has comment: http://stackoverflow.com/comment/133817083

http://stackoverflow.com/comment/118126261
has text: Worked for me! I had to source the .venv BEFORE running the program (otherwise "pyupdater" doesn't exist), which was easy enough to do by sourcing the environment then cd to a different directory.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/55034425

http://stackoverflow.com/comment/87311830
type: QuestionComment
score: 0
has text: I do notice that string concatenation in iteration (`stripped = stripped + i`) is not recommended and is consider O(N^2) in some style guide.
comment on: http://stackoverflow.com/q/50146709
type: Comment

http://stackoverflow.com/comment/87263321
type: Comment
type: QuestionComment
score: 0
has text: @Lemayzeur - Thanks, I know it's a warning and as I mentioned - I saw all existing answers. This case is a bit different
comment on: http://stackoverflow.com/q/50116971

http://stackoverflow.com/a/50095653
has body: When you call save method on model object then it will only update the model fields which we defined in the model. All other attributes of the model object will be ignored. That's the reason you didn't get any errors.
type: Answer
answers question: http://stackoverflow.com/q/50095511
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/50227900
score: 1
has body: I'm aware of the Run Keyword and Continue on Failure / Run Keyword And Ignore Error / Run keyword and return status Builtin keywords but I have a very wide set of test cases that should not be stopped for any reason on a specific scenario and I was wondering if there is an option not to make the execution stop on a failure by default, without having to manage it through these keywords and adding a non-business related syntax in my upper layer keywords.
type: Question
favorite count: 0
tagged with: testing
tagged with: robotframework
answer count: 2
tagged with: automated-tests
tagged with: atdd
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: Is there a way to configure Robot Framework so the execution is not stopped by a failure
has answer: http://stackoverflow.com/a/50234015
has answer: http://stackoverflow.com/a/50230159

http://stackoverflow.com/comment/87235836
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50107315
has text: @COLDSPEED i figured out my issue. i was incorrectly implementing the dropna code, which brought so many issues. implementing it correctly allowed for successful implementation of the ast.literal_eval code and also for tuple unpacking. Thanks a lot!

http://stackoverflow.com/a/50075573
has body: response['response']['results'] provides you with a list of dictionaries. [{},{},...] where each dictionary contains the following in your example: {id:'', type:'', sectionid:'', .... } If you want the list of all the webTitle in the results you'd have to iterate over the list obtained from response['response']['results'] and select the webTitle or any other required key in the resulting dictionary. Here's an example webTitleList = [] # Make the request for the JSON results = response['response']['results'] for result in results: webTitleList.append(result['webTitle']) # Now the webTitleList contains the list of all the webTitles in the returned json However, you can also simplify the selection of the webTitle by using list comprehension on results. There are numerous examples on StackOverflow for the same.
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50075452
has comment: http://stackoverflow.com/comment/87207939
upvote count: 1

http://stackoverflow.com/comment/87317023
has text: Nearly there, getting an error AttributeError: module 'pandas' has no attribute 'Dataframe'
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50149344

anaconda
tags question: http://stackoverflow.com/q/50220922
tags question: http://stackoverflow.com/q/50075351
tags question: http://stackoverflow.com/q/50122873
tags question: http://stackoverflow.com/q/50223686
tags question: http://stackoverflow.com/q/50215901
tags question: http://stackoverflow.com/q/50141734
tags question: http://stackoverflow.com/q/50103364
tags question: http://stackoverflow.com/q/50197152
tags question: http://stackoverflow.com/q/50196387
type: Tag
tags question: http://stackoverflow.com/q/50106303
tags question: http://stackoverflow.com/q/50125472
tag name: anaconda
tags question: http://stackoverflow.com/q/50138241
tags question: http://stackoverflow.com/q/50211567
tags question: http://stackoverflow.com/q/50093121
tags question: http://stackoverflow.com/q/50208859
tags question: http://stackoverflow.com/q/50142626
tags question: http://stackoverflow.com/q/50136894
tags question: http://stackoverflow.com/q/50134329
tags question: http://stackoverflow.com/q/50085173
tags question: http://stackoverflow.com/q/50195080
tags question: http://stackoverflow.com/q/50105833
tags question: http://stackoverflow.com/q/50162165
tags question: http://stackoverflow.com/q/50189972
tags question: http://stackoverflow.com/q/50164698
tags question: http://stackoverflow.com/q/50155527
tags question: http://stackoverflow.com/q/50190482
tags question: http://stackoverflow.com/q/50111663
tags question: http://stackoverflow.com/q/50096641
tags question: http://stackoverflow.com/q/50215931
tags question: http://stackoverflow.com/q/50170040
tags question: http://stackoverflow.com/q/50184736
tags question: http://stackoverflow.com/q/50216508
tags question: http://stackoverflow.com/q/50229857
tags question: http://stackoverflow.com/q/50105421
tags question: http://stackoverflow.com/q/50185227

http://stackoverflow.com/q/50226219
has comment: http://stackoverflow.com/comment/87469778
has comment: http://stackoverflow.com/comment/87470172
has comment: http://stackoverflow.com/comment/87470037
tagged with: database
has comment: http://stackoverflow.com/comment/87469882
tagged with: python
has comment: http://stackoverflow.com/comment/87469885
has answer: http://stackoverflow.com/a/64239467
has comment: http://stackoverflow.com/comment/113598092
tagged with: nlp
has comment: http://stackoverflow.com/comment/87469957
tagged with: sql
type: UnansweredQuestion
answer count: 1
has title: Natural language interface to database using python
type: Question
has body: I am working on a project related to natural language process using python. In my project, I have my database and some data related to finance and I have to create my own page and if I give a question for example what is the net income of apple? then I have to transfer my question into a query like select net_income from finance where name = apple and get the answer to my question. I've completed tokenizing the given question and removed stop words from it. I am unable to convert the tokens and add them into the query. I am very thankful if anyone could help me by giving your ideas?
score: 0

http://stackoverflow.com/a/50178535
has body: Change the following: Step 1 From string: self.click = "0" To numeric: self.click = 0 Step 2 From: self.RightBar = ... + self.click, ... To: self.RightBar = ... + str(self.click), ... Snippets def build(self): self.click = 0 ... self.RightBar = Label(text = "MONEY:" + "\n" + "\nUNITS:" + "\n" + "\nDAY:" + "\n" + "\nCLICKS:" + " " + str(self.click) Output
type: Answer
has comment: http://stackoverflow.com/comment/87374384
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50178190
answers question: http://stackoverflow.com/q/50178190

http://stackoverflow.com/q/50091006
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/50091044
tagged with: python
has title: Python - convert string to simple YYYY date format
duplicate of: http://stackoverflow.com/q/6556581
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/6556581
favorite count: 0
type: Question
has body: New to Python, and have already spent 30 minutes reviewing old responses, but still can't figure this out. 'Year' variable is a string. Examples: 1990, 2010. I need to convert to date format, but just with the 4 year "digits". Tried the following, but none are working: date1 = datetime.datetime.date('Year', "%Y") datetime.datetime.strftime('Year', "%Y") wcData.astype(str).apply(lambda x: pd.to_datetime('Year', format='%Y')) df.astype(str).apply(lambda x: pd.to_datetime(x, format='%Y%m%d')) Please help!
downvote count: 3

subprocess
tags question: http://stackoverflow.com/q/50138249
tag name: subprocess
tags question: http://stackoverflow.com/q/50157963
tags question: http://stackoverflow.com/q/50220129
type: Tag
tags question: http://stackoverflow.com/q/50111465
tags question: http://stackoverflow.com/q/50080859
tags question: http://stackoverflow.com/q/50114657
tags question: http://stackoverflow.com/q/50097661
tags question: http://stackoverflow.com/q/50097852
tags question: http://stackoverflow.com/q/50085360
tags question: http://stackoverflow.com/q/50128629
tags question: http://stackoverflow.com/q/50152689
tags question: http://stackoverflow.com/q/50228676
tags question: http://stackoverflow.com/q/50164514
tags question: http://stackoverflow.com/q/50144269
tags question: http://stackoverflow.com/q/50192674
tags question: http://stackoverflow.com/q/50199166
tags question: http://stackoverflow.com/q/50191964
tags question: http://stackoverflow.com/q/50137439
tags question: http://stackoverflow.com/q/50127494
tags question: http://stackoverflow.com/q/50134704
tags question: http://stackoverflow.com/q/50105545
tags question: http://stackoverflow.com/q/50225840
tags question: http://stackoverflow.com/q/50131836
tags question: http://stackoverflow.com/q/50195368
tags question: http://stackoverflow.com/q/50147470
tags question: http://stackoverflow.com/q/50198611

http://stackoverflow.com/comment/87280802
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50131187
type: AnswerComment
has text: By the way if there have \xef\xbb\xbf\xef\xbb\xbf which code this is?

heatmap
tags question: http://stackoverflow.com/q/50192121
tags question: http://stackoverflow.com/q/50087868
tags question: http://stackoverflow.com/q/50120777
tags question: http://stackoverflow.com/q/50180620
tags question: http://stackoverflow.com/q/50218109
tag name: heatmap
type: Tag
tags question: http://stackoverflow.com/q/50173642
tags question: http://stackoverflow.com/q/50086404

http://stackoverflow.com/q/50210304
has comment: http://stackoverflow.com/comment/87439236
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87437523
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/72155853
downvote count: 0
has body: I want to change the brown areas to RED (or another color). Just I don't know how to get the ranges for brown and put them in python code. I know how to change a single color, but not a range of colors. Any Ideas? Thanks
score: 19
favorite count: 0
has answer: http://stackoverflow.com/a/50215020
tagged with: opencv
upvote count: 19
tagged with: colors
tagged with: python-imaging-library
has title: Change the colors within certain range to another color using OpenCV
tagged with: python
tagged with: image-processing

http://stackoverflow.com/q/50195834
answer count: 0
has comment: http://stackoverflow.com/comment/87408805
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34201168
linked to: http://stackoverflow.com/q/35019030
downvote count: 0
upvote count: 1
tagged with: django
tagged with: django-rest-framework
has title: Django formatting query as specific json
has body: I am using Django Rest framework to create API for existing clients. my model.py is st like this: class Unit(models.Model): name = models.CharField(max_length=250, null=True, blank=True) summary = models.TextField(null=True, blank=True) location = models.ForeignKey(Location, null=True, blank=True) class Location(models.Model): name = models.CharField(max_length=250, null=True, blank=True) # refrenced in response json as category_name def __unicode__(self): return unicode(self.name) def __str__(self): return unicode(self.name) My API should be like this and I cannot change formatting in client side: { "data": [ { "category_name": "Block A -1", "items": [ { "id": "26", "name": "negar", "summary": "" }, { "id": "27", "name": "art coffee", "summary": "" } ] }, { "category_name": "Block B 2", "items": [ { "id": "14", "name": "kid house", "summary": "" }, { "id": "15", "name": "teen bookstore", "summary": "", } ] } ] } I read that must use APIView with customized serializer but cannot find way to format query into given format. Is there any correct way or simple trick to format queries as spacial json format? related questions reviewd: Where to change the form of json response in django rest framework? How to return custom JSON in Django REST Framework Custom JSON representation of query result Retrieving a Foreign Key value with django-rest-framework serializers
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: python
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/26664769
linked to: http://stackoverflow.com/q/17280007

http://stackoverflow.com/comment/87358066
type: QuestionComment
has text: my terminal simply ignored the lines with describe() and printed out ``` Training examples summary: Validation examples summary: Training targets summary: Validation targets summary: ``` and then carries on training the model.
comment on: http://stackoverflow.com/q/50169437
score: 0
type: Comment

http://stackoverflow.com/comment/87602629
has text: Did one of the solutions below help? Feel free to accept one if it did (green tick on left), or ask for clarification.
type: QuestionComment
comment on: http://stackoverflow.com/q/50205543
score: 0
type: Comment

http://stackoverflow.com/q/50105629
tagged with: python
has comment: http://stackoverflow.com/comment/87230640
has comment: http://stackoverflow.com/comment/87230327
has comment: http://stackoverflow.com/comment/87230973
tagged with: numpy
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/50105667
accepted answer: http://stackoverflow.com/a/50105667
has comment: http://stackoverflow.com/comment/87229245
answer count: 1
has title: Bizarre behaviour of pandas Series.value_counts()
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/87229736
has comment: http://stackoverflow.com/comment/87230196
tagged with: pandas
has comment: http://stackoverflow.com/comment/87229294
has body: I have a Pandas Series with numerical data and I want to find its unique values together with their frequency-appearance. I use the standard procedure # Given the my_data is a column of a pd.Dataframe df unique = df[my_data].value_counts() print unique And here is the results that I get # -------------------OUTPUT -0.010000 46483 -0.010000 16895 -0.027497 12215 -0.294492 11915 0.027497 11397 What I don't get is why I have the "same value" (-0.01) occurring twice. Is that an internal threshold (small value) or is something that I am doing wrong?? Update If I store the dataframe in csv and read it again I get the correct result, namely: # -------------------OUTPUT -0.010000 63378 -0.027497 12215 -0.294492 11915 0.027497 11397 Solution Based on the discussion, I found the source of the problem and the solution. As mentioned it is a floating-point precision which can be solved with rounding the values. Though, I wouldn't be able to see that without pd.set_option('display.float_format', repr) Thanks a lot for the help!!
has comment: http://stackoverflow.com/comment/87228429

http://stackoverflow.com/comment/87452544
type: Comment
comment on: http://stackoverflow.com/q/50217615
score: 0
type: QuestionComment
has text: At least tree bugs in the JSON according to https://jsonlint.com/

http://stackoverflow.com/a/50096512
has body: You can do that with regular expressions. import re sentence = 'The best balls team is the NYCC State Warriors since they have the A+++ players and best coach and they should win most games this break.' result = {} words = set(re.findall(r'([^ .,!?;]+)', sentence)) for word in words: re_consec = r'{}\s+([^ .,!?;]{})[^\w]'.format(re.escape(word), '{' + str(len(word) + 1) + '}') matches = re.findall(re_consec, sentence) if matches: result[word] = matches This gives the next result: {'NYCC': ['State'], 'The': ['best'], 'and': ['best', 'they'], 'best': ['balls', 'coach'], 'is': ['the'], 'most': ['games'], 'the': ['NYCC', 'A+++'], 'this': ['break'], 'win': ['most']}
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50095796

http://stackoverflow.com/comment/87598309
comment on: http://stackoverflow.com/q/50221512
score: 0
has text: I believe the current answer is lacking some critical practical aspects because the question itself is missing 1) a system description 2) system configuration (e.g. HyperThreading, Turbo Boost active) 3) the python version 4) Un-normalized performance numbers. @KellanM Please add them to the question so that there is a chance to give you a practical answer.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50117962
type: Answer
has body: Another option: &gt;&gt;&gt; ((df == 0) | df.isnull()).sum() a 2 b 3 c 5 dtype: int64 &gt;&gt;&gt; Also: &gt;&gt;&gt; (df.eq(0) | df.isnull()).sum() a 2 b 3 c 5 dtype: int64 &gt;&gt;&gt;
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50117840

http://stackoverflow.com/q/50219904
score: 14
answer count: 5
has title: django - prefetch only the newest record?
has answer: http://stackoverflow.com/a/67072525
possible better answer: http://stackoverflow.com/a/61357290
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/61357290
has answer: http://stackoverflow.com/a/50220347
accepted answer: http://stackoverflow.com/a/50220075
upvote count: 14
has answer: http://stackoverflow.com/a/73088829
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87457035
downvote count: 0
tagged with: django-queryset
has body: I am trying to prefetch only the latest record against the parent record. my models are as such class LinkTargets(models.Model): device_circuit_subnet = models.ForeignKey(DeviceCircuitSubnets, verbose_name="Device", on_delete=models.PROTECT) interface_index = models.CharField(max_length=100, verbose_name='Interface index (SNMP)', blank=True, null=True) get_bgp = models.BooleanField(default=False, verbose_name="get BGP Data?") dashboard = models.BooleanField(default=False, verbose_name="Display on monitoring dashboard?") class LinkData(models.Model): link_target = models.ForeignKey(LinkTargets, verbose_name="Link Target", on_delete=models.PROTECT) interface_description = models.CharField(max_length=200, verbose_name='Interface Description', blank=True, null=True) ... The below query fails with the error AttributeError: 'LinkData' object has no attribute '_iterable_class' Query: link_data = LinkTargets.objects.filter(dashboard=True) \ .prefetch_related( Prefetch( 'linkdata_set', queryset=LinkData.objects.all().order_by('-id')[0] ) ) I thought about getting LinkData instead and doing a select related but ive no idea how to get only 1 record for each link_target_id link_data = LinkData.objects.filter(link_target__dashboard=True) \ .select_related('link_target')..? EDIT: using rtindru's solution, the pre fetched seems to be empty. there is 6 records in there currently, atest 1 record for each of the 3 LinkTargets &gt;&gt;&gt; link_data[0] &lt;LinkTargets: LinkTargets object&gt; &gt;&gt;&gt; link_data[0].linkdata_set.all() &lt;QuerySet []&gt; &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/87457107
has answer: http://stackoverflow.com/a/50220075
favorite count: 0
type: Question

http://stackoverflow.com/a/50123474
has comment: http://stackoverflow.com/comment/87287502
type: Answer
score: 0
has body: You can stay in numpy and accomplish this. Looking at a single line from a matrix you can set your row of A equal to a vector and then create a row sum that allows you to check the index and find if it is true. For example: a = A[0, :] row_sum = a*x sum(row_sum) &lt;= B[0] The last line will return just True or False. Then if you want to change a single index you could update your row_sum array by using row_sum[3] = a[3]*new_val and run your analysis again.
answers question: http://stackoverflow.com/q/50123308

http://stackoverflow.com/a/50164805
has comment: http://stackoverflow.com/comment/87367180
has comment: http://stackoverflow.com/comment/87354142
has comment: http://stackoverflow.com/comment/87347864
type: Answer
has comment: http://stackoverflow.com/comment/87366343
has comment: http://stackoverflow.com/comment/87367360
answers question: http://stackoverflow.com/q/50160791
has comment: http://stackoverflow.com/comment/87354535
score: 0
has body: NOTE: This Answer, after being posted, was discovered by @Bridgey to be wrong. See his other Answer. It turns out that the problem was that the two lines: WSGIProcessGroup myapp WSGIApplicationGroup %{GLOBAL} should have been inside the &lt;Directory&gt;! So, the myapp.conf now looks like this: &lt;VirtualHost *:80&gt; ServerName yourdomain.com WSGIDaemonProcess myapp python-home=/var/www/myapp/myapp/venv WSGIScriptAlias / /var/www/myapp/myapp.wsgi &lt;Directory /var/www/myapp/myapp&gt; WSGIProcessGroup myapp WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; In fairness, this is as per the example in the docs. Big thanks to all those who commented :)

http://stackoverflow.com/comment/87268105
type: AnswerComment
has text: Also, make sure the you return a response when you have a POST'ed but invalid form. Right now, you aren't handling that.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50119999

http://stackoverflow.com/comment/87412735
has text: you can check now.
type: QuestionComment
comment on: http://stackoverflow.com/q/50197832
type: Comment
score: 0

http://stackoverflow.com/q/50225497
score: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87468997
has comment: http://stackoverflow.com/comment/87468721
downvote count: 1
favorite count: 0
type: Question
has title: How to set @property for each element in a list using python?
has comment: http://stackoverflow.com/comment/87468541
has body: I'm creating a class to store time.Say class TimePoint(object): def __init__(self): # a time list to store year, month, day, hour, minute, second self.time_unit = [-1, -1, -1, -1, -1, -1] And I want to limit the range of each element in self.time_unit, for example, 0 &lt; self.time_unit[1] &lt;= 12, which means month range 1~12.So, I want to use @property to decorator self.time_unit's each element.Say import arrow class TimePoint(object): def __init__(self): self.time_unit = [-1, -1, -1, -1, -1, -1] self.oor = False time_now = arrow.now() self.year = time_now.year self.month = time_now.month self.day = time_now.day self.hour = time_now.hour self.minute = time_now.minute self.second = time_now.second @property def t_unit(self): return self.time_unit @t_unit.setter def t_unit(self, value): if value &lt; 0 or value &gt; 9999: self.time_unit[0] = self.year self.oor = True if self.time_unit[0] &lt; 0 or self.time_unit[0] &gt; 9999: self.time_unit[0] = self.year self.oor = True if self.time_unit[1] &lt; 0 or self.time_unit[1] &gt; 12: self.time_unit[1] = self.month self.oor = True if self.time_unit[2] &lt; 0 or self.time_unit[2] &gt; 31: self.time_unit[2] = self.day self.oor = True if self.time_unit[3] &lt; 0 or self.time_unit[3] &gt; 24: self.time_unit[3] = self.hour self.oor = True if self.time_unit[4] &lt; 0 or self.time_unit[4] &gt; 60: self.time_unit[4] = self.minute self.oor = True if self.time_unit[5] &lt; 0 or self.time_unit[5] &gt; 60: self.time_unit[5] = self.second self.oor = True But, @property and @t_unit.setter just decorator the whole list self.time_unit , not elements in self.time_unit.So, how to decorator self.time_unit's element? Should I write @property for each element? @property def t_unit_first(self): return self.time_unit[0]
has comment: http://stackoverflow.com/comment/87468844
has comment: http://stackoverflow.com/comment/87468841
has comment: http://stackoverflow.com/comment/87468634
has comment: http://stackoverflow.com/comment/87468786
tagged with: python
tagged with: class

http://stackoverflow.com/comment/87463566
has text: I don't quite understand your wording. Anyway new update is better. +1
score: 0
comment on: http://stackoverflow.com/a/50222874
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87402107
type: AnswerComment
comment on: http://stackoverflow.com/a/50186227
has text: This cleared up the error. I marked useful but it won't publicly display...Any idea why it is so slow and doesn't stop at breakpoints unless I put a delay before the breakpoint? Or why it seriously takes sometimes almost 30 seconds to start the debugger, and 10 seconds to step over anything? I'm noticing this on 2 machines at work. :(
score: 0
type: Comment

http://stackoverflow.com/q/50183068
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87383689
tagged with: python
tagged with: permissions
has comment: http://stackoverflow.com/comment/87384047
has comment: http://stackoverflow.com/comment/87406676
score: 0
tagged with: installation
has answer: http://stackoverflow.com/a/79507224
answer count: 1
has comment: http://stackoverflow.com/comment/87383966
has title: OSError: [Errno 13] Permission denied when installing virtualenv...
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/87416479
type: Question
has body: I don't understand why the following gives an error nor how to fix it... any help would be most appreciated. (Note that this question is similar but different than this one.) dhcp-18-41:WakeUp6 jbs$ sudo -H virtualenv -p /usr/local/Cellar/python@2/2.7.15 env Password: Running virtualenv with interpreter /usr/local/Cellar/python@2/2.7.15 Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 11, in &lt;module&gt; sys.exit(main()) File "/Library/Python/2.7/site-packages/virtualenv.py", line 665, in main popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 13] Permission denied
has comment: http://stackoverflow.com/comment/87384136

http://stackoverflow.com/q/50099922
linked to: http://stackoverflow.com/q/38134643
has title: AttributeError: 'DataFrame' object has no attribute 'label'
accepted answer: http://stackoverflow.com/a/50099969
has comment: http://stackoverflow.com/comment/87217060
type: Question
tagged with: pandas
score: 3
has answer: http://stackoverflow.com/a/50099969
downvote count: 1
favorite count: 0
has body: I created a data frame using the following line: df = pd.read_csv('/Users/cs213/Desktop/class1.csv', sep = ',', error_bad_lines=False) and if print the columns as such print (df.columns) I get Index(['Text', 'label'], dtype='object') But if I wanted to use the columns as in here df = df[df.Text.apply(lambda x: x.isnumeric())] df = df[df.Text.apply(lambda x: x !="")] df = df[df.label.apply(lambda x: x !="")] I get the following error: AttributeError: 'DataFrame' object has no attribute 'label' I have already tried the solution in here: Data-frame Object has no Attribute and it did not work. Sample of the CSV file Here is the output of df.head()
upvote count: 4
has comment: http://stackoverflow.com/comment/87216492
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/102427720
answer count: 1
has comment: http://stackoverflow.com/comment/87216853

http://stackoverflow.com/a/50194755
upvote count: 3
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/50194711
type: Answer
has body: Any documentation on Tkinter will tell you the answer. In fact, it's usually literally the very first thing it will tell you. Entry in the Tkinter Book starts off with: The Entry widget is a standard Tkinter widget used to enter or display a single line of text. When to use the Entry Widget The entry widget is used to enter text strings. This widget allows the user to enter one line of text, in a single font. To enter multiple lines of text, use the Text widget. Entry in the Tkinter reference starts with: The purpose of an Entry widget is to let the user see and modify a single line of text. If you want to display multiple lines of text that can be edited, see Section 24, “The Text widget”. And so on.

http://stackoverflow.com/q/50202235
type: Question
accepted answer: http://stackoverflow.com/a/50204232
linked to: http://stackoverflow.com/q/50070775
tagged with: python
tagged with: rdd
has title: Analysis of Movie Ratings percentages across Occupation and Movie Genre
has body: I just started learning Spark Programming and Python programming: Can you please help me understand my mistake in my code: I am running code in Jupyter Notebooks, interactive mode. The below test code is working fine, where I tested the concept: rdd = sc.parallelize([('librarian', (1, [0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])), ('librarian', (1, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]))]) result = rdd.reduceByKey(lambda x, y: ((x[0]+y[0]), (x[1][0]+y[1][0]), (x[1][1]+y[1][1]), (x[1][2]+y[1][2]), (x[1][3]+y[1][3]), (x[1][4]+y[1][4]), (x[1][5]+y[1][5]), (x[1][6]+y[1][6]), (x[1][7]+y[1][7]), (x[1][8]+y[1][8]), (x[1][9]+y[1][9]), (x[1][10]+y[1][10]), (x[1][11]+y[1][11]))) print (result.top(3)) Output: [('librarian', (2, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0))] Below also works fine: #[(movieid, genre_list)] aggregateRDD = movieRDD.reduceByKey(lambda x, y: ((x[0]+y[0]), (x[1][0]+y[1][0]), (x[1][1]+y[1][1]))) print (aggregateRDD.top(3)) Output: [(1682, [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), (1681, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), (1680, [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0])] But, when I use a similar concept in my program, it doesn't accept. What am I doing wrong: ############################################################################## ### Analysis of Movie Ratings percentages across Occupation and Movie Genre ############################################################################## from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("local").setAppName("popularMovie") sc = SparkContext(conf =conf) ###import movie ratings into RDD ratingLines = sc.textFile("C:/SparkCourse/ml-100k/u.data") ###import user details into RDD userLines = sc.textFile("///SparkCourse/ml-100k/u.user") ###import movie data into RDD movieLines = sc.textFile("C:/SparkCourse/ml-100k/u.item") ###import genre data into RDD genreLines = sc.textFile("C:/SparkCourse/ml-100k/u…
type: AnsweredQuestion
tagged with: apache-spark
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50204232
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87262092
type: QuestionComment
comment on: http://stackoverflow.com/q/50104189
type: Comment
has text: If I understand, maybe I am wrong, it looks you are creating labels in a for loop by rewriting over the same var name, and packing it. Later you need to reference the labels and you can't. Just append the label widgets into a list, instead of rewriting the same name. Later you can refer to the list with the indexes you want (or with another for loop).
score: 1

http://stackoverflow.com/comment/87241764
type: Comment
score: 0
type: AnswerComment
has text: When I use `os.popen()`: `File "/usr/lib/python3.5/os.py", line 1035, in popen bufsize=buffering) File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg) OSError: [Errno 7] Argument list too long`
comment on: http://stackoverflow.com/a/50112159

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/50215247
tag name: matplotlib-basemap

http://stackoverflow.com/q/50175875
tagged with: django
type: UnansweredQuestion
tagged with: python
tagged with: django-rest-framework
score: 4
has answer: http://stackoverflow.com/a/50176229
has comment: http://stackoverflow.com/comment/87368940
has answer: http://stackoverflow.com/a/50177925
has title: Python catch previous exception in broad handler
answer count: 2
has body: Some of my api views have something like this: try: do_stuff() except KeyError as exc: logger.log(exc) raise APIException("No good") Ideally I don't want to log in every piece of code like this but use a general exception handler that catches APIException, so I changed my code to: try: do_stuff() except KeyError as exc: raise APIException(exc) exception_handler.py def exception_handler(...): logger.log(exc) # I want to log the KeyError... return Response({"message": "try again sam"}, status_code=400) My problem is the exc in the handler isn't the keyerror but the apiexception, can I somehow get the KeyError from sys.exc_info or stacktrace?
downvote count: 0
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/comment/87369437
has text: @tgordon18 Made the method for arrays.
type: Comment
comment on: http://stackoverflow.com/a/50175924
type: AnswerComment
score: 0

http://stackoverflow.com/q/50135808
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/63096028
has comment: http://stackoverflow.com/comment/87291484
tagged with: python
has title: python requirements: how to get identical versions?
accepted answer: http://stackoverflow.com/a/50136104
has body: This question is a consequence of the principal solution of requirement specifation: python django pip update problems: how to get compatible versions? I try to synchronize the python requirements between a server and the local development systems. Both are Ubuntu 16.04., so this should be a problem. The server gives me a requirement file (after pip-installing django as described in the other quewtion). But pip-installing the requirements on the local machine gives some errors, like this: Could not find a version that satisfies the requirement python- apt==1.1.0b1 (from -r requirements.txt (line 3)) (from versions: 0.0.0, 0.7.8) No matching distribution found for python-apt==1.1.0b1 (from -r requirements.txt Is there a way to ensure, that requirements can be met on similar systems without getting such errors caused by version incompatiblities (or of cause alterantively solve the incompatibility problems)? Do I need virtual environments to solve this? Or even pipenv? Or is there a simple straightforward way to have two systems with compatible python and package environments?
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50136104
possible better answer: http://stackoverflow.com/a/63096028
linked to: http://stackoverflow.com/q/50072998
downvote count: 0
tagged with: virtualenv
favorite count: 0
type: Question
tagged with: pipenv

pyqt5
tags question: http://stackoverflow.com/q/50194909
type: Tag
tags question: http://stackoverflow.com/q/50164712
tags question: http://stackoverflow.com/q/50112785
tags question: http://stackoverflow.com/q/50109747
tags question: http://stackoverflow.com/q/50180751
tags question: http://stackoverflow.com/q/50201738
tags question: http://stackoverflow.com/q/50092615
tags question: http://stackoverflow.com/q/50097765
tags question: http://stackoverflow.com/q/50081891
tags question: http://stackoverflow.com/q/50079415
tags question: http://stackoverflow.com/q/50118684
tags question: http://stackoverflow.com/q/50221046
tags question: http://stackoverflow.com/q/50134448
tags question: http://stackoverflow.com/q/50128066
tags question: http://stackoverflow.com/q/50137395
tags question: http://stackoverflow.com/q/50104507
tags question: http://stackoverflow.com/q/50135885
tags question: http://stackoverflow.com/q/50156607
tags question: http://stackoverflow.com/q/50148978
tags question: http://stackoverflow.com/q/50086893
tags question: http://stackoverflow.com/q/50196837
tags question: http://stackoverflow.com/q/50096286
tags question: http://stackoverflow.com/q/50182532
tags question: http://stackoverflow.com/q/50127246
tags question: http://stackoverflow.com/q/50127402
tags question: http://stackoverflow.com/q/50167096
tags question: http://stackoverflow.com/q/50115934
tags question: http://stackoverflow.com/q/50081088
tags question: http://stackoverflow.com/q/50125376
tags question: http://stackoverflow.com/q/50135339
tag name: pyqt5
tags question: http://stackoverflow.com/q/50176661
tags question: http://stackoverflow.com/q/50078373
tags question: http://stackoverflow.com/q/50147889
tags question: http://stackoverflow.com/q/50183044
tags question: http://stackoverflow.com/q/50136882
tags question: http://stackoverflow.com/q/50093086
tags question: http://stackoverflow.com/q/50197876
tags question: http://stackoverflow.com/q/50093507
tags question: http://stackoverflow.com/q/50168084
tags question: http://stackoverflow.com/q/50211133
tags question: http://stackoverflow.com/q/50104099
tags question: http://stackoverflow.com/q/50124231
tags question: http://stackoverflow.com/q/50128293
tags question: http://stackoverflow.com/q/50139812
tags question: http://stackoverflow.com/q/50227128
tags question: http://stackoverflow.com/q/50076903
tags question: http://stackoverflow.com/q/50222954
tags question: http://stackoverflow.com/q/50103167
tags question: http://stackoverflow.com/q/50134036
tags question: http://stackoverflow.com/q/50077228
tags question: http://stackoverflow.com/q/50181124

http://stackoverflow.com/q/50221351
has body: I have a json file and I would like to convert it into a data frame with several columns (hour, frappucino, soda, coffee, tea, water, milkshake, nothing, sandwich, pie, muffin, cookie) and put the values at the right place. If someone can help me, it would be great. :)
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87460444
linked to: http://stackoverflow.com/q/50221047
has answer: http://stackoverflow.com/a/50221621
has comment: http://stackoverflow.com/comment/87460031
answer count: 1
has title: How to convert this specific json file into a data frame?
type: Question
has comment: http://stackoverflow.com/comment/87460761
tagged with: pandas

http://stackoverflow.com/q/50195984
has answer: http://stackoverflow.com/a/50627020
favorite count: 0
type: Question
tagged with: slurm
has title: interacting with slurm jobs in python
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has body: I need to interact with slurm on a cluster through python. Specifically, I need to submit a bunch of jobs, check which ones succeeded, resubmit those that failed, collect the results, etc. In R, there is a package called BatchJobs which provides this functionality. What is the equivalent in Python? I saw PySlurm around but it looks like that is still under development and wouldn't have all the functionality that I need.
score: 1

http://stackoverflow.com/q/50109009
tagged with: filter
answer count: 2
has body: I have a file (file1.txt) where the first column contains strings, I want to filter in another file (file2.txt) the lines whose strings correspond exactly to the list 'indref' (see code). The problem is that the resulting file (see the short example) is also appending those strings that 'start' with the values that I want to append. I would just like to append the specific strings (those in 'indref'). Thank you. import numpy as np indref = ['p1', 'p3'] with open('file1.txt') as oldfile, open('file2.txt', 'w') as newfile: for line in oldfile: if any(x in line for x in indref): newfile.write(line) Example of file1.txt p1 4.252613E+01 p2 4.245285E+01 p3 4.272667E+01 p4 4.255809E+01 p5 4.284104E+01 p6 4.292802E+01 p7 4.295814E+01 p8 4.286242E+01 p9 4.286862E+01 p10 4.258108E+01 file2.txt: p1 4.252613E+01 p3 4.272667E+01 p10 4.258108E+01
has comment: http://stackoverflow.com/comment/87235319
tagged with: string
type: Question
has answer: http://stackoverflow.com/a/50109038
possible better answer: http://stackoverflow.com/a/50109038
has comment: http://stackoverflow.com/comment/87235334
has comment: http://stackoverflow.com/comment/87235439
has title: how to filter a txt file with specific strings
has answer: http://stackoverflow.com/a/50109130
accepted answer: http://stackoverflow.com/a/50109130
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/51511558
answers question: http://stackoverflow.com/q/50076117
has body: I am the main ArUco developer. I personally recommend the first 10 markers of the ARUCO_MIP_36h12 dictionary. Unless you are working at an extremely low resolution, there is no real improvement in working with small markers such as 4x4 or 3x3. This is because internally the library reduces the detected marker to a small size (of around 50x50 bits regardless its dimensions in the actual image) and it is in this resolution in which the code is analyzed. The fully explained pipeline of the ArUco library is described in the latest paper https://www.researchgate.net/publication/325787310_Speeded_Up_Detection_of_Squared_Fiducial_Markers in Sect 3.2. Also, you can have more information in the documentation at https://docs.google.com/document/d/1QU9KoBtjSM2kF6ITOjQ76xqL7H0TEtXriJX5kwi9Kgc
downvote count: 0
score: 19
has comment: http://stackoverflow.com/comment/127059451
has comment: http://stackoverflow.com/comment/92895163
type: Answer
upvote count: 19

http://stackoverflow.com/comment/87325526
comment on: http://stackoverflow.com/q/50154015
has text: Can you post your required output?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50172357
tagged with: dataframe
favorite count: 0
type: Question
answer count: 0
upvote count: 2
has title: Join 3 rows on a dataframe
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44319649
downvote count: 0
tagged with: python
score: 2
duplicate of: http://stackoverflow.com/q/44319649
tagged with: pandas
has body: I have a DataFramethat looks like this a b c d e f g h i 0 NaN NaN NaN 15 23 71 NaN NaN NaN 1 45 31 85 NaN NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN NaN 52 66 28 and I want to join the three rows as the following Expected result : a b c d e f g h i 0 45 31 85 15 23 71 52 66 28

http://stackoverflow.com/a/50203966
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50203776
score: 1
type: Answer
has body: Your one_line() function doesn't explicitly return anything, so it effectively returns None (of type NoneValue). Try changing as indicated below: def one_line(x, y): # print(' '*x, 'x'*y) return ' '*x, 'x'*y

http://stackoverflow.com/comment/87386296
has text: Use `response = s3_bucket.delete_objects(...` to get the result for the delete request. Then `print(response['Errors'])` to output it. What is the output there?
comment on: http://stackoverflow.com/q/50180425
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87450201
score: 2
has text: @Aran-Fey Thanks for first two points, I corrected them. Regarding #3, you are wrong. A set can be updated with iterables: https://docs.python.org/3/library/stdtypes.html#frozenset.update.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50216056

http://stackoverflow.com/q/50155870
has title: Why does the '\n' get stored as one item using a for loop?
has answer: http://stackoverflow.com/a/50155955
has body: This question mostly has to do with me wanting to better understand how python works. So I just made a simple function that is a more dynamic version of the .split() function, (it allows for multiple splits, one of which is the '\n' so I can better format some CSV information) but I don't know exactly why one aspect of it works. When you iterate through a string, such as "Hello there!\nGeneral Kenobi.", with a for loop, such as - for letter in string, why would the 'letter' variable store '\n' as one string, rather than '\' and in the next iteration 'n'? Code that I know does this: myString = "This is a string\nThis is a string" for letter in myString: print(repr(letter)) Just to be clear, I love that it does this, but I just want to know why. Thanks!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87329546
has comment: http://stackoverflow.com/comment/87329450
tagged with: string
has answer: http://stackoverflow.com/a/50155941
tagged with: iteration
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87329539
has answer: http://stackoverflow.com/a/50155961
tagged with: python
has comment: http://stackoverflow.com/comment/87329609
score: 2
upvote count: 2
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/87329445

http://stackoverflow.com/comment/87521464
has text: i am backend developer my job is creating REST API for mobile apps and backend admin
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50214614

http://stackoverflow.com/q/50200614
has comment: http://stackoverflow.com/comment/87468360
tagged with: libreoffice-base
tagged with: openoffice-base
type: Question
has title: Best way to run Macro on LibreOffice or OpenOffice SubForm "Fill parameters" Event
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has body: I try for more than a week to fill out a SQL query parameter by running a macro on the "Fill Parameters" event in the subform by searching for a method to fill the parameter under the Parameters object with MRI without success. Searches for guides and code samples on Google and the relevant forums also found nothing. Have I missed something or am I looking in the wrong place? Thanks in advance! Sql query: SELECT * FROM "Table1" WHERE "Record-Id" = :Record-Id Macro code to display an event object in Python: def main (oEvent): ctx = XSCRIPTONTONT.getComponentContext (); mri (ctx, oEvent);
answer count: 0
tagged with: libreoffice-basic
score: 1
has comment: http://stackoverflow.com/comment/87446593

http://stackoverflow.com/q/50127959
favorite count: 0
type: Question
has body: I have been recently using win32com.client from python as an API for windows applications but am struggling to understand some basic things. I had been using it with a program called WEAP, in the following way import win32com.client win32com.client.Dispatch("WEAP.WEAPApplication") Now, I want to use it with Excel and have found alternatives to the previous lines, one of them as follows (taken from Python: Open Excel Workbook using Win32 COM Api) import win32com.client as win32 excel = win32.gencache.EnsureDispatch('Excel.Application') Does anyone know the difference between using win32.Dispatch and win32.gencache.EnsureDispatch and other alternatives? Does anyone know pros and cons of each one? or some advice regarding when one or another should be used? I have looked for advice and i have found some useful answers, eg: Python: Open Excel Workbook using Win32 COM Api win32com.client.Dispatch works but not win32com.client.gencache.EnsureDispatch http://pythonexcels.com/python-excel-mini-cookbook/ https://mail.python.org/pipermail/python-win32/2011-August/011738.html However, they are usually focused on answering specific issues, and not describing the bigger picture of the differences between Dispatch, gencache.EnsureDispatch, and perhaps further alternatives, which is what i want. Any advice would be greatly appreciated.
answer count: 2
possible better answer: http://stackoverflow.com/a/53833740
has answer: http://stackoverflow.com/a/53833740
has title: win32.Dispatch vs win32.gencache in Python. What are the pros and cons?
tagged with: python
linked to: http://stackoverflow.com/q/39877278
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50163150
linked to: http://stackoverflow.com/q/11623461
upvote count: 28
has answer: http://stackoverflow.com/a/50163150
tagged with: win32com
downvote count: 0
score: 28

http://stackoverflow.com/comment/87392962
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50187951
has text: @HeadOverFeet, you're welcome. I updated my answer with more informations.

http://stackoverflow.com/comment/87283586
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50090767
type: Comment
has text: Sorry, maybe this is due to my mathematical background, a 2D Matrix consisting of m rows and n columns, consists of n (m,1) (m-D) vectors or of m (1, n) (n-D) vectors. so 7 elements does not mean 7d, but it can be interpreted like that (in this case here). btw, if one wouldn't interpret it as such structures, the curse of dimensionality wouldn't play such an important role since then most of the problems could just be cast into 2D-matrices or 3D Tensors

http://stackoverflow.com/q/50140811
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has body: Basically as in the question. I want to create a bot which will delete a message with an attachment if the author of the message does not have either the bot or trusted role within my server. Currently i have this: **if message.attachments: if not "*roleID*" or "roleID" in [role.id for role in message.author.roles]: await client.delete_message(message) await client.send_message(message.channel, "Sorry mate only trusted members or bots can attach things to prevent spam")**
has title: How to make a discord bot which deletes messages with attachments if the author doesn't have certain roles
tagged with: python
tagged with: discord
has answer: http://stackoverflow.com/a/50141398

http://stackoverflow.com/a/50086533
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50085616
has body: Does it means that the effect of these N batches of input are combined/condensed into the dW? Since the i-th row of X is a 1-d array that is related to the i-th flatten image. If I transpose X into T X , then it's columns to represent those flatten images. If N increase, although the dimension of the result(dW) won't change, the intermediate steps of computing each element of T d L dW = X * --- d Y , increase, which means N dW = Sum ( pixel_info * class_scores_deriv. ) i,j n=1 i,n n,j , which N is the batch size. Clearly each class_scores_derivative_(n,j) "join" the determination of dW_(i,j), but this implies that the division by batch_size = N is needed, because the summation above is not the average effect of that batch, but what I need is dW to represent the average impact of that batch. If I divide each element of class_scores_deriv., which is the line dx = (self._y - self._t) / batch_size, then N 1 Sum ( pixel_info * --- class_scores_deriv. ) n=1 i,n N n,j 1 N = --- Sum ( pixel_info * class_scores_deriv. ) N n=1 i,n n,j 1 = --- dW N , which is the real dW I want. So the answer (I hope) should be The entire batch determine the dW, but to condense it, the divisions in SoftmaxCrossEntropy::backward(self, dout=1) is needed.

http://stackoverflow.com/a/50099534
has comment: http://stackoverflow.com/comment/87215578
accepted answer of: http://stackoverflow.com/q/50099210
has comment: http://stackoverflow.com/comment/87216096
score: 1
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/87215654
has comment: http://stackoverflow.com/comment/87215928
answers question: http://stackoverflow.com/q/50099210
has comment: http://stackoverflow.com/comment/87215719
has body: There are different ways to implement this behavior. The simplest is to have a class _Person which is the same as your current Person class: class _Person: def __init__(self, name, male, alter): self.name = name self.male = male self.__alter = alter def print_beschreibung(self): if self.male: print("Ich heiße " + self.name + ", bin männlich,", self.__alter, "Jahre alt") else: print("Ich heiße " + self.name + ", bin weiblich,", self.__alter, "Jahre alt") def get_alter(self): return self.__alter def set_alter(self, neues_alter): self.__alter = neues_alter class Kind(_Person): pass class Erwachsener(_Person): def __init__(self, name, male, alter, lohn, ist_verheiratet, kinder): super().__init__(name, male, alter) self.__lohn = lohn self.ist_verheiratet = ist_verheiratet self.kinder = kinder class Pensionierter(_Person): pass Then you have a function Person which behaves like a class and returns a corresponding Erwachsener, Kind or Pensionierter class: def Person(*args, **kwargs): alter = args[2] if alter &lt; 18: return Kind(*args, **kwargs) elif 18 &lt;= alter &lt;= 61: return Erwachsener(*args, **kwargs) else: return Pensionierter(*args, **kwargs) Then you can use this function like this: peter = Person("Peter Lustig", True, 52, 0, False, 0) print(isinstance(peter, Erwachsener)) peter.print_beschreibung() If you want Person to be a class, you are going to have to do some magic: class Person: def __new__(cls, *args, **kwargs): alter = args[2] if alter &lt; 18: cls = Kind elif alter &lt; 61: cls = Erwachsener else: cls = Pensionierter return object.__new__(cls) # The rest of the class Then you can use it as above: peter = Person("Peter Lustig", True, 52,0,False,0) print(isinstance(peter, Erwachsener)) # prints True peter.print_beschreibung() But you can also to thing like this: print(isinstance(peter, Person)) # prints True
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87215832

http://stackoverflow.com/a/70513186
downvote count: 0
answers question: http://stackoverflow.com/q/50176096
type: Answer
upvote count: 1
has body: Alternatively, you can split the dataframe into parts you want to apply drop_first=True and parts you don't. Then concatenate them together. df1 = df.iloc[:, 0:2] df2 = df.iloc[:, 2:] df1 = pd.get_dummies(df1 ,drop_first=True) df = pd.concat([df1, df2], axis=1)
score: 1

http://stackoverflow.com/a/50130017
has comment: http://stackoverflow.com/comment/87278103
accepted answer of: http://stackoverflow.com/q/50129974
score: 3
answers question: http://stackoverflow.com/q/50129974
has comment: http://stackoverflow.com/comment/87278068
has body: Using re.search import re address = '6A McCarthy Way' address2 = 'McCarthy Way 6A' address3 = 'McCarthy Way 6AAAA' print(re.search("(\d+\w*)", address).group()) print(re.search("(\d+\w*)", address2).group()) print(re.search("(\d+\w*)", address3).group()) Output: 6A 6A 6AAAA
type: Answer
has comment: http://stackoverflow.com/comment/87278032
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50224982
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87550814
has comment: http://stackoverflow.com/comment/87540372
upvote count: 7
has comment: http://stackoverflow.com/comment/87551280
has comment: http://stackoverflow.com/comment/87487609
has body: Simply compile it To get the best performance I recommend Numba (easy usage, good performance). Alternatively Cython may be a good idea, but with a bit more changes to your code. You actually got everything right and implemented a easy to understand (for a human and most important for a compiler) solution. There are basically two ways to gain performance Vectorize the code as @scnerd showed. This is usually a bit slower and more complex than simply compile a quite simple code, that only uses some for loops. Don't vectorize your code and than use a compiler. From a simple looping aproach this is usually some work to do and leads to a slower and more complex result. The advantage of this process is that you only need numpy, which is a standard dependency in nearly every Python project that deals with some numerical calculations. Compile the code. If you have already a solution with a few loops and no other, or only a few non numpy functions involved this is often the simplest and fastest solution. A solution using Numba You do not have to change much, I changed the pow function to np.power and some slight changes to the way arrays accessed in numpy (this isn't really necessary). import numba as nb import numpy as np #performance-debug info import llvmlite.binding as llvm llvm.set_option('', '--debug-only=loop-vectorize') @nb.njit(fastmath=True) def Delta_Gaussf_nb(Nw, N_bd, N_kp, hw, width,eigv): Delta_Gauss = np.zeros((Nw,N_kp,N_bd,N_bd),dtype=float) for w1 in range(Nw): for k1 in range(N_kp): for i1 in range(N_bd): for j1 in range(N_bd): if ( j1 &gt;= i1 ): Delta_Gauss[w1,k1,i1,j1] = np.exp(np.power((eigv[k1,j1]-eigv[k1,i1]-hw[w1])/width,2)) return Delta_Gauss Due to the 'if' the SIMD-vectorization fails. In the next step we can remove it (maybe a call outside the njited function to np.triu(Delta_Gauss) will be necessary). I also parallelized the function. @nb.njit(fastmath=True,parallel=True) def Delta_Gaussf_1(Nw, N_bd, N_kp, hw, width,eigv): Delta_Gauss = np.zero…
has comment: http://stackoverflow.com/comment/87540048
has comment: http://stackoverflow.com/comment/87481477
score: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/50220638
has comment: http://stackoverflow.com/comment/87540613
has comment: http://stackoverflow.com/comment/87540014
answers question: http://stackoverflow.com/q/50220638

http://stackoverflow.com/comment/87193746
score: 0
has text: @Goyo sorry for the lack of clarity, i want to do clustering on this dataset. Expected to have a new column containing the clustering class for each `RFM_class` . So what i was doing was creating a new empty dataframe for clustering calculation. But i wasn't able to do iteration of clustering in each `RFM_class`
comment on: http://stackoverflow.com/q/50088353
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50198730
tagged with: python
score: 0
answer count: 1
has title: Scrapy: why endless log: Crawled 14091 pages (at 0 pages/min)?
has answer: http://stackoverflow.com/a/50200125
tagged with: web-crawler
tagged with: scrapy
has body: when the program runs for a time, the CPU usage is 100%, and the program seems doesn't crawl pages. When i kill the program, I get the following log: 2018-05-06 18:21:43 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/exception_count': 479, 'downloader/exception_type_count/twisted.internet.error.ConnectError': 1, 'downloader/exception_type_count/twisted.internet.error.ConnectionRefusedError': 146, 'downloader/exception_type_count/twisted.internet.error.TimeoutError': 332, 'downloader/request_bytes': 7834053, 'downloader/request_count': 14825, 'downloader/request_method_count/GET': 14825, 'downloader/response_bytes': 155349329, 'downloader/response_count': 14346, 'downloader/response_status_count/200': 14316, 'downloader/response_status_count/302': 21, 'downloader/response_status_count/400': 9, 'dupefilter/filtered': 90830, 'finish_reason': 'shutdown', 'finish_time': datetime.datetime(2018, 5, 6, 10, 21, 43, 859725), 'item_scraped_count': 1781, 'log_count/DEBUG': 15880, 'log_count/INFO': 14672, 'memusage/max': 601972736, 'memusage/startup': 55906304, 'request_depth_max': 428, 'response_received_count': 14091, 'scheduler/dequeued': 14825, 'scheduler/dequeued/memory': 14825, 'scheduler/enqueued': 143352, 'scheduler/enqueued/memory': 143352, 'start_time': datetime.datetime(2018, 5, 6, 9, 8, 22, 330943)} 2018-05-06 18:21:44 [scrapy.core.engine] INFO: Spider closed (shutdown)
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/87325851
has text: I still don't understand why you recommend using an HTML parser. I mean, even BS has an XML parser: `soup = BeautifulSoup(content, 'xml')` would be a way of doing the same as the OP with a different library. But why do you explicitly suggest using `'html.parser'`?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50148546
type: AnswerComment

http://stackoverflow.com/a/50187356
score: 0
has body: have to manually force a figure draw ax.figure.canvas.draw() self.show() Try it: import numpy as np import sys from PyQt5.QtCore import QUrl,QRect,QSize from PyQt5.QtWebEngineWidgets import QWebEngineSettings, QWebEngineView, QWebEnginePage from PyQt5.QtWidgets import (QApplication, QMainWindow,QMenu,QHBoxLayout,QVBoxLayout,QFrame,QLabel, QSizePolicy, QMessageBox, QWidget, QPushButton,QRadioButton, QTextBrowser,QDialog,QGroupBox,QTabWidget,QComboBox,QListWidget) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import shapefile as shp import matplotlib.pyplot as plt import random data_square=[(0,0),(1,0),(1,1),(0,1),(0,0),(1,1)] data_rectangle=[(0,0),(2,0),(2,1),(0,1),(0,0),(1,1)] class MyBrowser(QWebEnginePage): def userAgentForUrl(self, url): return "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" class Web(QWebEngineView): def load(self, url): self.setUrl(QUrl(url)) def adjustTitle(self): self.setWindowTitle(self.title()) def disableJS(self): settings = QWebEngineSettings.globalSettings() settings.setAttribute(QWebEngineSettings.JavascriptEnabled, False) class App(QDialog): def __init__(self): super().__init__() self.title= 'Test Building PyQT5 with Tabs' self.left = 40 self.top = 40 self.width = 400 self.height = 100 self.initUI() def initUI(self): #self.setWindowTitle(self.title) #self.setGeometry(100,100,1000,800) #self.create_my_layout() #my_main_window_layout=QVBoxLayout() #self.setLayout(my_main_window_layout) #self.show() self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.create_my_layout() windowLayout = QVBoxLayout() #windowLayout.addWidget(self.horizontalGroupBox) self.setLayout(windowLayout) self.show() def my_combo_active(self,index): my_specific_country = self.my_combo.itemText(index) if my_specific_country == 'Afghanistan': m = PlotCanvas(self.my_graphic, width=5, height=5, dpi=100…
has comment: http://stackoverflow.com/comment/87396809
has comment: http://stackoverflow.com/comment/87400474
answers question: http://stackoverflow.com/q/50183044
type: Answer

http://stackoverflow.com/comment/106266186
has text: --no-browser argument solved it, though
comment on: http://stackoverflow.com/q/50136894
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87337232
type: Comment
has text: The "double-underscore" prevents access to the attribute (except by getters), so it kind of emulates a private attribute.
score: 0
comment on: http://stackoverflow.com/a/50158326
type: AnswerComment

http://stackoverflow.com/comment/87464959
type: QuestionComment
has text: Thanks! I ended up using Affinity Propagation. When I used hierarchical clustering, it resulted in some very weird clusters for some reason.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50177981

http://stackoverflow.com/a/50129444
type: Answer
has body: Actually, the website shows today's matches first (at the top), and then the next days'. So, if you want to get today's matches, you can simply use find(), which return the first match found. Using this will give you what you want: today = soup.find('div', class_='match-day') But, if you want to explicitly specify the date, you can find the tag containing today's date, by using text='2018-05-02' as a parameter for the find() method. But, note that in the page source, the tag is 2018-05-02 and not a tag. After getting this tag, use .parent to get the tag. today = soup.find('span', text='2018-05-02').parent Again, if you want to make the solution more generic, you can use datetime.date.today() instead of the hard-coded date. today = soup.find('span', text=datetime.date.today()).parent You'll have to import the datetime module for this.
answers question: http://stackoverflow.com/q/50120344
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50120344
has comment: http://stackoverflow.com/comment/87309017

http://stackoverflow.com/comment/87235065
score: 0
type: Comment
has text: @belek I've added the updated solution. Let me know.
type: AnswerComment
comment on: http://stackoverflow.com/a/50078447

http://stackoverflow.com/a/50219979
has body: I tried to make it as similar to your code as possible and it's quite simple to understand. I think I considered all required conditions. If not, tell me. from string import ascii_letters def validity_check(input_chars): try: # if cant be splitted raises Exception which results in restart char_1, char_2 = input_chars.split("-") # if characters not in alphabet restarts chars_in_alphabet = char_1 in ascii_letters and char_2 in ascii_letters if not chars_in_alphabet: return False # if characters are the same letter restarts same_latter = char_1.lower() == char_2.lower() if same_latter: return False # I'm not sure if you want to check if the first letter # is small and the second one is capital # if so add this block # chars_letter_size = char_1 in ascii_letters.lower() and char_2 in ascii_letters.upper() # if not chars_letter_size: # return False return True except: return False while True: ask = input("Please enter two different characters in the form c1-c2: ") if validity_check(ask): break
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50219683
has comment: http://stackoverflow.com/comment/87457389

http://stackoverflow.com/a/50120983
answers question: http://stackoverflow.com/q/50083553
type: AcceptedAnswer
downvote count: 0
upvote count: 21
score: 21
has comment: http://stackoverflow.com/comment/118757930
accepted answer of: http://stackoverflow.com/q/50083553
type: Answer
has body: Because packages do not do any package lookup in subtree. Adding a package to packages will only include the package itself and all direct submodules, but none of the subpackages. For example, if you have a source tree with package spam containing a module eggs and subpackage bacon: src └── spam ├── __init__.py ├── eggs.py └── bacon └── __init__.py Specifying packages=['spam'] will include only spam and spam.eggs, but not spam.bacon, so spam.bacon will not be installed. You have to add it separately to include the complete source codebase: packages=['spam', 'spam.bacon']. To automate the building of the packages list, setuptools offers a handy function find_packages: from setuptools import find_packages, setup setup( packages=find_packages(), ... )
has comment: http://stackoverflow.com/comment/118757734

http://stackoverflow.com/comment/87262826
score: 0
comment on: http://stackoverflow.com/q/50122334
type: Comment
type: QuestionComment
has text: @Prunesquallor I'm ready to believe you, but trying the answer in the linked question with your example works for me, so if that question is indeed not a duplicate, you should probably give an explanation as to why and what didn't work for you

http://stackoverflow.com/comment/87439066
has text: I have made it a bit clearer now
comment on: http://stackoverflow.com/q/50209250
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87181302
type: QuestionComment
has text: Have you worked through the official tutorial?
score: 0
comment on: http://stackoverflow.com/q/50082563
type: Comment

http://stackoverflow.com/comment/87441695
type: Comment
type: QuestionComment
has text: @abccd sorry to keep coming back to you but I changed member to message.author and I still got an error saying: '`AttributeError: 'NoneType' object has no attribute 'id` on line 59 which is `await client.add_roles(message.author, role)` EDIT: Fixed, thanks for your help, I changed the name="admin" to id="[id]"
comment on: http://stackoverflow.com/q/50192452
score: 0

http://stackoverflow.com/q/50100765
has title: sublabel or supylabel or subxlabel
duplicate of: http://stackoverflow.com/q/16150819
tagged with: matplotlib
has body: Is there a matplotlib function as suptitle but for xlabel and ylabel, something like supylabel, or matlab suplabel EDIT: I opened a ticket about it in matplotlib github: github.com/matplotlib/matplotlib/issues/11147
has comment: http://stackoverflow.com/comment/87220219
linked to: http://stackoverflow.com/q/16150819
has comment: http://stackoverflow.com/comment/87218315
type: Question
has comment: http://stackoverflow.com/comment/87219962
has comment: http://stackoverflow.com/comment/87415536
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87415465
tagged with: python
has comment: http://stackoverflow.com/comment/87220584
score: 0

http://stackoverflow.com/comment/87346452
type: Comment
has text: @DougSmythies: sorry, I forgot the colon at the end of the line. Fixed
type: AnswerComment
comment on: http://stackoverflow.com/a/50164059
score: 0

http://stackoverflow.com/q/50174227
linked to: http://stackoverflow.com/q/35705038
has answer: http://stackoverflow.com/a/50174661
has title: Auto - Incrementing pyspark dataframe column values
tagged with: python
has comment: http://stackoverflow.com/comment/87365798
type: Question
upvote count: 4
type: UnansweredQuestion
has body: I am trying to generate an additional column in a dataframe with auto incrementing values based on the global value.However all the rows are generated with the same value and the value is not incrementing. Here is the code def autoIncrement(): global rec if (rec == 0) : rec = 1 else : rec = rec + 1 return int(rec) rec=14 UDF autoIncrementUDF = udf(autoIncrement, IntegerType()) df1 = hiveContext.sql("select id,name,location,state,datetime,zipcode from demo.target") df1.withColumn("id2", autoIncrementUDF()).show() Here is the result df +---+------+--------+----------+-------------------+-------+---+ | id| name|location| state| datetime|zipcode|id2| +---+------+--------+----------+-------------------+-------+---+ | 20|pankaj| Chennai| TamilNadu|2018-03-26 11:00:00| NULL| 15| | 10|geetha| Newyork|New Jersey|2018-03-27 10:00:00| NULL| 15| | 25| pawan| Chennai| TamilNadu|2018-03-27 11:25:00| NULL| 15| | 30|Manish| Gurgoan| Gujarat|2018-03-27 11:00:00| NULL| 15| +---+------+--------+----------+-------------------+-------+---+ But i am expecting the below result +---+------+--------+----------+-------------------+-------+---+ | id| name|location| state| datetime|zipcode|id2| +---+------+--------+----------+-------------------+-------+---+ | 20|pankaj| Chennai| TamilNadu|2018-03-26 11:00:00| NULL| 15| | 10|geetha| Newyork|New Jersey|2018-03-27 10:00:00| NULL| 16| | 25| pawan| Chennai| TamilNadu|2018-03-27 11:25:00| NULL| 17| | 30|Manish| Gurgoan| Gujarat|2018-03-27 11:00:00| NULL| 18| +---+------+--------+----------+-------------------+-------+---+ Any help is appreciated.
answer count: 1
downvote count: 0
score: 4
favorite count: 0
tagged with: user-defined-functions
tagged with: apache-spark-sql
tagged with: apache-spark
tagged with: pyspark

hdf5
tags question: http://stackoverflow.com/q/50165398
tags question: http://stackoverflow.com/q/50120015
type: Tag
tags question: http://stackoverflow.com/q/50222486
tags question: http://stackoverflow.com/q/50117513
tags question: http://stackoverflow.com/q/50149446
tag name: hdf5

http://stackoverflow.com/comment/87334630
type: QuestionComment
comment on: http://stackoverflow.com/q/50157862
has text: Afaik heroku shows complete installation log while you are pushing, could you please post the log here? And you can also open bash into your heroku container and check that all requirements were installed
score: 0
type: Comment

http://stackoverflow.com/comment/87394360
comment on: http://stackoverflow.com/q/50186375
score: 0
type: QuestionComment
has text: Quite interesting. If I do 'sudo python failing_script.py' it says signalr module is missing if I do it without the 'sudo' it throws another error which is not related to the module import but rather to another peace of code inside of the file.
type: Comment

http://stackoverflow.com/q/50143132
has comment: http://stackoverflow.com/comment/87304721
has comment: http://stackoverflow.com/comment/87304624
has title: 'utf-8' codec can't decode byte 0x95 in position 11: invalid start byte
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87305098
has comment: http://stackoverflow.com/comment/87304503
tagged with: python
has body: I'm using python 3.6 and this is my code: import csv with open('data1.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(row) And then I got this: runfile('/Users/rong/Desktop/untitled0.py', wdir='/Users/rong/Desktop') Traceback (most recent call last): File "&lt;ipython-input-18-a9ca6afc41f8&gt;", line 1, in &lt;module&gt; runfile('/Users/rong/Desktop/untitled0.py', wdir='/Users/rong/Desktop') File "/Users/rong/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/Users/rong/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/Users/rong/Desktop/untitled0.py", line 15, in &lt;module&gt; for row in reader: File "/Users/rong/anaconda3/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in position 11: invalid start byte I'm not sure which encoding should I use for 0x95, anyone helps plese?
has comment: http://stackoverflow.com/comment/87305053
has comment: http://stackoverflow.com/comment/87304887
has comment: http://stackoverflow.com/comment/87304895
has comment: http://stackoverflow.com/comment/87304531
has comment: http://stackoverflow.com/comment/87305080
has comment: http://stackoverflow.com/comment/87304903
tagged with: encoding
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87304925
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87305214
has comment: http://stackoverflow.com/comment/87305067
has comment: http://stackoverflow.com/comment/87305174
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87304963

http://stackoverflow.com/comment/87199253
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50091254
type: Comment
has text: inherit from a class, yes, from an instance? more difficult :) what could be possible would be to redefine `__exit__` on `stdout` itself.

http://stackoverflow.com/comment/87219241
score: 0
comment on: http://stackoverflow.com/a/50101283
type: Comment
type: AnswerComment
has text: @timgeb You are correct about the global argument thing, but I have no idea what he wants to do so I just copy pasted from his code :) I guessed this is what he wanted cause otherwise his question makes zero sense.. Ill wait for clarification anyways..

http://stackoverflow.com/a/50157988
answers question: http://stackoverflow.com/q/50157369
downvote count: 0
has body: You can also use the c_ column assembly object: &gt;&gt;&gt; np.c_[[10,11,12]] array([[10], [11], [12]]) or &gt;&gt;&gt; np.c_[10:13] array([[10], [11], [12]]) or with linspace semantics &gt;&gt;&gt; np.c_[10:12:3j] array([[10.], [11.], [12.]])
has comment: http://stackoverflow.com/comment/139699091
upvote count: 5
type: Answer
score: 5

http://stackoverflow.com/q/50125972
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50129062
has body: i am parsing a HTML page using Beautifulsoup (python3.x) i am trying to get data from < p> tags for which i have written def getBody(url): html_page = requests.get(url) soup = BeautifulSoup(html_page.content, 'html.parser') Con = "".join([p.text for p in soup.find_all("p")]) #print(Con) return Con but in doing so i am getting text from the below htmltag. How can i remove this? Comments are closed for this article.
tagged with: python
has title: how to remove tags of a specific class?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50129062

http://stackoverflow.com/q/50192011
type: Question
tagged with: python
tagged with: python-3.x
tagged with: flask-principal
tagged with: flask-login
has answer: http://stackoverflow.com/a/50199546
score: 2
upvote count: 2
has title: Flask-Principal require Triggering Exception before Flask-Login request_loader Called
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: For some time I've used Flask-Login to handle traditional username/password authentication requests and Flask-Principal to handle authorization checks against routes on subsequent requests. All has been well. I'm now trying to leverage Flask-Login's "request_loader" decorator to handle header-based authentication within the same request that hits protected endpoints. The problem I'm having is that Flask-Principal's "require" decorators seem to be executing before Flask-Login's "request_loader". In the below example, I'm having a 403 Unauthorized HTTP Exception fire before the code even tries to authenticate the user. I must be missing something silly given the point of header-based authentication -- I believe -- is for it execute prior to any endpoint authorization checks... Flask-Login Use: login_manager = LoginManager(app) login_manager.anonymous_user = User login_manager.session_protection = 'strong' @login_manager.request_loader def load_user_from_request(request): # do stuff, return User if found Flask-Principal Use: @blueprint.route('/some/endpoint', methods=['GET']) @read_permission.require(http_exception=403) def some_function(): # Do stuff Edit: As a side note, Flask's "before_request" function seems to be called before any of these others so, in theory, I might be able to handle header-based authentication from there, but it seems dirty not to be using the Flask-Login function designed for this purpose...
favorite count: 0

http://stackoverflow.com/a/50119842
has comment: http://stackoverflow.com/comment/87300340
has comment: http://stackoverflow.com/comment/87299145
downvote count: 0
has comment: http://stackoverflow.com/comment/87333767
has comment: http://stackoverflow.com/comment/87338468
has comment: http://stackoverflow.com/comment/87375827
answers question: http://stackoverflow.com/q/50119668
has body: 'chunck_generator' will return a 'generator' object not an actual element of the chunk. You need to iterate the object to get the chunk out of it. &gt;&gt;&gt; def my_generator(x): ... for y in range(x): ... yield y ... &gt;&gt;&gt; g = my_generator(10) &gt;&gt;&gt; print g.__class__ &lt;type 'generator'&gt; &gt;&gt;&gt; ele = next(g, None) &gt;&gt;&gt; print ele 0 &gt;&gt;&gt; ele = next(g, None) &gt;&gt;&gt; print ele 1 So to fix your code you just need to either loop over the generator for chunk in chunck_generator(filename, header=False,chunk_size = 10 ** 5): yield chunk.to_sql() But it seems convoluted. I would just do this: import pandas.io.sql as psql import pandas as pd from sqlalchemy import create_engine def sql_generator(engine, filename, header=False,chunk_size = 10 ** 5): frame = pd.read_fwf( filename, colspecs=[[0,12],[12,13]], index_col=False, header=None, iterator=True, chunksize=chunk_size ): for chunk in frame: yield chunk.to_sql( 'sample_table', engine, if_exists='replace', schema='sample_schema', index=False ) if __name__ == &quot;__main__&quot;: filename = r'test_file.txt' engine = create_engine('postgresql://USEE:PWD@IP:PORT/DB') for sql in sql_generator(engine, filename): print sql
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/50144309
answers question: http://stackoverflow.com/q/50144173
has comment: http://stackoverflow.com/comment/87306855
type: Answer
has body: I figured it out by going to the github page for the tutorial. Apparently, I had to delete any vec files that had a length of zero.
score: 0

http://stackoverflow.com/q/50081988
has body: I have 6 posts in my database and I want to show 3 posts per page. Everything is working without any error but when I click 'next page' link, same posts are reloading. Here the steps, http://127.0.0.1:8000/blog/ is loading succesfully and there are 3 posts in page. Also, 'next page' link is also on the bottom of the page as expected. When I click nextpage, URL is changing into: http://127.0.0.1:8000/blog/?page=2 But as I said, first page's posts are reloading. url.py: path('',views.getPosts,name="bloghome"), path('/<int:selected_page>/',views.getPosts,name="bloghome"), view.py function about pagination: def getPosts(request,selected_page=1): posts = Posts.objects.all() pages = Paginator(posts,3) #Show 3 post per page try: returned_page = pages.get_page(selected_page) except EmptyPage: returned_page = pages.page(pages.num_pages) return render(request,'blog.html',{'page':returned_page, 'posts':returned_page.object_list }) Post listing page's template: {% extends 'blog_mainpage_assets.html' %} {%load static%} {% block document_body%} {%for post in posts%} {{post.post_title}} {%endfor%} {% if page.has_previous %} Back {% endif %} {% if page.has_next %} Next {% endif %} {% endblock document_body%}
accepted answer: http://stackoverflow.com/a/50083103
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50083103
answer count: 1
tagged with: url
tagged with: query-string
type: Question
has title: Next page button not working same page is reloading
tagged with: pagination
tagged with: django
tagged with: python

http://stackoverflow.com/a/50199907
accepted answer of: http://stackoverflow.com/q/50199606
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87431278
has comment: http://stackoverflow.com/comment/87417079
has comment: http://stackoverflow.com/comment/87426839
has comment: http://stackoverflow.com/comment/87428909
has comment: http://stackoverflow.com/comment/87426826
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87431054
upvote count: 1
answers question: http://stackoverflow.com/q/50199606
has comment: http://stackoverflow.com/comment/87430669
has comment: http://stackoverflow.com/comment/87417409
has body: nltk.pos_tag() returns a list of 2-tuples. The first element of each tuple is the word, the second a part of speech tag corresponding to the word. For example: &gt;&gt;&gt; tagged = nltk.pos_tag('This is a test'.split()) &gt;&gt;&gt; tagged [('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('test', 'NN')] Assuming that you would like to write each word and its tag per line: with open(tagged_file, 'w') as f: for pair in tagged: print(' '.join(pair), file=f) This would create a file containing: This DT is VBZ a DT test NN You can alter the file format as required.

http://stackoverflow.com/a/50184729
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50084448
has body: Your solution works. I'm adding another option for future viewers who might stumble upon this question wanting to specify colors. It is to explicitly specify the text to be "black" using alt.value('black') Admittedly, 'black' is not the same as "unsetting" the encoding, but it could be what someone wants for their plot. c2 = c1.mark_text().encode( text='a', color=alt.value('black') )
type: Answer
score: 2

http://stackoverflow.com/comment/87349777
has text: Bearing in mind that this is only a shallow copy. If (for some insane reason) the individual elements of the hand are mutable, there may still be issues.
comment on: http://stackoverflow.com/a/50165918
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50101238
has comment: http://stackoverflow.com/comment/87220331
answers question: http://stackoverflow.com/q/50100635
score: 8
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87220040
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50100635
has body: In case you want to highlight two rows (say index 2 and 4) it is a almost a duplicate of this answer new_df.style.apply(lambda x: ['background: lightgreen' if x.name in [2,4] else '' for i in x], axis=1) If instead you are looking to highlight every row that contain a given name in a list (i.e. lst = ['car', 'boat']) you can use new_df.style.apply(lambda x: ['background: lightgreen' if (set(lst).intersection(x.values)) else '' for i in x], axis=1)
upvote count: 8
type: Answer

http://stackoverflow.com/comment/87384970
has text: There was a time where I could download vs code, install an extension, and be writing and debugging scripts in minutes. Time to jump ship yet?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50181124

http://stackoverflow.com/q/50156653
has comment: http://stackoverflow.com/comment/87331197
score: 2
tagged with: random
tagged with: while-loop
has body: Apologies in advance for the Python 101 nature of this question. I have yet to wrap my mind around while loops. This example is a homework assignment from a book for beginners: Write a program that randomly opens different fortune cookies and prints each message. The user only needs to hit 'enter' to open one cookie after another. Here is what I have so far... import random cookie_number=random.randrange(3)+1 prompt="" while not prompt: prompt=input("Open Cookie") if cookie_number==1: print("your lucky numbers are 3, 22, 107") elif cookie_number==2: print("you are lucky in love today") elif cookie_number==3: print("buy stocks today") else: print("stay away from MSG")
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87331777
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: Using "random" in a python prog. with "while", "if" and elif"
has answer: http://stackoverflow.com/a/50156770

http://stackoverflow.com/comment/87271303
type: AnswerComment
has text: Then you have your answer. Your CMD is wrong. You probably meant to write `CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]`
score: 1
comment on: http://stackoverflow.com/a/50126665
type: Comment

http://stackoverflow.com/a/50148898
has comment: http://stackoverflow.com/comment/87316020
type: AcceptedAnswer
type: Answer
has body: You seem to be destroying the window after you change the label to "Access Granted": mainlog.destroy() If you remove destroying the window, "Access Granted" is displayed. If you really want the window to be destroyed after logging in successfully, add mainlog.update() before sleep(1). if access == True: lberror.config(text= "Access Granted") mainlog.update() sleep(1) mainlog.destroy() return access return mode
accepted answer of: http://stackoverflow.com/q/50148819
score: 0
answers question: http://stackoverflow.com/q/50148819

http://stackoverflow.com/a/50161107
has comment: http://stackoverflow.com/comment/87340667
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87340687
accepted answer of: http://stackoverflow.com/q/50161081
has comment: http://stackoverflow.com/comment/87340484
has comment: http://stackoverflow.com/comment/87340744
has comment: http://stackoverflow.com/comment/87340777
has comment: http://stackoverflow.com/comment/87340528
type: Answer
has body: You can also set ignore_index=True when appending. df_output = df_i.append(df_output, ignore_index=True) Also you can concatenate the dataframes: df_output = pd.concat((df_output, df_i), axis=0, ignore_index=True) As @jpp suggested in his answer, you can load the list of dataframes and concatenate them in 1 go.
answers question: http://stackoverflow.com/q/50161081
has comment: http://stackoverflow.com/comment/87340730
score: 1

http://stackoverflow.com/a/50120613
has comment: http://stackoverflow.com/comment/87262986
score: 16
type: Answer
upvote count: 16
answers question: http://stackoverflow.com/q/50110571
has comment: http://stackoverflow.com/comment/110643308
has comment: http://stackoverflow.com/comment/87262214
has body: Signal 18 is just the handler for Ctrl+Z. (Technically it maps to SIGTSTP.) The signal tells the process to suspend. Since the signal is generally meaningless to a Windows process, git-bash suppresses the message, but it still lets you know that it suppressed that signal. Unfortunately, MinTTY, the default git-bash terminal, doesn't connect up the console correctly for native Windows console applications. So even ignoring the warning message, the python interpreter isn't really working correctly anyway. (More info) In order to get python hooked up correctly you need to use winpty to launch python. The command: winpty python test.py will work. You could also use git-cmd if you need access to git commands, or open a standard Windows command prompt and run python there if you don't.
downvote count: 0

http://stackoverflow.com/comment/87447680
comment on: http://stackoverflow.com/a/50208197
type: AnswerComment
has text: Thanks, everything I needed. It really moves me forward with some python concepts I was having trouble with.
score: 0
type: Comment

http://stackoverflow.com/comment/87359321
score: 0
type: AnswerComment
has text: Hmm, I did notice I had a typo in the command. It should be `pyvenv`, not `pyenv`. If you copied the wrong command from my answer, could you please try again? Sorry about that!
type: Comment
comment on: http://stackoverflow.com/a/50169687

http://stackoverflow.com/q/50217922
score: 1
tagged with: serial-port
tagged with: timeout
tagged with: python
has answer: http://stackoverflow.com/a/50447211
answer count: 2
type: UnansweredQuestion
has body: I am working on opening communication with an Agilent power supply using PyVISA, and I keep getting a timeout error when I query for the instrument Id. My code is: import visa rm = visa.ResourceManager() res = rm.list_resources() print("Find following resources: ") print(res) print("Opening " + res[-1]) inst = rm.open_resource(res[-1]) inst.timeout = 100000 # timeout 100s inst.write_termination = '\n' inst.read_termination = '\n' print(inst.query('*IDN?')) The output I am getting is: Find following resources: (u'ASRL5::INSTR',) Opening ASRL5::INSTR Traceback (most recent call last): File "&lt;ipython-input-10-66ffef23c46a&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Sabri/Anaconda2/untitled0.py', wdir='C:/Users/Sabri /Anaconda2') File "C:\Users\Sabri\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Users\Sabri\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 86, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Users/Sabri/Anaconda2/untitled0.py", line 20, in &lt;module&gt; print(inst.query('*IDN?')) File "C:\Users\Sabri\Anaconda2\lib\site-packages\pyvisa\resources\messagebased.py", line 564, in query return self.read() File "C:\Users\Sabri\Anaconda2\lib\site-packages\pyvisa\resources\messagebased.py", line 413, in read message = self._read_raw().decode(enco) File "C:\Users\Sabri\Anaconda2\lib\site-packages\pyvisa\resources\messagebased.py", line 386, in _read_raw chunk, status = self.visalib.read(self.session, size) File "C:\Users\Sabri\Anaconda2\lib\site-packages\pyvisa\ctwrapper\functions.py", line 1584, in read ret = library.viRead(session, buffer, count, byref(return_count)) File "C:\Users\Sabri\Anaconda2\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 188, in _return_handler raise errors.VisaIOError(ret_value) VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed. I have tried specifying the termin…
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: PyVISA RS232 Timeout Error (Agilent Power Supply)
has answer: http://stackoverflow.com/a/61134681
tagged with: pyvisa

http://stackoverflow.com/q/50138213
upvote count: 1
answer count: 1
favorite count: 0
has body: I have a dbf file with about 9 million records and 2.5 GB size. A lot of space is taken up by a 80 size character field used to store 1 of about 10 different character strings. To save on file size, I want to replace the character field by an integer field and use a relational database at a later stage to get the full character field if needed. Currently I have the following Python script which uses the dbf library (http://pythonhosted.org/dbf/). The script seems to be working (tested on a smaller dbf file), but it runs for several hours when I try to run it with the full dbf file. import dbf tabel = dbf.Db3Table('dataset.dbf') tabel.open() with tabel: tabel.add_fields('newfield N(2, 0)') for record in tabel: if record.oldfield == 'string_a ': dbf.write(record, newfield=1) elif record.oldfield == 'string_b ': dbf.write(record, newfield=2) elif record.oldfield == 'string_c ': dbf.write(record, newfield=3) elif record.oldfield == 'string_d ': dbf.write(record, newfield=4) elif record.oldfield == 'string_e ': dbf.write(record, newfield=5) elif record.oldfield == 'string_f ': dbf.write(record, newfield=6) elif record.oldfield == 'string_g ': dbf.write(record, newfield=7) elif record.oldfield == 'string_h ': dbf.write(record, newfield=8) elif record.oldfield == 'string_i ': dbf.write(record, newfield=9) elif record.oldfield == 'string_j ': dbf.write(record, newfield=10) else: dbf.write(record, newfield=0) dbf.delete_fields('dataset.dbf', 'oldfield') As you may be able to see from the code, I am new to both Python and the dbf library. Can this script be made to run more efficiently?
type: Question
has title: How could I improve this Python script to replace records in dbf file?
has comment: http://stackoverflow.com/comment/87295341
tagged with: python
has answer: http://stackoverflow.com/a/50139561
accepted answer: http://stackoverflow.com/a/50139561
type: AnsweredQuestion
tagged with: dbf
downvote count: 0
score: 1

http://stackoverflow.com/comment/87320514
score: 0
has text: *I want to strip off the "[" and "]"* Ok so what is the Python string function to strip specific characters. e.g. whitespace and then brackets? Or substitute ' [' with ''? You need to show a little effort, SO is not a code-writing service. Did you notice after you strip ' [' that your string of numbers has regular chunks of length 11?
type: QuestionComment
comment on: http://stackoverflow.com/q/50151163
type: Comment

http://stackoverflow.com/q/50210087
answer count: 1
has title: Replacing numbers by random numbers in a changing file in Python/C++
linked to: http://stackoverflow.com/q/4289331
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50211639
accepted answer: http://stackoverflow.com/a/50211639
has comment: http://stackoverflow.com/comment/87440708
has body: I need to mix my data. I've got some numbers in a file and I need it to be mixed, like for example, change all 4's on 20, but don't change 14's to 120's doing this. I thought a lot and I'm not really sure if it's possible, because there's a big number of digits and I need to do replacement hundred times with a random values. Anyone did something like that? Anyone knows it's possible?
tagged with: python
has comment: http://stackoverflow.com/comment/87438671
type: Question
tagged with: c++
score: 0
has comment: http://stackoverflow.com/comment/87438068
has comment: http://stackoverflow.com/comment/87438502

http://stackoverflow.com/q/50074969
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87186575
has comment: http://stackoverflow.com/comment/87168886
tagged with: boto3
tagged with: amazon-web-services
has title: How to store text file with utf-8 encoding into AWS S3 bucket?
type: Question
score: 0
tagged with: amazon-s3
tagged with: python
has body: I am just wondering how to write a text file encoded with utf-8 into AWS S3 directly, without needing to save that text file (temporarily or not) into local computer. To be concrete, as shown below, I think I could manage to save the file, which was downloaded from the web and was parsed with BeautifulSoup library locally, and to store that file into the designated S3 bucket. import codecs import boto3 import requests from bs4 import BeautifulSoup url = 'https://www.sec.gov/Archives/edgar/data/732247/0000950144-00-012588.txt' r = requests.get(url) soup = BeautifulSoup(r.content, "lxml") text = soup.get_text("\n") txt_path = 'report.txt' # Saving the parsed file into local directory in the name of 'report.txt' with codecs.open(txt_path, 'w', encoding='utf-8') as fout: fout.write(text) # Loading the parsed file 'report.txt' and saving it into AWS S3 # with the 'my-bucket-name' as the bucket name # and 'report_s3.txt' as the file name in that bucket s3 = boto3.resource('s3') with codecs.open('report.txt', 'rb', encoding='utf-8') as fin: text = fin.read() s3.Object('my-bucket-name', 'report_s3.txt').put(Body=text) But, I would like to skip that local-saving process and want to directly save that parsed file with utf-8 encoding into S3 bucket. Is there any good idead to do that? Thank you in advance!
answer count: 0

http://stackoverflow.com/comment/87290432
has text: With what you have here, it seems like a pretty good question. Did you try the `conda activate` command I suggested?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50093121

http://stackoverflow.com/comment/87373738
comment on: http://stackoverflow.com/q/50178055
has text: Thanks! Perfect.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50118240
has title: Perform calculation on multiple columns at once with pandas
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50118327
downvote count: 0
accepted answer: http://stackoverflow.com/a/50118292
has answer: http://stackoverflow.com/a/50118292
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/87253816
has body: I have a big dataframe with more than 1 million rows. The current df has only columns X,a,b,c. I want to perform a calculation that yields new columns: new_a,new_b,new_c (see picture) The calculation is: new_a = a/(X^2) I already have a way to do it in python: col_list = ['a','b','c'] def new(col,X): score = col/(X**2) return score new_col = ['new_a','new_b','new_c'] def calculate(df): for i in range(len(new_col)): df[new_col[i]] = df.apply(lambda row: new(row[col_list[i]],row['X']),axis=1) calculate(df) I wonder if there is another way to achieve the same goal? This current way of doing it is fine but takes a lot of time to run and somehow yields weird results for certain operations. Thank you.
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50118327

http://stackoverflow.com/a/50128477
upvote count: 1
score: 1
has body: The problem is just that you're not importing the modules correctly. Just as you use import spam, not import spam.py, for a Python module, you use import spam, not import spam.cp35-win_amd64 for an extension module. Notice that the example you linked to does it like that: &gt;&gt;&gt; import helloworld Hello World If you're wondering why you got exactly the error you did: the - character isn't part of a name, it's an arithmetic operator. So you were telling it you want to import the module cp35 - win_amd64 from the package spam, and that confused the parser, so it gave you a SyntaxError. Since you asked about your particular toolset: Yes, those all work together. In fact, as documented on the wiki, all Python 3.5 installers from python.org are built with Visual C++ 14.0, which is the compiler that comes with Visual Studio 2017, and come with a distutils that can automatically detect and use it. (If you have an old version of setuptools—type pip show setuptools to see if the version number is at least 34.4.0—it can cause problems, but those problems prevent Cython packages from compiling at all.)
has comment: http://stackoverflow.com/comment/87275889
answers question: http://stackoverflow.com/q/50128198
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87196183
type: AnswerComment
has text: Yes, Feel free to ask questions.
comment on: http://stackoverflow.com/a/50089850
score: 0
type: Comment

http://stackoverflow.com/q/50165399
has comment: http://stackoverflow.com/comment/87350600
accepted answer: http://stackoverflow.com/a/50166512
tagged with: python
has answer: http://stackoverflow.com/a/50166512
tagged with: scipy
score: 2
has comment: http://stackoverflow.com/comment/87350703
has comment: http://stackoverflow.com/comment/87351129
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I have a dataset like this: elevation Tree_cover dNBR below_ground_carbon_combusted DOB_lst 0 266.444444 39.555556 0.47 1110.603930 221.879608 1 683.222222 7.555556 0.48 2901.511339 236.847916 2 270.777778 44.111111 0.54 5822.440530 222.909241 3 473.444444 76.333333 0.73 4643.891015 183.100876 4 470.666667 79.888889 0.64 5919.393383 183.100876 5 486.333333 76.444444 0.68 5120.039877 183.100876 6 453.000000 79.222222 0.63 7090.889123 183.100876 7 412.555556 73.888889 0.48 2636.000936 183.100876 8 628.000000 45.444444 0.60 10075.698853 195.514770 9 631.555556 3.000000 0.45 6144.187670 178.886703 And I want to fit a curve to the data with scipy's optimized curve like so: from scipy.optimize import curve_fit from math import e import pandas as pd def func(data, c1, c2, c3, c4, c5, c6, c7): var1 = (-(df['elevation'] - c6)**2) var2 = 2 * c7 var3 = var1 / var2 return (c1 + c2) * (e**c3 * df['dNBR']) * (e**c4 * df['Tree_cover']) * (e**c5 * df['DOB_lst']) * e**var3 popt, pcov = curve_fit(func, df.drop(['below_ground_carbon_combusted'], axis = 1), df['below_ground_carbon_combusted']) but I can an error saying the curve can't be optimized and I can't figure out why since with other functions (which are simpler) this general workflow works fine. This is the full error: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning)
type: AnsweredQuestion
has title: Scipy Optimized Curve - warning the covariates could not be estimated
tagged with: pandas

http://stackoverflow.com/a/50096593
has comment: http://stackoverflow.com/comment/87209692
has comment: http://stackoverflow.com/comment/87209600
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87209485
has body: I would recomand to follow those steps: Find a correlation between dates and number of sales or any other variables (but i think date will do the trick people buy more stuff on holidays and weekends usually ) you can use the numpy library for that here assuming that the sales follows seasonal trends or weekends picks sales, you should compute those features based on dates you can add columns to your data frame such as dayofweek , season .. , pandas is great for that dt.dayofweek its as simple as that, split your data to train set and test set. Now cool stuff, you can try Linear regression using the sklearn here i think it will work great! you can try other algorithm as well such as Ridge regression... alot of examples can be found on the sklearn web site http://scikit-learn.org Evaluate your model !
accepted answer of: http://stackoverflow.com/q/50096372
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50096372

minimax
type: Tag
tag name: minimax
tags question: http://stackoverflow.com/q/50192878

http://stackoverflow.com/q/50197186
has body: I'm sort of new to python, and using Anaconda3-5.1.0 on windows 10 i need to install package kwant, kwant is n't coming for anaconda windows , so i try pip install it ,after some struggle and reading here I found kwant-1.3.2-cp36-cp36m-win_amd64.whl so it match the platform , but this package need scipy and numpy and this comes with anaconda and when i try to pip install kwant ,i get this THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them. scipy&gt;=0.14 from https://files.pythonhosted.org/packages/62/e2/364f0bcc641aeff79d743c732769d5dc31a1e78c27699229431412c4b425/scipy-1.1.0-cp36-none-win_amd64.whl#sha256=698c6409da58686f2df3d6f815491fd5b4c2de6817a45379517c92366eea208f (from kwant==1.3.2): Expected sha256 698c6409da58686f2df3d6f815491fd5b4c2de6817a45379517c92366eea208f Got 7072c63cb59028a73b639b354c0054525b002ef2d87a1d45ed7cdeba736b5cc6 numpy&gt;=1.8.1 from https://files.pythonhosted.org/packages/af/e4/7d7107bdfb5c33f6cf33cdafea8c27d1209cf0068a6e3e3d3342be6f3578/numpy-1.14.3-cp36-none-win_amd64.whl#sha256=560e23a12e7599be8e8b67621396c5bc687fd54b48b890adbc71bc5a67333f86 (from kwant==1.3.2): Expected sha256 560e23a12e7599be8e8b67621396c5bc687fd54b48b890adbc71bc5a67333f86 Got 143abb1baa1e5a3427ed09a4f52223aa3947bf76ca25dc4c71da0c2ae663040a as i said I have updated scipy and numpy packages so how could i update the HASHES so i can use kwant package
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/54231274
type: Question
upvote count: 3
type: UnansweredQuestion
tagged with: package
downvote count: 0
favorite count: 0
has title: How to update packages hashes?
score: 3

http://stackoverflow.com/comment/87467904
type: QuestionComment
comment on: http://stackoverflow.com/q/50225203
type: Comment
has text: `[u'1']` is not comparable to `'1'` (list vs string).
score: 0

http://stackoverflow.com/comment/87259539
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50120775
has text: Well why are you using that module at all? Maybe read their docs, they'll probably explain what the purpose of it is.
type: Comment

http://stackoverflow.com/a/50104456
score: 7
has comment: http://stackoverflow.com/comment/87227500
type: AcceptedAnswer
upvote count: 7
has comment: http://stackoverflow.com/comment/87227493
has comment: http://stackoverflow.com/comment/87227086
has comment: http://stackoverflow.com/comment/87227605
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87227994
answers question: http://stackoverflow.com/q/50104370
has comment: http://stackoverflow.com/comment/87226414
has comment: http://stackoverflow.com/comment/87226561
has comment: http://stackoverflow.com/comment/87226376
has body: Just print in a double loop using shifted indices and modulo: Numberset1 = [10,11,12] Numberset2 = [1,2,3,4,5] for i,n in enumerate(Numberset1): for j in range(len(Numberset2)): print(n,Numberset2[(j+i) % len(Numberset2)]) result: 10 1 10 2 10 3 10 4 10 5 11 2 11 3 11 4 11 5 11 1 12 3 12 4 12 5 12 1 12 2 or generate the tuples using list comprehension: [(n,Numberset2[(j+i) % len(Numberset2)]) for i,n in enumerate(Numberset1) for j in range(len(Numberset2))] which gives: [(10, 1), (10, 2), (10, 3), (10, 4), (10, 5), (11, 2), (11, 3), (11, 4), (11, 5), (11, 1), (12, 3), (12, 4), (12, 5), (12, 1), (12, 2)] how it works: Numberset2[(j+i) % len(Numberset2)] is accessing the jth index of Numberset, with, added the offset of the outer bound (0, 1, ... etc...) If we leave j+i it reaches len(Numberset2) and we get array out of bounds exception. To make sure that index is shifted and remains in range, we add a modulo operator so it wraps around.
has comment: http://stackoverflow.com/comment/87227474
has comment: http://stackoverflow.com/comment/87226185
accepted answer of: http://stackoverflow.com/q/50104370

http://stackoverflow.com/a/55848505
has comment: http://stackoverflow.com/comment/119140416
has comment: http://stackoverflow.com/comment/100796830
has comment: http://stackoverflow.com/comment/138990861
downvote count: 1
answers question: http://stackoverflow.com/q/50149562
has comment: http://stackoverflow.com/comment/100794552
has comment: http://stackoverflow.com/comment/118798740
score: 98
has comment: http://stackoverflow.com/comment/101690935
has body: JupyterLab 3.0+ Install jupyterlab and ipympl. For pip users: pip install --upgrade jupyterlab ipympl For conda users: conda update -c conda-forge jupyterlab ipympl Restart JupyterLab. Decorate the cell containing plotting code with the header: %matplotlib widget # plotting code goes here JupyterLab 2.0 Install nodejs, e.g. conda install -c conda-forge nodejs. Install ipympl, e.g. conda install -c conda-forge ipympl. [Optional, but recommended.] Update JupyterLab, e.g. conda update -c conda-forge jupyterlab==2.2.9==py_0. [Optional, but recommended.] For a local user installation, run: export JUPYTERLAB_DIR="$HOME/.local/share/jupyter/lab". Install extensions: jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter labextension install jupyter-matplotlib Enable widgets: jupyter nbextension enable --py widgetsnbextension. Restart JupyterLab. Decorate with %matplotlib widget.
has comment: http://stackoverflow.com/comment/108493794
has comment: http://stackoverflow.com/comment/119171005
has comment: http://stackoverflow.com/comment/111891963
has comment: http://stackoverflow.com/comment/99781626
upvote count: 99
type: Answer
has comment: http://stackoverflow.com/comment/118797461
has comment: http://stackoverflow.com/comment/119171087
has comment: http://stackoverflow.com/comment/122255242
has comment: http://stackoverflow.com/comment/105740972

http://stackoverflow.com/a/50156689
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50156579
type: Answer
has body: Change the related_name from user to userprofile user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') and to not forget to passe the user into context.
downvote count: 0

http://stackoverflow.com/q/50080496
score: 0
answer count: 1
type: Question
has title: Embed an http server in a long running python process
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/50081629
tagged with: tornado
has body: Using python 3. Lets say I am processing a loop around a large database query. Effectively my loop around the result set cursor can be a billion iterations. I'd like to give a user an ability to call out to an http server embedded in the same process that would give some statistics on the progress of the query. So far I have tried this with IOLoop using Tornado http server. The problem is that I have to basically transfer the control back to IOLoop on some number of rows to get the HTTP request to get serviced. That seems wasteful. Transferring that control has a price. Tornado would let me support multiple connections, but I don't actually care for that - one connection is fine. What I would prefer would be to simply interrupt the loop, service the HTTP request and resume.

http://stackoverflow.com/a/50142307
has body: I figured out what I was doing wrong - I saved a stale link to the container before bulk creating it. Bulk creating it put one copy of the row in the database. Then, when I used the stale link (and saved), that put in a second copy of the row - this one without any children pointing up towards it. The solution was to move the stale link until after the bulk create, like this: bulk_insert_id = uuid.uuid4() requirements = [] for requirement in self.children: r = models.Container( parent=self.db, bulk_insert_id=bulk_insert_id, ) requirements.append(r) # don't use the link here, it will be stale when we make the requirements models.Container.objects.bulk_create(requirements) requirements = models.Container.objects.filter(bulk_insert_id=bulk_insert_id) # new stuff for requirement, child in zip(requirements, self.children): child.db_id = requirement
type: Answer
answers question: http://stackoverflow.com/q/50142058
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50142058

http://stackoverflow.com/a/50196298
downvote count: 0
type: AcceptedAnswer
has body: From the canonical tcl/tk documentation: A word consists of any number of adjacent characters that are letters, digits, or underscores, or a single character that is not one of these. If the display submodifier is given, this only examines non-elided characters, otherwise all characters (elided or not) are examined. In your case the character after "3.0" is # which is "not one of these", so that single character is considered to be a word, and thus the "wordend" modifier stops after that single character. If you want a hashtag plus the word following it to be given the tag, your second index should be of the form "line.char+1c wordend" (eg: "3.0+1c wordend") so that you look for the end of the word beginning with the first character after the hash, not beginning with the hash itself.
accepted answer of: http://stackoverflow.com/q/50195694
type: Answer
answers question: http://stackoverflow.com/q/50195694
score: 2
upvote count: 2

http://stackoverflow.com/a/50308083
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50170588
downvote count: 0
upvote count: 2
has body: I use to install my virtual envs with pipenv that installs pew as a requirement. pew lets you install temporary virual environments that are deleted as you exit those special virtual environments. So... Make a new empty virtual environment and activate it on the fly: pew mktmpenv -p /usr/bin/python3.6 Install your package: pip install somedistro See what are the requirements of your distro (as well as requirements of requirements...): pip list Deactivate and delete the temporary environment. exit In addition, temporary virtual environments are very useful at packaging tests.

tensorboard
tags question: http://stackoverflow.com/q/50206882
type: Tag
tags question: http://stackoverflow.com/q/50171872
tags question: http://stackoverflow.com/q/50132514
tags question: http://stackoverflow.com/q/50082220
tags question: http://stackoverflow.com/q/50122654
tags question: http://stackoverflow.com/q/50169767
tag name: tensorboard

http://stackoverflow.com/a/50177265
type: Answer
has comment: http://stackoverflow.com/comment/87372246
has comment: http://stackoverflow.com/comment/87372863
has comment: http://stackoverflow.com/comment/87371657
has comment: http://stackoverflow.com/comment/87371692
has comment: http://stackoverflow.com/comment/87372196
score: 0
has body: @EduardoRibeiro, "i just dont know how to add the spaces" -- so, is that all you want to know? – palivek yes, how can i add spaces before and after '(' and ')' – Eduardo Ribeiro I would go with listcomp: def expander(exp): special = ('(', ')') return ''.join(c if c not in special else c + ' ' for c in exp) Which would give: &gt;&gt;&gt; expander("(define x 5) ( + (* 2 x) 7)") '( define x 5) ( + ( * 2 x) 7) ' EDIT: that wont work becouse i need spaces between 5 and ) and between 7 and ) But you gave me the general idea, thank you – Eduardo Ribeiro 13 mins ago def expander(exp): chars = ('(', ')') return ''.join(c if c not in chars else ' ' + c + ' ' for c in exp) Which gives: &gt;&gt;&gt; expander("(define x 5) ( + (* 2 x) 7)") ' ( define x 5 ) ( + ( * 2 x ) 7 ) '
answers question: http://stackoverflow.com/q/50176817
has comment: http://stackoverflow.com/comment/87372293
has comment: http://stackoverflow.com/comment/87373227
has comment: http://stackoverflow.com/comment/87371769

variables
tags question: http://stackoverflow.com/q/50106148
tag name: variables
tags question: http://stackoverflow.com/q/50108263
tags question: http://stackoverflow.com/q/50078664
tags question: http://stackoverflow.com/q/50152084
tags question: http://stackoverflow.com/q/50206468
tags question: http://stackoverflow.com/q/50212975
tags question: http://stackoverflow.com/q/50104938
tags question: http://stackoverflow.com/q/50198256
tags question: http://stackoverflow.com/q/50075613
tags question: http://stackoverflow.com/q/50092443
tags question: http://stackoverflow.com/q/50225015
tags question: http://stackoverflow.com/q/50156626
tags question: http://stackoverflow.com/q/50203009
tags question: http://stackoverflow.com/q/50098611
tags question: http://stackoverflow.com/q/50145969
tags question: http://stackoverflow.com/q/50165912
type: Tag
tags question: http://stackoverflow.com/q/50075317

http://stackoverflow.com/comment/87184826
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50084497
score: 2
has text: @PM2Ring: I think that could have a _lot_ of bearing on the speed difference! (Various Python versions have hacks that prevent particular common forms of repeated concatenation having quadratic running time; I don't remember which version(s) the hack(s) were introduced in, though.)

http://stackoverflow.com/q/50114303
score: 0
has title: Ignore external sources being compressed in mezzanine
tagged with: mezzanine
type: Question
has answer: http://stackoverflow.com/a/50128335
has body: Tring to load external source in contact form template, mezzanine Example {% block extra_js %} {{ block.super }} &lt;script src="https://www.google.com/recaptcha/api.js" async defer&gt;&lt;/script&gt; {% endblock %} Compressor exception compressor.exceptions.UncompressableFileError: 'https://www.google.com/recaptcha/api.js' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed
possible better answer: http://stackoverflow.com/a/74728765
tagged with: django
tagged with: python
tagged with: django-compressor
has answer: http://stackoverflow.com/a/74728765
accepted answer: http://stackoverflow.com/a/50128335
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/87463265
has text: when i do hostname on command line, i get the name of my laptop. is that correct?
type: AnswerComment
comment on: http://stackoverflow.com/a/50222778
score: 0
type: Comment

http://stackoverflow.com/a/50125594
accepted answer of: http://stackoverflow.com/q/50125386
has body: What you are looking for is slope or first order difference more exactly, to get an idea where the curve starts to smooth out, you can calculate the first order difference / slope and find out the first index where the slope is below a certain threshold: import matplotlib.pyplot as plt import numpy as np x = np.array(range(10)) y = np.array([0.3, 0.37, 0.41, 0.52, 0.64, 0.68, 0.71, 0.72, 0.73, 0.74]) slopes = np.diff(y) / np.diff(x) idx = np.argmax(slopes &lt; 0.02) # find out the first index where slope is below a threshold fig, ax = plt.subplots() ax.plot(x, y) ax.scatter(x[idx], y[idx], s=200, facecolors='none', edgecolors='r')
type: AcceptedAnswer
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/50125386
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/87276019

http://stackoverflow.com/q/50228982
accepted answer: http://stackoverflow.com/a/50230049
tagged with: matplotlib
has body: I am trying to plot a histogram using the matplotlib.hist() function. Below code is not getting the correct histogram X axis is the years (age), X axis I want to have 0 20, 25, 30, 35, 40, 45, 50, 55 Y axis is the probability Someone can help me to get the correct histogram ? import matplotlib.pyplot as plt list_age = ['26','28','26','36','38','31','22','31','25','30','37','27','27','29','27','21','27','38','31','41','28','31','28','33','26','39','37','24','31','34','39','33','22', '30','24','29','28','34','27','28','26','26','25','40','24','37','24','28','26','29','26','31','23','31','36','32','25','31','25','33','36','27','28', '25','27','39','36','30','31','34','23','31','32','31','33','32','39','35','35','22','34','25','35','35','41','20','21','35','32','30','22','21','23','33','25','30','24','39','24','27','22','33','30','27','30','23','29','30','22','31','29','31','24','29','25','24','26','29','31','24','32','21','25','29','30'] list_age.sort() bins = 55 plt.hist(list_age, bins, facecolor='g') plt.xlabel('Years') plt.ylabel('Probability') plt.grid(True) plt.show()
has title: Plot a histogram using Python with manual bins
type: Question
tagged with: python-3.x
answer count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50230049

http://stackoverflow.com/comment/87243569
type: QuestionComment
comment on: http://stackoverflow.com/q/50111612
has text: The documentation that you've linked to for the `apply` function explains that these are the indices of the leaves that each sample ends up at.
score: 1
type: Comment

http://stackoverflow.com/a/50137408
answers question: http://stackoverflow.com/q/50137367
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87294932
type: Answer
has comment: http://stackoverflow.com/comment/87294736
has body: Since you tagged numpy, you should use it for indexing / slicing. Here's an example: res = np.array([-1000 for x in range(0,10)]) res[1]=2 res[5]=3 res[7]=4 output = np.mean(res[res &gt; -1000]) # 3.0 Read the numpy docs for more details on indexing logic.
accepted answer of: http://stackoverflow.com/q/50137367
has comment: http://stackoverflow.com/comment/87294957
has comment: http://stackoverflow.com/comment/87294510
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/87294843

http://stackoverflow.com/comment/87207150
type: QuestionComment
comment on: http://stackoverflow.com/q/50095233
has text: please show `FileSerializer` and model
score: 0
type: Comment

http://stackoverflow.com/q/50112359
downvote count: 3
linked to: http://stackoverflow.com/q/8370206
has title: How to get the list of all built in functions in Python
favorite count: 0
upvote count: 17
type: Question
tagged with: python-3.x
has body: How to get the list of all built in functions in Python from Python prompt/command line as we get the list of keywords from it?
has answer: http://stackoverflow.com/a/50112452
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50112479
has comment: http://stackoverflow.com/comment/87241918
tagged with: python
tagged with: python-3.6
linked to: http://stackoverflow.com/q/22864221
tagged with: built-in
answer count: 2
score: 14
has comment: http://stackoverflow.com/comment/87242114
tagged with: function
duplicate of: http://stackoverflow.com/q/22864221
has comment: http://stackoverflow.com/comment/87242245

http://stackoverflow.com/a/50086011
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50085833
accepted answer of: http://stackoverflow.com/q/50085833
has body: If the element might not have that attribute, use element.get('AboutMe') to get the attribute value or None if the attribute is not present. get is a standard function for ElementTree implementations. https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get

http://stackoverflow.com/comment/87312224
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50146993
has text: I tried that. Append will not work either, previous append gets overwritten when the stack pops
score: 0

http://stackoverflow.com/comment/87351899
type: Comment
comment on: http://stackoverflow.com/a/50166899
score: 0
type: AnswerComment
has text: Could it be that you're confused about what I'm asking? I'm not asking about _why_ it works, I'm asking about _how_. I understand that lists have order and sets do not. Anywho, the other answer already provided me the documentation.

http://stackoverflow.com/comment/87359174
comment on: http://stackoverflow.com/q/50170814
score: 2
has text: Welcome to SO. Please show us what you have tried so far by adding some relevant code. Have a look at [How to provide a Minimal Example](https://stackoverflow.com/help/mcve)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50211473
accepted answer: http://stackoverflow.com/a/50212204
tagged with: dataframe
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
answer count: 1
has title: Join DataFrames on multiple columns in order to get precised results
downvote count: 0
has body: I have some problems with pandas dataframes join. This is frustrating because it is full of the misspellings and errors. There are two dataframes: the customer dataframe (cust_df) and the credit cards dataframe (cc_df). Both dataframes contains : its id column, name, date of birth, national id number and mobile number. I want to get CUST_ID (from custdf) for every CC_ID (from ccdf). Usually we can do pd.join then stated the key columns; however in this case the unique keys are not accurate (some of them are wrong) thats why multiple columns are needed. Below are the example: Sample data for cust_df: CUST_ID , NAME , DOB, NTLNO , MOBILE 231412 ,W CUMI , 17/02/1989 00:00 , 952547890 ,85320818335 123433 ,S KAMU W , 28/04/1989 00:00 , 444466213 ,81217354673 324123 ,K D SUMI , 05/01/1983 00:00 , 677676999 ,82938489231 324123 ,M SAMI , 17/02/1989 00:00 , 657567577 , 81217354674 231432 ,MOSE N , 17/02/1989 00:00 , 123423355 ,83320818575 Sample data for cc_df: CC_ID , FNAME,MNAME,LNAME,DOB,NTLNO,MOBILE 1234 , MOSE, NAMU, ,17/02/1989 00:00 , 123423355, 83320818575 2345 , MAWON, ,SAMI, 17/02/1989 00:00, 657567577, 81217354674 3243 , KOME, DODO, SUMI, 05/01/1983 00:00, 76999, 82938489331 4365 , SAPI, KAMU, WEWE , 28/04/1989 00:00 , 444466213, 81217354673 4534 , WAKU, CUMI, ,17/02/1989 00:00 , 52547890, 85320818335 The problems are: 1. Name, In cc_df, the names are separated while in cust_df names are concatenated, sometimes in its short form. Example: Sumi Cumi -> S Cumi. 2. NTLNO &amp; MOBILE NTLNO &amp; MOBILE are unique identifiers but because of the wrong input some of it are wrong. What is the most accurate way to get the CUST_ID for every CC_ID ?
has comment: http://stackoverflow.com/comment/87439959
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50212204

http://stackoverflow.com/comment/87457679
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50220058
has text: Thanks so much, this does seem to do it! Is there any reason this my `Date` format to: `2018-04-29` instead of the `'%m/%d/%Y'` I have specified?
type: Comment

http://stackoverflow.com/comment/87292905
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50136944
has text: I edited the post @jpp Abe
score: 0

http://stackoverflow.com/comment/87427683
comment on: http://stackoverflow.com/a/50204534
type: AnswerComment
score: 0
type: Comment
has text: read below please

http://stackoverflow.com/a/50191097
has body: You can use the "Convert to CSV" module and download the dataset. To use in Azure Notebooks, in a library that you want to use you can upload the CSV. To access in a notebook, you can then reference the file name to read the CSV.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50189497
score: 1
type: Answer

http://stackoverflow.com/q/50137512
has title: Run Python as windows a service - call another python scrip with modules
tagged with: service
has comment: http://stackoverflow.com/comment/87308602
type: Question
has body: Im trying to run python as windows service. The following this post is working okay: https://gist.github.com/guillaumevincent/d8d94a0a44a7ec13def7f96bfb713d3f But when I try to import some of my other python and call from this service it wont work. code of service : import servicemanager import socket import sys import win32event import win32service import win32serviceutil import datetime # impoort own module from modules import copy_log class TestService(win32serviceutil.ServiceFramework): _svc_name_ = "TestService7" _svc_display_name_ = "Test Service7" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): rc = None while rc != win32event.WAIT_OBJECT_0: now = datetime.datetime.now() with open('C:\\test\\TestService.log', 'a') as f: self.count = self.count + 1 f.write(str(self.count) + ' :: '+str(now) + '\n') f.write('________________\n') f.write('test service running...\n') #call own module "Here is simple function im my seprare python project and is not working" copy_log.CopyTest() rc = win32event.WaitForSingleObject(self.hWaitStop, 1000*10) def main(self): pass if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(TestService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(TestService) example of file/module that is called by python service: import datetime from shutil import copyfile class CopyTest(object): def __init__(self): print(self.__str__()) pass def copy_it(self): copyfile("C://test_read/aaa.txt", "C:///test_write/aaa.txt") and is not working that. I don't know why?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87293509
has comment: http://stackoverflow.com/comment/87325091
tagged with: python
has comment: http://stackoverflow.com/comment/87306707
has comment: http://stackoverflow.com/comment/87324635
tagged with: call
score: 0
tagged with: windows

http://stackoverflow.com/a/50130449
upvote count: 2
type: Answer
score: 0
downvote count: 2
answers question: http://stackoverflow.com/q/50130234
has comment: http://stackoverflow.com/comment/87316139
has comment: http://stackoverflow.com/comment/87293064
has body: Are you sure all the arguments you are passing to the psycopg2 connect function are correct? conn=p.connect(dbname='app_db', user='postgres', host='localhost', password='samet', port=5432) The database name, username, host, password, and port all could possibly be incorrect.

http://stackoverflow.com/q/50145032
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87349687
answer count: 1
has title: Make predictions from a trained classifier python #Scikitlearn #SVM
has answer: http://stackoverflow.com/a/50165966
type: Question
score: -2
tagged with: text-classification
has comment: http://stackoverflow.com/comment/87308192
tagged with: svm
has comment: http://stackoverflow.com/comment/87312152
favorite count: 0
upvote count: 0
tagged with: predict
downvote count: 2
has body: I need help classifying unseen data. I have a sample set of data. ID Comment Category 2017_01 inadequate stock Availability 2017_02 Too many failures Quality 2017_03 no documentation Customer Service 2017_04 good product Satisfied 2017_05 long delivery times Delivery I have trained a multilevel text classifier using this data. I tested the fit of data using MultinomialNB and SVM and I have chosen SVM as the final model # Support Vector Machines - calculating the SVM Fit from sklearn.linear_model import SGDClassifier text_clf_svm = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()),('clf-svm', SGDClassifier(loss='hinge', penalty='l2',alpha=1e-3, n_iter=5, random_state=42))]) text_clf_svm = text_clf_svm.fit(X_train, y_train) predicted_svm = text_clf_svm.predict(X_train) np.mean(predicted_svm == y_train) 0.8850102669404517 I tested the model on a comment from this year print(text_clf_svm.predict(["This is obsolete and being replaced by another product. not very robust and we have had many failures"])) ['Quality'] Question: How do I pass in the unseen data from 2018 (Below) to get classified as above? ID Comment Category 2018_01 This product is obsolete 2018_02 Tech Support takes too long 2018_03 2 out of 3 products failed 2018_04 Delivery to APAC takes too long
tagged with: scikit-learn
tagged with: python

http://stackoverflow.com/comment/87312908
type: Comment
score: 0
type: AnswerComment
has text: you cann't pass like that you need pass model instance
comment on: http://stackoverflow.com/a/50147126

http://stackoverflow.com/q/50183915
tagged with: python
has comment: http://stackoverflow.com/comment/87480593
linked to: http://stackoverflow.com/q/50243130
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50242383
has comment: http://stackoverflow.com/comment/87385378
answer count: 3
downvote count: 0
tagged with: apache-spark
tagged with: amazon-s3
has body: I am using PyCharm 2018.1 using Python 3.4 with Spark 2.3 installed via pip in a virtualenv. There is no hadoop installation on the local host, so there is no Spark installation (thus no SPARK_HOME, HADOOP_HOME, etc.) When I try this: from pyspark import SparkConf from pyspark import SparkContext conf = SparkConf()\ .setMaster("local")\ .setAppName("pyspark-unittests")\ .set("spark.sql.parquet.compression.codec", "snappy") sc = SparkContext(conf = conf) inputFile = sparkContext.textFile("s3://somebucket/file.csv") I get: py4j.protocol.Py4JJavaError: An error occurred while calling o23.partitions. : java.io.IOException: No FileSystem for scheme: s3 How can I read from s3 while running pyspark in local mode without a complete Hadoop install locally? FWIW - this works great when I execute it on an EMR node in non-local mode. The following does not work (same error, although it does resolve and download the dependancies): import os os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages "org.apache.hadoop:hadoop-aws:3.1.0" pyspark-shell' from pyspark import SparkConf from pyspark import SparkContext conf = SparkConf()\ .setMaster("local")\ .setAppName("pyspark-unittests")\ .set("spark.sql.parquet.compression.codec", "snappy") sc = SparkContext(conf = conf) inputFile = sparkContext.textFile("s3://somebucket/file.csv") Same (bad) results with: import os os.environ['PYSPARK_SUBMIT_ARGS'] = '--jars "/path/to/hadoop-aws-3.1.0.jar" pyspark-shell' from pyspark import SparkConf from pyspark import SparkContext conf = SparkConf()\ .setMaster("local")\ .setAppName("pyspark-unittests")\ .set("spark.sql.parquet.compression.codec", "snappy") sc = SparkContext(conf = conf) inputFile = sparkContext.textFile("s3://somebucket/file.csv")
linked to: http://stackoverflow.com/q/50242843
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53272645
linked to: http://stackoverflow.com/q/28029134
has comment: http://stackoverflow.com/comment/87422541
has answer: http://stackoverflow.com/a/50242383
has title: How can I read from S3 in pyspark running in local mode?
has answer: http://stackoverflow.com/a/50239574
possible better answer: http://stackoverflow.com/a/50239574
upvote count: 6
tagged with: pyspark
score: 6

http://stackoverflow.com/comment/87211426
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50096756
has text: Oh ok now it works, could you update the dict--based variant for 2.6 too? `new_data = {k:v.format(**fd) for k,v in data.items()}`
type: Comment

http://stackoverflow.com/comment/87398603
type: QuestionComment
comment on: http://stackoverflow.com/q/50190900
has text: can you show us how you get/make `tips`? otherwise, we can't verify the behaviour you are talking about (the issue may be relevant to other code not shown here)
score: 0
type: Comment

pre-trained-model
tag name: pre-trained-model
tags question: http://stackoverflow.com/q/50204613
type: Tag

http://stackoverflow.com/comment/87343972
type: AnswerComment
comment on: http://stackoverflow.com/a/50162485
score: 0
type: Comment
has text: That gives me ValueError: unconverted data remains: 0 - not sure what that means!

http://stackoverflow.com/comment/87343608
comment on: http://stackoverflow.com/q/50162838
type: Comment
has text: Your lambda needs to check the type of its input arg and do something different for a list.
score: 0
type: QuestionComment

http://stackoverflow.com/a/50148506
answers question: http://stackoverflow.com/q/50148148
score: 3
has body: My answer is going to deviate from Ashish's answer because he considers the exchange from $ to tzsh and tzsh to $ as 1 transaction, while my approach considers $-to-tzsh and tzsh-to-$ as separate transactions: i = 0 currency = 1000 while currency &gt; 1: if i % 2 == 0: # if converting from $ to tzsh currency = 83.5 * currency else: # if converting from tzsh to $ currency = currency / 86.8 i += 1 print(i) Result: 358
type: Answer
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/87246839
score: 0
comment on: http://stackoverflow.com/a/50108826
type: Comment
type: AnswerComment
has text: but I expected to 10 precisions/recalls, but here I have 11.

http://stackoverflow.com/q/50099347
has comment: http://stackoverflow.com/comment/87218078
answer count: 1
has answer: http://stackoverflow.com/a/50102677
has body: Example image : I'm working on a project in Python with OpenCV where I need to fade the colors of an image a little to make it darker. Things have been going ok so far except that I'm getting weird mis-colorations in the resulting image where large areas are either white or purple or similar. See the attached example. I can't find any explanation for this even after extensive Googling. Any ideas what might be causing this? My code looks like this: poster = stbt.load_image("test1.png") b, g, r = cv2.split(poster) val = 40 b -= val g -= val r -= val poster = cv2.merge((b, g, r)) cv2.imshow("frame2", poster) cv2.waitKey(0) cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/87215577
tagged with: opencv
has comment: http://stackoverflow.com/comment/87215923
score: 0
has title: Python opencv/cv2 mis-colorations
has comment: http://stackoverflow.com/comment/87215834
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/87215272
has comment: http://stackoverflow.com/comment/87216770
type: UnansweredQuestion

http://stackoverflow.com/a/50237104
downvote count: 0
has comment: http://stackoverflow.com/comment/87561426
upvote count: 1
has comment: http://stackoverflow.com/comment/87592894
answers question: http://stackoverflow.com/q/50217133
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87561610
has comment: http://stackoverflow.com/comment/87592884
has body: The Session ID should have the format projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt; (being &lt;Project ID&gt; the ID of the GCP project where your agent is located and &lt;Session ID&gt; the ID you use for your ongoing session), as can be seen in this documentation page. In your code I see that you are calling the detect_intent_texts() function like: project_id = "newagent/agent/environments/draft/users/&lt;User Number&gt;" session_id = str(uuid.uuid4()) texts = "Que tal?" language_code = "es-ES" I see two main errors here: The Project ID has the wrong format, it should be the ID of your GCP project, which usually has a format like my-first-project or similar, and slashes / are not supported, so you are using a wrong Project ID. The text should be a Python list of strings, like ["hello"] and not just "hello". Just as an example, the following minimal code provides the result below: import dialogflow def detect_intent_texts(project_id, session_id, texts, language_code): session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) for text in texts: text_input = dialogflow.types.TextInput(text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent(session=session, query_input=query_input) print('Fulfillment text: {}\n'.format(response.query_result.fulfillment_text)) detect_intent_texts("my-project","abcd",["hello"],"en-US") Result: user@my-project:~/dialogflow$ python detect_intent_minimal.py Session path: projects/my-project/agent/sessions/abcd Fulfillment text: Hi! Therefore I suspect that changing the project_id to its correct value and the texts to a list should solve your issues. EDIT: I have been able to reproduce the issue that you are seeing with a 403 PermissionDenied message by using a Service Account without the required permissions. In order to run intents in Dialogflow, you…

http://stackoverflow.com/q/50184367
tagged with: php
tagged with: node.js
has body: Is there any way to make the bloat effect for image? Not necessarily from the center. Any solution in Python/Node.js/PHP. Google did not return results Example: link
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Bloat effect for image
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50184565
tagged with: python

http://stackoverflow.com/q/50195277
accepted answer: http://stackoverflow.com/a/50195327
possible better answer: http://stackoverflow.com/a/50195433
score: 1
has answer: http://stackoverflow.com/a/50195433
tagged with: http
tagged with: post
favorite count: 0
type: Question
answer count: 2
downvote count: 0
has title: Flask running request.method 'POST' by default instead of 'GET'
has answer: http://stackoverflow.com/a/50195327
upvote count: 1
tagged with: python
tagged with: flask
has body: I am developing this Flask application where I press 'Login' button and I am redirected to "Dashboard". Here's a simplified code for my default route which opens login page: @app.route('/', methods=['POST', 'GET']) def home(): if not session.get('logged_in'): if request.method == 'GET': return render_template('login.html') elif request.method == 'POST': if # Username and Password are correct from the login form session['logged_in'] = True return dashboard() else: return render_template('login.html', message = "Wrong username or password") else: return render_template('dashboard.html') The login.html has a form with form action="/" method="POST" which triggers the condition elif request.method == 'POST' in default route('/') above Here's simplified code for route('/dashboard') @app.route('/dashboard', methods=['POST', 'GET']) def dashboard(): if session.get('logged_in'): if request.method == 'GET': return "it was GET" elif request.method == 'POST': return "it was POST" else: return render_template('login.html') Here comes the problem. The dashboard route runs POST method after login although (according to my concept) it should run GET method (as GET is default). The output it gives is "it was POST". Please help. Thanks :)
tagged with: get
type: AnsweredQuestion

http://stackoverflow.com/comment/87395393
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50189248
has text: You are telling what is the solution , just try a loop and iterate through dictionary and check the condition , if it met increase some counter.
score: 0

http://stackoverflow.com/q/50145046
answer count: 1
has comment: http://stackoverflow.com/comment/87308297
favorite count: 0
type: Question
has title: Read a list of another file in python
has body: My text file named test.txt is like below. [['A', 3.992303979497981], ['V', 2.2251878737397264], ['V', 2.703754348429766], ['A', 3.900215472550781], ['A', 4.99003388996634] [['C', 3.5329528530441805], ['A', 1.1530906322097374], ['A', 2.666421771048816], ['V', 1.2859199105217558], ['B', 0.40879871489389696] From another file code.py, How can I read the each line as a list with only values? mean I want to get the values in a mylist like mylist = [[[A],[V],[V],[A],[A]], [[C],[A],[A],[V],[B]]] I tried doing below but It is not working. import ast with open('test.txt', 'r') as fp: mylisttrain = [ast.literal_eval(line) for line in fp] price=[] for x in range(0,2): for y in range(0,10): price.append([mylisttrain[x][y][0]]) It gives output like [[A],[V],[V],[A],[A], [C],[A],[A],[V],[B]] But, I want output like this. [[[A],[V],[V],[A],[A]], [[C],[A],[A],[V],[B]]] I want each line of input to be in a sub-list of its own.
has comment: http://stackoverflow.com/comment/87308240
tagged with: python
score: -1
tagged with: parsing
has comment: http://stackoverflow.com/comment/87308247
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87308370
has answer: http://stackoverflow.com/a/50145071
downvote count: 1
accepted answer: http://stackoverflow.com/a/50145071

http://stackoverflow.com/q/50229561
has answer: http://stackoverflow.com/a/50229628
has title: Transforming dataframe (transposing)
score: 1
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have a dataframe that looks like this: df=pd.DataFrame(columns=["AC_YEAR","Physics"],data=[[2010,8],[2010,9],[2011,7],[2010,3],[2011,4]]) And I want to transform it into: df2=pd.DataFrame(columns=[2010,2011],data=[[8,7],[9,4],[3,]]) Some of the options I have tried (without luck) are: df2 = pd.DataFrame(columns=[]) for year in [2010,2011]: pd.concat([df2,(df[df["AC_YEAR"]==year].iloc[:,1])], axis=1, join="inner", ignore_index=True) Any help? Thanks!
upvote count: 1
accepted answer: http://stackoverflow.com/a/50229628
favorite count: 0
type: Question

http://stackoverflow.com/q/50111172
tagged with: udp
has body: So im having trouble with this one portion of my program. Right now with my current code i can connect and communicate with another computer via the terminal but i am unable to send an integer and have it be recognized as such. I need to be able to send a number to a server, and get the server to manipulate the number (e.g. add 1), and then return the result to client and printout the result on the server side. I cannot for the life of me get it to recognize this communication as an integer instead of a string! Here is how i connect in the terminal Server side: python ./udpEchoServer.py -s 4004 And here is how i connect in the terminal Client side: python ./udpEchoServer.py -c [IP ADDRESS OF THE SERVER] 4004 Here is my code so far: #! /usr/bin/env python # Client and server for udp (datagram) echo. # # Usage: udpecho -s [port] (to start a server) # or: udpecho -c host [port] &lt;file (client) import sys from socket import * ECHO_PORT = 50000 + 7 BUFSIZE = 1024 def main(): if len(sys.argv) &lt; 2: usage() if sys.argv[1] == '-s': server() elif sys.argv[1] == '-c': client() else: usage() def usage(): sys.stdout = sys.stderr print 'Usage: udpecho -s [port] (server)' print 'or: udpecho -c host [port] &lt;file (client)' sys.exit(2) def server(): if len(sys.argv) &gt; 2: port = eval(sys.argv[2]) else: port = ECHO_PORT s = socket(AF_INET, SOCK_DGRAM) s.bind(('', port)) print 'udp echo server ready' while 1: data, addr = s.recvfrom(BUFSIZE) print 'server received %r from %r' % (data, addr) s.sendto(data, addr) def client(): if len(sys.argv) &lt; 3: usage() host = sys.argv[2] if len(sys.argv) &gt; 3: port = eval(sys.argv[3]) else: port = ECHO_PORT addr = host, port s = socket(AF_INET, SOCK_DGRAM) s.bind(('', 0)) print 'udp echo client ready, reading stdin' while 1: line = sys.stdin.readline() if not line: break s.sendto(line, addr) data, fromaddr = s.recvfrom(BUFSIZE) print 'client received %r from %r' % (data, fromaddr) main()
type: AnsweredQuestion
score: 0
tagged with: macos
answer count: 1
tagged with: terminal
tagged with: server
type: Question
has title: How to send and manipulate an integer in a UDP connection in the terminal
tagged with: python
accepted answer: http://stackoverflow.com/a/50111491
has answer: http://stackoverflow.com/a/50111491

http://stackoverflow.com/comment/87269258
comment on: http://stackoverflow.com/a/50105428
has text: Thanks @Sam. The code is working however I am getting escape and new line characters in the json. How do I remove those? One of the example: ```"team_members": ["\"Ali Smith", " Jon Doe\"\n"```
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50079735
has comment: http://stackoverflow.com/comment/87191439
tagged with: keras
score: 34
has comment: http://stackoverflow.com/comment/100727813
has comment: http://stackoverflow.com/comment/87195398
favorite count: 0
has comment: http://stackoverflow.com/comment/88658042
type: Question
has answer: http://stackoverflow.com/a/60536082
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87221972
has comment: http://stackoverflow.com/comment/87189581
has answer: http://stackoverflow.com/a/62984641
has body: For several days now, I'm trying to replicate my keras training results with pytorch. Whatever I do, the pytorch model will overfit far earlier and stronger to the validation set then in keras. For pytorch I use the same XCeption Code from https://github.com/Cadene/pretrained-models.pytorch. The dataloading, the augmentation, the validation, the training schedule etc. are equivalent. Am I missing something obvious? There must be a general problem somewhere. I tried thousands of different module constellations, but nothing seems to come even close to the keras training. Can somebody help? Keras model: val accuracy > 90% # base model base_model = applications.Xception(weights='imagenet', include_top=False, input_shape=(img_width, img_height, 3)) # top model x = base_model.output x = GlobalMaxPooling2D()(x) x = Dense(512, activation='relu')(x) x = Dropout(0.5)(x) predictions = Dense(4, activation='softmax')(x) # this is the model we will train model = Model(inputs=base_model.input, outputs=predictions) # Compile model from keras import optimizers adam = optimizers.Adam(lr=0.0001) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # LROnPlateau etc. with equivalent settings as pytorch Pytorch model: val accuracy ~81% from xception import xception import torch.nn.functional as F # modified from https://github.com/Cadene/pretrained-models.pytorch class XCeption(nn.Module): def __init__(self, num_classes): super(XCeption, self).__init__() original_model = xception(pretrained="imagenet") self.features=nn.Sequential(*list(original_model.children())[:-1]) self.last_linear = nn.Sequential( nn.Linear(original_model.last_linear.in_features, 512), nn.ReLU(), nn.Dropout(p=0.5), nn.Linear(512, num_classes) ) def logits(self, features): x = F.relu(features) x = F.adaptive_max_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) x = self.last_linear(x) return x def forward(self, input): x = self.features(input) x = self.logits(x) return x device = torch.devic…
tagged with: python
upvote count: 34
has comment: http://stackoverflow.com/comment/87194545
has comment: http://stackoverflow.com/comment/95677355
has comment: http://stackoverflow.com/comment/97582637
has comment: http://stackoverflow.com/comment/88440861
has comment: http://stackoverflow.com/comment/101057120
has title: Pytorch vs. Keras: Pytorch model overfits heavily
has comment: http://stackoverflow.com/comment/106956511
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88700862
tagged with: pytorch
has comment: http://stackoverflow.com/comment/87196838

http://stackoverflow.com/a/50756275
answers question: http://stackoverflow.com/q/50214020
has body: At least for Anaconda python, this can be fixed by installing the package conda install mkl-service, which allows you to call import mkl. On the other hand, it is not available via pip install, so I cannot say how it would work there.
downvote count: 0
has comment: http://stackoverflow.com/comment/133508738
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/50122132
has body: You can use a list comprehension with list slicing: matrix = [[3,5,7,9], [6,8,12,14], [2,1,0,5], [7,8,9,10]] new_matrix = [i[:2] for i in matrix] Output: [[3, 5], [6, 8], [2, 1], [7, 8]]
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50122098
downvote count: 0

http://stackoverflow.com/comment/87340699
score: 1
type: Comment
type: QuestionComment
has text: It is part of a bigger program I'm writing, but that's all I have for that one part
comment on: http://stackoverflow.com/q/50161348

http://stackoverflow.com/q/50199088
downvote count: 0
upvote count: 1
score: 1
has body: I have a tensor t = {t[0], t[1], ..., t[m]} . For each element i in this tensor, I would like to calculate t[i]*i, which will result in a new tensor t' with the same shape, and the following values: t' = {t[0]*0, t[1]*1, ..., t[m]*m}. How can I implement this? I have tried using a for loop, but it failed, as the following error was raised. TypeError: `Tensor` objects are not iterable when eager execution is not enabled. To iterate over this tensor use `tf.map_fn`.
has title: How to calculate the expected values (entry*index) of a tensor for each index
has answer: http://stackoverflow.com/a/50206664
possible better answer: http://stackoverflow.com/a/50206664
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50199527
accepted answer: http://stackoverflow.com/a/50199527
tagged with: python
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/87232415
comment on: http://stackoverflow.com/a/50107575
type: Comment
score: 0
type: AnswerComment
has text: That's it! Thank you!

http://stackoverflow.com/q/50110666
has comment: http://stackoverflow.com/comment/87328838
answer count: 0
has body: I have some code which looks like: #!/usr/bin/env python """ test out threading with PySpin and matplotlib """ import datetime import threading from matplotlib import pyplot as plt import PySpin __LOCK = threading.Lock() # Set up figure __FIG = plt.figure() __AXES = __FIG.add_axes([0, 0, 1, 1]) # Get camera __SYSTEM = PySpin.System.GetInstance() __CAM = __SYSTEM.GetCameras().GetByIndex(0) def test(): """ test thread for streaming image """ while True: with __LOCK: print('test thread: ' + str(datetime.datetime.now())) image = get_image() # pylint: disable=unused-variable def get_image(): """ grabs image and returns numpy array """ image = __CAM.GetNextImage() # Initialize image data image_data = None # Ensure image is complete if not image.IsIncomplete(): # Get image data image_data = image.GetNDArray() # Release image image.Release() return image_data def main(): """ test """ # Start Acquisition __CAM.Init() __CAM.BeginAcquisition() # Start thread thread = threading.Thread(target=test) thread.start() # Update plot while True: #import time #time.sleep(0.01) with __LOCK: print('primary thread: ' + str(datetime.datetime.now())) plt.pause(0.01) return 0 if __name__ == '__main__': main() Unfortunately when I run it, I get an output like this: primary thread: 2018-04-30 21:21:49.297240 primary thread: 2018-04-30 21:21:49.325118 primary thread: 2018-04-30 21:21:49.352918 primary thread: 2018-04-30 21:21:49.381198 primary thread: 2018-04-30 21:21:49.408484 primary thread: 2018-04-30 21:21:49.436476 primary thread: 2018-04-30 21:21:49.463705 primary thread: 2018-04-30 21:21:49.492506 primary thread: 2018-04-30 21:21:49.520737 primary thread: 2018-04-30 21:21:49.548624 primary thread: 2018-04-30 21:21:49.577559 primary thread: 2018-04-30 21:21:49.604856 primary thread: 2018-04-30 21:21:49.633234 test thread: 2018-04-30 21:21:49.660484 test thread: 2018-04-30 21:21:49.661107 test thread: 2018-04-30 21:21:49.661617 test thread: 2018-04-30 21:21:49.662168 test thread: 2018-04-30…
tagged with: pyspin
tagged with: multithreading
downvote count: 0
has title: Python threading and locks
has comment: http://stackoverflow.com/comment/99374016
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87302594
tagged with: locking
has comment: http://stackoverflow.com/comment/87302658
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87238634
has comment: http://stackoverflow.com/comment/87302669
score: 2

http://stackoverflow.com/comment/87397654
type: Comment
comment on: http://stackoverflow.com/q/50190283
has text: show us what you've tried and show us how it fails.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87170618
comment on: http://stackoverflow.com/q/50077168
has text: @solarissmoke form.errors shows
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50088372
downvote count: 0
answers question: http://stackoverflow.com/q/50086924
upvote count: 5
type: Answer
has body: Here is what I had to do get things working. Here are the instructions to install python 3 and django on aws using boto3 within user-data UserData="""#!/bin/bash yum install httpd php php-mysql -y yum install python36 python36-virtualenv python36-pip -y pip install --upgrade pip cd /home/ec2-user python3 -m venv /home/ec2-user/venv source /home/ec2-user/venv/bin/activate pip install django pip install --upgrade pip yum update -y service httpd start chkconfig httpd on """ thanks to the tip from @dpwrussell I had to remove sudo since it's not required. next, I had to change directory to get the virtual env under my user home.
score: 5

http://stackoverflow.com/comment/87422162
score: 0
type: Comment
type: AnswerComment
has text: @titanium I've tuned the second case a bit. It's completely unreadable now but for larger problem size it gives a considerable speed up.
comment on: http://stackoverflow.com/a/50112867

http://stackoverflow.com/q/50101119
tagged with: string
downvote count: 1
favorite count: 0
has title: Changing a string iteratively
has answer: http://stackoverflow.com/a/50101317
type: Question
has comment: http://stackoverflow.com/comment/87218863
has answer: http://stackoverflow.com/a/50101324
possible better answer: http://stackoverflow.com/a/50101324
has comment: http://stackoverflow.com/comment/87219499
has comment: http://stackoverflow.com/comment/87219260
has comment: http://stackoverflow.com/comment/87219218
has answer: http://stackoverflow.com/a/50101353
has answer: http://stackoverflow.com/a/50101445
has comment: http://stackoverflow.com/comment/87275812
has answer: http://stackoverflow.com/a/50101272
has comment: http://stackoverflow.com/comment/87257011
tagged with: python
has answer: http://stackoverflow.com/a/50101308
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87219043
has body: I am trying to write in Python a script that takes a string and returns a list of string by iteratively moves the letters in the original sequence. For example : ACGT-->TACG -->GTAC-->CGTA-->STOP (original sequence) I am a beginner in programming, here is what I've succeed to do liste=[] seq=list('ACGT') nseq=list("test") while nseq!=seq: for i in range (0, len(seq)): nseq[i]=seq[i-1] ''.join(nseq) liste.append(nseq) It only returns the first step like TACG and doesn't go on. Output : ['T', 'A', 'C', 'G']multiple time (endless loop) Expected output : TACG GTAC CGTA
has comment: http://stackoverflow.com/comment/87219445
has answer: http://stackoverflow.com/a/50101325
upvote count: 3
answer count: 7
accepted answer: http://stackoverflow.com/a/50101272

http://stackoverflow.com/a/50168360
has body: Using the dow_number generated, you can apply condition to check and subtract date using date_sub(), df = df.withColumn('Date1',F.when(df['dow_number'] == 6,F.date_sub(df.Date,1)).when(df['dow_number'] == 7,F.date_sub(df.Date,2)).otherwise(df.Date)) +----------+----------+---+----+----+----------+ | Date|dow_number| id|dogs|cats| Date1| +----------+----------+---+----+----+----------+ |2018-05-04| 5| 1| 2| 0|2018-05-04| |2018-05-05| 6| 2| 0| 1|2018-05-04| |2018-05-06| 7| 2| 0| 1|2018-05-04| +----------+----------+---+----+----+----------+ I believe, you don't need dow_number to change as well.If you need, either you can use date_format on new date and get it (or) apply another condition as above. Hope this helps!
type: Answer
answers question: http://stackoverflow.com/q/50168018
score: 2
accepted answer of: http://stackoverflow.com/q/50168018
has comment: http://stackoverflow.com/comment/114629544
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87355247
downvote count: 0

http://stackoverflow.com/comment/87426977
has text: my intention with this was to get each line of data from the DAT files on a different column, while this does get all of the data from all 38 of the DAT files into the excel document, they're all stacked on the 38th column of the excel file in a column thats 152000 cells long (38DAT files at 4000 entries per each)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50204202

http://stackoverflow.com/q/50105806
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: aws-lambda
type: Question
has body: Whenever an error is raised in AWS Lambda (either built-in or custom errors), an error message is constructed and returned. The error message has the fields errorType, errorMessage, and stackTrace. I would like to wrap my code in a try/except block and add additional fields to before I raise the error, but can't figure out a way to do so. Any idea how this can be done? try: some_function() except Exception as e: # Pass additional information/add fields into e # Something like e['additional_data'] = 'something' raise e
type: UnansweredQuestion
tagged with: python
has title: Adding fields to Python AWS Lambda error messages
answer count: 0
score: 1

http://stackoverflow.com/comment/87539475
score: 0
type: AnswerComment
has text: Great. Thank you very much. I guess I got it now. :-)
type: Comment
comment on: http://stackoverflow.com/a/50184306

http://stackoverflow.com/comment/87361137
comment on: http://stackoverflow.com/a/50171774
type: Comment
score: 0
has text: One issue with your Explaination : If you see my code along with the search,iam even counting the no of occurences of a sub-string.
type: AnswerComment

ascii
tags question: http://stackoverflow.com/q/50162137
tags question: http://stackoverflow.com/q/50096342
type: Tag
tag name: ascii

gradient-descent
tags question: http://stackoverflow.com/q/50225723
tag name: gradient-descent
tags question: http://stackoverflow.com/q/50080134
tags question: http://stackoverflow.com/q/50101699
tags question: http://stackoverflow.com/q/50105249
type: Tag
tags question: http://stackoverflow.com/q/50175711

http://stackoverflow.com/q/50154948
tagged with: wrapper
tagged with: sql
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/87327414
has title: Python abstraction-layer for SQL
has comment: http://stackoverflow.com/comment/87327497
type: UnansweredQuestion
tagged with: database
tagged with: python
has body: I'm currently using Python to store files in a JSON Database. However the JSON has started to become rather large, and inefficient (reading a 20MB file, changing one value, writing 20MB back to disk again, takes rather long) So, I was thinking about switching to SQL (SQLite or Mysql), however I don't want to change my entire code. So far, I've been reading the JSON into lists/arrays and access them rather easily database["key"] = "NewValue" But if I switched to SQL, I'd have to deal with long SQL queries (select from.....insert into....), apart from the entire overhead-stuff (connect, execute, etc.). That requires me to rewrite every single data-access in my code. Is there a way (maybe some sort of wrapper), where I can just keep my existing code-base, and let the wrapper the conversion for me in the background?
score: 0
answer count: 0

http://stackoverflow.com/q/50145104
has comment: http://stackoverflow.com/comment/87308314
has title: How to make a Case/Switch in python with no all breaks, and code between 2 cases
has comment: http://stackoverflow.com/comment/92790062
has answer: http://stackoverflow.com/a/50196145
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50196135
has body: I know Java and C and I used to use Switch statements, but there aren't in python. I see many ways of use if-elif-else to remplace, but any that remplace completly. Example of code that I want remplace. switch(expression) { case a: doA(); case b: doB(); case c: doC(); break; case d: case e: doDE() break; case f: case g: doFG(): case h: doH(); break; case i: doI(); default: foo(); break; } As you can see not all case are follow by break, and there is code between some cases that only executed with one case, but there is also common code that is executed in both case. I see a many ways, but any that allow this at same time. And I think this is the real diference between if-elif-else, and switch-case. So there is any way of do this will be great, or it's only posible with repeted functions calls and complex if with all posibilities?. Thank you.
score: 1
has answer: http://stackoverflow.com/a/50196135
has comment: http://stackoverflow.com/comment/87308352
linked to: http://stackoverflow.com/q/60208
tagged with: switch-statement
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87308440
answer count: 2
tagged with: if-statement
downvote count: 0
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50196145

http://stackoverflow.com/comment/87404589
type: Comment
comment on: http://stackoverflow.com/q/50193562
score: 0
type: QuestionComment
has text: Not really, but you need to make sure that the url has actually called the view, before trying to debug whatever it is.. however it may be the main issue... this `request.GET['status']` in your view can only receive values from arguments after `?` in URLs: `localhost:8000/job/status_update?status=blabla`. in case you don't have this parameter, your view will raise `KeyError` error

http://stackoverflow.com/a/50123220
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87265465
score: 0
accepted answer of: http://stackoverflow.com/q/50123009
type: Answer
answers question: http://stackoverflow.com/q/50123009
has body: frompyfunc cannot analyze your function or implicitly vectorize its execution. Its implementation is basically a for loop, calling your function repeatedly. Here is a link to the implementation of frompyfunc itself, although most of the parts you're interested in don't happen there. Here is a link to one of the ufunc inner loops used for ufuncs created from Python objects; I believe frompyfunc will use that or one of the loops shortly above it in the source code. You can see the repeated use of PyEval_CallObject to call the Python callable.
has comment: http://stackoverflow.com/comment/87265421

http://stackoverflow.com/a/50105678
has comment: http://stackoverflow.com/comment/87229025
answers question: http://stackoverflow.com/q/50105373
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Well ... that printed output[3] kinda looks like a half filled tuple. so, you might need to check output[i][0] instead. Also, i'd suggest using __contains to do the string comparison and you don't need to write range(0,n): by default it starts at zero so a simple range(n) does the exact same thing ;> deletedFlag = np.zeros((len(output),1)) for i in range(len(output)): if output[i][0].__contains("deleted"): deletedFlag[i] = 1

http://stackoverflow.com/comment/87332831
type: AnswerComment
comment on: http://stackoverflow.com/a/50156559
has text: The number of filters is related to the capability of your model. We can't know the correct number, but it does have an influence. Testing, testing, testing, that's how people choose the most suited models.
type: Comment
score: 0

machine-learning
tags question: http://stackoverflow.com/q/50166987
type: Tag
tags question: http://stackoverflow.com/q/50209981
tags question: http://stackoverflow.com/q/50144314
tags question: http://stackoverflow.com/q/50139417
tags question: http://stackoverflow.com/q/50143825
tags question: http://stackoverflow.com/q/50152311
tags question: http://stackoverflow.com/q/50137980
tags question: http://stackoverflow.com/q/50192731
tags question: http://stackoverflow.com/q/50088113
tags question: http://stackoverflow.com/q/50082882
tags question: http://stackoverflow.com/q/50211458
tags question: http://stackoverflow.com/q/50169437
tags question: http://stackoverflow.com/q/50185399
tags question: http://stackoverflow.com/q/50191729
tags question: http://stackoverflow.com/q/50076076
tags question: http://stackoverflow.com/q/50217492
tags question: http://stackoverflow.com/q/50197560
tags question: http://stackoverflow.com/q/50183080
tags question: http://stackoverflow.com/q/50080721
tags question: http://stackoverflow.com/q/50219738
tags question: http://stackoverflow.com/q/50204825
tags question: http://stackoverflow.com/q/50162787
tags question: http://stackoverflow.com/q/50176515
tags question: http://stackoverflow.com/q/50144413
tags question: http://stackoverflow.com/q/50076633
tags question: http://stackoverflow.com/q/50078784
tags question: http://stackoverflow.com/q/50216816
tags question: http://stackoverflow.com/q/50180298
tags question: http://stackoverflow.com/q/50098066
tags question: http://stackoverflow.com/q/50111190
tags question: http://stackoverflow.com/q/50092913
tags question: http://stackoverflow.com/q/50172184
tags question: http://stackoverflow.com/q/50087301
tags question: http://stackoverflow.com/q/50218613
tags question: http://stackoverflow.com/q/50218408
tags question: http://stackoverflow.com/q/50181272
tags question: http://stackoverflow.com/q/50128278
tags question: http://stackoverflow.com/q/50092917
tags question: http://stackoverflow.com/q/50131032
tags question: http://stackoverflow.com/q/50183045
tags question: http://stackoverflow.com/q/50151585
tags question: http://stackoverflow.com/q/50180967
tags question: http://stackoverflow.com/q/50219134
tags question: http://stackoverflow.com/q/50176861
tags question: http://stackoverflow.com/q/50144597
tags question: http://stackoverflow.com/q/50156010
tags question: http://stackoverflow.com/q/50153049
tags question: http://stackoverflow.com/q/50099623
tags question: http://stackoverflow.com/q/50181642
tags question: http://stackoverflow.com/q/50213640
tags question: http://stackoverflow.com/q/50140155
tags question: http://stackoverflow.com/q/50189781
tags question: http://stackoverflow.com/q/50216041
tags question: http://stackoverflow.com/q/50100174
tags question: http://stackoverflow.com/q/50081415
tags question: http://stackoverflow.com/q/50201913
tags question: http://stackoverflow.com/q/50218562
tags question: http://stackoverflow.com/q/50222628
tags question: http://stackoverflow.com/q/50106516
tags question: http://stackoverflow.com/q/50086764
tags question: http://stackoverflow.com/q/50125058
tags question: http://stackoverflow.com/q/50125844
tags question: http://stackoverflow.com/q/50141228
tags question: http://stackoverflow.com/q/50090363
tags question: http://stackoverflow.com/q/50149850
tags question: http://stackoverflow.com/q/50176137
tags question: http://stackoverflow.com/q/50210953
tags question: http://stackoverflow.com/q/50169854
tags question: http://stackoverflow.com/q/50163386
tags question: http://stackoverflow.com/q/50167692
tags question: http://stackoverflow.com/q/50077865
tags question: http://stackoverflow.com/q/50212175
tags question: http://stackoverflow.com/q/50105969
tags question: http://stackoverflow.com/q/50203106
tags question: http://stackoverflow.com/q/50140500
tags question: http://stackoverflow.com/q/50222607
tags question: http://stackoverflow.com/q/50120211
tags question: http://stackoverflow.com/q/50129485
tags question: http://stackoverflow.com/q/50116244

http://stackoverflow.com/q/50194291
upvote count: 1
tagged with: python
has body: So I have a python file that enters Instagram.com, puts the account credentials, and finally enters the keys into the search box after logging in. Once it puts the keys into the search box, I can't see to submit the keys so Instagram can take me to the account page (ex: I put @streetgoodies in the instagram search bar, i click enter, and it brings me to www.instagram.com/streetgoodies/) Is there any way i can submit the keys into the search so it can redirect me to the search query that i have requested? from time import sleep from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # start a new browser session browser = webdriver.Chrome('PATH/TO/DRIVER') # navigate to a webpage browser.get('https://www.instagram.com') # find login link login_elem = browser.find_element_by_xpath( '//*[@id="react-root"]/section/main/article/div[2]/div[2]/p/a') # click login in button login_elem.click() # send login info credentials to correct input boxes browser.find_element_by_xpath("//input[@name='username']").send_keys('USERNAME') browser.find_element_by_xpath("//input[@name='password']").send_keys('PASSWORD') # click final login button browser.find_element_by_xpath("//button[contains(.,'Log in')]").click() # find hidden search bar searchbox = WebDriverWait(browser, 10).until( EC.visibility_of_element_located( (By.XPATH, "//input[@placeholder='Search']") ) ) # send search into input searchbox.send_keys('streetgoodies') searchbox.submit() The searchbox.submit() is causing the issue (I believe) Thank you!!
has title: Python / Selenium - Can't submit the keys in Instagram search input
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: instagram
score: 0
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50198956
tagged with: automation
has answer: http://stackoverflow.com/a/50198956
answer count: 1

http://stackoverflow.com/a/50101389
has body: Instead of plotting new scatter plots for each image it would make sense to update the scatter plot's data. The advantage is that the map only needs to be created once, saving some time. from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np Duration = 6 #hours Xpos1 = np.random.normal(-4, 0.6, size=(Duration,10)) Ypos1 = np.random.normal(51.25, 0.6, size=(Duration,10)) plt.figure(figsize=(20,10)) m = Basemap(width=300000,height=300000,projection='lcc', resolution='c',lat_0=51.25,lon_0=-4) m.drawmapboundary(fill_color='turquoise') m.fillcontinents(color='white',lake_color='aqua') m.drawcountries(linestyle='--') scatter = m.scatter([], [], s=10, c='k', marker='o', label = 'Aurelia aurita', zorder=2) for i in range (0,Duration): x,y = m(Xpos1[i],Ypos1[i]) scatter.set_offsets(np.c_[x,y]) plt.savefig('GIF10P%d' %i) plt.show()
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50098388
score: 3
answers question: http://stackoverflow.com/q/50098388

http://stackoverflow.com/comment/87174998
has text: Yes, but then you want to construct an array out of the small arrays. If you're only interested in the reconstructed array then reshaping is what you want
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50079194

http://stackoverflow.com/comment/87239103
comment on: http://stackoverflow.com/q/50110774
score: 1
has text: what does `print(len(message))` say? Is `print(message)` what you expect? (Inserted above the `uncombine = binsascii...` line)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87469074
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50225479
has text: I was able to implement your function into my code however, there does not seem to be any speed up at all, maybe even a slow down. Does it perhaps have anything to do with fig.canvas.draw()?
type: AnswerComment

http://stackoverflow.com/q/50166810
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: python
has title: main thread load tensorflow model, used in child thread error
answer count: 0
has body: main thread load tensorflow model, used in child thread error. I create two thread, one is main thread, is used for load model, then create child thread, and pass load model return value to child thread。 But，when child thread use the parameter to do inference
downvote count: 0

http://stackoverflow.com/a/50193456
answers question: http://stackoverflow.com/q/50192934
has comment: http://stackoverflow.com/comment/87413742
has body: Task exception was never retrieved - is not actually exception propagated to stdout, but a log message that warns you that you never retrieved exception in one of your tasks. You can find details here. I guess, most easy way to avoid this message in your case is to retrieve exception from task manually: coro = WebSocketCommonProtocol.run() # you don't need any wrapper task = asyncio.ensure_future(coro) try: #start discord client client.run(token) finally: # retrieve exception if any: if task.done() and not task.cancelled(): task.exception() # this doesn't raise anything, just mark exception retrieved
score: 5
has comment: http://stackoverflow.com/comment/87413822
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50192934
type: Answer
has comment: http://stackoverflow.com/comment/87411161
has comment: http://stackoverflow.com/comment/87543110
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87226060
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50096472
type: QuestionComment
has text: @PaxVobiscum yes i am sure, i made an error while copying the code.

http://stackoverflow.com/comment/87445033
has text: text mode in a networked drive, that's the key. On a local drive it doesn't make much difference, but on a networked, it does!
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50212980

http://stackoverflow.com/comment/87312107
type: QuestionComment
has text: I suspect that if you submitted these command separately, it would work, i.e. you have two DDL commands that you are submitting as one. Have you considered parsing the file, command-by-command, and submitting them in sequence?
comment on: http://stackoverflow.com/q/50143656
score: 0
type: Comment

http://stackoverflow.com/q/50165763
linked to: http://stackoverflow.com/q/10973766
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50165784
has body: I tried to run the following code. def fahrenheit(T): return (9.0/5)*T + 32 temp = [2 , 43 , 54 , 67 , 78 , 89.9] map(fahrenheit,temp) Why does map function prints &lt;map at 0x15a6cf17550&gt;
tagged with: python
duplicate of: http://stackoverflow.com/q/10973766
score: 0
has title: Map function error in Python
has comment: http://stackoverflow.com/comment/87349492
answer count: 1
type: Question

http://stackoverflow.com/a/55102551
answers question: http://stackoverflow.com/q/50076514
type: Answer
has body: If you don't want to write the column names which becomes really inconvenient if you have multiple keys you may use df = pd.DataFrame(web_stats, columns = web_stats.keys())
score: 0

http://stackoverflow.com/comment/87350878
comment on: http://stackoverflow.com/a/50166225
type: AnswerComment
score: 0
has text: Okay so i fixed the issue with the error but now im stuck on some input, I want it so the user can type the name at the end of the code like 'bob' and it pop up bobs stats(age, pay, gender), and i dont want to use an if statement because that would mean creating a new if statement everytime a new name is created
type: Comment

http://stackoverflow.com/a/50138569
upvote count: 1
type: Answer
has body: Based on your comment, I think the culprit is in your call to render_template(). You not only need to pass the template name, but also the variables used in the template. See here for the flask-docs So you should actually be doing return render_template("portfolio.html", rows2=rows2) ... where the left-hand-side is the name in the template, and the right-hand-side is the variable you assigned to in your logic.
accepted answer of: http://stackoverflow.com/q/50138445
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87296411
answers question: http://stackoverflow.com/q/50138445
has comment: http://stackoverflow.com/comment/87296030
score: 1

http://stackoverflow.com/q/50175903
favorite count: 0
has answer: http://stackoverflow.com/a/50176549
score: 3
linked to: http://stackoverflow.com/q/9541025
has title: Making copies of built-ins classes
tagged with: python
type: Question
tagged with: python-3.x
has body: I'm trying to write function which creates classes from classes without modifying original one. Simple solution (based on this answer) def class_operator(cls): namespace = dict(vars(cls)) ... # modifying namespace return type(cls.__qualname__, cls.__bases__, namespace) works fine except type itself: &gt;&gt;&gt; class_operator(type) Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: type __qualname__ must be a str, not getset_descriptor Tested on Python 3.2-Python 3.6. (I know that in current version modification of mutable attributes in namespace object will change original class, but it is not the case) Update Even if we remove __qualname__ parameter from namespace if there is any def class_operator(cls): namespace = dict(vars(cls)) namespace.pop('__qualname__', None) return type(cls.__qualname__, cls.__bases__, namespace) resulting object doesn't behave like original type &gt;&gt;&gt; type_copy = class_operator(type) &gt;&gt;&gt; type_copy is type False &gt;&gt;&gt; type_copy('') Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: descriptor '__init__' for 'type' objects doesn't apply to 'type' object &gt;&gt;&gt; type_copy('empty', (), {}) Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: descriptor '__init__' for 'type' objects doesn't apply to 'type' object Why? Can someone explain what mechanism in Python internals prevents copying type class (and many other built-in classes).
upvote count: 3
type: UnansweredQuestion
tagged with: cpython
tagged with: types
answer count: 1
has comment: http://stackoverflow.com/comment/87370762
downvote count: 0
has comment: http://stackoverflow.com/comment/87370483
has comment: http://stackoverflow.com/comment/87370380
tagged with: copy

http://stackoverflow.com/comment/87207627
has text: @Granitosaurus : This one: https://cdn-az.allevents.in/banners/2d76d5624f4e4b83155a51d60b3872fb-rimg-w525-h350-gmir.jpg
score: 0
comment on: http://stackoverflow.com/q/50091118
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50184733
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50184706
type: Answer
has comment: http://stackoverflow.com/comment/87386693
has body: Not sure why you want this but you can assign and check if exists in the same statement like: import itertools as it for b in (x.get_next() for x in it.repeat(a) if x.is_next()): fn(b)
score: 2

http://stackoverflow.com/q/50147251
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/101754
downvote count: 0
tagged with: python
has body: I have an application in python and I want to run it on android. the applications has several libraries how can I do it? thanks for your help
duplicate of: http://stackoverflow.com/q/101754
tagged with: android
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50597064
upvote count: 2
has title: How can I run a python script on android?
score: 2

http://stackoverflow.com/a/50228205
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/50192121
has body: I was able to find out (not very clean tho, in my opinion) solution to this, which is using matplotlib.colors.LinearSegmentedColormap. The code looks like this: # NOTE: jupyter notebook mode %matplotlib inline import seaborn as sns from matplotlib.colors import LinearSegmentedColormap boundaries = [0.0, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0] # custom boundaries # here I generated twice as many colors, # so that I could prune the boundaries more clearly hex_colors = sns.light_palette('navy', n_colors=len(boundaries) * 2 + 2, as_cmap=False).as_hex() hex_colors = [hex_colors[i] for i in range(0, len(hex_colors), 2)] colors=list(zip(boundaries, hex_colors)) custom_color_map = LinearSegmentedColormap.from_list( name='custom_navy', colors=colors, ) sns.heatmap( vmin=0.0, vmax=1.0, data=data, cmap=custom_color_map, xticklabels=labels, yticklabels=labels, linewidths=0.75, )
score: 1
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50192121

http://stackoverflow.com/comment/87462176
type: QuestionComment
has text: `print ('{0:10} {1:5}'.format("Exercices","Points"))` python 3.6 print is a function - it needs `()`
comment on: http://stackoverflow.com/q/50222356
type: Comment
score: 0

http://stackoverflow.com/comment/87441694
type: AnswerComment
score: 1
type: Comment
has text: Edit: I misunderstood, you can make 'How' the root with 0, but then, you should change the head of delete to 'How': `[0, 3, 3, 0, 5, 3, 3]`, otherwise, your tree will have 2 roots.
comment on: http://stackoverflow.com/a/50209676

http://stackoverflow.com/comment/87361949
score: 0
type: AnswerComment
has text: @BackdoorCipher To be honest, I could not really make much sense of your code, and how it is connected to the actual question. What exactly are you counting, how often a "good" or "bad" word appear in the text? In this case, do it the other way around and create a `Counter` from the text, then iterate the good/bad words and look up the counts in the `Counter`. Or if you just need the accumulated counts, use the `set` and a `sum(x in bad_words_set for x in text)`
type: Comment
comment on: http://stackoverflow.com/a/50171774

http://stackoverflow.com/q/50080530
has comment: http://stackoverflow.com/comment/87177337
downvote count: 0
has comment: http://stackoverflow.com/comment/87177160
tagged with: cumulative-sum
possible better answer: http://stackoverflow.com/a/50080871
has comment: http://stackoverflow.com/comment/87177114
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50081087
has comment: http://stackoverflow.com/comment/87177157
tagged with: pandas
has body: I am trying to track inventory levels of individual items over time comparing projected outbound and availability. There are times in which the projected outbound exceed the availability and when that occurs I want the Post Available to be 0. I am trying to create the Pre Available and Post Available columns below: Item Week Inbound Outbound Pre Available Post Available A 1 500 200 500 300 A 2 0 400 300 0 A 3 100 0 100 100 B 1 50 50 50 0 B 2 0 80 0 0 B 3 0 20 0 0 B 4 20 20 20 0 I have tried the below code: def custsum(x): total = 0 for i, v in x.iterrows(): total += df['Inbound'] - df['Outbound'] x.loc[i, 'Post Available'] = total if total &lt; 0: total = 0 return x df.groupby('Item').apply(custsum) But I receive the below error message: ValueError: Incompatible indexer with Series I am a relative novice to Python so any help would be appreciated. Thank you!
has comment: http://stackoverflow.com/comment/87177391
tagged with: python
has comment: http://stackoverflow.com/comment/87177449
tagged with: methods
accepted answer: http://stackoverflow.com/a/50081087
has title: Grouping By and Referencing Shifted Values
favorite count: 0
has comment: http://stackoverflow.com/comment/87177165
type: Question
has comment: http://stackoverflow.com/comment/87177483
answer count: 2
has answer: http://stackoverflow.com/a/50080871
upvote count: 3

http://stackoverflow.com/q/50075496
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: plotly
score: 10
upvote count: 10
type: Question
accepted answer: http://stackoverflow.com/a/51108340
has body: I need to have multiple line plots inside one of the subplots of the figure in Dash plots. In the below code there are 3 subplots 'Price' , 'MMA30' and 'Volume' in the figure as 3 separate subplots. I want to have the 'Price' and 'MMA30' in one subplot. Code for reproducing: import dash,requests,pandas as pd from dash.dependencies import Output, Input import dash_core_components as dcc import dash_html_components as html import plotly.tools as tls from io import StringIO app = dash.Dash(__name__) app.layout = html.Div([ html.Div(['Name : ', dcc.Input(id='input',value='ACC',type='text') ]), dcc.Graph(id='price_volume') ]) @app.callback( Output('price_volume', 'figure'), [Input(component_id='input', component_property = 'value')] ) def update_graph(in_data): p=requests.get('http://finance.google.com/finance/getprices?q='+in_data+'&amp;x=NSE&amp;i=61&amp;p=1d&amp;f=d,c,v').text a=pd.read_csv(StringIO(p),skiprows=range(7),names =['date','Close','Volume']) a['date']=pd.to_datetime(a.date.str[1:],unit='s').dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata') a['Date']=a.date.dt.date a['Time']=a.date.dt.time df = a'Date','Time','Close','Volume' df['MMA30']=df.Close.rolling(window=30).mean() fig = tls.make_subplots(rows=3, cols=1, shared_xaxes=True,vertical_spacing=0.009,horizontal_spacing=0.009) fig['layout']['margin'] = {'l': 30, 'r': 10, 'b': 50, 't': 25} fig.append_trace({'x':df.Time,'y':df.Close,'type':'scatter','name':'Price'},1,1) fig.append_trace({'x':df.Time,'y':df.MMA30,'type':'scatter','name':'MMA30'},2,1) fig.append_trace({'x':df.Time,'y':df.Volume,'type':'bar','name':'Volume'},3,1) fig['layout'].update(title='1 Minute plot of '+in_data) return fig if __name__ == '__main__': app.run_server(debug=True) I tried to merge the 'Price' and 'MMA30' plots into one subplot by changing no of subplots to 2 rows &amp; 1 column in the tls.make_subplot line and changed the fig.append_trace to fig.append_trace([{'x':df.Time,'y':df.Close,'type':'scatter','name':'Price'}, {'x…
has title: Python / Dash : Multiple graphs inside a single subplot of the the figure
tagged with: plotly-dash
has answer: http://stackoverflow.com/a/51108340

http://stackoverflow.com/comment/87341257
has text: However, `umap` can not still be found.
comment on: http://stackoverflow.com/a/50161617
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50206054
type: Answer
has comment: http://stackoverflow.com/comment/87454275
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50194282
has comment: http://stackoverflow.com/comment/87455116
upvote count: 2
answers question: http://stackoverflow.com/q/50194282
has body: Here is a cleaned up version that appears to work. I removed the threshold variable since it can up to sign be absorbed into the normal vector. The downside is that we have to check two cases. My gut feeling is that the jump at zero in the threshold variable was throwing the solver off. import numpy as np from scipy.optimize import linprog N = 100 def test(X, Y): if not (X.size and Y.size): return True, np.full((2,), np.nan) A = np.r_[-X, Y] b = np.repeat((-1, 1), (X.shape[0], Y.shape[0])) res1 = linprog(c=[0,0], A_ub=A, b_ub=b-1e-6, bounds=2*[(None, None)]) res2 = linprog(c=[0,0], A_ub=A, b_ub=-b-1e-6, bounds=2*[(None, None)]) if res1['success']: return True, res1['x'] elif res2['success']: return True, res2['x'] else: return False, np.full((2,), np.nan) def split(locations, p, margin): proj = np.einsum('ij,j', locations, p[:2]) X = locations[proj &lt; p[2] - margin] Y = locations[proj &gt; p[2] + margin] return X, Y def validate(locations, p, p_recon, margin): proj = np.einsum('ij,j', locations, p[:2]) X = locations[proj &lt; p[2] - margin] Y = locations[proj &gt; p[2] + margin] if not (X.size and Y.size): return True return ((np.all(np.einsum('ij,j', X, p_recon) &gt; 1) and np.all(np.einsum('ij,j', Y, p_recon) &lt; 1)) or (np.all(np.einsum('ij,j', X, p_recon) &gt; -1) and np.all(np.einsum('ij,j', Y, p_recon) &lt; -1))) def random_split(locations): inX = np.random.randint(0, 2, (locations.shape[0],), dtype=bool) return locations[inX], locations[~inX] for minv in range(10): margin = 1/(2**minv) locations = np.random.uniform(-1,1,[N,2]) P = np.random.normal(0, 1, (50, 3)) tests, P_recon = zip(*(test(*split(locations, p, margin)) for p in P)) assert all(validate(locations, *ps, margin) for ps in zip(P, P_recon)) control = [test(*random_split(locations))[0] for p in P] print('test:', np.mean(tests), 'control:', np.mean(control)) Sample output: test: 1.0 control: 0.0 test: 1.0 control: 0.0 test: 1.0 control: 0.0 test: 1.0 control: 0.0 test: 1.0 control: 0.0 test: 1.0 c…
downvote count: 0

http://stackoverflow.com/q/50152856
favorite count: 0
type: Question
has body: I am trying to create a new language model (Luxembourgish) in spaCy, but I am confused on how to do this. I followed the instructions on their website and did a similar thing as in this post. But what I do not understand is, how to add data like a vocab or wordvectors. (e.g. "fill" the language template) I get that there are some dev tools for same of these operations, but their execution is poorly documented so I do not get how to install and use them properly, especially as they seem to be in python 2.7 which clashes with my spacy installation as it uses python 3. As for now I have a corpus.txt (from a wikipediadump) on which I want to train and a language template with the defaults like stop_words.py, tokenizer_exceptions.py etc. that I created and filled by hand. Anyone ever done this properly and could help me here?
tagged with: windows
linked to: http://stackoverflow.com/q/47196799
accepted answer: http://stackoverflow.com/a/50215001
tagged with: python
score: 11
tagged with: nlp
has answer: http://stackoverflow.com/a/50215001
upvote count: 11
type: AnsweredQuestion
has title: spacy create new language model with data from corpus
tagged with: spacy
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87312814
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50136406
has text: @RasmusEkman You can also move the class inside the parent class and call `self.child = self.child_class()`. See edit.

http://stackoverflow.com/comment/87404993
has text: @pickenpack What do you mean 'add an csv writer'?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50193855

http://stackoverflow.com/q/50229735
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 1
upvote count: 1
has title: Performance impact of new calculated column with Python (Pandas)
favorite count: 0
type: Question
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/50229827
has answer: http://stackoverflow.com/a/50229827
tagged with: pandas
has body: I'm playing around with Python, numpy and more with the intention to get into tensorflow and machine learning and really understand everything, not just the "how to run" parts. In many cases, I need to pre-process the data for visualisation with the matplotlib and I am not sure if there is a more performant way or even "on-the-fly" processing to efficiently get the same result as the code below returns (df is a pandas dataframe): def calculate(s): cl = 100 if s["income-class"] == "&lt;=50K" else 300 return cl df["incomeClassNum"] = df.apply(lambda row: calculate(row), axis=1) plt.scatter(df"age", df"education-num", s=df["incomeClassNum"]) plt.show() Thanks for any advice and feedback, Martin

http://stackoverflow.com/a/50087919
answers question: http://stackoverflow.com/q/50080859
accepted answer of: http://stackoverflow.com/q/50080859
score: 0
type: Answer
has body: SSHTunnel So I had to research SSH Tunnel which creates a randomly generated local bind port to map the remote destinaton port to. In short after repeat attempts I managed to get my end result, however if you are seeking an answer to a problem like mine I will provide my code and also an example that hopes to fit all instead of my specific issue from sshtunnel import SSHTunnelForwarder import paramiko import time SSHTunnelForwarder.SSH_TIMEOUT = SSHTunnelForwarder.TUNNEL_TIMEOUT = 5.0 ### Setting up the SSHTunnel ### with SSHTunnelForwarder( SERV, #IP of 10.10.10.1 ssh_username='admin', ssh_pkey="...", remote_bind_address=(SERV, 80), # map the 10.10.10.1 port 80 ) as tunnel: ### preliminary SSH connection ### client = paramiko.SSHClient() # set up SSH connection client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(SERV, username='admin', key_filename='...') ### Setting up the pyvirtualdisplay on local machine ### display = Display(size=(1024, 768), visible=0) # set virtual window size display.start() driver=webdriver.Chrome('/usr/local/bin/chromedriver') # I'm using Chromedriver print(tunnel.local_bind_port) # this prints the randomly generated local port, for example in my case it would be localhost:32842 and would display the web page of the remote host time.sleep(5) URL='http://localhost'+':'+str(tunnel.local_bind_port) driver.get(URL) time.sleep(10) print(driver.title) screenshot=driver.get_screenshot_as_file('newscreen.png') Simplified with SSHTunnelForwarder( &lt;REMOTE_HOST IP&gt;, ssh_username=&lt;ssh_username&gt;, ssh_pkey=&lt;location of own private key&gt;, remote_bind_address=(&lt;REMOTE_HOST&gt;, &lt;REMOTE_PORT&gt;), ) as tunnel: client = paramiko.SSHClient() # set up SSH connection client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(&lt;REMOTE_IP&gt;, username=&lt;ssh_username&gt;, key_filename=&lt;location of own private key&gt;) display = Display(size=(1024, 768), visible=0) display.start() driver=webdr…
type: AcceptedAnswer

http://stackoverflow.com/comment/87267837
comment on: http://stackoverflow.com/q/50124816
score: 4
type: Comment
type: QuestionComment
has text: The problem is that you have a `print(token_dictionary)` inside the `for` loop. So you're printing the whole dictionary over and over again. Just dedent that line so it only happens after the loop is done.

http://stackoverflow.com/comment/87406056
type: AnswerComment
has text: Also, I tried your code with my data but got an error regarding `nans` though there were no `nan` values. I added the details into the question.
comment on: http://stackoverflow.com/a/50190838
type: Comment
score: 0

http://stackoverflow.com/comment/134240342
score: 2
type: Comment
has text: You could also run the `export` command on the terminal you are working on, or in set it as an environment variable in case you use an IDE (ex pyCharm). On this case you will use this variable for specific projects only, not for every python tool running on your machine.
comment on: http://stackoverflow.com/a/69990888
type: AnswerComment

pca
tags question: http://stackoverflow.com/q/50211652
tag name: pca
tags question: http://stackoverflow.com/q/50101117
tags question: http://stackoverflow.com/q/50113639
type: Tag
tags question: http://stackoverflow.com/q/50145394
tags question: http://stackoverflow.com/q/50120211

http://stackoverflow.com/a/50139291
score: 2
upvote count: 2
downvote count: 0
has body: In your code I see u = inf or u = L[...], yet in original pseudocode u is a graph vertice, not weight. In other words you confused distances with vertices. Perhaps use strings to name vertices? Provide example of your graph format. Is G[1] a dictionary with transition keys? list of pairs of a transition with its weight? Looks like in different place it is interpreted differently. {u,v} or {v,u} == i[0] is obviously error, you likely meant {u,v} == i[0] or {v,u} == i[0]
answers question: http://stackoverflow.com/q/50139050
type: Answer

http://stackoverflow.com/q/50223227
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87463955
has body: It is unclear to me how the following works: In [1]: student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] In [2]: sorted(student_tuples, key=lambda student: student[2]) Out [2]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] # sort by age but, In [3]: st = lambda student: student[2] In [4]: st(student_tuples) Out [4]: ('dave', 'B', 10) Why does the [2] in the former sample refer to the index for the individual tuples, when in a lambda function it returns the 2nd tuple in the list?
duplicate of: http://stackoverflow.com/q/32238196
type: Question
has comment: http://stackoverflow.com/comment/87463942
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87464154
tagged with: list
has title: python - sorting a sequence with key function
has answer: http://stackoverflow.com/a/50223253
score: 2
upvote count: 3
linked to: http://stackoverflow.com/q/32238196

http://stackoverflow.com/a/50348112
has comment: http://stackoverflow.com/comment/87747289
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87751848
answers question: http://stackoverflow.com/q/50153049
has body: I haven't run any experiment yet, but Scalable K-Means++ seems rather good for very large data sets (perhaps for those even larger than what you describe). You can find the paper here and another post explaining it here. Unfortunately, I haven't seen any code around I'd trust...

http://stackoverflow.com/q/50192786
accepted answer: http://stackoverflow.com/a/50195726
tagged with: spyder
tagged with: python
tagged with: color-scheme
type: AnsweredQuestion
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/50195726
has body: I do not know why but when I change the color scheme of the spyder editor (I have the latest version installed and I do it through preferences -> syntax coloring), the variable explorer's color remains the same: Since this is very distracting for me I searched it and found something more like a package called QDarkStylesheet that you can install and import, but it sounds a little tricky as I figured some people have reported several issues with it in GitHub! So, is there a straightforward way for making the variable explorer have the same dark color in spyder?
answer count: 1
tagged with: ide
has title: spyder IDE - make variable explorer to follow the color scheme of the Editor
favorite count: 0
type: Question
upvote count: 5

http://stackoverflow.com/q/50083912
type: UnansweredQuestion
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/87183554
tagged with: python
has body: I need to convert this python dict into binary json d = {'1': 'myval', '2': 'myval2'} json_binary_str = b'{"1": "myval", "2": "myval2"}' in python 3, I have this : import ujson ujson.dumps(d) but, this does not create binary string. How can I do this ?
has comment: http://stackoverflow.com/comment/87183612
has answer: http://stackoverflow.com/a/50083968
tagged with: ujson
has answer: http://stackoverflow.com/a/76063683
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/65688848
tagged with: http://stackoverflow.com/tag/json
favorite count: 0
type: Question
has title: fastest way to python dict to json binary string
has comment: http://stackoverflow.com/comment/87183565

http://stackoverflow.com/a/50179420
score: 0
answers question: http://stackoverflow.com/q/50159206
type: Answer
has body: I would suggest to run smoothly the add_weighted_edges_from() function in a directed graph. This just after placing your input data in a tuple list, as requested. Take a look to this documentation for more information import networkx as nx import matplotlib.pyplot as plt %matplotlib inline INPUT = [ (162600,117237,200), (192084,50240,200), (200854,125014,200), (166729,37059,5), (157279,77297,1), (186788,35124,2), (199103,112437,5), (194523,125618,5), (169139,103847,5), (156565,85646,5), (157159,85646,10), (168455,115687,15), (139567,108206,5), (172702,120323,5), (175029,120590,5), (167596,85646,10), (202163,83381,15), (163786,109135,5), (183035,124200,4), (154266,124200,2), (187899,124200,20), (190849,124200,8), (169657,118867,11), (157848,101997,2), (143224,87832,1), (140758,101009,21), (197618,101009,20), (175454,50240,4), (150071,112472,10), (199517,121453,20) ] G=nx.DiGraph() G.add_weighted_edges_from(INPUT) elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] &gt; 22] esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] &lt;= 21] pos = nx.spring_layout(G, k=1) plt.figure(figsize=(15,10)) # nodes nx.draw_networkx_nodes(G, pos, node_size=700) # edges nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6) nx.draw_networkx_edges(G, pos, edgelist=esmall, width=1, alpha=0.5, edge_color='b', style='dashed') # labels nx.draw_networkx_labels(G, pos, font_size=12, font_family='sans-serif') plt.axis('off') plt.show() This should be the output

http://stackoverflow.com/a/50201169
has body: Using str.split demo: s = """Module Available Used Remaining (Watts) (Watts) (Watts) ------ --------- -------- --------- 1 485.0 0.0 485.0""" for i in s.split("\n"): if i.strip()[0].isdigit(): val = i.split() print(val[2]) Using regex: import re val = re.findall("\d+\s+\d*\s+\d*\.\d*\s+\d*\.\d*\s+\d*\.\d*", s) for v in val: print(v.split()[2]) Output: 0.0
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50201139
type: Answer
score: 2

http://stackoverflow.com/q/50155101
has comment: http://stackoverflow.com/comment/87328028
type: Question
has body: I`m newbee in python. I have try for days with no luck:(. The respsonse working good when the name and adress are on the soap server. But some times the adress is --- on the soap server. How can I make --- response to None? in my soap.py import logging from suds.client import Client logging.getLogger('suds.client').setLevel(logging.DEBUG) from urllib import getproxies def return_address( country_code, vat_number): if country_code == None and vat_number == None: return None VIES_URL = "http://ec.europa.eu/taxation_customs/vies/checkVatSeice.wsdl" client = Client(VIES_URL, proxy=getproxies()) response = client.service.checkVat(countryCode= country_code, vatNumber= vat_number) return response if __name__== '__main__': address_returned = return_address( None, None)# print address_returned #innan if not "address_returned: if not address_returned: print address_returned['name'] print address_returned['address'] And # -*- coding: UTF-8 -*- import pymysql.cursors import sys import re import os from PIL import Image import base64 import cStringIO from soap import return_address if __name__== '__main__': # dsn_database = " dsn_hostname = "localhost" dsn_port = dsn_uid = dsn_pwd = #dsn_charset='utf8' conn = pymysql.connect(host=dsn_hostname, user=dsn_uid, passwd=dsn_pwd, db=dsn_database, charset='utf8', use_unicode=True) cursor=conn.cursor() cursor.execute("SELECT `uid`, `vat_number`, `country` FROM test") rows = cursor.fetchall() num_IDs = len( rows) cursor.execute("SELECT `uid`, `vat_number`, `company_adress`, `country`, `company_name` FROM oldcompany ") rows2 = cursor.fetchall() print rows2 for i in range (num_IDs): uID = str(rows[i][0]) vat_number = str(rows[i][1]) country_code = str(rows[i][2]) print "check: " vat_number = vat_number.strip() country_code = country_code.strip() response = None valid = False if country_code != 'None' and vat_number != 'None': print 'going to viet for: ', vat_number, country_code response = return_address( country_code, vat_number) if respon…
type: UnansweredQuestion
tagged with: soap
tagged with: python
has title: Python Soap response
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/87329054

http://stackoverflow.com/q/50140969
has comment: http://stackoverflow.com/comment/87301083
tagged with: python
has comment: http://stackoverflow.com/comment/87300226
has comment: http://stackoverflow.com/comment/87300643
has body: I am trying to install a python package from this API: https://github.com/CrowdEmotion/crowdemotion-api-client-python Following the instructions inside the link, I was told to install the package by typing this to the terminal: pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git However, this error won't stop to appear: Could not find a version that satisfies the requirement urllib3&gt;=1.15 (from crowdemotion-api-client-python==1.0.0) (from versions: ) No matching distribution found for urllib3&gt;=1.15 (from crowdemotion-api-client-python==1.0.0) I do have the last version of urllib3 installed in my computer, so I don't know what's going on.
has comment: http://stackoverflow.com/comment/87300216
has comment: http://stackoverflow.com/comment/87300277
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/87300703
linked to: http://stackoverflow.com/q/49748063
type: Question
has title: Python Could not find a version that satisfies the requirement urllib3>=1.15
has comment: http://stackoverflow.com/comment/87300547
has comment: http://stackoverflow.com/comment/87300208
tagged with: api
type: UnansweredQuestion

http://stackoverflow.com/comment/87236658
type: AnswerComment
has text: I didn't work with pandas before,but I will have a look at it. I looked at your solution, but that way I have to declare the values that I receive from the API in my code right looking at your setup?
type: Comment
comment on: http://stackoverflow.com/a/50109615
score: 0

arguments
tags question: http://stackoverflow.com/q/50197038
tags question: http://stackoverflow.com/q/50203934
tags question: http://stackoverflow.com/q/50206724
tags question: http://stackoverflow.com/q/50120578
tags question: http://stackoverflow.com/q/50103415
tag name: arguments
type: Tag
tags question: http://stackoverflow.com/q/50193084
tags question: http://stackoverflow.com/q/50193106

http://stackoverflow.com/comment/87275180
score: 1
type: Comment
type: QuestionComment
has text: I think `top` will show you the process, which would be `python`, not `run.py`.
comment on: http://stackoverflow.com/q/50128629

http://stackoverflow.com/q/50162847
accepted answer: http://stackoverflow.com/a/50163003
downvote count: 0
has answer: http://stackoverflow.com/a/50163003
favorite count: 0
score: 2
has body: I was reading Ian Goodfellow's GAN source code in Github (link https://github.com/goodfeli/adversarial/blob/master/deconv.py). In particular, at line 40/41, the code is: @functools.wraps(Model.get_lr_scalers) def get_lr_scalers(self): It's a rather unfamiliar way of using wraps, and it seems the goal is to replace the get_lr_scalers with a user defined function. But in that case, we don't really need a wrapper for that, right? I don't really know the purpose of wraps in this case.
type: AnsweredQuestion
tagged with: wrapper
tagged with: python
has answer: http://stackoverflow.com/a/50163046
has title: Why wrapper and wrapped function are the same for some python codes.
tagged with: python-decorators
type: Question
answer count: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/50163046

http://stackoverflow.com/comment/87396272
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50189524
has text: Now you have two comments that need to be moved into your question. Click on the edit button and paste in your comments. Select the code and type control-K to format it properly so it is legible. Thanks.

http://stackoverflow.com/q/50223954
has body: Edit: Long story short, I am looking for a way to switch a Label widget to Buttons. I have a Label with text in it, and I want to make it into 4 Buttons (2x2), and be able to switch between the two. I am beginning a choose your own adventure game and and having some trouble conceptualizing the best way to code the game that would be efficient and less taxing for the device/computer. The idea is that you go through some dialogue, and the container holding the widget for the dialogue would then have buttons for choices. I would like to find the best way to switch between going through dialogue and making choices. I've come up with a few ideas, some of which include writing code so that upon button press widgets are added and removed, and another idea (which is easier to implement but probably inefficient), is to create an entirely new screen used only for making choices, with everything being the same except for the middle widget which used to hold a text Label, but now will contain a vertical BoxLayout, with two BoxLayouts within for 4 buttons. Here is the code in the .kv file: #:import FadeTransition kivy.uix.screenmanager.FadeTransition &lt;RootScreen&gt;: transition: FadeTransition() StartScreen: LevelOneBedroomScreen: LevelOneBedroomScreenchoice: &lt;StartScreen&gt;: name: 'start' canvas.before: Rectangle: pos: self.pos size: self.size source: 'start_screen.png' FloatLayout: Image: source: 'start_screen.png' allow_stretch: True keep_ratio: False size_hint: 1, 1 Button: text: 'Start' size_hint: 0.4, 0.3 pos_hint: {'center_x':.5, 'center_y':.5} font_size: 70 on_release: root.manager.current = 'level one bedroom' &lt;LevelOneBedroomScreen&gt;: name: 'level one bedroom' BoxLayout: orientation: 'vertical' Label: text: 'Image of Bedroom' Label: text: 'Dialogue Text' BoxLayout: size_hint_y: .2 Label: text: 'left arrow' Button: text: 'choose' on_release: root.manager.current = 'level one bedroom choice' Label: text: 'right arrow' &lt;LevelOneBedroomScreenChoice&gt;: name…
answer count: 1
has comment: http://stackoverflow.com/comment/87465774
type: Question
has comment: http://stackoverflow.com/comment/87465683
has comment: http://stackoverflow.com/comment/87465744
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/50234987
has title: Python Kivy: switch between Label with text and BoxLayout with Buttons
score: 0

http://stackoverflow.com/q/50229639
upvote count: 2
accepted answer: http://stackoverflow.com/a/59235092
tagged with: index-error
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/59235092
has title: List index out of range in visualize_cv2.py
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/104671532
has body: I want to launch mask-rcnn model from visualize_cv2.py. My goal is train only on 1 element from class_names - person. For this I create class_names1(added full code from this python file for better understanding): import cv2 import numpy as np import os import sys import coco import utils import model as modellib ROOT_DIR = os.getcwd() MODEL_DIR = os.path.join(ROOT_DIR, "logs") COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5") if not os.path.exists(COCO_MODEL_PATH): utils.download_trained_weights(COCO_MODEL_PATH) class InferenceConfig(coco.CocoConfig): GPU_COUNT = 1 IMAGES_PER_GPU = 1 config = InferenceConfig() config.display() model = modellib.MaskRCNN( mode="inference", model_dir=MODEL_DIR, config=config ) model.load_weights(COCO_MODEL_PATH, by_name=True) class_names = [ 'BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush' ] class_names1 = class_names[1] def random_colors(N): np.random.seed(1) colors = [tuple(255 * np.random.rand(3)) for _ in range(N)] return colors colors = random_colors(len(class_names)) class_dict = { name: color for name, color in zip(class_names, colors) } def apply_mask(image, mask, color, alpha=0.5): """apply mask to image""" for n…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88266600
has comment: http://stackoverflow.com/comment/87481239
has comment: http://stackoverflow.com/comment/104681905
tagged with: python
tagged with: data-science
type: AnsweredQuestion
score: 2
tagged with: list

http://stackoverflow.com/q/50110785
answer count: 1
tagged with: maya
has body: I'm new to Python and I have the following code, I am trying to use the following sliders for the Colour, Translate, Rotate and Scale for the shapes I have in this code. Is there a way I can control all the shapes with these sliders? I can't seem to figure it out I've tried everything that I could. Any help would be appreciated, thank you. #Importing all Maya commands to Python import maya.cmds as cmds from functools import partial class CreateUI(): def __init__(self): windowID = "myWindowID" if cmds.window(windowID, exists=True): cmds.deleteUI(windowID) #-----------------------------------------------Layout of Interface masterWindow = cmds.window(windowID, title="User Interface", w=500, h=800, sizeable=False, resizeToFitChildren=True) ShapeLayout = cmds.rowColumnLayout(parent=masterWindow, numberOfColumns=1, columnOffset=[(2,"left",0)]) #-----------------------------------------------Shape Functions #Functions for creating shapes def mySphere(*args): cmds.polySphere() def myCube(*args): cmds.polyCube() def myCylinder(*args): cmds.polyCylinder() def myCone(*args): cmds.polyCone() def myTorus(*args): cmds.polyTorus() def myPlane(*args): cmds.polyPlane() def myDelete(*args): cmds.select() cmds.delete() #Gets rid of any shapes in the scene so that the user doesn't have to every time the UI is launched or the sript is run ShapeList = cmds.ls("mySphere*", "myCube*", "myCylinder*", "myCone*", "myTorus*", "myPlane*","pSphere*", "pCube*", "pCylinder*", "pCone*", "pTorus*", "pPlane*") if len(ShapeList)&gt;0: cmds.delete(ShapeList) #-----------------------------------------------Shape Buttons #Buttons for creating shapes cmds.button(label="Sphere", command=mySphere) cmds.button(label="Cube", command=myCube) cmds.button(label="Cylinder", command=myCylinder) cmds.button(label="Cone", command=myCone) cmds.button(label="Torus", command=myTorus) cmds.button(label="Plane", command=myPlane) cmds.button(label="Delete", command=myDelete) #COLOUR cmds.separator(h=20, style="none") cmds…
type: Question
has title: Using Sliders for shapes in Maya with Python
has answer: http://stackoverflow.com/a/50114976
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/50141921
tagged with: python
has comment: http://stackoverflow.com/comment/87331009
tagged with: systemd
answer count: 0
tagged with: twisted
has title: Daphne and Systemd: Pass file descriptors to children processes
score: 0
has body: I'm trying to run daphne 2.1 using multiprocessing. In the documentation I have: If you want to bind multiple Daphne instances to the same port on a machine, use a process supervisor that can listen on ports and pass the file descriptors to launched processes, and then pass the file descriptor with --fd NUM. I tried to this with a socket (dapnhe.socket): [Unit] Description=Daphne Socket worker %i [Socket] ListenStream=/usr/local/reduction/dist/daphne.sock Accept=yes [Install] WantedBy=sockets.target And with a service (daphne@.service) [Unit] Description=Daphne Service For Django %I After=syslog.target Requires=daphne.socket [Service] Type=simple RuntimeDirectory=daphne PIDFile=/run/daphne.pid WorkingDirectory=/usr/local/reduction/src ExecStartPre=/bin/bash -c 'systemctl set-environment FD=`echo %i | tr -d -`' ExecStart=/bin/bash -c '/usr/local/reduction/venv/bin/daphne -fd ${FD} server.asgi:application' Restart=always [Install] WantedBy=multi-user.target The %i has the form %d-%d-%d. I'm just removing the - before passing it to daphne. This doesn't work... Anyone knows how to pass an FD to daphne?
type: Question
has comment: http://stackoverflow.com/comment/87328975
has comment: http://stackoverflow.com/comment/87328853
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87328734
tagged with: daphne

http://stackoverflow.com/comment/87381817
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50181878
type: QuestionComment
has text: Possible duplicate of [Building a minimal plugin architecture in Python](https://stackoverflow.com/questions/932069/building-a-minimal-plugin-architecture-in-python)

http://stackoverflow.com/a/50096527
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50095511
has body: Why does it not occur any error? On a Model, you can define zero or more fields that have an equivalent in the database, but besides that, you can add zero or more functions, properties, attributes, etc. on the model as well. You probably already did that somehow. For example: class Symbol(models.Model): market = models.CharField( max_length=20, null=True, blank=True, ) def __init__(self, *args, **kwargs): super(Symbol, self).__init__(*args, **kwargs) self.cache = {} @property def market3(self): return self.market and self.market[:3] After all those models are in fact Python objects, with some magic attached such that if you change an attribute and there is a field with the same name, then it corresponds to that field. But usually models also have some extra logic, and attributes to make them more intelligent, handle parts of a request at the model level, calculate properties that depend one one or more fields, etc. By writing: s.i_dont_know = 1 You attached an attribute to the s object with name 'i_dont_know' and value 1. Note however that this attribute is not persistent: if you save the object, and later reload it from the database, then all the extra data you attached to it, will be gone. Unless of course you define a setter that adds some extra logic.

http://stackoverflow.com/comment/87182815
type: QuestionComment
comment on: http://stackoverflow.com/q/50083466
type: Comment
has text: concatenated hashes
score: 0

http://stackoverflow.com/comment/87229657
type: QuestionComment
has text: Hmm, not exactly sure what you're asking but you can always append an inconsequential (maybe?) padding to your x_arr within the while loop to increase length.
score: 0
comment on: http://stackoverflow.com/q/50106163
type: Comment

http://stackoverflow.com/comment/87427755
type: QuestionComment
comment on: http://stackoverflow.com/q/50203379
type: Comment
has text: @Martijn Pieters Same error after installing and compiling libffi from source. The attempted solution has been posted to Pastebin, since it wouldn't fit as a comment and a moderator deleted the suggested answer (which still hasn't solved the problem): https://pastebin.com/nrhUJymt
score: 0

http://stackoverflow.com/comment/87461632
score: 1
has text: just replace `'menu_ask'.lower()` by `menu_ask.lower()` . in other words delete the quotes of 'menu_ask'.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50222032

http://stackoverflow.com/a/50126629
score: 2
upvote count: 2
downvote count: 0
has body: When you created the container you published the ports. Your container would be accessible via port 8000 if it successfully built. However, as Shadow pointed out, your container exited with an error. That is why you must add the -a flag to your docker container ls command. docker container ls only shows running containers without the -a flag. I recommend forgoing the detached flag -d to see what is causing the error. Then creating a new container after you have successfully launched the one you are working on. Or simply run the following commands once you fix the issue. docker stop testing_first then docker container rm testing_first finally run the same command you ran before. docker run --name testing_first -d -p 8000:80 test_1 I ran into similar problems with the first docker instances I attempted to run as well.
type: Answer
answers question: http://stackoverflow.com/q/50126523

http://stackoverflow.com/q/50076704
answer count: 1
downvote count: 0
tagged with: git
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Best way to use my own module in my python project
tagged with: python-module
tagged with: python
has body: I can't find an answer for this question. Probably because I have not the good keywords. If this is too basic, please just tell me where to look for. We have a Python project our_project in which I want to use a little Python module that I wrote : my_module . our_project and my_module both have a git repo. I do not want to just put my_module.py into our_project/ because I want to keep improving my_module independently of our_project and be abble to use it in other projects. I'm looking for a simple way to acces the most rencent version of my_module from our_project. (for me and my collaborators) What should I do ?
accepted answer: http://stackoverflow.com/a/50076796
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87169669
has answer: http://stackoverflow.com/a/50076796

http://stackoverflow.com/a/50202479
accepted answer of: http://stackoverflow.com/q/50178711
score: 0
has body: Solution was to reshape input Tensor to proper Conv1D input shape: (-1, 214161, 1) audio = tf.reshape(audio, [-1, 214161, 1]) The solution shown above lets you run into a problem though, because the object returned by tf.reshape is not a Keras tensor but a standard tensor without _keras_history flag. My recommendation is to add: model.add(Reshape((214161, 1))) instead the solution above to your model.
answers question: http://stackoverflow.com/q/50178711
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/50199924
score: 9
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50199840
upvote count: 9
has comment: http://stackoverflow.com/comment/138716924
accepted answer of: http://stackoverflow.com/q/50199840
type: Answer
has body: Take a closer look at the string, they are all single slash. In [26]: my_str[0] Out[26]: '\\' In [27]: my_str[1] Out[27]: 'x' In [28]: len(my_str[0]) Out[28]: 1 And my_str.replace('\\','\') won't work because the token here is \', which escapes ' and waits for the another closing '. Use my_str.replace('\\', '') instead Update: after few more days, I realize the following discussion may also be helpful. If the intension of a string with escape ('\\x' or '\\u') are eventually hex/unicode literals, they can be decoded by escape_decode. import codecs print(len(b'\x32'), b'\x32') # 1 hex literal, '\x32' == '2' print(len(b'\\x32'), b'\\x32') # 4 chars including escapes print(codecs.escape_decode('\\x32', 'hex')) # chars-&gt;literal, 4-&gt;1 # 1 b'2' # 4 b'\\x32' # (b'2', 4) s = '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z' ed, _ = codecs.escape_decode(s, 'hex') print(len(s), s) print(len(ed), ed) # 49 \xa5\xc0\xe6aK\xf9\x80\xb1\xc8*$\xfbp(4\xd6{;Z # 22 b'\xa5\xc0\xe6aK\xf9\x80\xb1\xc8*\x01\x12$\xfbp\x1e(4\xd6{;Z'

http://stackoverflow.com/comment/87170505
comment on: http://stackoverflow.com/a/50076937
type: Comment
has text: Some of the methods you have used such as readlines I have not learnt. I think i have not learnt ".mean", but we have learnt to sum all the numbers together before dividing it by total data points to get the average
score: 0
type: AnswerComment

http://stackoverflow.com/a/77987435
type: Answer
has body: This happend to me, it seems you need to resync your primary key fields in that tables. I solved using PgAdmin4(v7.6). If you go inside 'Schemas' find 'Tables'.Now Right-click on the table that you updated 'View/Edit Data --> all Rows'. Scroll down on the table and find the last value of "product_id" that has been used. Now in 'Sequences' you should find 'Schemas' and in the sequence referred at that table 'right-click' and choose 'Properties' and in the 'Definitition Tab' update the 'Current value' with the first available value of the table you updated. Now when you insert a new record in table it start from that value.
answers question: http://stackoverflow.com/q/50138330
score: 0

http://stackoverflow.com/q/50214155
has comment: http://stackoverflow.com/comment/87445596
type: Question
has body: I want to calculate the number of bytes of each value in my data frame, is there a way to do this ? here is my data frame : 672 635 6740 2 1 3 1 1 1 531 0 673 635 6740 2 1 3 1 1 1 531 0 674 635 6740 2 1 3 1 1 1 531 0 675 635 6740 2 1 3 1 1 1 531 0 676 635 6740 2 1 3 1 1 1 531 0 677 635 6740 2 1 3 1 1 1 531 0 i want the fallowing result : 3 3 4 1 1 1 1 1 1 3 1 3 3 4 1 1 1 1 1 1 3 1 3 3 4 1 1 1 1 1 1 3 1 3 3 4 1 1 1 1 1 1 3 1 3 3 4 1 1 1 1 1 1 3 1 3 3 4 1 1 1 1 1 1 3 1
has comment: http://stackoverflow.com/comment/87446115
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87445783
has comment: http://stackoverflow.com/comment/87446540
has comment: http://stackoverflow.com/comment/87445640
has answer: http://stackoverflow.com/a/50214714
score: 0
answer count: 1
has title: How do I check the number of digits consumed by each value in data frame

http://stackoverflow.com/q/50101692
has answer: http://stackoverflow.com/a/50115829
has comment: http://stackoverflow.com/comment/105361418
tagged with: python
has comment: http://stackoverflow.com/comment/87224246
type: UnansweredQuestion
has body: Whenever I run .py code using terminal (ubuntu). I get this error. Traceback (most recent call last): File "./twitterstream.py", line 15, in &lt;module&gt; from pip._vendor import requests File "/usr/local/lib/python2.7/dist-packages/pip-10.0.1-py2.7.egg/pip/_vendor/requests/__init__.py", line 83, in &lt;module&gt; from pip._internal.compat import WINDOWS File "/usr/local/lib/python2.7/dist-packages/pip-10.0.1-py2.7.egg/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/usr/local/lib/python2.7/dist-packages/pip-10.0.1-py2.7.egg/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/usr/local/lib/python2.7/dist-packages/pip-10.0.1-py2.7.egg/pip/_internal/index.py", line 15, in &lt;module&gt; from pip._vendor import html5lib, requests, six ImportError: cannot import name requests All the errors are import errors. (pip) I have tried reinstalling pip and python. Any suggestions on this?
has answer: http://stackoverflow.com/a/52593425
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87220248
has comment: http://stackoverflow.com/comment/87224282
has answer: http://stackoverflow.com/a/50117550
downvote count: 0
has comment: http://stackoverflow.com/comment/87220102
has title: ImportError: cannot import name requests
has comment: http://stackoverflow.com/comment/87220889
tagged with: pip
has answer: http://stackoverflow.com/a/63934127
has answer: http://stackoverflow.com/a/54100356
has answer: http://stackoverflow.com/a/50509853
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/50991067
type: Question
has comment: http://stackoverflow.com/comment/87233831

http://stackoverflow.com/comment/87433641
type: Comment
has text: while this is a great approach and gives me a general idea of how to begin. the depth of the tree your solution gives is >20, where as the solution for N = 8 should have a depth only of 16, basically, i am going to make a tweak and group combinations with n-2 elements in common together, then try writing if states for it, this should in theory reduce the depth, lets see if it is optimal
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50204812

http://stackoverflow.com/comment/87222158
type: Comment
type: QuestionComment
score: 0
has text: @Ludo I don't know. I don't particularly think it is a bad question, just that people who aren't aware a one liner is possible don't think the question is very good. I don't really blame you.
comment on: http://stackoverflow.com/q/50102206

http://stackoverflow.com/comment/87338224
comment on: http://stackoverflow.com/q/50159989
type: Comment
score: 0
has text: I’m away from my code at the moment but I believe I tried that and it complained about not finding a module called ‘runner’
type: QuestionComment

http://stackoverflow.com/q/50098131
linked to: http://stackoverflow.com/q/1057431
has body: I have an abstract base class with a number of derived classes. I'm trying to achieve the same behaviour that I would get by placing all the derived classes in the same file as the base class, i.e. if my classes are Base, DerivedA, DerivedB, DerivedC in the file myclass.py I can write in another file import myclass a = myclass.DerivedA() b = myclass.DerivedB() c = myclass.DerivedC() but with each derived class in its own file. This has to be dynamic, i.e. such that I could e.g. delete derived_c.py and everything still works except that now I can no longer call myclass.DerivedC, or that if I add a derived_d.py, I could use it without touching the __init__.py so simply using from derived_c import DerivedC is not an option. I've tried placing them all in a subdirectory and in that directory's __init__.py use pkgutil.walk_packages() to import all the files dynamically, but I can't get them to then be directly in the module's namespace, i.e. rather than myclass.DerivedC() I have to call myclass.derived_c.DerivedC() because I can't figure out how (or if it's possible) to use importlib to achieve the equivalent of a from xyz import * statement. Any suggestions for how I could achieve this? Thanks! Edit: The solutions for Dynamic module import in Python don't provide a method for automatically importing the classes in all modules into the namespace of the package.
linked to: http://stackoverflow.com/q/14426574
type: Question
upvote count: 2
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/50098557
downvote count: 0
type: UnansweredQuestion
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87212755
score: 2
linked to: http://stackoverflow.com/q/301134
has title: Dynamically import all subclasses
has answer: http://stackoverflow.com/a/73707268

http://stackoverflow.com/a/50178363
has comment: http://stackoverflow.com/comment/87375046
has body: You can use groupby and apply function in pandas. This should be faster also. ## fill missing values all_records['Heart Rate'].fillna(90, inplace=True) ## use apply all_records['Inclusion Criteria'] = all_records.groupby('Icustay').apply(lambda x: (x['Heart Rate'].ge(90)) &amp; (x['Hours'].ge(0))).values.astype(int) print(all_records) Heart Rate Hours Icustay Inclusion Criteria 0 79.0 0.0 1001 0 1 91.0 1.5 1001 1 2 97.0 2.7 1001 1 3 90.0 3.4 1001 1 4 90.0 0.0 2010 1 5 94.0 29.4 2010 1 6 68.0 0.0 3005 0
answers question: http://stackoverflow.com/q/50177805
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/87264805
type: Comment
score: 0
has text: @What first argument for what?
comment on: http://stackoverflow.com/q/50123251
type: QuestionComment

http://stackoverflow.com/comment/87388979
type: Comment
type: QuestionComment
has text: Yes it would, but I can't imagine that's the most efficient method as it introduces disk IO into the problem rather than keeping everything in memory. I'm looking for the lowest latency possible here.
comment on: http://stackoverflow.com/q/50185654
score: 0

http://stackoverflow.com/a/50079070
downvote count: 0
answers question: http://stackoverflow.com/q/50078996
has body: def makeTriangle(s): print("S is %d" % s) triangle = 0 for a in range(1,s): print("a is: %d " % a) triangle = triangle + a print("Triangle: %d " % triangle) return triangle n = 3 while n &lt; 10: x = makeTriangle(n) n+=1 Put your return statement out of your for loop
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50078996
type: Answer
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/50207877
possible better answer: http://stackoverflow.com/a/50208354
accepted answer: http://stackoverflow.com/a/50208318
favorite count: 0
has answer: http://stackoverflow.com/a/50208318
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: python 2.7, scraping. import re findall, changing output so that only float number is left, calculating sum
has comment: http://stackoverflow.com/comment/87432939
has answer: http://stackoverflow.com/a/50208354
type: AnsweredQuestion
score: 0
tagged with: screen-scraping
has body: This is from scraping import re import urllib from BeautifulSoup import BeautifulSoup I have outputs like(print numbers_in_mill.text// 9.27[7] 9.25[8] 10.17[9] 10.72[10] How do I change these outputs to // 9.27 9.25 10.17 10.72 I want to remove the brackets + the number in the brackets, then I want to calculate the sum of all my float..numbers_in_mill +=float()
answer count: 2
tagged with: output
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87453595
comment on: http://stackoverflow.com/q/50218274
score: 0
has text: You can probably look at the shell source code and hack something in...
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50081191
has body: The loop below will take a list of directories and/or images, and it will return a list of images, including those images in the supplied directories. For each directory that it is given, it verifies that each file is indeed a valid image, before adding that image to the list. import os import argparse parser = argparse.ArgumentParser() parser.add_argument("-style_image", help="List of images and/or directories") params = parser.parse_args() style_image_input = params.style_image.split(',') valid_ext, style_input_sorted = [".jpg",".png"], None for image in style_image_input: if os.path.isdir(image): for file in os.listdir(image): print(file) ext = os.path.splitext(file)[1] if ext.lower() not in valid_ext: continue if style_input_sorted == None: style_input_sorted = file else: style_input_sorted += "," + file else: if style_input_sorted == None: style_input_sorted = image else: style_input_sorted += "," + image style_image_list = style_input_sorted.split(',') print(style_image_list) How can I use list comprehension to simplify this loop?
has answer: http://stackoverflow.com/a/50081392
tagged with: directory
tagged with: string
has comment: http://stackoverflow.com/comment/87178352
has title: How do I use list comprehension to simplify the sorting and adding of multiple lists and strings?
type: Question
has comment: http://stackoverflow.com/comment/87178314
tagged with: python
tagged with: sorting
tagged with: list-comprehension
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50081392
answer count: 1

http://stackoverflow.com/a/50093933
type: Answer
has body: There is typo mistake in spelling of DATABASES. Replace DATABSES = { 'default' :{ 'ENGINE' : 'django.db.backends.mysql', 'NAME' :'MasterQuote', 'USER' : 'root', 'PASSWORD' : 'root', 'HOST' : 'localhost', 'PORT' : '' } } with DATABASES = { 'default' :{ 'ENGINE' : 'django.db.backends.mysql', 'NAME' :'MasterQuote', 'USER' : 'root', 'PASSWORD' : 'root', 'HOST' : 'localhost', 'PORT' : '' } }
score: 0
answers question: http://stackoverflow.com/q/50093847

http://stackoverflow.com/comment/87440335
type: AnswerComment
has text: Read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/, try to figure it out, and if you get stuck, ask a new question on SO with a [mcve] that demonstrates only one of these problems as precisely as possible. But my first thought is that you have multiple files ending with the same pattern in different subdirectories, and if the program sees at least one it will mark the pattern as not missing, even if others have been removed, renamed, or aren't in some of the subdirectories.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50172195

http://stackoverflow.com/q/50129177
has comment: http://stackoverflow.com/comment/87276683
has answer: http://stackoverflow.com/a/50129255
has title: How to modify a object getting from a property decorator?
has comment: http://stackoverflow.com/comment/87276438
has body: Let's say, here is a class A. It has a private value _foo which is a json string, and access it with property getter and setter. The code is as the following: import json class A(object): _foo = '{"name":"name"}' @property def foo(self): return json.loads(self._foo) @foo.setter def foo(self, value): self._foo = json.dumps(value) Usually, I use foo to do something like following: a = A() print(a.foo['name']) But I'm in trouble when I want to modify it. a = A() print(a.foo) # Out: {'name': 'name'} a.foo['weight'] = 1 print(a.foo) # Out: {'name': 'name'} # have no change What I need to do is: foo = a.foo foo['weight'] = 1 a.foo = foo print(a.foo) Now, my question is how to implement this more intuitive and pythonic?
type: Question
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87276437
tagged with: python
has comment: http://stackoverflow.com/comment/87276374
has comment: http://stackoverflow.com/comment/87276784
has comment: http://stackoverflow.com/comment/87276285
score: 0

http://stackoverflow.com/q/50089400
has comment: http://stackoverflow.com/comment/87194900
tagged with: soappy
has comment: http://stackoverflow.com/comment/87201565
has comment: http://stackoverflow.com/comment/87202061
accepted answer: http://stackoverflow.com/a/50092991
has title: Introspecting a WSDL with Python Zeep
tagged with: soap
possible better answer: http://stackoverflow.com/a/50093489
tagged with: python
has body: I am attempting to use Zeep to describe the operations and types in a given WSDL, so that a program knows the operation names, their parameter names, the parameter types, and parameter attributes. This info will be used to dynamically generate a UI for a given WSDL. What I have got so far is just the string representations of the operations and types. Using code similar to what is found in this answer. Here's an example: from zeep import Client import operator wsdl = 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl' client = Client(wsdl) # get each operation signature for service in client.wsdl.services.values(): print("service:", service.name) for port in service.ports.values(): operations = sorted( port.binding._operations.values(), key=operator.attrgetter('name')) for operation in operations: print("method :", operation.name) print(" input :", operation.input.signature()) print() print() # get a specific type signature by name complextype = client.get_type('ns0:CartGetRequest') print(complextype.name) print(complextype.signature()) This gives an output like the following (shortened for brevity) [...] method : CartCreate input : MarketplaceDomain: xsd:string, AWSAccessKeyId: xsd:string, AssociateTag: xsd:string, Validate: xsd:string, XMLEscaping: xsd:string, Shared: ns0:CartCreateRequest, Request: ns0:CartCreateRequest[] method : CartGet input : MarketplaceDomain: xsd:string, AWSAccessKeyId: xsd:string, AssociateTag: xsd:string, Validate: xsd:string, XMLEscaping: xsd:string, Shared: ns0:CartGetRequest, Request: ns0:CartGetRequest[] [...] CartGetRequest {http://webservices.amazon.com/AWSECommerceService/2011-08-01}CartGetRequest(CartId: xsd:string, HMAC: xsd:string, MergeCart: xsd:string, ResponseGroup: xsd:string[]) The string representations returned by .signature() have the names and types, but I don't know how to parse them out individually. I have tried looping over each objects attrs with dir() as well, and they don't contain this i…
linked to: http://stackoverflow.com/q/3323001
has comment: http://stackoverflow.com/comment/87195439
has comment: http://stackoverflow.com/comment/87194985
tagged with: zeep
type: AnsweredQuestion
answer count: 2
tagged with: wsdl
has answer: http://stackoverflow.com/a/50092991
downvote count: 0
score: 24
linked to: http://stackoverflow.com/q/44885439
has answer: http://stackoverflow.com/a/50093489
upvote count: 24
favorite count: 0
type: Question

http://stackoverflow.com/q/50144388
has title: Python | tkinter: What does tkinter.END do?
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50144529
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/50144529
type: AnsweredQuestion
tagged with: tkinter
answer count: 2
score: 5
accepted answer: http://stackoverflow.com/a/50144534
tagged with: user-interface
has answer: http://stackoverflow.com/a/50144534
downvote count: 1
favorite count: 0
has body: Learning python through a book, and tkinter.END is used in a block of code without being explained import tkinter def count(text, out_data): """ Update out_data with the total number of As, Ts, Cs, and Gs found in text.""" data = text.get('0.0', **tkinter.END**) counts = {} for char in 'ATCG': counts[char] = data.count(char) out_data.set('Num As: {0} Num Ts: {1} Num Cs: {2} Num Gs: {3}'.format( counts['A'], counts['T'], counts['C'], counts['G'])) ... I've looked online, and I only run across examples of it, never mentioning it's function. I tried help(tkinter) in a shell and got END = 'end' which wasn't very useful. If more code is required, just let me know. Didn't want to post the entire code making you pointlessly read more for no reason.
type: Question

http://stackoverflow.com/comment/87481972
type: AnswerComment
comment on: http://stackoverflow.com/a/50193265
has text: @apostolos, Excellent, there's a green tick on the left you should click - this indicates to other users that the problem is solved.
type: Comment
score: 0

http://stackoverflow.com/a/50228990
has body: In python you need to use the OS primitive if you want to manipulate path. A quick example from what you provided: os.path.join("Microsoft Office","root","Office16") Assuming that your program is started from "C:\Program Files (x86)", it will build the path "C:\Program Files (x86)\Microsoft Office\root\Office16\" You have the doc there: https://docs.python.org/2/library/os.path.html
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50228777

http://stackoverflow.com/comment/87386655
comment on: http://stackoverflow.com/a/50184640
score: 0
type: Comment
has text: You are right, your way is more pythonic. :)
type: AnswerComment

http://stackoverflow.com/comment/87277547
has text: `join` does work. Also questions on this site should be well-researched, which I argue this one isn’t.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50129848
type: Comment

http://stackoverflow.com/q/50124024
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87266623
has comment: http://stackoverflow.com/comment/87267194
has comment: http://stackoverflow.com/comment/87267172
has comment: http://stackoverflow.com/comment/87266311
has body: What is the most efficient way to wait for a condition to be true before executing certain code? For example I want to execute code only if a file is modified. My code is within a 'white True:' loop. I'm not sure if this is the best thing to do or if this is common practice because the 'while True:' loop is constantly looping and using up the cpu. I can put a pause statement in there but I want to know what's the defacto way to do this? The script needs to be continuously running while waiting for the condition to be true. while True: modTime = os.path.getmtime('C:\\example1.xlsx') if(modTime &gt; curTime): #execute code #execute code #execute code curTime = modTime
linked to: http://stackoverflow.com/q/182197
score: 0
has comment: http://stackoverflow.com/comment/87266366
has comment: http://stackoverflow.com/comment/87269454
has comment: http://stackoverflow.com/comment/87266682
has comment: http://stackoverflow.com/comment/87266417
has comment: http://stackoverflow.com/comment/87266277
duplicate of: http://stackoverflow.com/q/182197
type: Question
duplicate of: http://stackoverflow.com/q/3274334
has title: Python - what is the best practice for waiting for a condition to be true before code executes? The script needs to be continuously running

http://stackoverflow.com/comment/109416168
score: 0
type: Comment
has text: I just ran pip install graphviz and fixed on my side, even after running 'conda install -c anaconda graphviz' and the following NEW packages will be INSTALLED: graphviz anaconda/win-64::graphviz-2.38-hfd603c8_2
type: AnswerComment
comment on: http://stackoverflow.com/a/60345296

http://stackoverflow.com/comment/87535088
score: 0
type: QuestionComment
has text: @pjcunningham Thanks for the hint. So I did so, and I cannot see any offset or limit in the SQL statements. Where can I find that flask-Admin uses it, as you mention?
comment on: http://stackoverflow.com/q/50214031
type: Comment

http://stackoverflow.com/a/50175231
has comment: http://stackoverflow.com/comment/87368425
has body: you should print the sql statement which you've generated, that makes it a lot easier to see what's wrong. But I guess you need quotes ' around string values for your ",".join(vals) (in case there are string values. So your code is producing insert into test (path,) values (test.com/test2,); but it should produce insert into test (`path`) values ('test.com/test2'); Otherwise try https://github.com/markuman/MariaSQL/ which makes it super easy to insert data to MariaDB/MySQL using pymysql.
has comment: http://stackoverflow.com/comment/87367853
type: Answer
has comment: http://stackoverflow.com/comment/87368118
has comment: http://stackoverflow.com/comment/87368214
has comment: http://stackoverflow.com/comment/87367943
score: 0
has comment: http://stackoverflow.com/comment/87367685
answers question: http://stackoverflow.com/q/50175109
has comment: http://stackoverflow.com/comment/87368552
has comment: http://stackoverflow.com/comment/87368301

scrapy
tags question: http://stackoverflow.com/q/50229856
tags question: http://stackoverflow.com/q/50110355
tags question: http://stackoverflow.com/q/50194819
tags question: http://stackoverflow.com/q/50166130
tags question: http://stackoverflow.com/q/50152546
tags question: http://stackoverflow.com/q/50083638
tags question: http://stackoverflow.com/q/50191646
tags question: http://stackoverflow.com/q/50083325
tags question: http://stackoverflow.com/q/50198730
tag name: scrapy
tags question: http://stackoverflow.com/q/50158045
tags question: http://stackoverflow.com/q/50110824
tags question: http://stackoverflow.com/q/50148061
tags question: http://stackoverflow.com/q/50189524
tags question: http://stackoverflow.com/q/50140480
tags question: http://stackoverflow.com/q/50118568
tags question: http://stackoverflow.com/q/50194545
tags question: http://stackoverflow.com/q/50140887
tags question: http://stackoverflow.com/q/50144983
tags question: http://stackoverflow.com/q/50097551
type: Tag
tags question: http://stackoverflow.com/q/50149940
tags question: http://stackoverflow.com/q/50190934
tags question: http://stackoverflow.com/q/50200752
tags question: http://stackoverflow.com/q/50192215
tags question: http://stackoverflow.com/q/50128291
tags question: http://stackoverflow.com/q/50184153
tags question: http://stackoverflow.com/q/50091118
tags question: http://stackoverflow.com/q/50087492
tags question: http://stackoverflow.com/q/50091655

pygobject
type: Tag
tags question: http://stackoverflow.com/q/50145227
tags question: http://stackoverflow.com/q/50222689
tag name: pygobject
tags question: http://stackoverflow.com/q/50156741

http://stackoverflow.com/a/50158134
type: Answer
answers question: http://stackoverflow.com/q/50157995
score: 0
has body: Instead of r.url , you should r.text to see the data. import requests payload = '8132-C' session = requests.Session() r = requests.get('https://www.gsa.state.al.us/ogb/production', params=payload) print(r.text)

http://stackoverflow.com/comment/87366163
type: QuestionComment
has text: Vendor names are not like general text. So I dont think Bag of words will behave any different than simple one-hot encoding. Try one-hot encoding them.
score: 0
comment on: http://stackoverflow.com/q/50164737
type: Comment

http://stackoverflow.com/q/50164368
answer count: 0
has comment: http://stackoverflow.com/comment/87346917
type: UnansweredQuestion
type: Question
has title: Bind a keyboard shortcut to exception in python
has comment: http://stackoverflow.com/comment/87347059
tagged with: exception
has body: One can send a KeyboardInterrupt to a running python program by pressing Ctrl-c. Is there a way to bind other keyboard combinations to custom python exceptions? Specifically, I usually stop my program by pressing ctrl+c and then it handles the exception and exits cleanly. However, occasionally I want to stop it such that it performs a different cleanup procedure on exit. My program usually runs for several days without stopping so when I am launching it I do not know which way I want to use to kill it. In a nutshell, I want to execute different cleanup procedures, based on some user input during runtime. My program is very computationally intensive so I would prefer a solution where I can send an exception rather than poll for user input.
has comment: http://stackoverflow.com/comment/87347025
has comment: http://stackoverflow.com/comment/87346804
tagged with: python
has comment: http://stackoverflow.com/comment/87346977
linked to: http://stackoverflow.com/q/21120947
has comment: http://stackoverflow.com/comment/87347115
tagged with: keyboardinterrupt
score: 0

http://stackoverflow.com/comment/87282841
type: Comment
type: QuestionComment
has text: What is `x1` here?
comment on: http://stackoverflow.com/q/50132383
score: 1

http://stackoverflow.com/q/50205543
has comment: http://stackoverflow.com/comment/87602629
has answer: http://stackoverflow.com/a/50205565
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/50205596
has answer: http://stackoverflow.com/a/50205560
has title: How to have Python convert a text file into a dictionary of lists?
has comment: http://stackoverflow.com/comment/87428116
upvote count: 1
has body: I'm given a text file that looks like this: name 1 2 3 4 othername 5 6 7 8 ... How do I get Python to find the names in the lines, turn them into keys as part of a dictionary, then the following numbers into a list corresponding to those keys?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87428162
has comment: http://stackoverflow.com/comment/87428172
type: UnansweredQuestion
tagged with: python
score: -3
has comment: http://stackoverflow.com/comment/87428192

http://stackoverflow.com/q/50135094
has comment: http://stackoverflow.com/comment/89196938
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51102890
has body: I am working with multilingual text data, among others with Russian using the Cyrillic alphabet and Turkish. I basically have to compare the words in two files my_file and check_file and if the words in my_file can be found in check_file, write them in an output file keeping the meta-information about these words from both input files. Some words are lowercased while other words are capitalised so I have to lowercase all the words to compare them. As I use Python 3.6.5 and Python 3 uses unicode as default, it handles lowercasing and later on capitalising the words correctly for Cyrillic. For Turkish however, some letters are not handled correctly. Uppercase 'İ' should correspond to lowercase 'i', uppercase 'I' should correspond to lowercase 'ı' and lowercase 'i' should correspond to uppercase 'İ' which is not the case if I type the following in the console: &gt;&gt;&gt; print('İ'.lower()) i̇ # somewhat not rendered correctly, corresponds to unicode 'i\u0307' &gt;&gt;&gt; print('I'.lower()) i &gt;&gt;&gt; print('i'.upper()) I I am doing as follows (simplified sample code): # python my_file check_file language import sys language = sys.argv[3] # code to get the files as lists my_file_list = [['ıspanak', 'N'], ['ısır', 'N'], ['acık', 'V']] check_file_list = [['109', 'Ispanak', 'food_drink'], ['470', 'Isır', 'action_words'], [409, 'Acık', 'action_words']] # get the lists as dict my_dict = {} check_dict = {} for l in my_file_list: word = l[0].lower() pos = l[1] my_dict[word] = pos for l in check_file_list: word_id = l[0] word = l[1].lower() word_cat = l[2] check_dict[word] = [word_id, word_cat] # compare the two dicts for word, pos in my_dict.items(): if word in check_dict: word_id = check_dict[word][0] word_cat = check_dict[word][1] print(word, pos, word_id, word_cat) This gives me only one result but it should give me the three words as result: acık V 409 action_words What I've done so far based on this question: Read the accepted answer which proposes to use PyICU but…
has comment: http://stackoverflow.com/comment/87292644
tagged with: python
score: 15
has comment: http://stackoverflow.com/comment/87288821
tagged with: python-3.x
tagged with: turkish
upvote count: 15
answer count: 2
tagged with: built-in
has title: Handle Turkish uppercase and lowercase correctly, need to modify/override built-in functions?
has comment: http://stackoverflow.com/comment/87294648
has answer: http://stackoverflow.com/a/59348889
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19703106
downvote count: 0
tagged with: cyrillic

http://stackoverflow.com/q/50166927
has title: output of beautiful soup nested loop vertically into dataframe
has body: How do I place the output of this web scrape (data) into a pandas DataFrame? The code below only displays one 'row' of data, and it is in a vertical arrangement. How do I make DataFrame look exactly like print(data) - ie. horizontal? Also, I'm such a newb - this is so 'not pythonic'. Please suggest how to make this into functions(?) ? I tried all sort of append and concat functions, but the nested looping is throwing everything into error. Please help. Thank you in advance. from bs4 import BeautifulSoup as bs import urllib.request import re import pandas as pd Url1 = 'http://www5.statcan.gc.ca/cimt-cicm/topNCountryCommodities-marchandises?lang=eng&amp;chapterId=27&amp;sectionId=0&amp;refMonth=' Url2 = '&amp;refYr=' Url3 = '&amp;freq=6&amp;countryId=999&amp;usaState=0&amp;provId=1&amp;arrayId=9900000&amp;commodityId=271111&amp;commodityName=Natural+gas%2C+liquefied&amp;topNDefault=10&amp;tradeType=3' regexQ = re.compile('Date1 Qty') regexC = re.compile('Footnote') regexV = re.compile('Date1 Val') import csv import collections for year in range(2016, 2018): for month in range(0, 13): sauce = urllib.request.urlopen(Url1+str(month)+Url2+str(year)+Url3).read().decode('utf-8') soup = bs(sauce, 'lxml') select = soup.find_all('option', selected=True) for i in select: Month=select[4] Year=select[3] month=Month.text year=Year.text #print(year) #print(month, year) value = [x.text.strip() for x in soup.find_all("td", {"headers": regexV})] country = [x.text.strip() for x in soup.find_all("a", {"href": regexC})] quantity = [x.text.strip() for x in soup.find_all("td", {"headers": regexQ})] total_list = [list(x) for x in zip(country,quantity,value)] for item in total_list: h=[year , month] data = h + item print(data) df = pd.DataFrame(data=data) df.head
tagged with: nested-loops
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50167371
tagged with: pandas
has answer: http://stackoverflow.com/a/50167371
answer count: 1
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/comment/87373651
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50178132
has text: Please check again, that doesn't look like OP's expected output
type: AnswerComment

http://stackoverflow.com/comment/87199603
type: AnswerComment
comment on: http://stackoverflow.com/a/50091650
has text: Good point about the fact that a compiler could `del` dead objects. In fact, even CPython with a plugin optimizer a la Victor Stinner's proposals (or something hacky built around `byteplay`) could do that.
type: Comment
score: 0

http://stackoverflow.com/a/69395295
upvote count: 3
answers question: http://stackoverflow.com/q/50205224
downvote count: 0
type: Answer
score: 3
has body: I found this implementation of Graph Edit Distance algorithms which uses NetworkX in Python. https://github.com/Jacobe2169/GMatch4py "GMatch4py is a library dedicated to graph matching. Graph structure are stored in NetworkX graph objects. GMatch4py algorithms were implemented with Cython to enhance performance."

http://stackoverflow.com/comment/87438769
comment on: http://stackoverflow.com/q/50202755
has text: I don't know about absl-py, but I have done this with YAML and a wrapper around the standard `argparse` library. The code is in [`ruamel.appconfig`](https://pypi.org/project/ruamel.appconfig/) and used in many of the utilities that I published on PyPI
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50076241
has body: The tuple G contains the set of edges, the set of vertices, and the weight of the edges. #Weighted Graph G = [['a', 'b' , 'c' , 'd'] [({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8)] I am trying to return the weight of an edge, given an edge. For example, for the edge {'a', 'b'}, I am trying to return the value 4. Is it possible to search for {'a', 'b'} and return this value?
has title: Searching for a set, within a tuple
score: 1
possible better answer: http://stackoverflow.com/a/50076371
has comment: http://stackoverflow.com/comment/87168603
type: Question
accepted answer: http://stackoverflow.com/a/50076323
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87168614
answer count: 2
has answer: http://stackoverflow.com/a/50076323
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50076371
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/87287247
type: Comment
comment on: http://stackoverflow.com/q/50134448
type: QuestionComment
has text: welcome to S.O.! Please show us what you have tried
score: 1

http://stackoverflow.com/a/50197429
accepted answer of: http://stackoverflow.com/q/50191768
upvote count: 2
has comment: http://stackoverflow.com/comment/87411975
answers question: http://stackoverflow.com/q/50191768
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/87416738
has comment: http://stackoverflow.com/comment/87411908
score: 2
has body: You don’t need docker for this. There are a couple of options, you should choose depending on what your Java application is doing. If the Java application is a client - based on swing, weblaunch, or providing UI directly - you will want to turn the python functionality to be wrapped in REST/HTTP calls. If the Java application is a server/webapp - executing within Tomcat, JBoss or other application container - you should simply wrap the python scrip inside a exec call. See the Java Runtime and ProcessBuilder API for this purpose.
downvote count: 0
has comment: http://stackoverflow.com/comment/87411857

http://stackoverflow.com/comment/87328344
type: QuestionComment
has text: you should use dictionaries as a replacement for switch cases in python as explained here https://stackoverflow.com/a/103081/8370670 . And if you are using python3 you should use print with end parameter to print text without a newline at the end.
comment on: http://stackoverflow.com/q/50155284
score: 0
type: Comment

http://stackoverflow.com/comment/87470648
comment on: http://stackoverflow.com/a/50226580
type: Comment
has text: @PatrickArtner Thats why I have checked first if the value is there in d or not. Otherwise I could also have used a default dict. But I guess the OP needs a simple answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87376934
has text: There are `25*26 + (25**2 * (26 choose 2)) + ((25**3 * (26 choose 3)) = 40 828 775` different strings available, if I did the calculation correctly. Are you sure you want them all?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50179713

http://stackoverflow.com/comment/87272956
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50126952
has text: I use the PyQt to mimics the web browser and make the website load all content firstly. I think that, if the content generating/loading is finished, I can then crawl the javascript-generated content.

http://stackoverflow.com/a/50193639
downvote count: 0
answers question: http://stackoverflow.com/q/50130706
has comment: http://stackoverflow.com/comment/87464534
accepted answer of: http://stackoverflow.com/q/50130706
upvote count: 5
type: Answer
score: 5
has body: The requires.txt is part of the dependency metadata, so you can use the same tools easy_install uses when installing the egg. Assuming the file requires.txt is in the current directory: In [1]: from pkg_resources import Distribution, PathMetadata In [2]: dist = Distribution(metadata=PathMetadata('.', '.')) Now you can filter all dependencies for your current platform with Distribution.requires(): In [3]: sys.version Out[3]: '3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]' In [4]: dist.requires() Out[4]: [Requirement.parse('idna&gt;=2.1'), Requirement.parse('asn1crypto&gt;=0.21.0'), Requirement.parse('six&gt;=1.4.1'), Requirement.parse('cffi!=1.11.3,&gt;=1.7'), Requirement.parse('cffi&gt;=1.7')] The list would be different if I used Python 2.7: In [4]: sys.version Out[4]: '2.7.10 (default, Oct 6 2017, 22:29:07) \n[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)]' In [5]: dist.requires() Out[5]: [Requirement.parse('idna&gt;=2.1'), Requirement.parse('asn1crypto&gt;=0.21.0'), Requirement.parse('six&gt;=1.4.1'), Requirement.parse('cffi!=1.11.3,&gt;=1.7'), Requirement.parse('cffi&gt;=1.7'), Requirement.parse('enum34'), Requirement.parse('ipaddress')] or PyPy: In [2]: sys.version Out[2]: '3.5.3 (fdd60ed87e941677e8ea11acf9f1819466521bf2, Apr 26 2018, 01:25:35)\n[PyPy 6.0.0 with GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)]' In [3]: d.requires() Out[3]: [Requirement.parse('idna&gt;=2.1'), Requirement.parse('asn1crypto&gt;=0.21.0'), Requirement.parse('six&gt;=1.4.1'), Requirement.parse('cffi!=1.11.3,&gt;=1.7')] Now, if you want to generate a list of requirement strings (like when you want to generate a requirements file for pip), convert the requirements to strings: In [8]: os.linesep.join(str(r) for r in dist.requires()) Out[8]: 'idna&gt;=2.1\nasn1crypto&gt;=0.21.0\nsix&gt;=1.4.1\ncffi!=1.11.3,&gt;=1.7' PEP 508 If you also want to take PEP 508 environment markers into account independent of the current platfo…
type: AcceptedAnswer

http://stackoverflow.com/q/50176304
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50176558
tagged with: python
has answer: http://stackoverflow.com/a/50176448
score: 4
tagged with: generator
downvote count: 0
has title: how to return multiple lines with python each time next() is called?
favorite count: 0
type: Question
upvote count: 4
has body: hello i am a beginner of python, there is a simple question. i'm asked to write a generator to traverse a txt file, each row in the file is 3 coordinates of a point (x,y,z) how to return 5 points(5 lines) each time next() is called? here is my code, i can only generate one line each time thx a lot! import itertools def gen_points(name): f=open(name) for l in f: clean_string=l.rstrip() x,y,z=clean_string.split() x= float(x) y= float(y) z= float(z) yield x,y,z f.close() file_name=r"D:\master ppt\Spatial Analysis\data\22.txt" a=gen_points(file_name) g=itertools.cycle(a) print(next(g))

http://stackoverflow.com/a/50161995
has comment: http://stackoverflow.com/comment/87342419
answers question: http://stackoverflow.com/q/50160676
has comment: http://stackoverflow.com/comment/87352632
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87344405
has body: So - not enough reputation to comment and ask for more info. To me it sounds like you have similar filenames in the bottom of the structure that you want copied to the same target folder? Ie you want all ACO files to end up in a folder named ACO??? You can only have one file with that name in a folder. So this first version will actually overwrite any similar named file in the target folder. Can you clarify what you really need? Ie an example of the target folder contents and filenames. # folder.py import os import sys import platform import shutil walk_dir = sys.argv[1] if platform.system() == 'Windows': delimiter = '\\' else: delimiter = '/' print('walk_dir = ' + walk_dir) print('walk_dir (absolute) = ' + os.path.abspath(walk_dir)) for root, subdirs, files in os.walk(walk_dir): print('--\ncurrent = ' + root) for filename in files: file_path = os.path.join(root, filename) print('\t- file %s (full path: %s)' % (filename, file_path)) target_name = root[root.rfind(delimiter)+2:len(root)] if not os.path.isdir(filename): os.mkdir(filename) target = filename + delimiter + filename + target_name shutil.copy2(file_path,target) Call it like this: C:\\Users\\MBobak\\Documents\\python folder.py Loop If you can give me more information I may be able to give you a better answer.
score: 3
has comment: http://stackoverflow.com/comment/87342909
upvote count: 3

http://stackoverflow.com/a/50243832
accepted answer of: http://stackoverflow.com/q/50195997
answers question: http://stackoverflow.com/q/50195997
downvote count: 0
score: 7
upvote count: 7
type: Answer
has comment: http://stackoverflow.com/comment/87585990
has body: Answering this for the most general case first. A dodge can be implemented by shifting the artists in the figure by some amount. It might be useful to use points as units of that shift. E.g. you may want to shift your markers on the plot by 5 points. This shift can be accomplished by adding a translation to the data transform of the artist. Here I propose a ScaledTranslation. Now to keep this most general, one may write a function which takes the plotting method, the axes and the data as input, and in addition some dodge to apply, e.g. draw_dodge(ax.errorbar, X, y, yerr =y/4., ax=ax, dodge=d, marker="d" ) The full functional code: import matplotlib.pyplot as plt from matplotlib import transforms import numpy as np import pandas as pd def draw_dodge(*args, **kwargs): func = args[0] dodge = kwargs.pop("dodge", 0) ax = kwargs.pop("ax", plt.gca()) trans = ax.transData + transforms.ScaledTranslation(dodge/72., 0, ax.figure.dpi_scale_trans) artist = func(*args[1:], **kwargs) def iterate(artist): if hasattr(artist, '__iter__'): for obj in artist: iterate(obj) else: artist.set_transform(trans) iterate(artist) return artist X = ["a", "b"] Y = np.array([[1,2],[2,2],[3,2],[1,4]]) Dodge = np.arange(len(Y),dtype=float)*10 Dodge -= Dodge.mean() fig, ax = plt.subplots() for y,d in zip(Y,Dodge): draw_dodge(ax.errorbar, X, y, yerr =y/4., ax=ax, dodge=d, marker="d" ) ax.margins(x=0.4) plt.show() You may use this with ax.plot, ax.scatter etc. However not with any of the seaborn functions, because they don't return any useful artist to work with. Now for the case in question, the remaining problem is to get the data in a useful format. One option would be the following. df1 = pd.DataFrame({'x':list('ffffssss'), 'y':[1,2,3,4,5,6,7,8], 'h':list('abababab')}) df2 = df1.copy() df2['y'] = df2['y']+0.5 N = len(np.unique(df1["x"].values))*len([df1,df2]) Dodge = np.linspace(-N,N,N)/N*10 fig, ax = plt.subplots() k = 0 for df in [df1,df2]: for (n, grp) in df.groupby("h"): x = grp.groupby("x").me…
type: AcceptedAnswer

http://stackoverflow.com/comment/87218927
has text: Well, since none of your three functions do anything, you can just delete them?
comment on: http://stackoverflow.com/q/50101185
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/comment/87187800
has text: so then, where is the answer?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50085847

http://stackoverflow.com/comment/87620234
type: Comment
type: AnswerComment
has text: note that only when I use the `combine_nets ` code it doesn't work. When I train on the net directly it of course, memorizes the single example, as expected.
score: 0
comment on: http://stackoverflow.com/a/50270587

http://stackoverflow.com/a/50148654
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50148436
type: Answer
has body: Since you are not explaining how you display trees I'll give you two examples. First how to get the coordinates of a mouse cilck: from tkinter import * root = Tk() root.geometry('200x200') def click(event): print(event.x,event.y) root.bind('&lt;Button-1&gt;', click) root.mainloop() Second, a way to pick objects on a canvas: import tkinter as tk import random def on_click(event): current = event.widget.find_withtag("current") if current: item = current[0] color = canvas.itemcget(item, "fill") label.configure(text="you clicked on item with id %s (%s)" % (item, color)) else: label.configure(text="You didn't click on an item") root = tk.Tk() label = tk.Label(root, anchor="w") canvas = tk.Canvas(root, background="bisque", width=400, height=400) label.pack(side="top", fill="x") canvas.pack(fill="both", expand=True) for color in ("red", "orange", "yellow", "green", "blue", "violet"): x0 = random.randint(50, 350) y0 = random.randint(50, 350) canvas.create_rectangle(x0, y0, x0+50, y0+50, outline="black", fill=color) canvas.bind('&lt;ButtonPress-1&gt;', on_click) root.mainloop()
score: 1

http://stackoverflow.com/a/70855052
has comment: http://stackoverflow.com/comment/130622810
type: Answer
has body: In older versions of PyJWT like 1.7 decode is required at the end: jwt.encode(payload, "SECRET_KEY", algorithm='HS256').decode('utf-8') If you are using the recent versions like 2.3.1 it is not necessary to dump or decode, a string will be generated already in UTF-8
score: 2
answers question: http://stackoverflow.com/q/50104782
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87334532
comment on: http://stackoverflow.com/a/50158287
score: 1
has text: Note you do lose the order of the original dataframe. This may or may not be important.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87273097
type: Comment
comment on: http://stackoverflow.com/q/50127352
type: QuestionComment
score: 0
has text: questions: 1) can you consider that the arrays are always growing? This means that in the new arrays there will be more information than in the old ones? 2) are the arrays always generated in the same order old and new?

http://stackoverflow.com/comment/87293366
has text: I did, but just get all nan when I do that
score: 0
comment on: http://stackoverflow.com/a/50137117
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50171141
tagged with: python
downvote count: 5
has comment: http://stackoverflow.com/comment/87376682
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87376850
answer count: 2
possible better answer: http://stackoverflow.com/a/50172001
upvote count: 2
has answer: http://stackoverflow.com/a/50180153
accepted answer: http://stackoverflow.com/a/50180153
has body: x = np.arange(0.3, 12.5, 0.6) print(x) [ 0.3 0.9 1.5 2.1 2.7 3.3 3.9 4.5 5.1 5.7 6.3 6.9 7.5 8.1 8.7 9.3 9.9 10.5 11.1 11.7 12.3] x = np.arange(0.3, 12.5, 0.6,int) print(x) [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
favorite count: 0
type: Question
has title: python numpy arange dtpye? why converting to integer was zero
has answer: http://stackoverflow.com/a/50172001
score: -3

http://stackoverflow.com/comment/87397448
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50190301
has text: It'll be better if you decide to try on your own first and show us that code.
score: 0

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/50089338
tags question: http://stackoverflow.com/q/50118797
tags question: http://stackoverflow.com/q/50209741
tags question: http://stackoverflow.com/q/50083362
tags question: http://stackoverflow.com/q/50217445
tags question: http://stackoverflow.com/q/50096984
tags question: http://stackoverflow.com/q/50191997
type: Tag
tags question: http://stackoverflow.com/q/50166145
tags question: http://stackoverflow.com/q/50176335
tags question: http://stackoverflow.com/q/50092818

http://stackoverflow.com/a/50104834
score: 1
type: Answer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50104782
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50104782
has comment: http://stackoverflow.com/comment/87227095
has comment: http://stackoverflow.com/comment/87228610
has body: Try importing json, and on your return use json.dumps(response_details): return Response(json.dumps(response_details), status=response_details['status'])

http://stackoverflow.com/comment/87205332
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50094461
score: 1
has text: What do u expect the output for: l1 = [12,23,34], l2=[13,34] res = ? This will give some more insight on problem understanding.

http://stackoverflow.com/q/50122145
tagged with: pandas
has body: I can produce horizontal stacked bars from a multi-index dataframe with this code: arrays = [np.array(['bar', 'bar', 'bar', 'baz', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux', 'qux']), np.array(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'])] s = abs(pd.Series(np.random.randn(12), index=arrays)) ax = s.unstack(level=1).plot.barh(stacked=True, colormap='Paired') plt.show() this outputs but I would like the largest segment on each bar (regardless of category) to always appear at the base of the bar (i.e. on the left). I haven't found any parameters for barh() that do the trick, and sorting s on level 0 doesn't help given the unstack-ing.
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87266072
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87262245
has comment: http://stackoverflow.com/comment/87262196
has comment: http://stackoverflow.com/comment/87266432
upvote count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50122514
favorite count: 0
has answer: http://stackoverflow.com/a/50124160
downvote count: 0
has title: pandas (horizontal) stacked bars, with per-bar segment sorting

http://stackoverflow.com/comment/87407375
score: 0
type: Comment
type: QuestionComment
has text: look into [`pandas.DataFrame.sample()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html)
comment on: http://stackoverflow.com/q/50195187

http://stackoverflow.com/a/55943881
score: 35
has comment: http://stackoverflow.com/comment/122971403
upvote count: 35
has comment: http://stackoverflow.com/comment/130577209
answers question: http://stackoverflow.com/q/50125472
downvote count: 0
type: Answer
has body: I try to create a virtual env with python 2.7 with anaconda, the base env is python 3.7. I encounter the exactly same problem. It turns out that there isn't such problem with other virtual envs with python 3.7 or 3.6. This post works perfectly to solve my problem on win7 with anaconda prompt. It basically says you need to add the following directories into your user environment path in windows (go to Start and type in: View Advanced System Settings, then select Environmental Variables: then select Path and click Edit: finally you can click New and add a path): C:\your_directory_to_anaconda3\Anaconda3\Scripts C:\your_directory_to_anaconda3\Anaconda3\ C:\your_directory_to_anaconda3\Anaconda3\Library\bin -- This is the directory for openssl
has comment: http://stackoverflow.com/comment/130392895

http://stackoverflow.com/comment/87193603
type: Comment
comment on: http://stackoverflow.com/q/50088789
type: QuestionComment
has text: You tried several things but they don't seem "right". Why not?
score: 1

http://stackoverflow.com/a/50126110
score: 1
has body: The problem is that without using list you are appending a reference to the same and only list col_placement you are working with (as you can see the results are not only wrong, but they are also the same). Using list creates a new copy (a instant snapshot of col_placement) that will not be modified when col_placement does as you keep going through the rest of the program. So essentially list(col_placement) is the same as col_placement.copy() or col_placement[:].
type: Answer
answers question: http://stackoverflow.com/q/50126058
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50162990
has comment: http://stackoverflow.com/comment/87349628
answers question: http://stackoverflow.com/q/50159989
type: Answer
has comment: http://stackoverflow.com/comment/87351868
has body: try python -m unittest test.runner. Here's the structure I used. ├── README.md ├── src │ ├── __init__.py │ └── foo.py └── test ├── __init__.py └── test_foo.py └── runner.py my foo.py contains a simple function, foo. I changed the import statement in the test_foo.py to the following: from src.foo import foo. I also ran directly from runner.py with the following changes. from test import test_foo and then in the command line at the parent directory, python -m unittest test.runner This structure only works from the parent directory. If I try it in the test directory, it fails to import.
score: 0
has comment: http://stackoverflow.com/comment/87352524
has comment: http://stackoverflow.com/comment/87351794
has comment: http://stackoverflow.com/comment/87351766

http://stackoverflow.com/a/50324991
has comment: http://stackoverflow.com/comment/102461343
has comment: http://stackoverflow.com/comment/119267616
has body: It is possible, but not easy. I would recommend you to use GradientBoostingClassifier from scikit-learn, which is similar to xgboost, but has native access to the built trees. With xgboost, however, it is possible to get a textual representation of the model and then parse it: from sklearn.datasets import load_iris from xgboost import XGBClassifier # build a very simple model X, y = load_iris(return_X_y=True) model = XGBClassifier(max_depth=2, n_estimators=2) model.fit(X, y); # dump it to a text file model.get_booster().dump_model('xgb_model.txt', with_stats=True) # read the contents of the file with open('xgb_model.txt', 'r') as f: txt_model = f.read() print(txt_model) It will print you a textual description of 6 trees (2 estimators, each consists of 3 trees, one per class), which starts like this: booster[0]: 0:[f2&lt;2.45] yes=1,no=2,missing=1,gain=72.2968,cover=66.6667 1:leaf=0.143541,cover=22.2222 2:leaf=-0.0733496,cover=44.4444 booster[1]: 0:[f2&lt;2.45] yes=1,no=2,missing=1,gain=18.0742,cover=66.6667 1:leaf=-0.0717703,cover=22.2222 2:[f3&lt;1.75] yes=3,no=4,missing=3,gain=41.9078,cover=44.4444 3:leaf=0.124,cover=24 4:leaf=-0.0668394,cover=20.4444 ... Now you can, for example, extract all splits from this description: import re # trying to extract all patterns like "[f2&lt;2.45]" splits = re.findall('\[f([0-9]+)&lt;([0-9]+.[0-9]+)\]', txt_model) splits It will print you the list of tuples (feature_id, split_value), like [('2', '2.45'), ('2', '2.45'), ('3', '1.75'), ('3', '1.65'), ('2', '4.95'), ('2', '2.45'), ('2', '2.45'), ('3', '1.75'), ('3', '1.65'), ('2', '4.95')] You can further process this list as you wish.
has comment: http://stackoverflow.com/comment/119279899
upvote count: 20
has comment: http://stackoverflow.com/comment/122920997
type: Answer
has comment: http://stackoverflow.com/comment/122920951
score: 20
answers question: http://stackoverflow.com/q/50175901
downvote count: 0

http://stackoverflow.com/q/50144283
linked to: http://stackoverflow.com/q/50112085
has answer: http://stackoverflow.com/a/50144339
possible better answer: http://stackoverflow.com/a/50144339
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87307368
downvote count: 0
has comment: http://stackoverflow.com/comment/87306837
has body: I have a numpy array src = np.random.rand(320,240) and another numpy array idx of size (2 x (320*240)). Each column of idx indexes an entry in a result array dst, e.g., idx[:,20] = [3,10] references row 3, column 10 in dst and the assumption is that 20 corresponds to the flattened index of src, i.e., idx establishes a mapping between the entries of src and dst. Assuming dst is initialized with all zeros, how can I copy the entries in src to their destination in dst without a loop?
has title: Python: Mapping between two arrays with an index array
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50144383
accepted answer: http://stackoverflow.com/a/50144383
tagged with: numpy
has comment: http://stackoverflow.com/comment/87306925

http://stackoverflow.com/a/50081942
score: 3
upvote count: 3
downvote count: 0
has body: Here's how you catch and use the output of linregress. from scipy.stats import linregress slope, intercept, r_value, p_value, std_err = linregress(T, smaxis) def a_predict(T): return intercept + slope*T T_min, T_max = min(T), max(T) a_min, a_max = a_predict(T_min), a_predict(T_max) plt.plot([T_min, T_max], [a_min, a_max], 'r--') print(slope, intercept, r_value, p_value, std_err) output: 0.10753736192332683 -1.3585120207927215 0.9841584242334624 0.015841575766537552 0.013698301731763748 (I got this from the documentation). But it may be more convenient for you to convert your lists into numpy arrays first. import numpy as np x = np.array(T) Then you can do vectorized calculations as in the example in the documentation: plt.plot(x, intercept + slope*x, 'r--')
accepted answer of: http://stackoverflow.com/q/50081796
answers question: http://stackoverflow.com/q/50081796
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87230036
type: QuestionComment
has text: (Posting the above comment as a comment and not an answer because I don't have a quick fix that would solve the problem; the best thing to do is simply to not call `goto()` inside a function bound to the canvas. But if he doesn't do that, how would the OP achieve his desired behavior?)
comment on: http://stackoverflow.com/q/50105860
score: 0
type: Comment

http://stackoverflow.com/a/50218988
has comment: http://stackoverflow.com/comment/87479593
has body: I just tried with 1.8.12 (and also with 1.8.14 the current and preferred version as well as with the current development version). I see on the Files page a link to myfile.py (as I removed the word myfile from the \file command). On the myfile.py page I see 1 link to myfile.func but the reference goes nowhere. When attempting the same with a C function it does work. Looking into the HTML code I see (for C), in the Functions part: &lt;a class="el" href="bb_8c.html#a916cba588658b3be41b91489a560a664"&gt;c_func&lt;/a&gt; and &lt;a href="#a916cba588658b3be41b91489a560a664"&gt;More...&lt;/a&gt; and further down in the Function Documentation part: &lt;a id="a916cba588658b3be41b91489a560a664"&gt;&lt;/a&gt; &lt;h2 class="memtitle"&gt;&lt;span class="permalink"&gt;&lt;a href="#a916cba588658b3be41b91489a560a664"&gt;&amp;#9670;&amp;nbsp;&lt;/a&gt;&lt;/span&gt;c_func()&lt;/h2&gt; Looking into the HTML code I see (for Python), in the Functions part: &lt;a class="el" href="myfile_8py.html#a3f1962c8fd3ce4b252b1015bf4cb3c32"&gt;myfile.func&lt;/a&gt; and &lt;a href="myfile_8py.html#a3f1962c8fd3ce4b252b1015bf4cb3c32"&gt;More...&lt;/a&gt; and further down in the Function Documentation part: &lt;a id="file_a3f1962c8fd3ce4b252b1015bf4cb3c32"&gt;&lt;/a&gt; &lt;h2 class="memtitle"&gt;&lt;span class="permalink"&gt;&lt;a href="#file_a3f1962c8fd3ce4b252b1015bf4cb3c32"&gt;&amp;#9670;&amp;nbsp;&lt;/a&gt;&lt;/span&gt;func()&lt;/h2&gt; Clearly the file_ in the Python version should not be present (the file_ has nothing to do with the filename as a filename like something.py gives the same result). Note: I found in the code, memberdef.cpp: // member is in a namespace, but is written as part of the file documentation // as well, so we need to make sure its label is unique. Edit: base on the suggestion I already made in the comments I just I've just pushed this as a proposed patch to github (pull request 720, https://github.com/doxygen/doxygen/pull/720).
has comment: http://stackoverflow.com/comment/87479197
score: 0
answers question: http://stackoverflow.com/q/50217315
has comment: http://stackoverflow.com/comment/87466091
has comment: http://stackoverflow.com/comment/87482211
type: Answer
has comment: http://stackoverflow.com/comment/87474086

http://stackoverflow.com/comment/87167529
comment on: http://stackoverflow.com/a/50075519
has text: That has worked! Is there anyway to just go straight to the line with the input? instead of printing Didnt find name for each line its not on since this txt file is going to have around 50 lines in it...
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50085212
favorite count: 0
type: Question
has body: Df1: Country Sex Year Bin NZ M 2005 1 NZ F 2005 1 NZ M 2007 3 KR F 2005 2 ... Df2: Country Sex Year Rate NZ M 2005 0.5 NZ M 2006 0.4 NZ F 2005 0.6 NZ F 2006 0.3 ... Desired Outcome: Country Sex Year Bin Rate NZ M 2005 1 0.5 NZ F 2005 1 0.6 NZ M 2007 3 NaN KR F 2005 2 NaN How do I join the dataframe of Df2 to achieve the desired outcome by matching the input on [Country, Sex and Year] of Df1. I've attempted merge/join but it seems to only recognize 1 column as the criteria for mapping and ended up joining all inputs together..
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/87186130
duplicate of: http://stackoverflow.com/q/41815079
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/41815079
score: 0
has title: Column Mapping on Multi-columns
answer count: 1
accepted answer: http://stackoverflow.com/a/50085272
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50085272

http://stackoverflow.com/a/60649344
answers question: http://stackoverflow.com/q/50120037
type: Answer
has body: I happened to get this error for my code and upgrading the Dash package helped to fix the issue. pip install dash --upgrade Before it was v1.4.0, an upgrade made it v1.9.1
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87276790
score: 0
has text: Running it from command line works, it doesn't generate this issue. How could that be?
type: QuestionComment
comment on: http://stackoverflow.com/q/50129135
type: Comment

http://stackoverflow.com/comment/87427888
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50169914
has text: Well, you will have to call the menu from somewhere and I didn't think this would be an obstacle for you. I changed the code so now I first create tha main window and call the popup menu from there. But how do you want it to behave? You'll have to think about that. Maybe what you want is a regular popup menu. It's possible to use the Tkinter menu for that.
type: Comment

http://stackoverflow.com/q/50204441
has answer: http://stackoverflow.com/a/50204607
has answer: http://stackoverflow.com/a/50232894
has comment: http://stackoverflow.com/comment/87425869
tagged with: python
tagged with: list-comprehension
answer count: 4
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50204710
downvote count: 0
possible better answer: http://stackoverflow.com/a/50204710
upvote count: 1
score: 1
has body: Stupid question but I can't make this work for the life of me. I have a simple function that takes a column value, and returns all rows with that column value. Say it returns all the books by a publisher: def book_publisher(publisher, df): books = df.loc[df['publisher_name'] == name]['book_name'] return [books] Using this function, I'd like to get a list of lists for books by all publishers: [[book1, book2,],[book3, book4]] The end goal is to created a dictionary like so: {publisher1:[list of books], publisher2:[list of books]} I figured I would just use zip(list of publishers, list of books) to get there but cannot figure out how to get a list of books for each publisher.
accepted answer: http://stackoverflow.com/a/50204607
has title: Python apply function to a list, store result as a list
has answer: http://stackoverflow.com/a/54324239
favorite count: 0
type: Question

http://stackoverflow.com/q/50116728
answer count: 2
upvote count: 1
type: UnansweredQuestion
has title: skimage max image resolution (memoryerror)
favorite count: 0
has answer: http://stackoverflow.com/a/50209331
has answer: http://stackoverflow.com/a/50128080
downvote count: 0
score: 1
has body: At the moment i'm using scikit-image as a way to process my images in python. But after some testing I found out that scikit-image doesn't work with images which have a to high resolution. I tried to use a image with a resolution of 3024 x 4032 but it results in a MemoryError error. This happens on multiple different methods provided by scikit-image. I've found out that it does work if I downscale the image to a way lower resolution. I want to know the maximum allowed resolution is so that I can downscale my images without losing too much of it's quality. And that I can check if a resolution is too big.
tagged with: scikit-image
tagged with: python
tagged with: image-processing
type: Question

http://stackoverflow.com/comment/87384579
comment on: http://stackoverflow.com/a/50181068
has text: Welcome to Stack Overflow, typos should be deleted (by clicking the `delete` button) since not many people will benefit from finding typographical error questions.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50195280
has comment: http://stackoverflow.com/comment/87407511
type: Answer
accepted answer of: http://stackoverflow.com/q/50127246
answers question: http://stackoverflow.com/q/50127246
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: I was able to fix the issue with the low-density, poor resolution pixmaps by inferring the fact that a 30x30 pixmap ought not to be as large as it was on my screen - in the end, I found that I needed to use setDevicePixelRatio(X) where X is a float greater than 1.0. See the below example: # Device pixel ratio must be set AFTER loading the data! print(pix_map.devicePixelRatio()) # 1.0 pix_map.loadFromData(image_data) pix_map.setDevicePixelRatio(2.0) print(pix_map.devicePixelRatio()) # 2.0

http://stackoverflow.com/comment/109746723
has text: @iowatt not sure what you are trying to point out but it's the same in any python3 version. The check you need to test is `isinstance(True, int)`.
type: Comment
comment on: http://stackoverflow.com/a/50118464
score: 0
type: AnswerComment

http://stackoverflow.com/a/50197071
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50197038
type: Answer
has body: You can use *args def f(*args): return(sum(args)) &gt;&gt;&gt;f(1,2,3,4) 10 &gt;&gt;&gt;f(1,2) 3

http://stackoverflow.com/q/50170673
has answer: http://stackoverflow.com/a/50170722
possible better answer: http://stackoverflow.com/a/50170722
type: AnsweredQuestion
tagged with: list
answer count: 3
has title: Split the string and save it into a list orderly in python
score: 1
has body: In the codes,result shows "['fi', 'lou', 'you']".But i want to split the string "fi lou you",and save 'fi' in a[0], 'lou' in a[1],'you' in a[2].How can i achieve it. a=['fi lou you'.split()] print(a[0])
downvote count: 1
tagged with: string
favorite count: 0
type: Question
upvote count: 2
tagged with: split
has answer: http://stackoverflow.com/a/50170864
has comment: http://stackoverflow.com/comment/87358663
has comment: http://stackoverflow.com/comment/87395362
tagged with: python
has answer: http://stackoverflow.com/a/50170803
accepted answer: http://stackoverflow.com/a/50170803

http://stackoverflow.com/comment/87345973
type: Comment
score: 2
has text: I think you're looking for the [descriptor protocol](https://docs.python.org/3/howto/descriptor.html).
type: QuestionComment
comment on: http://stackoverflow.com/q/50163988

http://stackoverflow.com/a/50138987
has comment: http://stackoverflow.com/comment/87297911
has comment: http://stackoverflow.com/comment/87298082
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50138015
answers question: http://stackoverflow.com/q/50138015
score: 0
has comment: http://stackoverflow.com/comment/87298560
type: Answer
has body: This should help. Demo: from bs4 import BeautifulSoup import requests import json import os import re # Download the page url = 'https://bato.to/chapter/1204541.com' source = requests.get(url).text soup = BeautifulSoup(source, "html.parser") scr = soup.find_all("script") pattern = re.compile(r"var\s+images\s+=(.*)") #Regex to get the script with var images for i in scr: m = pattern.search(i.text) if m: print(json.loads(m.group(1).replace(";", ""))) Output: {u'56': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/db2065e24505b2b3ef633917cca106864aa22baf_436436_800_1138.png', u'54': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/ef7215fe9b2dc00607518a8b14d92e8848ba71b0_507280_800_1138.png', u'42': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/4fdd26894c2a900d4c0cc3ddcf340973419a93a6_533468_800_1138.png', u'48': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/dcc84a86d5379c830f0c0087339cb685ca757999_547146_800_1138.png', u'43': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/0ca26c4e3d2d26be25b9bca9b50302ccf1117f80_579802_800_1138.png', u'49': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/de9b88d1ccfc9acf6a437fff49bf73a535af6370_886149_1600_1138.png', u'52': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/d3c65f840473c8f14de55fda2581e0fa24433410_563860_800_1138.png', u'53': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/373a7b778e7d335d6d75f611c43559286b3905a0_523659_800_1138.png', u'24': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/4b8d797546fc185eedcb7efbad5e1e50a4f565cc_479310_800_1138.png', u'25': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/39c1028bc26adb25171e79b8c739422b8d7c6780_492937_800_1138.png', u'26': u'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/e27a386a1f7e95fade1822e5f71dc23797289f08_1069178_1600_1138.png', u'27': u'https://file-comic-…
has comment: http://stackoverflow.com/comment/87297754

http://stackoverflow.com/q/50177846
has answer: http://stackoverflow.com/a/50178014
answer count: 2
tagged with: pycharm
tagged with: installation
has comment: http://stackoverflow.com/comment/87373036
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87373058
has title: Can a virtual environment be used with two versions of python say 2.7.10 and 3.0?
has body: I would like to know if a given virtual environment can be used with two Python interpreters and if so how. If not, what is the best way to switch interpreters to test the code with two versions? (Bonus: I was trying to do this from within Pycharm so any specifics on this particular IDE would be great too). There is a similar question here: Activating the virtualenv of two different version of Python but it's not exactly the same for two reasons. First, because I'm interested NOT IN TWO VIRTUAL ENVIRONMENTS but instead in using only ONE ENVIRONMENT which was not addressed there. Second, because I'm interested in alternating and as one of the responses very accurately states it, PyCharm has some tools to address this problem.
tagged with: python
tagged with: virtualenv
linked to: http://stackoverflow.com/q/45809731
type: Question
accepted answer: http://stackoverflow.com/a/50178080
possible better answer: http://stackoverflow.com/a/50178014
has answer: http://stackoverflow.com/a/50178080

http://stackoverflow.com/a/50082998
has comment: http://stackoverflow.com/comment/87182017
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50082965
upvote count: 1
answers question: http://stackoverflow.com/q/50082965
has comment: http://stackoverflow.com/comment/87182042
has body: The main problem here is that you do actually generate a new number each time, even if the guess was wrong. Instead you should generate the first random number outside of the loop, and only generate a new random number if the guess was correct: import random guess = '0' answer = random.randrange(1, 100) while (guess) != 'exit': answer = str(answer) guess = input('Enter a number between 1 and 100 or enter exit to exit: ') if not guess.isdigit(): if guess == "exit": print('Game closed') break else: print('Your guess was not a digit, try again') guess = (guess) if guess == answer: print('Correct') answer = random.randrange(1, 100) #make new random number if guess is correct elif guess &gt; answer : print('Too high, try again') elif guess &lt; answer : print('Too low, try again')
type: Answer
has comment: http://stackoverflow.com/comment/87181911

http://stackoverflow.com/comment/87251175
has text: Thank you Joe for your detailed explanation. The `df.rolling` is exactly what I was looking for!
type: Comment
comment on: http://stackoverflow.com/a/50116357
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87283848
has text: For significant performance improvements, you need to consider 3rd party libraries, e.g. see [this answer](https://stackoverflow.com/a/48600345/9209546).
type: Comment
comment on: http://stackoverflow.com/q/50132383
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87364667
has text: I should note as well. I plan to transfer what I wrote to a raspberry pi so I'm avoiding calling the os
comment on: http://stackoverflow.com/q/50172934
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87421877
type: Comment
has text: No solution works for me.. :(
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50187767

http://stackoverflow.com/comment/87308840
score: 0
type: Comment
type: AnswerComment
has text: Traceback (most recent call last): File "C:\Users\mohdi\Downloads\Python\Python OOP RPG.py", line 72, in <module> character.equipArmor() File "C:\Users\mohdi\Downloads\Python\Python OOP RPG.py", line 33, in equipArmor print(str(select) + ". " + str(armor["Name"])) TypeError: string indices must be integers
comment on: http://stackoverflow.com/a/50145314

http://stackoverflow.com/comment/87421956
score: 0
has text: Sure. I've edited the post.
type: Comment
comment on: http://stackoverflow.com/q/50197027
type: QuestionComment

http://stackoverflow.com/comment/87398532
has text: No, google "python mysql parameter substitution" and make an attempt.
type: QuestionComment
comment on: http://stackoverflow.com/q/50190682
type: Comment
score: 0

http://stackoverflow.com/comment/120861410
has text: you can use Kaggle for testing your model.
type: QuestionComment
comment on: http://stackoverflow.com/q/50209661
type: Comment
score: 0

http://stackoverflow.com/comment/87201570
comment on: http://stackoverflow.com/q/50092665
score: 0
type: QuestionComment
has text: Without knowing what you want to use `partotal` for, it's very hard to suggest how to build it. Are you looking for a 4x3 array? An array of 4 lists? Or an array of arrays? Something different? You can build a 4x3 array out of either `np.array([par1, par2, par3, par4])` or by just `stack`ing the arrays together, but I don't know if that's what you're looking for.
type: Comment

http://stackoverflow.com/q/50209928
tagged with: python
has title: PySCIPOpt/SCIP - isLPSolBasic() not in pyscipopt.scip.Model
score: 0
has body: I developed a gomory cut for a LP problem (based on 'test-gomory.py' test file) which I could not manage to run. Finally, I copied the test file to check whether I'd the same trouble. Indeed I got the same message: if not scip.isLPSolBasic(): AttributeError: 'pyscipopt.scip.Model' object has no attribute 'isLPSolBasic' I have downloaded SCIPOptSuite 5.0.1 win64, set up path and installed pyscipiopt using pip on conda. I cannot figure what is wrong, except that I may have failed to install pyscipopt properly? Thank you for pointing me in the right direction.
answer count: 1
tagged with: scip
type: Question
tagged with: discrete-mathematics
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50210208

http://stackoverflow.com/a/50134204
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/50123599
has comment: http://stackoverflow.com/comment/87307690
type: Answer
accepted answer of: http://stackoverflow.com/q/50123599
upvote count: 2
has body: This approach works as expected for me. I had to make a couple of minor changes however: 1) I had to change the names of the functions from get and post to do_get and do_post. Django seems to do something special when the functions are named the same as the HTTP methods themselves. 2) I inlined calling as_view() directly in the urls.py. So after doing that: urlpatterns = [ # for GET path('A/&lt;str:param1&gt;/&lt;path:param2&gt;', views.AQuery.as_view({'get':'do_get'}), name='A query GET') # for POST path('A', views.AQuery.as_view({'post':'do_post'}), name='A query POST') ... ] The result: GET A/param1/param2 -&gt; 200 OK GET A/ -&gt; 405 Method Not Allowed POST A/param1/param2 -&gt; 405 Method Not Allowed POST A/ -&gt; 200 OK
type: AcceptedAnswer

http://stackoverflow.com/comment/87194765
has text: I agree with Adi219, the error seems not to be in the posted line. Please post more context!
comment on: http://stackoverflow.com/q/50088113
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50090072
tagged with: python-2.7
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/87196439
answer count: 4
has answer: http://stackoverflow.com/a/50090200
type: Question
has answer: http://stackoverflow.com/a/50090096
possible better answer: http://stackoverflow.com/a/50090096
tagged with: python-3.x
has title: Why did we use Lambda as function argument here?
has comment: http://stackoverflow.com/comment/87196399
linked to: http://stackoverflow.com/q/3755136
has comment: http://stackoverflow.com/comment/87196495
has answer: http://stackoverflow.com/a/50090211
accepted answer: http://stackoverflow.com/a/50090211
has answer: http://stackoverflow.com/a/50090181
tagged with: python
has comment: http://stackoverflow.com/comment/87196790
has comment: http://stackoverflow.com/comment/87196344
has comment: http://stackoverflow.com/comment/87196299
has body: Few questions on the below code to find if a list is sorted or not: Why did we use lambda as key here ? Does it always mean key of a list can be derived so ? In the enumerate loop , why did we compare key(el) &lt; key(lst[i]) and not key(el) &lt;key(el-1) or lst[i+1] &lt;lst[i] ? def is_sorted(lst, key=lambda x:x): for i, el in enumerate(lst[1:]): if key(el) &lt; key(lst[i]): # i is the index of the previous element return False return True hh=[1,2,3,4,6] val = is_sorted(hh) print(val) (NB: the code above was taken from this SO answer)
type: AnsweredQuestion

http://stackoverflow.com/q/50142334
type: Question
answer count: 0
upvote count: 2
score: 2
type: UnansweredQuestion
downvote count: 0
tagged with: nlme
tagged with: http://stackoverflow.com/tag/r
tagged with: statsmodels
has body: I'm trying to compare two models using R's nlme package import rpy2.robjects.robject as r &gt;&gt; politeness = pd.read_csv('http://www.bodowinter.com/tutorial/politeness_data.csv') &gt;&gt; mdl1=nlme.gls(Formula('frequency ~ 1'), data=politeness, method="ML", na_action="na.omit") &gt;&gt; mdl2=nlme.lme(Formula('frequency ~ 1'), data=politeness, method="ML", random=Formula("~1|subject"), na_action="na.omit") &gt;&gt; print(r.anova(mdl1,mdl2)) This prints lots of output but not the one I'm really interested in. In R I simply get: Model df AIC BIC logLik Test L.Ratio p-value mdl1 1 2 932.8611 937.6988 -464.4306 mdl2 2 3 833.2497 840.5063 -413.6249 1 vs 2 101.6114 &lt;.0001 Is there a way to get something similar in python (statsmodels?)?
has title: comparing mixed models in python
tagged with: python
favorite count: 0

http://stackoverflow.com/q/50124334
has body: I have created a unique member-level dataframe that looks like this: memberid codes cost memberA {c1, c2} 100.0 memberB {c2, c3} 120.0 memberC {c1, c5} 200.0 The values of codes are sets. I am trying to get some correlations between individual codes and cost, in order to eventually build a predictive model using some other features I have. Outside Pandas I have created a Counter() that sorted the codes by prevalence: all_codes = [] for entry in df['codes'].values: for code in entry: all_codes.append(code) common_code_info = Counter(all_codes).most_common() common_codes = [el[0] for el in common_code_info] There is a total of ~500 codes in common_codes, and I would like to create the same amount of dummy variables, but I am not sure how can I do it in Pandas. I tried something like: for code in common_codes: if code in df['codes'].values: df['has_'+code] = 1 else: df['has_'+code] = 0 but it didn't work (all dummy columns are zeroes). Is there a simple way to populate these dummy columns, since get_dummies can not be used because the "source" of the potential dummy variables lives outside the dataframe? Unless there is a simpler way to do everything I am looking for just using Pandas. EDIT: The codes are diagnostic codes, so they have values like C801, R911, etc. The resulting dataframe should look like: memberid codes cost has_c1 has_c2 has_c3 memberA {c1, c2} 100.0 1 1 0 memberB {c2, c3} 120.0 0 1 1 memberC {c1, c5} 200.0 1 0 0 I have also tried: for code in common_codes: df['has_'+code] = np.where(code in df['codes'], 1, 0) but this didn't work either. Code for the sample dataframe: data = {'memberid': ['memberA', 'memberB', 'memberC'], 'codes': [{c1, c2}, {c2, c3}, {c1, c5}], 'cost': [100.0, 120.0, 200.0]} df = pd.DataFrame(data, columns = ['memberid', 'codes', 'cost'])
tagged with: pandas
has title: batch-populate dummy variable columns in pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50124681
accepted answer: http://stackoverflow.com/a/50124681
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87267374
tagged with: dummy-variable
has comment: http://stackoverflow.com/comment/87267248
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/87225879
comment on: http://stackoverflow.com/a/50076944
type: AnswerComment
has text: Fine, btw, event.keysym == "backspace" must be BackSpace and event.keysym == "return" must be Return for it to work, and you forgot to call the main() function, but thanks anyway @Coal_ :)
score: 0
type: Comment

face-recognition
tags question: http://stackoverflow.com/q/50187670
tags question: http://stackoverflow.com/q/50164291
tag name: face-recognition
type: Tag

http://stackoverflow.com/a/73680462
answers question: http://stackoverflow.com/q/50144628
upvote count: 4
has body: I wanted to have JSON output, so that I could handle it nicer in Promtail and Loki. I just updated the formatter in my logging.json, which I use as a dictConfig "formatters": { "normalFormatter": { "format": "{\"time\": \"%(asctime)s\", \"name\": \"[%(name)s]\", \"levelname\": \"%(levelname)s\", \"message\": \"%(message)s\"}" } } Load the config and get the root logger like: import json import logging # setup logger with open("logging.json") as f: config_dict = json.load(f) logging.config.dictConfig(config_dict) # get root logger logger = logging.getLogger(__name__) If you want to use dictConfig, please make sure you gave all necessary fields. https://docs.python.org/3/library/logging.config.html You may want to define a formatter, a handler (which is using the formatter) and the logger (which is using the handler) e.g. logging.json { "version": 1, "disable_existing_loggers": false, "formatters": { "normalFormatter": { "format": "{\"time\": \"%(asctime)s\", \"name\": \"[%(name)s]\", \"levelname\": \"%(levelname)s\", \"message\": \"%(message)s\"}" } }, "handlers": { "demohandler": { "level": "INFO", "formatter": "normalFormatter", "class": "logging.handlers.TimedRotatingFileHandler", "filename": "./files/logs/YourLogFile.log", "when": "d", "interval": 30, "backupCount": 4, "utc": true } }, "loggers": { "root": { "handlers": ["demohandler"], "level": "INFO" }, "someModule": { "handlers": ["demohandler"], "level": "INFO", "propagate": 0 } } }
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/q/50174305
has comment: http://stackoverflow.com/comment/87366044
has comment: http://stackoverflow.com/comment/87366588
score: 0
has body: I am a Java programmer making his way into Python, and some things are just baffling. For example, adding variables to functions, dynamically. For example: def main(): print ("Hello World") main.temp = 50 print (main.temp) What does that even mean? Why would you want to add a variable to a function? Why is that allowed? And why am I allowed to reference the function via main.temp?
has comment: http://stackoverflow.com/comment/87366633
has comment: http://stackoverflow.com/comment/87366403
has comment: http://stackoverflow.com/comment/87365612
has comment: http://stackoverflow.com/comment/87365562
answer count: 1
has comment: http://stackoverflow.com/comment/87366600
has comment: http://stackoverflow.com/comment/87365638
linked to: http://stackoverflow.com/q/33959795
type: Question
has comment: http://stackoverflow.com/comment/87366808
linked to: http://stackoverflow.com/q/338101
has comment: http://stackoverflow.com/comment/87366359
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87366203
has comment: http://stackoverflow.com/comment/87365743
has title: Python - Adding variable to functions on the fly. Why is this possible?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50174357
duplicate of: http://stackoverflow.com/q/338101

http://stackoverflow.com/comment/87396846
has text: Yeah, it didnt do anything though...
comment on: http://stackoverflow.com/q/50187281
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87421471
has text: You likely need to set the `encoding`: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50202369
type: Comment

http://stackoverflow.com/comment/87316197
has text: My app intends to install the program first and close it, then later on aims to launch it. there are some processes in between
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50144847
score: 0

http://stackoverflow.com/comment/87270960
comment on: http://stackoverflow.com/q/50120769
type: Comment
type: QuestionComment
score: 1
has text: Also, the `webbrowser.open()` starts another process using `subprocess.popen()` to run the browser.

http://stackoverflow.com/q/50109629
tagged with: python
has comment: http://stackoverflow.com/comment/87237370
tagged with: conv-neural-network
score: 0
has title: Image classification with Keras: "expected activation_1 to have shape (2,) but got array with (1,)"
tagged with: keras
answer count: 1
tagged with: tensorflow
has body: I'm training an image classifier to distinguish cats and dogs, from the Kaggle set. Here's my relevant code: FINAL_ACTIVATION = "softmax" OPTIMIZER = keras.optimizers.Adamax() STRIDES = (2, 2) DROPOUT = 0.5 model = Sequential() model.add(Conv2D(32, (3, 3), input_shape = INPUT_SHAPE)) model.add(keras.layers.ELU()) model.add(MaxPooling2D(pool_size = (2, 2), strides = STRIDES)) model.add(Conv2D(64, (3, 3))) model.add(keras.layers.ELU()) model.add(MaxPooling2D(pool_size = (2, 2), strides = STRIDES)) model.add(Conv2D(128, (3, 3))) model.add(keras.layers.ELU()) model.add(MaxPooling2D(pool_size = (2, 2), strides = STRIDES)) model.add(Conv2D(128, (3, 3))) model.add(keras.layers.ELU()) model.add(MaxPooling2D(pool_size = (2, 2), strides = STRIDES)) model.add(Flatten()) model.add(Dense(100)) model.add(keras.layers.ELU()) model.add(Dropout(DROPOUT)) model.add(Dense(50)) model.add(keras.layers.ELU()) model.add(Dropout(DROPOUT)) model.add(Dense(2)) model.add(Activation(FINAL_ACTIVATION)) model.compile( loss="categorical_crossentropy", optimizer = OPTIMIZER, metrics = ["accuracy"] ) train_datagen = ImageDataGenerator( rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True ) train_generator = train_datagen.flow( x_train, y_train, batch_size = BATCH_SIZE ) model.summary() model.fit_generator( train_generator, steps_per_epoch = x_train.shape[0] // BATCH_SIZE, epochs = EPOCHS ) Due to the large number of training files, there's no testing set. However, when I try to train this network I get the error "ValueError: Error when checking target: expected activation_1 to have shape (2,) but got array with shape (1,)." What am I doing wrong here? Convolutional neural networks are still a little bit of black magic to me, so I may be making some beginner mistakes here. I figure I probably am. Here's my model: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================…
has answer: http://stackoverflow.com/a/50110117
type: Question
tagged with: neural-network
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87245898

http://stackoverflow.com/q/50149707
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/87317469
has comment: http://stackoverflow.com/comment/87326420
score: 0
has comment: http://stackoverflow.com/comment/87336599
has answer: http://stackoverflow.com/a/50168151
has title: Not Null Constraint Failed - null=True already set
has comment: http://stackoverflow.com/comment/87317528
answer count: 1
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
has body: I am changing my register model so that there is a foreign key referencing a location. What I want to achieve, is to have a relationship where the Register model can have 0 to many locations. Originally I set a manytomany field which I realised was a mistake as it gives each Register all of the locations in existence. I just want a subset for each Register. My model now looks like: class Register(AbstractBaseUser, models.Model): username = models.CharField(max_length=20,default='',blank=True) password = models.CharField(max_length=80,default='',blank=True) email = models.CharField(max_length=255,default='',blank=True) #Added 2nd May #locations = models.ManyToManyField(Location) #3rd May change to foreign key locations = models.ForeignKey(Location,on_delete=models.CASCADE, blank=True, null=True, default='') USERNAME_FIELD = 'username' The model referenced is: class Location(models.Model): locationname = models.CharField(max_length=80,default='',blank=True) address = models.ForeignKey(Address, on_delete=models.CASCADE) geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='') When I try to migrate I get the error below. I have ran makemigrations and if I run it again it states there are no changes. "NOT NULL constraint failed: register_register.locations_id" I have been searching other posts and it suggested adding the null=True argument which I have added, but I still get this error. I can't find any posts where this has been done and it still gives this error.

http://stackoverflow.com/q/50152243
downvote count: 3
answer count: 7
has answer: http://stackoverflow.com/a/50152304
has answer: http://stackoverflow.com/a/50152541
has answer: http://stackoverflow.com/a/50152733
has answer: http://stackoverflow.com/a/50152857
favorite count: 0
has answer: http://stackoverflow.com/a/50152289
possible better answer: http://stackoverflow.com/a/50152289
type: Question
tagged with: python-3.x
has title: How to compare int and list of int in python3
has answer: http://stackoverflow.com/a/50158846
has body: Compare a list of int with an int: a = [-1,-1,0,2] a &gt; 1 I want to get a result looks like: [False,False,False,True] How can I do this in Python3 ?
score: -2
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50152310
upvote count: 1
accepted answer: http://stackoverflow.com/a/50152310

http://stackoverflow.com/comment/87310930
has text: @TeodoricoLevoff Also note, that you might need to use `np.allclose()` rather than `np.all()` if you're dealing with floating point numbers.
comment on: http://stackoverflow.com/a/50146326
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50113684
favorite count: 0
type: Question
upvote count: 2
has title: Unable to read images using an opencv in python
has answer: http://stackoverflow.com/a/50406755
has comment: http://stackoverflow.com/comment/87244397
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: opencv
score: 2
has comment: http://stackoverflow.com/comment/87245194
downvote count: 0
has body: hello I am trying to train this model that is used to detect if a person's eye is open or closed. I want to read .jpg images from dataset folder using opencv library in python. The code is def load_images(self,dataframe): output = np.zeros((len(dataframe),self.image_shape[0],self.image_shape[1])) for index,row in dataframe.iterrows(): img = cv2.imread(row["file_location"].replace(row["file_location"],"home/samuel/Desktop/eye-closed/dataset_B_FacialImages")) if img is None: print ("Cv2 error: Unable to read from '"+row["file_location"].replace(row["file_location"],"home/samuel/dataset/eye-closed/dataset_B_Eye_Images/closedLeftEyes/*.jpg")+"'") continue img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) output[index] = img return output I is giving me the error Cv2 error: Unable to read from 'home/samuel/dataset/eye-closed/dataset_B_Eye_Images/closedLeftEyes/*.jpg' I don't know what is wrong. Can anyone help me with this?
linked to: http://stackoverflow.com/q/3964681

http://stackoverflow.com/comment/87255208
comment on: http://stackoverflow.com/q/50118684
type: Comment
score: 0
has text: ComboBox has no clear function. QComboBox is different to ComboBox
type: QuestionComment

http://stackoverflow.com/a/68381018
downvote count: 0
has body: I usually just declare the base class's __init__ with @abc.abstractmethod. If my base class does not have an __init__, I add a trivial one. Something like this: class AbstractClass(abc.ABC): @abc.abstractmethod def __init__(self): pass # other useful non-abstract methods... class ChildClass(AbstractClass): def __init__(self): pass if __name__ == '__main__': child = ChildClass() # allowed abstract = AbstractClass() # TypeError
upvote count: 9
answers question: http://stackoverflow.com/q/50099600
type: Answer
has comment: http://stackoverflow.com/comment/139823931
score: 9

http://stackoverflow.com/comment/87295668
type: Comment
type: QuestionComment
has text: This depends on how you send you data, but you may be running into [buffering issues](https://docs.python.org/3.3/howto/sockets.html#using-a-socket).
comment on: http://stackoverflow.com/q/50138555
score: 0

http://stackoverflow.com/q/50212950
has title: Add space between Persian numeric and letter with python re
has answer: http://stackoverflow.com/a/50214293
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50214293
answer count: 3
has answer: http://stackoverflow.com/a/50213549
upvote count: 1
downvote count: 1
tagged with: regex
has comment: http://stackoverflow.com/comment/87443379
has answer: http://stackoverflow.com/a/50213141
type: Question
possible better answer: http://stackoverflow.com/a/50213141
has comment: http://stackoverflow.com/comment/87443549
linked to: http://stackoverflow.com/q/22565100
tagged with: python
has body: I want to add space between Persian number and Persian letter like this: "سعید123" convert to "سعید 123" Java code of this procedure is like below. str.replaceAll("(?&lt;=\\p{IsDigit})(?=\\p{IsAlphabetic})", " "). But I can't find any python solution.
tagged with: persian
favorite count: 0
has comment: http://stackoverflow.com/comment/113428500

http://stackoverflow.com/a/50165871
has comment: http://stackoverflow.com/comment/87350247
accepted answer of: http://stackoverflow.com/q/50165379
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50165379
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87350629
has body: Is this what you need ? ('Zone: '+df.zone.astype(str)+', Script: '+df.script+','+df.totalcount.astype(str)+' Successful Completions') Out[648]: 0 Zone: 2.0, Script: Consumers,1 Successful Comp... 1 Zone: 2.0, Script: Inventory,1 Successful Comp... 2 Zone: 2.0, Script: Orders_Details,1 Successful... 3 Zone: 3.0, Script: Consumers,1 Successful Comp... 4 Zone: 3.0, Script: Inventory,1 Successful Comp... 5 Zone: 3.0, Script: Orders_Details,1 Successful... 6 Zone: 6.0, Script: Birthday,1 Successful Compl... dtype: object
score: 1
type: Answer

http://stackoverflow.com/a/50201499
has comment: http://stackoverflow.com/comment/87420588
type: Answer
has comment: http://stackoverflow.com/comment/87420557
has comment: http://stackoverflow.com/comment/87420440
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87420261
has body: Base on your description , I think you need pub_cat_group = headline_df.groupby(['PUBLISHER', 'CATEGORY'])['TITLE'].count() # I am adding the unstack, here for you to plot New=pub_cat_group.sort_values().groupby(level=[0,1]).head(10).unstack() Update: pub_cat_group.sum(level=0).sort_values().head(10)
answers question: http://stackoverflow.com/q/50201057
has comment: http://stackoverflow.com/comment/87420372

http://stackoverflow.com/q/50154447
has comment: http://stackoverflow.com/comment/87326733
has comment: http://stackoverflow.com/comment/87326421
has answer: http://stackoverflow.com/a/50154710
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/50154670
has comment: http://stackoverflow.com/comment/87326462
score: -2
tagged with: arrays
has comment: http://stackoverflow.com/comment/87326433
has title: Errors trying to append specific number of floats from user input
tagged with: input
has answer: http://stackoverflow.com/a/50154670
tagged with: python
type: AnsweredQuestion
downvote count: 4
answer count: 3
upvote count: 2
accepted answer: http://stackoverflow.com/a/50154658
favorite count: 0
type: Question
has body: x={} continueQ=input("would you like to continue?")) if (continueQ=="yes"): #if there is less than 4 if x&lt;4: variable=float(input("Input a float to append to the array:") x.append(variable) print(x) else: print(x) else: print("Goodbye!") There are a few errors in this code, could someone help me how to create an if statement to check if there are minimum than 4 values inside an array . Also how to append to an array from an input.
has comment: http://stackoverflow.com/comment/87326401
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50154658

http://stackoverflow.com/q/50115074
has answer: http://stackoverflow.com/a/50115158
has title: Pandas round is truncating in some cases
tagged with: rounding
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
tagged with: truncate
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/87264847
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87249028
answer count: 1
has body: I am using the following code and as you can see in the 2nd row, the rounding is correct while in the 3rd row, the data is being truncated. import pandas as pd import numpy as np data = [[11,10],[17.50,11.01],[21.95,22.5]] df = pd.DataFrame(data,columns=['A','B']) df['avg'] = df"A", "B".mean(axis=1) df['avg_round'] = df['avg'].apply(lambda x: np.round(x, decimals=2)) I have tried this as well and the results are identical: df['avg] = df"A", "B".mean(axis=1).round(2)
has comment: http://stackoverflow.com/comment/87247314
favorite count: 0
type: Question

http://stackoverflow.com/a/50190893
answers question: http://stackoverflow.com/q/50190463
upvote count: 2
has body: Well, when you receive an TypeError: 'NoneType' object is not subscriptable error you are trying to do something like None[0]. And your problem is here: self.word2weight = None and then you are trying to access it here: np.mean([self.word2vec[w] * self.word2weight[w] Maybe you need to call the function fit first which writes in word2weight
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50190463
has comment: http://stackoverflow.com/comment/87408160

http://stackoverflow.com/comment/87225798
comment on: http://stackoverflow.com/a/50099648
score: 0
type: Comment
type: AnswerComment
has text: It is working, but after the pool the objects' attributes which should have something now are empty.

http://stackoverflow.com/comment/87254623
type: QuestionComment
score: 8
type: Comment
comment on: http://stackoverflow.com/q/50118669
has text: Do you ever run your function? You're just defining it in the code you have posted.

http://stackoverflow.com/comment/87238578
has text: What in particular is bad design? The reason for this bottle neck is I need to run two class functions against each other to test, while keeping sub functions (used within the swap functions) constant. Thank you by the way!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50110615

http://stackoverflow.com/comment/87241918
has text: I think you are looking for this https://stackoverflow.com/questions/8370206/how-to-get-a-list-of-built-in-modules-in-python
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50112359

http://stackoverflow.com/comment/87294940
score: 0
comment on: http://stackoverflow.com/q/50138043
type: Comment
type: QuestionComment
has text: @What this specific file has more than one set of data

http://stackoverflow.com/q/50092110
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50225535
type: AnsweredQuestion
score: 2
has body: I have a TF model which I need to convert to int8 for implementation in an embedded device. I am attempting to use toco to convert it, yet I am having trouble determining how to instantiate toco with the input args properly: &lt;USER&gt;:~/.local/bin$ python3 toco \ &gt; --input_file=&lt;PATH&gt;/frozen_graph.pb \ &gt; --output_file=&lt;PATH&gt;/tflite_graph.tflite \ &gt; --input_format=TENSORFLOW_GRAPHDEF \ &gt; --output_format=TFLITE \ &gt; --inference_type=QUANTIZED_UINT8 \ &gt; --output_arrays=Sidmoid \ &gt; --input_arrays=IteratorGetNext \ &gt; --input_shapes=1:16:16:1 \ &gt; --mean_values=128 \ &gt; --std_values=127 WARNING:tensorflow:From &lt;USER&gt;.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version. Instructions for updating: Use the retry module or similar alternatives. 2018-04-27 11:40:33.699249: F tensorflow/contrib/lite/toco/model_cmdline_flags.cc:240] Check failed: mean_values.size() == model_flags-&gt;input_arrays_size() Aborted (core dumped) I understand there is an issue with the mean_values input arg, however I don't understand the intended usage of: --mean_values="" string mean_values parameter for image models, comma-separated list of doubles, used to compute input activations from input pixel data. Each entry in the list should match an entry in --input_arrays. I have tried also ",128,128,", as my interpretation is that you wouldn't want a mean value for your batch size/channel dims, but the documentation says that it needs an input for each input in the list should match an element in input_arrays. I am also unsure what to put for the input_arrays arg, as most places I've seen code examples just use input but to me it seems you'd need the name of the node in the graph. I think I'm misunderstanding something here, but I just can't seem to figure it out. Any help would be appreciated!
has title: Error when attempting to convert TF model using toco
has answer: http://stackoverflow.com/a/50225535
tagged with: tensorflow-lite
answer count: 1

http://stackoverflow.com/a/50137204
accepted answer of: http://stackoverflow.com/q/50136699
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50136699
has body: You probably miss-placed one ")" Try: tf.stack([tf.reduce_mean(tf.gather(ten_variables, index)) for index in ten_indices]) instead of tf.stack([tf.reduce_mean(tf.gather(ten_variables, index) for index in ten_indices)]) It is usually helpful to split these complex lines into single instructions and debug them one-by-one.

pandas-groupby
tags question: http://stackoverflow.com/q/50086225
tags question: http://stackoverflow.com/q/50117068
type: Tag
tags question: http://stackoverflow.com/q/50201517
tags question: http://stackoverflow.com/q/50074981
tags question: http://stackoverflow.com/q/50106519
tags question: http://stackoverflow.com/q/50101384
tags question: http://stackoverflow.com/q/50091321
tags question: http://stackoverflow.com/q/50093238
tags question: http://stackoverflow.com/q/50146978
tags question: http://stackoverflow.com/q/50139128
tags question: http://stackoverflow.com/q/50147967
tags question: http://stackoverflow.com/q/50208007
tags question: http://stackoverflow.com/q/50169311
tags question: http://stackoverflow.com/q/50122880
tags question: http://stackoverflow.com/q/50106651
tags question: http://stackoverflow.com/q/50228776
tags question: http://stackoverflow.com/q/50074955
tags question: http://stackoverflow.com/q/50220770
tags question: http://stackoverflow.com/q/50078524
tags question: http://stackoverflow.com/q/50228673
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/50222547
tags question: http://stackoverflow.com/q/50168147
tags question: http://stackoverflow.com/q/50205003
tags question: http://stackoverflow.com/q/50145982
tags question: http://stackoverflow.com/q/50157773

http://stackoverflow.com/q/50129229
accepted answer: http://stackoverflow.com/a/50129493
has answer: http://stackoverflow.com/a/50129493
answer count: 1
has body: I have an index the holds location data for stores. When using python's elasticsearch_dsl I'd like to find the nearest stores for a given location, sorted by distance. Since ES already calculates the distance, is it possible to get it as a part of the search result? Can it be achieved using elasticsearch_dsl in a single query? Or do I have to do post processing on the location lat,lon and calculate the distances manually? Thanks.
type: Question
type: AnsweredQuestion
score: 0
tagged with: elasticsearch
tagged with: python
tagged with: elasticsearch-dsl
has title: elasticsearch_dsl search by geo location distance and get results and distance

http://stackoverflow.com/q/50194706
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I want to calculate mean square displacement of N particles for which I have the trajectory of particles' positions over time. The code I've written has 3 for loops that makes it extremely slow. Could you please help me how I can replace for loops with some sort of vectorized capabilities of numpy or pandas? Here is my code: ntime = 10 # number of times represented in data atom_count = 3 # number of particles norigin = 5 # number of origins is half number of time steps nmin = 2 # minimum number of intervals to contribute to diffusivity nmax = norigin # maximum number of intervals to contribute to diffusivity dt = 1.0 # timestep # creating sample trajectory of particles traj = pd.DataFrame(np.random.rand(ntime*atom_count,3), columns=['x', 'y', 'z']) traj['frame_id'] = np.repeat(np.arange(ntime)+1, atom_count) traj['particle_id'] = np.tile(np.arange(atom_count)+1, ntime) traj = traj'frame_id', 'particle_id', 'x', 'y', 'z' print(traj.head(6)) ndata = traj.shape[0] # number of rows of data # store mean square displacements in msd time_vec= np.arange(dt, norigin*dt+1, dt) msd_xyz = np.zeros((norigin,3)) # loop over all particles for i in range(atom_count): # loop over all time origins for j in range(norigin): jstart = j*atom_count + i # loop over all time windows for k in range(nmin, nmax): kend = jstart + k*atom_count msd_xyz[k, :] += (traj.ix[kend, ['x', 'y', 'z']].values - traj.ix[jstart, ['x', 'y', 'z']].values)**2 msd_xyz = msd_xyz / (atom_count * norigin) msd = np.mean(msd_xyz, axis=1) # total MSD averaged over x, y, z directions print() print("MSD (averaged over all particles and time origins):") print(msd)
tagged with: numpy
has title: Vectorized calculation of Mean Square Displacement in Python
type: UnansweredQuestion
tagged with: python
tagged with: vectorization
has answer: http://stackoverflow.com/a/50195640

http://stackoverflow.com/q/50095688
has comment: http://stackoverflow.com/comment/87209451
has comment: http://stackoverflow.com/comment/87207680
linked to: http://stackoverflow.com/q/50087442
score: 0
has comment: http://stackoverflow.com/comment/87209611
has comment: http://stackoverflow.com/comment/87209512
tagged with: python
tagged with: flask-restful
has title: Import error in a Flask application
has comment: http://stackoverflow.com/comment/87208161
type: Question
has body: I'm building a flask application and using an extension flask-marshmallow to serialise flask-alchemy query output. The problem is I'm unable to import marshmallow object to models, where I'm using it. __init__.py from flask import Flask from flask_login import LoginManager from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow # local imports from config import app_config db = SQLAlchemy() login_manager = LoginManager() def create_app(config_name): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile('config.py') db.init_app(app) login_manager.init_app(app) login_manager.login_message = "You must be logged in to access this page." ## this is the object, I want to import to models ma = Marshmallow(app) ## migrate = Migrate(app, db) from app import models from .operations import operations as ops_blueprint app.register_blueprint(ops_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) return app I'm trying to import the ma object in the following models.py file: from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash ## here I'm importing ma, but getting the error mentioned in the last part of this question from app import db, login_manager, ma ## from sqlalchemy import func class User(UserMixin, db.Model): """ Creates a users table """ __tablename__ = 'users' id = db.Column(db.BigInteger, primary_key=True) username = db.Column(db.String(60), unique=True) password_hash = db.Column(db.String(128)) @property def password(self): raise AttributeError('password should not be readable') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) @login_manager.user_loader def load_user(user_id): return User.query.get(int(us…
answer count: 0
has comment: http://stackoverflow.com/comment/87210462
type: UnansweredQuestion
tagged with: flask
tagged with: flask-sqlalchemy

http://stackoverflow.com/a/50098112
has comment: http://stackoverflow.com/comment/87221891
has comment: http://stackoverflow.com/comment/87269175
has comment: http://stackoverflow.com/comment/87346026
has comment: http://stackoverflow.com/comment/87221792
score: 2
has comment: http://stackoverflow.com/comment/87354527
has comment: http://stackoverflow.com/comment/87346744
has comment: http://stackoverflow.com/comment/87241418
has body: Regarding the ascontiguousarray method, I'm assuming that it's pretty slow as python has to do some memory works to return a C-like contiguous array. EDIT 1: I saw this answer, apparently openCV's imread function should already return a contiguous array. I am not very familiar with ctypes, but happen to use the PyBind library and can only recommend using it. It implements Python's buffer protocol hence allowing you to interact with python data with almost no overhead. I've answered a question explaining how to pass a numpy array from Python to C/C++, do something dummy to it in C++ and return a dynamically created array back to Python. EDIT 2 : I've added a simple example that receives a Numpy array, send it to C and prints it from C. You can find it here. Hope it helps! EDIT 3 : To answer your last comment, yes you can definitely do that. You could modify your code to (1) instantiate a 2D numpy array in C++, (2) pass its reference to the data to your C function that will modify it instead of declaring a Matrix and (3) return that instance to Python by reference. Your function would become: void ndarray_to_matrix(unsigned char* src, double * x, long* shape, long* strides) { int nb = shape[0]; int h = shape[1]; int w = shape[2]; int c = shape[3]; int step_b = strides[0]; int step_h = strides[1]; int step_w = strides[2]; int step_c = strides[3]; int b, i, j, k; int index1, index2 = 0; for(b = 0; b &lt; nb ; ++b) { for(i = 0; i &lt; h; ++i) { for(k= 0; k &lt; c; ++k) { for(j = 0; j &lt; w; ++j) { index1 = k*w*h + i*w + j; index2 = step_b*b + step_h*i + step_w*j + step_c*k; X.vals[b][index1] = src[index2]/255.; } } } } } And you'd add, in your C++ wrapper code // Instantiate the output array, assuming we know b, h, c,w py::array_t&lt;double&gt; x = py::array_t&lt;double&gt;(b*h*c*w); py::buffer_info bufx = x.request(); double*ptrx = (double *) bufx.ptr; // Call to your C function with ptrx as input ndarray_to_matrix(src, ptrx, shape, strides); // now reshape x x.reshape…
type: Answer
has comment: http://stackoverflow.com/comment/87338829
upvote count: 2
answers question: http://stackoverflow.com/q/50090052
has comment: http://stackoverflow.com/comment/87274350
has comment: http://stackoverflow.com/comment/87443913
downvote count: 0
has comment: http://stackoverflow.com/comment/87309586

http://stackoverflow.com/comment/87387920
comment on: http://stackoverflow.com/q/50185390
score: 1
type: Comment
type: QuestionComment
has text: Your print statement has bad indentation. If you read the traceback it would tell you this.

http://stackoverflow.com/comment/87335531
score: 0
comment on: http://stackoverflow.com/q/50158588
has text: Yes @NathanBlaine agreed, but we only have this way to convert day to date, is there a way we can find how many weeks are there for each month per year, for eg say Jan in 2017 has 5 weeks, and for eg Feb has 5 weeks to then 201710 is Feb and Not March. It's a strange requirement I know, but...
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87398742
score: 0
has text: @JakeShropshire I was able to run your code without any issues. The 2 functions were charged and the while loop was run correctly. The out of range came when I ran the plant the sixth time (see enclosed picture https://i.sstatic.net/VpQkp.png)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50185847

http://stackoverflow.com/comment/87620222
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50301348
has text: There shouldn't be any need to install package (user can if they wish, but best practice should not require it). This is especially important if you are in development mode and may be you just want you package to be copied in private folder with your own version without effecting system level package.
type: Comment

http://stackoverflow.com/comment/87423872
score: 0
has text: @DanielleM.: it is *absolutely* a waste of time. The issue is not even with cryptography here.
type: Comment
comment on: http://stackoverflow.com/q/50203379
type: QuestionComment

http://stackoverflow.com/a/50132327
has comment: http://stackoverflow.com/comment/87284045
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50129828
has comment: http://stackoverflow.com/comment/87283168
has comment: http://stackoverflow.com/comment/87283451
has comment: http://stackoverflow.com/comment/87282976
has body: An issue I can see in your code is that you have an infinite while True loop, where you create your pool, but you never actually close it. You keep now creating pools, but as you never close and join the pool, the "old" threads will most likely just hang there, and a fraction of a second later you create more of them. My guess is you just eventually exhaust your resources and hit a process or kernel limit somewhere. I would move pool creation outside of the while loop and just keep using the same pool in your loop. This is the whole idea of a pool - to have processes or threads waiting for work to appear, removing process/thread creation overhead when launching repetitive tasks. If there is a reason to relaunch the pool (I cannot figure out what that could be - if you need to renew your workers occasionally, you could use maxtasksperchild in your pool declaration), then at least close the old pool properly as you will not be feeding any more work to it.
type: Answer
has comment: http://stackoverflow.com/comment/87283348
has comment: http://stackoverflow.com/comment/87282789
has comment: http://stackoverflow.com/comment/87283034

http://stackoverflow.com/a/50134333
accepted answer of: http://stackoverflow.com/q/50134221
type: Answer
answers question: http://stackoverflow.com/q/50134221
score: 0
has body: Use collections.OrderedDict to specify the order of your values. Below are a couple of ways you can do this. from collections import OrderedDict od1 = OrderedDict(sorted(d.items())) od2 = OrderedDict([('o1', [1, 2, 3]), ('o2', [0, -1]), ('o3', [7, 8, 10, 11])]) Then when you run itertools.product the order of iteration will be in line with your OrderedDict order.
type: AcceptedAnswer

http://stackoverflow.com/comment/87258383
type: QuestionComment
comment on: http://stackoverflow.com/q/50120299
has text: Make your function return the value (or values) from each run of the simulation and store them in a list. When all runs are done, you should be able to calculate the statistics you want across all of the games played from what's in the list.
score: 1
type: Comment

http://stackoverflow.com/a/50168980
score: 2
type: Answer
answers question: http://stackoverflow.com/q/50168047
upvote count: 2
downvote count: 0
has body: Here is one way of doing it, but without any for-loops: import random running = True answer = random.randint(100, 200) print("A secret random integer between 100 and 200 has been generated.\nCan you guess what it is?") low = 100 high = 200 while running: usr_inp = int(input("Make a guess between "+str(low)+" and "+str(high)+": ")) if usr_inp &lt; low or usr_inp &gt; high: print("Invalid input! Please make a guess between "+str(low)+" and "+str(high)+": ") elif usr_inp &lt; answer: print("Wrong number! The secret number is larger than "+str(usr_inp)+".") low = usr_inp + 1 elif usr_inp &gt; answer: print("Wrong number! The secret number is less than "+str(usr_inp)+".") high = usr_inp - 1 elif usr_inp == answer: print("Congratulations! You got the right number.") running = False

http://stackoverflow.com/q/50155133
tagged with: statistics
has comment: http://stackoverflow.com/comment/87327873
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87330656
score: 0
tagged with: math
tagged with: python
accepted answer: http://stackoverflow.com/a/50156130
possible better answer: http://stackoverflow.com/a/50156956
tagged with: numpy
has answer: http://stackoverflow.com/a/50156130
has body: I have some question about this python code. I need help to understand the output answers. I have a simple great code in python for generating poission, normal and beta distribution, I want help to understand the figures that come out. Before posting my code, lets think of a simple scenario: Each minute a certain amount of car is coming in to the city, the mean arrival is 63 and sigma is 25, ok so here is my code: import scipy as sp import numpy as np import matplotlib.pyplot as plt mu, sigma = 64, 24 #normal distribution s = np.random.normal(mu, sigma, 1000) count, bins, ignored = plt.hist(s, 30, normed=True) plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins -mu )**2 / (2 * sigma**2)), linewidth=2, color='r') plt.show() #Poisson distribution s = np.random.poisson(5, 10000) import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 14, normed=True) plt.show() #Beta distribution s = np.random.beta(mu, sigma, 1000) count, bins, ignored = plt.hist(s, 30, normed=True) plt.show() Here is result of the code: Poisson Normal Beta Question 1: What do these numbers tell based on the scenario? Question 2: Is it possible to change the X lines (-0,15 to 175 on poisson), (-3 to 4 on normal) and (0.55 to 0.85 on beta)? Questions 3 and 4: I have asked inside the code. Thank you
has title: Poission/Normal and Beta distribution in Python - Help understanding the statistics
answer count: 2
has answer: http://stackoverflow.com/a/50156956
has comment: http://stackoverflow.com/comment/87328591
has comment: http://stackoverflow.com/comment/87329773
type: Question

http://stackoverflow.com/comment/87270053
comment on: http://stackoverflow.com/a/50123596
score: 1
has text: In case you haven't seen it yet, this thread may be useful: https://github.com/pyinstaller/pyinstaller/issues/3308
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50208821
has comment: http://stackoverflow.com/comment/87460336
has comment: http://stackoverflow.com/comment/87435995
has comment: http://stackoverflow.com/comment/87443130
has comment: http://stackoverflow.com/comment/87459863
has comment: http://stackoverflow.com/comment/87459155
answers question: http://stackoverflow.com/q/50208600
has comment: http://stackoverflow.com/comment/87438137
has body: First thing is you are only asking for a single data block when you are doing this: user = request.form oracle_id = user['id'] Instead use getlist ids = request.form.getlist('id') name = request.form.getlist('name') and then: stmt = "insert into today( id, name, status, remark) VALUES(%s, %s, %s, %s)" for i, id in enumerate(ids): cur.executemany(stmt, (id, name[i],.......)) cur.commit() Something like that, work on it, I have provided you the hint. Secondly you can use GET POST in a single route to differentiate between your SELECT and INSERT request. Just do something like this: if request.method == 'POST': #insert sql part here else: #get sql part here Suggestion: I would highly recommend using Models, it keeps your code simple and helps you transform messy app into clean one. You can read about Python SqlAlchemy, there are simples examples that you can use. You can call query and insert or update functions using these models to handle it smoothly.
has comment: http://stackoverflow.com/comment/87459820
score: 0
has comment: http://stackoverflow.com/comment/87434775
has comment: http://stackoverflow.com/comment/87435604
has comment: http://stackoverflow.com/comment/87437253
type: Answer
has comment: http://stackoverflow.com/comment/87459188

http://stackoverflow.com/q/50135885
has comment: http://stackoverflow.com/comment/87299940
has comment: http://stackoverflow.com/comment/87299623
has comment: http://stackoverflow.com/comment/87299776
has comment: http://stackoverflow.com/comment/87299882
has comment: http://stackoverflow.com/comment/87299500
tagged with: python
has answer: http://stackoverflow.com/a/50141211
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50141211
has body: I am having trouble running if part of code where user name and password is wrong.program does not show any error. And how can i set userfullname of Index class to lable in admin_object = userFullname.setText() ? import sqlite3 from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import QMessageBox from Login_form import Login_form from Admin_Home_form import AdminHome_Form class Index(QtWidgets.QDialog, Login_form): def __init__(self): QtWidgets.QDialog.__init__(self) self.loginFormDesign(self) self.login_button.clicked.connect(self.login_check) def login_check(self): uname = self.U_name_text.text() password = self.pass_text.text() # self.userfullname = userfullname connection = sqlite3.connect("taylorDB.db") result = connection.execute("SELECT USER_EMAIL FROM USERS WHERE USER_EMAIL = ? AND USER_PASSWORD = ?", (uname, password)) for dbemail in result: # After this code does not work if value does not match print(dbemail[0]) if dbemail[0] != uname: buttonReply = QMessageBox.question(self, 'Login Invalid', "Check User Name or Password!", QMessageBox.Close) if buttonReply == QMessageBox.Close: print("invalid login") else: result = connection.execute("SELECT USER_FULLNAME FROM USERS WHERE USER_EMAIL = ?", (dbemail)) self.userfullname = result.fetchone() print(self.userfullname) self.accept() class admin_operation(QtWidgets.QMainWindow, AdminHome_Form, Index): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.adminHomeFormDesign(self) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) login_object = Index() admin_object = admin_operation() if login_object.exec() == QtWidgets.QDialog.Accepted: # admin_object.userFullname.setText() #I want to set the value of userfullname here? admin_object.show() sys.exit(app.exec_()) My basic are not so strong please guide me .
tagged with: sqlite
answer count: 1
has title: Login authentication error in python pyqt5 and how to set instance variable in lable?
tagged with: pyqt5
type: Question

http://stackoverflow.com/q/50077356
tagged with: python
has title: Redirecting stdout from a secondary thread (multithreading with a function instead of class?)
answer count: 1
accepted answer: http://stackoverflow.com/a/50078592
has comment: http://stackoverflow.com/comment/87172814
linked to: http://stackoverflow.com/q/21071448
has answer: http://stackoverflow.com/a/50078592
score: 2
tagged with: pyqt
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87172952
has body: I am trying to get my stdout displayed on a QTextEdit made via Qt Designer (PyQt5). Actually I made it work yet it doesn't show the info at the same time it was made. Instead it waits for the process to completely end and only then it shows all the information at once. I understand that this should be solved via threading. Also since the QTextEdit (itself) is a GUI element i need a different approach. I found the answer I was looking for here: This question is referenced to: Redirecting stdout and stderr to a PyQt4 QTextEdit from a secondary thread @three_pineapples provided the answer. My question is pretty much exactly the same, thus the answer is also correct. But my scenario is a little different and I'm having trouble making it work. In all the threading answers I only see them using Classes. But the thing is in my main class I have a function that does all the stuff that would be printed on the QTextEdit. Sometimes it takes minutes to complete. I am looking for a way for the example code below to work using the answer provided by @three_pineapples. Here is the example code: import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtGui import QTextCursor from ui_form import Ui_Form class EmittingStream(QObject): # test textWritten = pyqtSignal(str) def write(self, text): self.textWritten.emit(str(text)) class Form(QMainWindow): def __init__(self, parent=None): super(Form, self).__init__(parent) # Install the custom output stream sys.stdout = EmittingStream(textWritten=self.normalOutputWritten) # test self.ui = Ui_Form() self.ui.setupUi(self) self.ui.pushButton_text.clicked.connect(self.test_write) def __del__(self): # test # Restore sys.stdout sys.stdout = sys.__stdout__ def normalOutputWritten(self, text): # test """Append text to the QTextEdit.""" cursor = self.ui.textEdit.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.ui.textEdit.setTextCursor(cursor) self.ui.tex…
has comment: http://stackoverflow.com/comment/87172050
has comment: http://stackoverflow.com/comment/87172856
favorite count: 0
has comment: http://stackoverflow.com/comment/87173162
type: Question
upvote count: 2
tagged with: multithreading
has comment: http://stackoverflow.com/comment/87172706
downvote count: 0
has comment: http://stackoverflow.com/comment/87171948
tagged with: stdout

http://stackoverflow.com/q/50189781
type: UnansweredQuestion
tagged with: machine-learning
has body: When I train a model with Tensorflow 1.4.1, I use feature column like this: school_col = tf.feature_column.categorical_column_with_vocabulary_list( "school", [1, 2, 3, 4, 5, 6, 7], dtype=tf.int64) Then I want to use C++ to load the model and do inference, so I try to build libtensorflow-core.a by running tensorflow/contrib/makefile/build_all_linux.sh on MacOS. I've appended tensorflow/core/kernels/lookup_table_op.cc tensorflow/core/kernels/initializable_lookup_table.cc tensorflow/core/kernels/lookup_table_init_op.cc tensorflow/core/kernels/lookup_util.cc tensorflow/core/ops/lookup_ops.cc to the tensorflow/contrib/makefile/tf_op_files.txt. However, when I run the C++ program on CentOS 7, TF raised an error: No OpKernel was registered to support Op 'HashTableV2' with these attrs. Registered devices: [CPU], Registered kernels: Node: input_layer_1/school_indicator/school_lookup/hash_table = HashTableV2container="", key_dtype=DT_INT64, shared_name="", use_node_name_sharing=false, value_dtype=DT_INT64 How can I solve this problem?
tagged with: tensorflow
has title: No OpKernel was registered to support Op 'HashTableV2'
upvote count: 1
score: 1
tagged with: python
favorite count: 0
type: Question
tagged with: c++
answer count: 0
downvote count: 0

http://stackoverflow.com/q/50152210
tagged with: python
linked to: http://stackoverflow.com/q/3906137
tagged with: enumerate
tagged with: read-data
type: AnsweredQuestion
score: 0
has title: How to enter into enumarate() loop more than one time
answer count: 1
has body: I want to read a big data file 100 by 100. But my script reads only first 100 line, then it never enters in "for loop" for the rest. More clearly, in the end, I get only lines from 0 to 100, but I want also 100-200, 200-300, 300-400 etc. I can't see what the problem is. (I use python 3.4. All data in .csv file is number. I already know to use islice() but I want particularly use enumerate() function.) I would be very happy if you could help. pathInput = "input.csv" f = open(pathInput, 'r') sizeOfList = 100 iD = 0 while iD&lt;1000: dataset = [] for i, line in enumerate(f): if i&lt;(iD + sizeOfList): dataset.append(line) print(dataset) iD += sizeOfWindow
tagged with: loops
type: Question
linked to: http://stackoverflow.com/q/41585078
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50152427
accepted answer: http://stackoverflow.com/a/50152427

http://stackoverflow.com/comment/87240513
comment on: http://stackoverflow.com/q/50111642
score: 0
has text: @abamert, ok show me both a more intuitive, and a more compact (but not taken to golf extremes).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50179762
answer count: 1
tagged with: scikit-learn
type: Question
has title: How do I calculate a score in a scikit-learn MLPClassifier. Getting numpy.float64 is not iterable
tagged with: python
has body: I am using a scikit-learn MLPClassifier (neural network) to classify some images. The image data is returned as a multidimensional array of floats. If I don't convert the 1 hot-encoded labels to floats, I get a label mismatch when trying to train the model, so I convert them. However, when I go to score the predictions, now I get " 'numpy.float64' object is not iterable ". Any suggestions on how to get this to work? import numpy as np import sys import pandas as pd from skimage import io from skimage import transform as trans from sklearn.neural_network import MLPClassifier as NN from sklearn.model_selection import train_test_split #Get the data print ("Reading CSV...") data = pd.read_csv(filepath_or_buffer="hot_dog_data.csv", nrows=30) X = data.values[1:,0] Y = data.values[1:,1:8] #convert the images to RGB number arrays print ('Converting Images...') img_converts = [] for line in X: img = io.imread("./images/"+line) img = trans.resize(img,(300,400), mode='constant') img_converts.append(img) X = np.array(img_converts) # Split into train and test vars trainX, testX, trainY, testY = train_test_split(X,Y, test_size=0.17) # Reshape the image arrays into 2-D arrays so it will fit the model xa, xb, xc, xd = trainX.shape d2_trainX = trainX.reshape((xa, xb*xc*xd)) xe, xf, xg, xh = testX.shape d2_testX = testX.reshape((xe, xf*xg*xh)) clf = NN(solver='lbfgs',hidden_layer_sizes=(5, 2), random_state=1) # Recast the Y data so the fit won't get a label mismatch trainY = np.asarray(trainY, dtype=np.float) testY = np.asarray(testY, dtype=np.float) print ('The machine is learning...') clf.fit(d2_trainX, trainY) print ('Predicting...') count = 1 for line in clf.predict(d2_testX): print (count, line ) count += 1 print 'Calculating Accuracy...' count = 1 for x,line in clf.score(d2_testX, testY): print (count, line) sys.exit()
has comment: http://stackoverflow.com/comment/87376686
has answer: http://stackoverflow.com/a/50179970
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87376871
score: 0
accepted answer: http://stackoverflow.com/a/50179970

keystroke
type: Tag
tag name: keystroke
tags question: http://stackoverflow.com/q/50219672

http://stackoverflow.com/comment/87491648
type: Comment
has text: Unfortunately not.
type: AnswerComment
comment on: http://stackoverflow.com/a/50192216
score: 0

http://stackoverflow.com/q/50161510
has answer: http://stackoverflow.com/a/50163359
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/8029532
type: Question
has comment: http://stackoverflow.com/comment/87341439
has body: I'm working on a Django project with a ListView that has both a search form, known in the view's context as search_form, and a filter form, filter_form. The interface looks like this: Both the search_form and the filter_form ultimately change what is returned by the ListView's get_queryset method. I would like to make it such that when you first apply a filter and then do a search, it will search the filtered results. At the moment, the 'reverse' functionality has already been implemented: when you first search and then filter, it will filter the search results. This is because of a hidden input element in the filter_form: {{ filter_form.guide }} Guide {% if filter_form.is_guide_filled %} clear {% endif %} For comparison, the search bar has the following template, _search.html: search close In the main list view, index.html, the search template is included like so: {% block search_form %} {% with action='dashboard:families' placeholder='Search Families' %} {% include '_search.html' %} {% endwith %} {% endblock %} In order to make the search form persist the filters, I've noticed that for the guide field only, the following works: I would like to generalize this to include all the filters. I've tried the following: {% if filter_form %} {% for field in filter_form %} {% with field_name=field.name %} {% endwith %} {% endfor %} {% endif %} However, if I try this I literally get "field_name" in the querystring: As I understand from the DTL docs, the dot-notation implements dictionary lookup, attribute lookup, and list-index lookup. If I were to try something like request.GET.field.name it would probably try to look up "field" in the request.GET dictionary-like object and not find anything. In regular Python, what I'd essentially like to do is request.GET[field.name] I thought I could make this work with a with block, but apparently this doesn't work. Any advice on how to implement this? Update If I specify the name attribute for the input element as "{{field_name}}" inst…
has comment: http://stackoverflow.com/comment/87341629
linked to: http://stackoverflow.com/q/8000022
has title: In a Django template, how to specify a dictionary key which is itself an attribute?
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/50162018
has comment: http://stackoverflow.com/comment/87342255
has answer: http://stackoverflow.com/a/50162018
has comment: http://stackoverflow.com/comment/87341810
type: AnsweredQuestion
tagged with: django-templates
answer count: 2
accepted answer: http://stackoverflow.com/a/50163359
score: 1

http://stackoverflow.com/comment/87182598
score: 0
has text: Your generator is already outputting a probability vector with softmax, so the code you already have should be fine
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50082781

http://stackoverflow.com/comment/87238914
type: Comment
has text: @user2357112 What I have on GitHub includes unit tests. And mutating (only single values and equal-length slice assignment, of course). It’s part of another project, and relies on a general-purpose slicing helper, but cleaning it up is probably easier than rewriting it on the fly. (It’s probably worth noting that I never found an actual use for it, except as a demonstration of the slicing helper library…)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50110109

http://stackoverflow.com/comment/87311125
type: QuestionComment
comment on: http://stackoverflow.com/q/50133828
score: 0
type: Comment
has text: Yes...sorry that was a mistake

http://stackoverflow.com/comment/87225780
comment on: http://stackoverflow.com/q/50104264
type: QuestionComment
has text: Can you develop a little bit ? Do you mean to create a list that will contain all my robot and then loop on this list ? Thank you. (At first, it was my idea but I had difficulty to implement it.
type: Comment
score: 0

http://stackoverflow.com/q/50121539
duplicate of: http://stackoverflow.com/q/11523918
linked to: http://stackoverflow.com/q/5677853
tagged with: python-webbrowser
favorite count: 0
type: Question
has body: import time import webbrowser print(time.ctime()) targetTime = time.ctime() if(targetTime == "Tue May 01 11:05:17 2018"): webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ") This is what I tried already and it doesn't open the link when the time comes. I read through the time library but I couldn't find anything to help me. My target is for the program to open a link at a time that I want. Any help appreciated.
tagged with: time
type: UnansweredQuestion
has title: Run function at a specific time in python
has comment: http://stackoverflow.com/comment/87261136
tagged with: python
has comment: http://stackoverflow.com/comment/87260861
has answer: http://stackoverflow.com/a/50122024
has answer: http://stackoverflow.com/a/50121587
answer count: 2
linked to: http://stackoverflow.com/q/11523918
score: 1
upvote count: 3
downvote count: 2

http://stackoverflow.com/comment/87487382
score: 0
type: Comment
type: QuestionComment
has text: I've added my `ug` vector which seems to be the problem here...
comment on: http://stackoverflow.com/q/50223406

http://stackoverflow.com/comment/87296379
type: Comment
score: 1
type: QuestionComment
has text: I just changed ** delim = 'at' ** to ** delim = ' at ' ** and it's working now. Thanks all. :)
comment on: http://stackoverflow.com/q/50138814

http://stackoverflow.com/q/50174404
tagged with: tkinter
answer count: 2
linked to: http://stackoverflow.com/q/10133856
has comment: http://stackoverflow.com/comment/87366005
has body: I want to insert an image into my tkinter but I received error: TclError: image "pyimage7" doesn't exist. I am using WinPython-64-3.3.5.9. I tried "rozmery.gif" but didn't help. from tkinter import * from PIL import ImageTk, Image app_root = Tk() #Setting it up img = ImageTk.PhotoImage(Image.open("rozmery.png")) #Displaying it imglabel = Label(app_root, image=img).grid(row=1, column=1) app_root.mainloop()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87389510
downvote count: 0
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/88063436
has answer: http://stackoverflow.com/a/50525663
has title: Python insert image into Tkinter error
tagged with: python
has answer: http://stackoverflow.com/a/74507295
type: Question
upvote count: 4

http://stackoverflow.com/a/50105667
score: 6
has comment: http://stackoverflow.com/comment/87229776
upvote count: 6
has comment: http://stackoverflow.com/comment/87229240
has comment: http://stackoverflow.com/comment/87230429
accepted answer of: http://stackoverflow.com/q/50105629
has body: I think it's a float precision issue similar to the following one: In [1]: 0.1 + 0.2 Out[1]: 0.30000000000000004 In [2]: 0.1 + 0.2 == 0.3 Out[2]: False so try this: df[my_data].round(6).value_counts() UPDATE: Demo: In [14]: s = pd.Series([-0.01, -0.01, -0.01000000000123, 0.2]) In [15]: s Out[15]: 0 -0.01 1 -0.01 2 -0.01 3 0.20 dtype: float64 In [16]: s.value_counts() Out[16]: -0.01 2 -0.01 1 0.20 1 dtype: int64 In [17]: s.round(6).value_counts() Out[17]: -0.01 3 0.20 1 dtype: int64
type: Answer
has comment: http://stackoverflow.com/comment/87230006
has comment: http://stackoverflow.com/comment/87229191
downvote count: 0
answers question: http://stackoverflow.com/q/50105629
type: AcceptedAnswer

http://stackoverflow.com/comment/87331661
score: 0
type: Comment
type: QuestionComment
has text: How exactly do you arrive at `"o4_24d_20170708_20170801"`? In your input (`"o4_20170708_20170801"`) `24` does not exist anywhere.
comment on: http://stackoverflow.com/q/50156908

http://stackoverflow.com/q/50083284
tagged with: python
tagged with: tensorflow
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has body: I have trouble of using tf.keras.estimator.model_to_estimator to convert a Keras's model to make it run in tensorflow. Here is the model code in keras from tensorflow.python.keras.applications.inception_v3 import InceptionV3 from tensorflow.python.keras._impl.keras.models import Model, load_model from tensorflow.python.keras._impl.keras.layers import Input, Convolution2D, MaxPooling2D, Activation,GlobalAveragePooling2D,\ Dropout, Dropout, Flatten, Dense, Lambda, BatchNormalization def measure_accuracy() ... def dense_block() ... gen_tr= ... gen_vl= ... input_shape = (config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1], 3) input_tensor = Input(input_shape, name='input_tensor') base_model = InceptionV3(input_tensor=input_tensor,weights='imagenet', include_top=False) x = base_model.output x = Flatten()(x) x = dense_block(x, num_fv) embedding = Lambda(lambda x: K.l2_normalize(x, axis=1))(x) inputs = input_tensor outputs = embedding triplet_model = Model(inputs, outputs) triplet_model.compile(loss=triplet_loss,metrics=[measure_accuracy], optimizer=Adam(0.0001)) triplet_model.fit_generator(gen_tr, validation_data = gen_vl, epochs=50, verbose=2, workers=1, steps_per_epoch=32, validation_steps=25) The model seems to work perfectly in Keras, but the point here is I want to use tf.dataset as data pipeline so I convert model to tensorflow. Here is the code model_dir = os.path.join(os.getcwd(), "models/triplet_5") os.makedirs(model_dir, exist_ok=True) tf_model = tf.keras.estimator.model_to_estimator(keras_model=triplet_model, model_dir=model_dir) And here is the error FailedPreconditionError Traceback (most recent call last) ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 1326 try: -&gt; 1327 return fn(*args) 1328 except errors.OpError as e: ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata) 1311 return self._call_tf_sessionrun( -&gt; …
tagged with: keras
favorite count: 0
tagged with: tensorflow-estimator
score: 2
has title: Can not convert Keras's model to tensorflow's estimator using tf.keras.estimator.model_to_estimator

http://stackoverflow.com/q/50119432
has answer: http://stackoverflow.com/a/50119552
has comment: http://stackoverflow.com/comment/87256335
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50119720
possible better answer: http://stackoverflow.com/a/50119518
type: AnsweredQuestion
has title: Parse string with minus sign, retain minus sign
has comment: http://stackoverflow.com/comment/87260898
answer count: 3
has body: I have the following code: latlonginput = 'Latitude=28.0358214, Longitude=-82.59970229999999, Accuracy=4232m' import re try: #latlonginput = input['latlong'] geo_lat = format(re.split(r'(Latitude=|,)', latlonginput)[2]) geo_long = format(re.split(r'(Longitude=|,)', latlonginput)[2]) accuracy = format(re.split(r'(Accuracy=)', latlonginput)[2]) geo_coord = geo_lat + ',' + geo_long latlong = 'Detected Lat/Long: '+ geo_coord + '\n' latlong = latlong + 'Accuracy: ' + accuracy + '\n' latlong = latlong + 'Maps: placeholder' except: latlong = None return {'lat_long': latlong } In this case, with longitude being a negative value, it omits the negative. For example, this is the result: Detected Lat/Long: 28.0358214, Accuracy: 4232m Maps: placeholder I need to allow for negatives in either latitude or longitude. How can I adjust to do so? Thanks, Noob
has answer: http://stackoverflow.com/a/50119518
score: 0
accepted answer: http://stackoverflow.com/a/50119552

http://stackoverflow.com/a/60231161
answers question: http://stackoverflow.com/q/50119679
has body: As mentioned by @ilja-everilä in the comments, each record of your query is a KeyedTuple, which is like a namedtuple in Python, which means each field in it has a position in the tuple but also an attribute name. You can get a list of strings containing the attribute names of one of these records with the .keys() method, or if you actually have a column called keys that would blot out the .keys() method, you can also use the ._fields attribute. E.g.: &gt;&gt;&gt; myquery.all()[0].keys() ['ORM_Class', 'something_id'] or &gt;&gt;&gt; myquery.all()[0]._fields ['ORM_Class', 'something_id'] The above tells me I could access the second field using the something_id attribute: &gt;&gt;&gt; myquery.all()[0].something_id 235 You can also get a dictionary mapping all entity names of a record to their values using the ._asdict() method: &gt;&gt;&gt; myquery.all()[0]._asdict() {'ORM_Class': &lt;orm.my_orm.ORM_Class object at 0xdeadbeefc0ff&gt;, 'something_id': 235}
type: Answer
score: 0

http://stackoverflow.com/comment/87301883
type: QuestionComment
has text: What should the final dict look like? I'm guessing it would contain 200 smaller dicts as its values, but what are the keys?
comment on: http://stackoverflow.com/q/50141770
score: 0
type: Comment

http://stackoverflow.com/comment/134611744
score: 3
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50107230
has text: no luck with this solution :(

http://stackoverflow.com/q/50188930
has comment: http://stackoverflow.com/comment/87401098
has title: Click event not happening in Python with Selenium web driver
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/50210838
type: Question
has comment: http://stackoverflow.com/comment/87404390
accepted answer: http://stackoverflow.com/a/50210838
has body: Friends facing challenges again in following scenarios using Python with Selenium web driver:- Click event not happening on clicking the link name as "Area Rank Web". HTML Code for MSTR Report is as follows:- Area Rank Web Owner: Administrator Modified: 5/1/18 4:22:16 AM Subscriptions I tried following ways but not getting success: #driver.find_element_by_xpath(".//*[title='Area Rank Web']").click(); #driver.find_elements_by_class_name (("mstrLargeIconViewItemName") and contains(.,'Area Rank Web')).click() #driver.find_element_by_id("600E4BA841AC84797221F7BB5262C3E0").click() #driver.find_element_by_css_selector("600E4BA841AC84797221F7BB5262C3E0").click() #WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='mstrLargeIconViewItemText']/span[@class='mstrIcon-lg' and contains(.,'Area Rank Web')]"))).click() 2. There is a block having two values as:- AREA, DISTRICT. You can select more than value and then click on arrow button which moves selected content to the right side of block and then click on submit button HTML code: DSI ONC Tried following ways but click event is not happening
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50083589
tagged with: python
tagged with: class
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has body: In R, you can do something like this: x &lt;- 3 cl &lt;- class(x) class(x) &lt;- c("abc",cl) So variable 'x' will be an integer as well as belong to user-defined class 'abc'. I want to do a similar thing in Python. My variable 'x' should be considered as integer and should also have the attributes of user-defined class named "abc".
tagged with: oop
downvote count: 0
accepted answer: http://stackoverflow.com/a/50083663
has comment: http://stackoverflow.com/comment/87183180
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87183039
favorite count: 0
has title: Assign an additional class to a variable in python (equivalence in R shown)
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50083663

http://stackoverflow.com/a/50080921
has comment: http://stackoverflow.com/comment/87178158
has comment: http://stackoverflow.com/comment/87178363
has comment: http://stackoverflow.com/comment/87178382
accepted answer of: http://stackoverflow.com/q/50080854
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87181005
answers question: http://stackoverflow.com/q/50080854
has comment: http://stackoverflow.com/comment/87178126
has body: Your regex is stopping at the first literal dot. ([^.]*?( _snipped lots of text_ )[^.]*\. # ^^^^^^ The marked (^^^^) part captures all the text that is not a dot + the literal dot, then it is done. That is The Board has jurisdiction over this appeal under 5 U. You do not show the real text, you can change this special case to capture anything thats not a ) and then the ): '([^.]*?(I find|In sum|agree|affirm|disagree|I conclude|In light of| under| this appeal| The ALJ| I determine| we| based on| for the reasons| pursuant to| the decision is| jurisidiction|section|§+\d |conclude)[^)]*\))', tokenized, re.I | re.DOTALL | re.M))
has comment: http://stackoverflow.com/comment/87178162
type: Answer

http://stackoverflow.com/comment/87362085
has text: members is a list! wont you have to iterate though the list?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50172456

http://stackoverflow.com/q/50204999
linked to: http://stackoverflow.com/q/29950767
type: Question
type: UnansweredQuestion
has body: I am learning to use vim as an IDE for Python and followed this tutorial to setup my .vimrc file. My setup is working fine. Here, vim shows me the help for np.random.randint, but I could not figure out how to scroll through the displayed help and read about the other parameters. This feature is introduced by YouCompleMe (as far as I understand), so possible solution might be to change some configuration for it. Since, I am new to this, I am not even sure what this feature is called (auto complete does not seem to be the right name for displaying help) and therefore was not able to find help on web-searching. Any help will be appreciated, thanks.
tagged with: python
tagged with: vim
score: 0
has title: Scroll python function help in Vim
linked to: http://stackoverflow.com/q/34132809
tagged with: youcompleteme
answer count: 1
has answer: http://stackoverflow.com/a/50205859

http://stackoverflow.com/q/50220166
has answer: http://stackoverflow.com/a/50228022
type: Question
has body: Currently I'm using multiple exceptions in a for loop. However, they are still throwing exception errors and I'm not certain why they are not being handled. Here is my code: for x in range (15): actions.click_and_hold(element1).move_to_element(element2).release().perform() try: WebDriverWait(driver, 5).until( EC.visibility_of_element_located((elementLocator)) ) return True except (StaleElementReferenceException, TimeoutException): break Here is the error being thrown: StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: headless chrome=67.0.3396.30) (Driver info: chromedriver=2.36.540469 (1881fd7f8641508feb5166b7cae561d87723cfa8),platform=Mac OS X 10.13.4 x86_64)
has comment: http://stackoverflow.com/comment/87457431
tagged with: staleelementreferenceexception
type: UnansweredQuestion
has title: Multiple exceptions are not being handled
tagged with: python
has comment: http://stackoverflow.com/comment/87494520
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
score: 0
answer count: 1
tagged with: selenium

http://stackoverflow.com/q/50156741
has body: I'm trying to install PyGObject on a Python2.7 environment in PyCharm which fails with the following details: Running setup.py clean for PyGObject Failed to build PyGObject Installing collected packages: PyGObject Running setup.py install for PyGObject: started Running setup.py install for PyGObject: finished with status 'error' Complete output from command "C:\Users\ratch\PycharmProjects\Project\venv\Scripts\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\ratch\\AppData\\Local\\Temp\\pycharm-packaging\\PyGObject\\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\ratch\appdata\local\temp\pip-record-m6_taf\install-record.txt --single-version-externally-managed --compile --install-headers "C:\Users\ratch\PycharmProjects\Project\venv\include\site\python2.7\PyGObject": running install running build running build_py creating build creating build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\pygtkcompat copying pygtkcompat\generictreemodel.py -&gt; build\lib.win-amd64-2.7\pygtkcompat copying pygtkcompat\pygtkcompat.py -&gt; build\lib.win-amd64-2.7\pygtkcompat copying pygtkcompat\__init__.py -&gt; build\lib.win-amd64-2.7\pygtkcompat creating build\lib.win-amd64-2.7\gi copying gi\docstring.py -&gt; build\lib.win-amd64-2.7\gi copying gi\importer.py -&gt; build\lib.win-amd64-2.7\gi copying gi\module.py -&gt; build\lib.win-amd64-2.7\gi copying gi\pygtkcompat.py -&gt; build\lib.win-amd64-2.7\gi copying gi\types.py -&gt; build\lib.win-amd64-2.7\gi copying gi\_constants.py -&gt; build\lib.win-amd64-2.7\gi copying gi\_error.py -&gt; build\lib.win-amd64-2.7\gi copying gi\_option.py -&gt; build\lib.win-amd64-2.7\gi copying gi\_ossighelper.py -&gt; build\lib.win-amd64-2.7\gi copying gi\_propertyhelper.py -&gt; build\lib.win-amd64-2.7\gi copying gi\_signalhelper.py -&gt; build\lib.win-amd64-2.7\gi copying gi\__init__.py -&gt; build\lib.win-amd64-2…
has comment: http://stackoverflow.com/comment/87373482
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87451517
score: 3
tagged with: pygobject
upvote count: 3
downvote count: 0
has title: Installing PyGObject through PyCharm yields error command 'C:\\...\\cl.exe' failed with exit status 2
tagged with: pip
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50360611
has comment: http://stackoverflow.com/comment/87333232
type: Question
has comment: http://stackoverflow.com/comment/87369419
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/56117770
answers question: http://stackoverflow.com/q/50169945
score: 0
type: Answer
has body: This video explain it on a very simple way: https://www.youtube.com/watch?v=K9ypGzuP6xQ Basically, TensorFlow is not by default installed on PyCharm virtual environment. You can do it by downloading in the Project Interpreter menu

http://stackoverflow.com/comment/87386228
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50184386
type: Comment
has text: There are other answers there, not just the one with a temporary character. You just have to scroll a bit.

http://stackoverflow.com/comment/87333970
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50157862
type: QuestionComment
has text: I have checked my projects that were deployed to heroku - their `Procfile` file contains the `gunicorn` line only, without `python manage.py runserver`. Not sure if this is the problem, though. And I also did not use `django-heroku`, that is why I asked about requirements

http://stackoverflow.com/comment/87413484
type: Comment
comment on: http://stackoverflow.com/a/50198000
score: 0
type: AnswerComment
has text: I tried the second method assuming you will prefer that. Let me modify first method then.

http://stackoverflow.com/comment/87319460
comment on: http://stackoverflow.com/q/50150459
has text: Yes bruno, it's a log file containing markup that's why i'm using find()
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87430541
comment on: http://stackoverflow.com/q/50206582
has text: Similar: https://stackoverflow.com/questions/40667879/number-of-lines-with-number-of-words-less-than-5/40680360
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50145881
tagged with: tkinter
upvote count: 2
downvote count: 0
answer count: 1
has body: I want to create a Sudoku solver in tkinter as practice and I am trying to figure out how to actually create the grid in order for the user to input the sudoku board. I was thinking of using Entries for this but I would have to do 9x9 = 81 of them in total. e1 = Entry(master) e2 = Entry(master) e3 = Entry(master) . . . e81 = Entry(master) e1.grid(row=0, column = 0) e2.grid(row=0, column = 1) ae33.grid(row=0, column = 2) . . . e81.grid(row=9, column = 9) There has to be another way of doing this right?
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: How to create a large grid of entries in Tkinter effitienly?
tagged with: python
has answer: http://stackoverflow.com/a/50146059
score: 2

http://stackoverflow.com/q/50224015
accepted answer: http://stackoverflow.com/a/50224141
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50224141
has body: Using the python parse module. I am searching within a string. Searching for "AB Number" then multiple spaces then a number in the format 1-123456789. so "AB Number 1-727288292920" If i use this it finds it but its split over multiple matches:- search('AB Number{:s}{:d}{:D}{:d}',plain_text_body) If i use this it only matches the first digit and i cant work out why it wont match search('AB Number{:s}{\d+\D\d+}',plain_text_body) Also I think its possible to use regex outside of the pattern being captured but i cant make that work either for example - to catch multiple spaces should be:- search('AB Number\s+{\d+\D\d+}',plain_text_body) But it doesnt work. Any idea?
score: -3
tagged with: parsing
type: AnsweredQuestion
upvote count: 0
answer count: 1
downvote count: 3
favorite count: 0
has title: Python parse module search
type: Question
has comment: http://stackoverflow.com/comment/87465649
has comment: http://stackoverflow.com/comment/87465673
has comment: http://stackoverflow.com/comment/87465678

http://stackoverflow.com/q/50148024
downvote count: 0
has body: In the example below, Column C should be deleted because it already exists (Column A should remain) type(df): pandas.core.frame.DataFrame A B C 1 2 1 0 2 0 3 2 3 I tried creating a dictionary to later delete repeated values but got stuck dict_test = {} for each_column in df: dict_test[each_column] = dfeach_column.mean() dict_test The result came out to be dtype: float64, 'A' : A 1.33333 The problem above is that the dictionary is storing the 'Key and Value' in the Value section so I can't compare Values to one another
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50148139
has answer: http://stackoverflow.com/a/50148139
has title: How do I delete columns where the average of the column already exists
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/50174659
answers question: http://stackoverflow.com/q/50174556
has body: for key in 'db host user password'.split(): val = getattr(args, key) if val: kwargs[key] = val
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/87186651
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50085411
has text: I've updated the post, I don't know if that was what you asked for or isn't it. Thanks in advance for replying.

http://stackoverflow.com/a/50221133
answers question: http://stackoverflow.com/q/50218738
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: The page you are trying to scrape is full JavaScript generated. This http.request('https://www.iparkit.com/Minneapolis') would give almost nothing in this case. Instead, you must do what a real browser do - Process JavaScript, then try to scrape what has been processed. For this you can try Selenium. For your page, after running JavaScript you will get ~84 URLs, while trying to scrape without running JavaScript, you would get ~7 URLs. from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--headless") driver = webdriver.Chrome('PATH_TO_CHROME_WEBDRIVER', chrome_options=chrome_options) driver.get('https://www.iparkit.com/Minneapolis') content = driver.page_source Then you extract what you want from that content using BeautifulSoup in your case.
type: Answer
accepted answer of: http://stackoverflow.com/q/50218738

http://stackoverflow.com/a/50214799
upvote count: 12
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50213274
has body: The script transforms you dataset into a binary vector space model. Let's disect things one by one. First, if we examine the x_train content we see that each review is represented as a sequence of word ids. Each word id corresponds to one specific word: print(train_data[0]) # print the first review [1, 14, 22, 16, 43, 530, 973, ..., 5345, 19, 178, 32] Now, this would be very difficult to feed the network. The lengths of reviews varies, fractional values between any integers have no meaning (e.g. what if on the output we get 43.5, what does it mean?) So what we can do, is create a single looong vector, the size of the entire dictionary, dictionary=10000 in your example. We will then associate each element/index of this vector with one word/word_id. So word represented by word id 14 will now be represented by 14-th element of this vector. Each element will either be 0 (word is not present in the review) or 1 (word is present in the review). And we can treat this as a probability, so we even have meaning for values in between 0 and 1. Furthermore, every review will now be represented by this very long (sparse) vector which has a constant length for every review. So on a smaller scale if: word word_id I -&gt; 0 you -&gt; 1 he -&gt; 2 be -&gt; 3 eat -&gt; 4 happy -&gt; 5 sad -&gt; 6 banana -&gt; 7 a -&gt; 8 the sentences would then be processed in a following way. I be happy -&gt; [0,3,5] -&gt; [1,0,0,1,0,1,0,0,0] I eat a banana. -&gt; [0,4,8,7] -&gt; [1,0,0,0,1,0,0,1,1] Now I highlighted the word sparse. That means, there will have A LOT MORE zeros in comparison with ones. We can take advantage of that. Instead of checking every word, whether it is contained in a review or not; we will check a substantially smaller list of only those words that DO appear in our review. Therefore, we can make things easy for us and create reviews × vocabulary matrix of zeros right away by np.zeros((len(sequences), dimension)). And then just go through words in each review and flip the in…
score: 12

http://stackoverflow.com/comment/87209634
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50096657
has text: Can you post more of the sample html? The div tags are mismatching

http://stackoverflow.com/q/50174855
accepted answer: http://stackoverflow.com/a/51879187
answer count: 1
has answer: http://stackoverflow.com/a/51879187
has comment: http://stackoverflow.com/comment/87367792
type: Question
tagged with: serialization
tagged with: python
has comment: http://stackoverflow.com/comment/87367859
has title: Serialize custom object to XML string in Python
has body: It's a bit strange, but I didn't find any useful information on such (seemed) popular topic like XML serialization in Python! I'm new to Python, so forgive me dumb question in case it is. I have a class: class Purchase: @property def shortPurchaseDesc(self): return self._shortPurchaseDesc @shortPurchaseDesc.setter def shortPurchaseDesc(self, value): self._shortPurchaseDesc = value; class Result(): @property def resultCode(self): return self._resultCode; @resultCode.setter def resultCode(self, value): self._resultCode = value _purchase = Purchase() @property def purchase(self): return self._purchase; @purchase.setter def purchase(self, value): self._purchase = value And I want to get the XML string representation of it, something like: 2 test I've tried to use lxml.etree.tostring, but it says that Result can not be serialized. I think I'm missing something...
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87368145

http://stackoverflow.com/q/50171190
tagged with: pandas
has body: For example, I have this df: score 0 a b c 0.7 1 a b c 0.7 2 b c d 0.8 3 c d e 0.9 4 c d e 0.9 5 d e f 0.8 I want to take values which have the best score, but there are more than one datas. And I want to take the last of the best (based on example, means row 4). Can you help me please? Thank you in advance.
has answer: http://stackoverflow.com/a/50171406
has comment: http://stackoverflow.com/comment/87360001
downvote count: 0
has comment: http://stackoverflow.com/comment/87359742
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87481492
has answer: http://stackoverflow.com/a/50171392
type: Question
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has title: Take the best value in dataframe which have multiple same datas
has comment: http://stackoverflow.com/comment/87359946
answer count: 2

http://stackoverflow.com/comment/87299248
type: AnswerComment
has text: Here is the output when I use list(df) [0,1,2,3,4,5]
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50139123

http://stackoverflow.com/comment/87199186
score: 2
has text: I guess time.sleep() is pausing all other routes. I don't think hello2 or hello3 is answering until time.sleep is done.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50091265

http://stackoverflow.com/comment/99211804
type: AnswerComment
has text: Glad it could be of help! I hadn't actually given much thought to this answer, I have edited to improve the label placement, now they are centered.
comment on: http://stackoverflow.com/a/50161387
score: 0
type: Comment

http://stackoverflow.com/a/50270587
score: 7
has comment: http://stackoverflow.com/comment/87620234
downvote count: 0
has body: First, do not use eval() mode for any network. Set requires_grad flag to false to make the parameters non-trainable for only the second network and train the placeholder network. If this doesn't work, you can try the following approach which I prefer. Instead of using multiple networks, you can use a single network and use a non-trainable layer as a parallel connection after every trainable layer before non-linearity. For example look at this image: Set requires_grad flag to false to make the parameters non-trainable. Do not use eval() and train the network. Combining outputs of the layers before non-linearity is important. Initialize the parameters of the parallel layer and choose the post-operation such that it gives the same result as when you combine the parameters.
upvote count: 7
has comment: http://stackoverflow.com/comment/87587143
answers question: http://stackoverflow.com/q/50144597
has comment: http://stackoverflow.com/comment/87578540
has comment: http://stackoverflow.com/comment/87618999
type: Answer
has comment: http://stackoverflow.com/comment/87619730

http://stackoverflow.com/a/50229236
answers question: http://stackoverflow.com/q/50228163
score: 0
type: AcceptedAnswer
has body: Even simpler without reshaping : A = np.random.rand(3, 4, 4, 5) B = A[None] # Append a new dimension at the beginning, shape (1, 3, 4, 4, 5) B = A[:,:,None] # Append a new dimension in the middle, shape (3, 4, 1, 4, 5) B = A[:,:,:,:,None] # Append a new dimension at the end, shape (3, 4, 4, 5, 1) Basically, the position of None indicates where to add the new dimension.
has comment: http://stackoverflow.com/comment/87488875
accepted answer of: http://stackoverflow.com/q/50228163
type: Answer

http://stackoverflow.com/comment/87268033
score: 1
has text: @Prune can you find a better link?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50124901

http://stackoverflow.com/q/50130851
has comment: http://stackoverflow.com/comment/89154043
upvote count: 1
score: 1
has title: Django Channels Background Worker Instances
favorite count: 0
type: Question
tagged with: pusher
has body: I am working on a Django Channels-2 project, where channel layer is used to offload information from browsers to a consumer who analyses it and send the results back to the Browsers via groups mechanism. The data comes from pusher via a pusher-client, and is therefore the same for many client browsers. My first took was to set-up the following infrastructure: layout 1: (browser1: Pusher-client, websocket; ... browserN: Pusher-client, websocket) &lt;----> WebsocketConsumer(member of group; sends to channel, recieves from group) &lt;----> BackgroundWorker(listens on channel; sends to group) This layout works fine and it offloads the need to burden my server with the pusher connection, which is left to individual browsers. But this also means that I propagate multiple copies of the same event down to my Worker. I understand there are solutions to this problem, but they seemed a bit awkward to me. Also, this implies a lot of JavaScript-ing in the browsers. Even more so since only one websocket connection is permitted per browser tab and I need to traffic everything trough the same socket. Therefore I use the following set-up now: layout 2: (browser1: websocket; ... browserN: websocket) &lt;----> WebsocketConsumer(member of group; sends to channel, recieves from group) &lt;----> BackgroundWorker(pusher-client; listens on channel; sends to group) In this layout, the browser notifies the consumers It wants results of the data, and if the background worker hasn't started yet it is spawned and starts pusher-client and on every event received analyzes the data and sends the result to group and hence back to browsers. This all works very nice and fine. THE QUESTION: Now, when I run ./manage.py runworker *channel-name* The worker consumer isn't started until it is actually needed. And when the first message arrives to the channel it listens on, it is fired up and enters the event-loop of the pusher-client. Subsequent calls do not spawn additional workers, it would seems, and I …
answer count: 0
downvote count: 0
tagged with: django
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89391331
has comment: http://stackoverflow.com/comment/89343134
has comment: http://stackoverflow.com/comment/87484546
has comment: http://stackoverflow.com/comment/89156392
has comment: http://stackoverflow.com/comment/87484327
has comment: http://stackoverflow.com/comment/89343162
has comment: http://stackoverflow.com/comment/87449313
tagged with: channel

http://stackoverflow.com/q/50159760
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87337256
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/88403634
has comment: http://stackoverflow.com/comment/87337387
score: 0
has comment: http://stackoverflow.com/comment/87337345
answer count: 0
linked to: http://stackoverflow.com/q/19283118
tagged with: ioerror
has comment: http://stackoverflow.com/comment/87337524
has body: I am trying to open a file in my python code, but I get the error 'IOError: [Errno 0] Error'. You can see my code below: fd = open('./Aeolis_data/AeolisTimeStamp.pck1', 'wt') prevTimeStamp = pickle.load(fd) I get the same error when I try 'wb' as a second argument in the open function. I have tried putting 'rt' as a second argument in the open function, but then I get the error 'EOFError'. With 'rb', the same happens. Next to this I tried this (fd.seek(0, 2)), but it does not work as well. Does anyone know what the reason of this error could be and how to fix it? Thanks in advance!
has title: Error when opening file: IOError: [Errno 0] Error
has comment: http://stackoverflow.com/comment/87337319
type: Question

http://stackoverflow.com/comment/87405535
comment on: http://stackoverflow.com/a/50193803
type: Comment
has text: Yeap. I tried do this: RDD_Dados = RDD_one.map(lambda x: (x[0], [x[i][1] for i in range(1,int(n)+1)], x[int(n)+1][1])) and show me this error: TypeError: can only concatenate list (not "int") to list
score: 0
type: AnswerComment

http://stackoverflow.com/q/50137193
tagged with: http://stackoverflow.com/tag/pdf
has title: Pulling Byte from SQL Python returning bytearray
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50393104
tagged with: python
type: AnsweredQuestion
score: 0
has body: I am attempting to retrieve a PDF attachment from a table in MS SQL Server 2008. It is being stored as byte type, but is being returned in my query as a bytearray type. When I try to write that to the pdf file, I'm receiving a "file corrupt" message. Below is my code. I am attempting to copy this pdf file from the SQL server to a local folder. import pyodbc, os, base64, array cnxn = pyodbc.connect('DSN=SQL') cursor = cnxn.cursor() cursor.execute("SELECT content FROM digitalassetcontent") results = cursor.fetchone() for row in results: # print() with open("Output1.txt", "wb") as output_file: output_file.write(row) Expected output of the query = [binary] Sample Output I am receiving when running query = bytearray(b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xe2\x0cXICC_PROFILE\x00\x01\x01\x00\x00\x0cHLino\x02\x10\x00\x00mntrRGB XYZ \x07\xce\x00\x02\x00\t\x00\x06\x001\x00\x00acspMSFT\x00\x00\x00\x00IEC sRGB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf6\xd6\x00\x01\x00\x00\x00\x00\xd3-HP \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11cprt\x00\x00\x01P\x00\x00\x003desc\x00\x00\x01\x84\x00\x00\x00lwtpt\x00\x00\x01\xf0\x00\x00\x00\x14bkpt\x00\x00\x02\x04\x00\x00\x00\x14rXYZ\x00\x00\x02\x18\x00\x00\x00\x14gXYZ\x00\x00\x02,\x00\x00\x00\x14bXYZ\x00\x00\x02@\x00\x00\x00\x14dmnd\x00\x00\x02T\x00\x00\x00pdmdd\x00\x00\x02\xc4\x00\x00\x00\x88vued\x00\x00\x03L\x00\x00\x00\x86view\x00\x00
tagged with: sql
accepted answer: http://stackoverflow.com/a/50393104

tkinter
tags question: http://stackoverflow.com/q/50149179
tags question: http://stackoverflow.com/q/50132369
tags question: http://stackoverflow.com/q/50184848
tags question: http://stackoverflow.com/q/50148819
tags question: http://stackoverflow.com/q/50222747
tags question: http://stackoverflow.com/q/50185963
tags question: http://stackoverflow.com/q/50124932
tags question: http://stackoverflow.com/q/50192470
tags question: http://stackoverflow.com/q/50195029
tags question: http://stackoverflow.com/q/50203807
tags question: http://stackoverflow.com/q/50174404
tags question: http://stackoverflow.com/q/50092196
tags question: http://stackoverflow.com/q/50148235
tags question: http://stackoverflow.com/q/50130077
tags question: http://stackoverflow.com/q/50102179
tags question: http://stackoverflow.com/q/50135108
tags question: http://stackoverflow.com/q/50200075
tags question: http://stackoverflow.com/q/50175555
tags question: http://stackoverflow.com/q/50160783
tags question: http://stackoverflow.com/q/50103615
tags question: http://stackoverflow.com/q/50205877
tags question: http://stackoverflow.com/q/50137762
tags question: http://stackoverflow.com/q/50214819
tags question: http://stackoverflow.com/q/50164738
tags question: http://stackoverflow.com/q/50098019
tags question: http://stackoverflow.com/q/50123979
tags question: http://stackoverflow.com/q/50225586
tags question: http://stackoverflow.com/q/50196186
tags question: http://stackoverflow.com/q/50148436
tags question: http://stackoverflow.com/q/50181025
tags question: http://stackoverflow.com/q/50140602
tags question: http://stackoverflow.com/q/50194924
tags question: http://stackoverflow.com/q/50098072
tags question: http://stackoverflow.com/q/50199166
tags question: http://stackoverflow.com/q/50095212
tags question: http://stackoverflow.com/q/50215285
tags question: http://stackoverflow.com/q/50222466
tags question: http://stackoverflow.com/q/50126891
tags question: http://stackoverflow.com/q/50074610
tags question: http://stackoverflow.com/q/50158218
tags question: http://stackoverflow.com/q/50115626
tags question: http://stackoverflow.com/q/50175318
tags question: http://stackoverflow.com/q/50226886
tag name: tkinter
tags question: http://stackoverflow.com/q/50194711
tags question: http://stackoverflow.com/q/50216119
tags question: http://stackoverflow.com/q/50160827
tags question: http://stackoverflow.com/q/50101816
tags question: http://stackoverflow.com/q/50090451
tags question: http://stackoverflow.com/q/50148237
tags question: http://stackoverflow.com/q/50134633
tags question: http://stackoverflow.com/q/50085112
tags question: http://stackoverflow.com/q/50217481
tags question: http://stackoverflow.com/q/50086571
tags question: http://stackoverflow.com/q/50106448
tags question: http://stackoverflow.com/q/50156833
tags question: http://stackoverflow.com/q/50078142
tags question: http://stackoverflow.com/q/50189140
tags question: http://stackoverflow.com/q/50077698
tags question: http://stackoverflow.com/q/50078170
tags question: http://stackoverflow.com/q/50104189
tags question: http://stackoverflow.com/q/50084998
tags question: http://stackoverflow.com/q/50187281
tags question: http://stackoverflow.com/q/50076497
tags question: http://stackoverflow.com/q/50113898
tags question: http://stackoverflow.com/q/50119107
tags question: http://stackoverflow.com/q/50109515
tags question: http://stackoverflow.com/q/50085360
tags question: http://stackoverflow.com/q/50099385
tags question: http://stackoverflow.com/q/50227577
tags question: http://stackoverflow.com/q/50123315
tags question: http://stackoverflow.com/q/50228625
tags question: http://stackoverflow.com/q/50132276
tags question: http://stackoverflow.com/q/50150375
tags question: http://stackoverflow.com/q/50145881
tags question: http://stackoverflow.com/q/50195565
tags question: http://stackoverflow.com/q/50089293
tags question: http://stackoverflow.com/q/50087593
tags question: http://stackoverflow.com/q/50142776
tags question: http://stackoverflow.com/q/50092357

http://stackoverflow.com/comment/87332939
comment on: http://stackoverflow.com/q/50140371
has text: It worked and I updated the post @warren-weckesser. Unfortunately I cannot use photos yet!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50184575
tagged with: python
has comment: http://stackoverflow.com/comment/87386416
type: Question
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/50184594
answer count: 1
linked to: http://stackoverflow.com/q/19339
upvote count: 1
downvote count: 1
favorite count: 0
has title: List index out of range, apparently nothing wrong
has comment: http://stackoverflow.com/comment/87386437
tagged with: indexing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50184594
has body: transposta = [] nova_linha = [] for i in range (len(matriz)): for j in range(len(matriz[i])): nova_linha.append(matriz[i][j]) i+=1 transposta.append(nova_linha) j+=1 nova_linha = [] return transposta I am getting the list index out of range error in line nova_linha.append(matriz[i][j]) why is this happening?
has comment: http://stackoverflow.com/comment/87386394
tagged with: range

http://stackoverflow.com/a/61883953
type: Answer
has comment: http://stackoverflow.com/comment/130266120
downvote count: 4
upvote count: 2
answers question: http://stackoverflow.com/q/50104496
has body: on using this repo.config_writer().set_value("user", "name", "myusername").release() repo.config_writer().set_value("user", "email", "myemail").release() i got the below error "config_writer() missing 1 required positional argument: 'self'." i resolved it using os.system("git config --global user.name \"firstname lastname\"") os.system("git config --global user.email \"youremail@email.com\"")
score: -2

http://stackoverflow.com/comment/87413618
comment on: http://stackoverflow.com/a/50198252
type: AnswerComment
type: Comment
has text: @User2017 That's another question. | Please read [ask] and [help] and [mcve] and [SO question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) to know what we expect and other guidelines on [so].
score: 0

http://stackoverflow.com/a/50082857
downvote count: 0
has comment: http://stackoverflow.com/comment/87181608
has comment: http://stackoverflow.com/comment/87182947
answers question: http://stackoverflow.com/q/50082719
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87181744
has comment: http://stackoverflow.com/comment/87181570
has comment: http://stackoverflow.com/comment/87181883
has comment: http://stackoverflow.com/comment/87182033
has comment: http://stackoverflow.com/comment/87181779
type: Answer
has comment: http://stackoverflow.com/comment/87181576
has body: TL;DR: Use: CMD tangelo -np --port 9220 Instead of: CMD "tangelo --port 9220" Explanation: You have two ways to debug the problem: Inspect the logs of the container: $ docker run -d test 28684015e519c0c8d644fccf98240d1465acabab6d16c19fd59c5f465b7f18af $ sudo docker logs 28684015e519c /bin/sh: 1: tangelo --port 9220: not found Instead of running in detached mode, run in foreground with -i/--interactive (and optionally also -t/--tty): $ docker run -ti test /bin/sh: 1: tangelo --port 9220: not found As you can see from above, the problem is that tangelo --port 9220 is being interpreted as a single argument. Split it by removing quotes: CMD tangelo --port 9220 # this will use a shell or use the "exec" form (preferred, given that you don't need any shell features): CMD ["tangelo", "--port", "9220"] # this will execute tangelo directly or even better use ENTRYPOINT + CMD: ENTRYPOINT ["tangelo"] CMD ["--port", "9220"] # this will execute tangelo directly After this change, you'll still have a problem: $ sudo docker run -ti test ... [29/Apr/2018:02:43:39] TANGELO no such group 'nobody' to drop privileges to Tangelo is complaining about the fact that there is no user and group named nobody inside the container. Again, there are two things you can do: add a RUN to create the nobody user and group, or run Tangelo with the -np/--no-drop-privileges option: ENTRYPOINT ["tangelo"] CMD ["--no-drop-privileges", "--port", "9220"] It's fine if during the build you see intermediate containers: Docker creates them for each build step. The commands you specify in ENTRYPOINT or CMD are not executed during build, they're just recorded into the final image.
has comment: http://stackoverflow.com/comment/87181762
score: 2
has comment: http://stackoverflow.com/comment/87181590
accepted answer of: http://stackoverflow.com/q/50082719
upvote count: 2

http://stackoverflow.com/q/50144934
has body: I have a table like the following: prov_code stdev median counts average 15680 1518170208 NaN 0.003956 1.0 0.003956 9819 1326073214 NaN 0.005536 1.0 0.005536 12158 1396892758 0.002297 0.008135 5.0 0.007002 7294 1235493859 NaN 0.011872 1.0 0.011872 10241 1336302850 NaN 0.011971 1.0 0.011971 538 1013948579 NaN 0.012109 1.0 0.012109 12262 1407192602 NaN 0.014108 1.0 0.014108 1729 1053544775 0.003417 0.018708 3.0 0.018736 9987 1326336603 0.015904 0.024315 3.0 0.018938 5614 1184677494 0.001838 0.021293 4.0 0.020641 14932 1487910469 0.015710 0.022984 2.0 0.022984 2410 1073857090 0.006663 0.022355 4.0 0.023586 885 1023447968 NaN 0.023651 1.0 0.023651 I am printing this using: print(df1.nsmallest(50,columns=['average'])) I would like to print the 50 smallest values for average when the counts are higher than a certain number say 100. Help is appreciated!
tagged with: pandas
has title: Printing smallest values from a column from rows where values in a different column were larger using pandas
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87308036
has comment: http://stackoverflow.com/comment/87308029
score: 0

http://stackoverflow.com/comment/87184646
type: Comment
type: QuestionComment
has text: Why are you deferring the fields in the first place?
comment on: http://stackoverflow.com/q/50084468
score: 0

http://stackoverflow.com/comment/87198186
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50090868
has text: You would have to weigh the complications this would introduce to the grammar against the benefit of allowing an assignment statement in a lambda expression. Lambda expressions don't give you the ability to do anything you couldn't do with a function defined with a `def` statement, and in fact are a convenience that was almost eliminated from the language altogether during the design of Python 3.
type: QuestionComment

http://stackoverflow.com/comment/87328975
has text: Also, can you clarify the purpose of setting FD to a string transformation of `%i`? If I am reading systemd docs correctly, %i is the systemd "instance name". I don't see how the instance name could possibly be the right value to supply as a file descriptor argument.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50141921

http://stackoverflow.com/a/50141185
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/131725879
score: 1
has comment: http://stackoverflow.com/comment/87300747
type: Answer
answers question: http://stackoverflow.com/q/50140748
has body: I got it working without any source-modifications. Your directory "mkdir" must be named "mpIPC", which is the module name. You'll want your directory structure to look like at the bottom do not attempt to test this from within your source-directory, i.e. not from anywhere in project, as that will attempt to import, according to Python's module structure, from the directory "mpIPC" (which you will have created in 1)) (credit for this hint goes to this comment in the post you mentioned. Instead, try it from anywhere in your home-dir, for example. That is, supposing you ran python setup.py install first :) Directory tree: foobar ├── mpIPC │ ├── __init__.py │ ├── os.py │ └── prctl3_0.c └── setup.py
accepted answer of: http://stackoverflow.com/q/50140748
type: AcceptedAnswer

http://stackoverflow.com/q/50126502
answer count: 1
has title: django get_absolute_url on search result
type: Question
tagged with: django-queryset
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87271185
score: 0
tagged with: url
has comment: http://stackoverflow.com/comment/87271061
has answer: http://stackoverflow.com/a/50126938
has comment: http://stackoverflow.com/comment/87271304
tagged with: django
has body: I am building board web application on Django=1.11 and try to figure out its search query. I have following url.py, models.py, 'views.py` and structures structure blog--- blog | |- urls.py | |- setting.py | |- boards |- models.py |- views.py |- templates |- search.html urls.py url(r'^search/$', boards_views.search_list, name="search"), url(r'^boards/(?P&lt;pk&gt;\d+)/$', TopicListView.as_view(), name="board_topics"), url(r'^boards/(?P&lt;pk&gt;\d+)/topics/(?P&lt;topic_pk&gt;\d+)/$',PostListView.as_view(), name="topic_posts"), models.py class Board(models.Model): name = models.CharField(max_length=50) class Topic(models.Model): subject = models.CharField(max_length=255) board = models.ForeignKey(Board, related_name='topics', on_delete=models.DO_NOTHING) views = models.PositiveIntegerField(default=0) class Post(models.Model): tag = models.CharField(max_length=300) message = models.CharField(max_length=1000, default="") topic = models.ForeignKey(Topic, related_name='posts', on_delete=models.DO_NOTHING) def get_absolute_url(self): return reverse("blog:topic_posts", args=[self.id]) views.py class PostListView(ListView): model = Post context_object_name = 'posts' template_name = 'topic_posts.html' paginate_by = 5 def get_context_data(self, **kwargs): session_key = 'viewed_topic_{}'.format(self.topic.pk) if not self.request.session.get(session_key, False): self.topic.views += 1 self.topic.save() self.request.session[session_key] = True kwargs['topic'] = self.topic return super().get_context_data(**kwargs) def get_queryset(self): self.topic = get_object_or_404(Topic, board__pk=self.kwargs.get('pk'), pk=self.kwargs.get('topic_pk')) queryset = self.topic.posts.order_by('created_at') return queryset class TopicListView(ListView): model = Topic context_object_name = 'topics' template_name = 'boards/topics.html' paginate_by = 5 def get_context_data(self, **kwargs): kwargs['board'] = self.board return super().get_context_data(**kwargs) def get_queryset(self): self.board = get_obj…
tagged with: python
has comment: http://stackoverflow.com/comment/87271728
has comment: http://stackoverflow.com/comment/87271081
accepted answer: http://stackoverflow.com/a/50126938
has comment: http://stackoverflow.com/comment/87271271

http://stackoverflow.com/q/50229600
has body: I have recently installed python 3 in my windows 8 computer. When I try to download the numpy package using pip from the command line, it's not working. Here's a sample of the output: f:\python\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros' warnings.warn(msg) running install running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options running build_src build_src building py_modules sources building library "npymath" sources No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils error: Could not initialize compiler instance: do you have Visual Studio installed? If you are trying to build with MinGW, please use "python setup.py build -c mingw32" instead. If you have Visual Studio installed, check it is correctly installed, and the right version (VS 2008 for python 2.6, 2.7 and 3.2, VS 2010 for &gt;= 3.3). Original exception was: [WinError 3] The system cannot find the path specified: 'F:\\Visual Studio\\VC\\PlatformSDK\\lib', and the Compiler class was MSVCCompiler and "f:\python\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\MATRIX~1.MAT\\AppData\\Local\\Temp\\pip-install-rxex02t4\\numpy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close(); At First, it shows the download of the package, which seems to be downloaded correctly, only during the installation process that I see some errors...
has comment: http://stackoverflow.com/comment/87476505
has answer: http://stackoverflow.com/a/50229711
score: 1
tagged with: windows
has title: Fail to download python package
has comment: http://stackoverflow.com/comment/87476417
type: Question
tagged with: numpy
type: UnansweredQuestion
favorite count: 0
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87476387

http://stackoverflow.com/q/50137259
type: Question
has title: Displaying data with '_' characters from Flask API with Angular
has body: I'm trying to build components from my flask API. When I hit the route, I can see the data for the objects I want. However, when I intreprolate in hopes to see it from my front end, I only see certain properties(the ones that have no '_' in their names). For example.. this is what I get when I hit the route .../measurements: [ { "availability": 100.0, "id": 1, "time": "2015-11-28T00:10:00+00:00", "wind_direction": 30, "wind_speed": 1.41, "wind_speed_dispersion": 0.22 }, { "availability": 100.0, "id": 2, "time": "2015-11-28T00:20:00+00:00", "wind_direction": 30.4, "wind_speed": 1.45, "wind_speed_dispersion": 0.2 }, { "availability": 100.0, "id": 3, "time": "2015-11-28T00:30:00+00:00", "wind_direction": 30.1, "wind_speed": 1.01, "wind_speed_dispersion": 0.2 },.... } However when I integrate Flask with Angular and wish to display that same data a list. I only get values for those without any '_' in the angular model name. For example I get: id: 1 Time: 2015-11-28T00:10:00+00:00 Wind Speed: Wind Direction: Wind Dispersion: Availability:100 Measurement point id: My model on Flask app looks like this.. class AggregatedMeasurement(db.Model): id = db.Column(db.Integer, primary_key=True) created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) time = db.Column(db.DateTime, nullable=False) wind_speed = db.Column(db.Float, nullable=False) # in m/s wind_direction = db.Column(db.Float, nullable=False) # in degrees wind_speed_dispersion = db.Column(db.Float, nullable=False) # in m/s availability = db.Column(db.Float, nullable=False) # in percent And the model on my angular app is: export class AggregatedMeasurement { constructor( public id: number, public time: Date, public windSpeed: number, public windDirection: number, public windSpeedDispersion: number, public availability: number, ) { } } I ended up using marshmallow for object serialization/deserialization. And this is how schema looks. class AggregatedMeasurementSchema(Schema): id = fields.Int(dump_only=Tr…
has answer: http://stackoverflow.com/a/50137575
type: UnansweredQuestion
tagged with: python
tagged with: marshmallow
tagged with: flask
score: 0
tagged with: angular
answer count: 1

http://stackoverflow.com/a/59282922
downvote count: 0
has body: Try to replace your code with the following code: &lt;img src="{{form.image.url}}"/&gt; with: &lt;img src="{{form.instance.image.url}}"/&gt;
answers question: http://stackoverflow.com/q/50206542
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/87415414
has text: Can you use the same code to create a JVM without it being called from Python/SWIG? Just make `int main_fn()` into `int main( int argc, char **argv)` and make a stand-alone program that does nothing but create a JVM. If that works, you likely have some other code that's corrupting memory.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50181298

http://stackoverflow.com/q/50209981
favorite count: 0
type: AnsweredQuestion
tagged with: deep-learning
score: 1
has title: Neural network is not being trained, cross-entropy stays about the same
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50210698
type: Question
has comment: http://stackoverflow.com/comment/87437603
has body: I have written the following multilayer perceptron model in TensorFlow, but it is not training. The accuracy stays around 9%, which is equivalent to random guessing, and cross-entropy stay around 2.56 and does not vary much. The architecture is as follows: def create_model(fingerprint_input, model_settings, is_training): if is_training: dropout_prob = tf.placeholder(tf.float32, name='dropout_prob') fingerprint_size = model_settings['fingerprint_size'] label_count = model_settings['label_count'] weights_1 = tf.Variable(tf.truncated_normal([fingerprint_size, 128], stddev=0.001)) weights_2 = tf.Variable(tf.truncated_normal([128, 128], stddev=0.001)) weights_3 = tf.Variable(tf.truncated_normal([128, 128], stddev=0.001)) weights_out = tf.Variable(tf.truncated_normal([128, label_count], stddev=0.001)) bias_1 = tf.Variable(tf.zeros([128])) bias_2 = tf.Variable(tf.zeros([128])) bias_3 = tf.Variable(tf.zeros([128])) bias_out = tf.Variable(tf.zeros([label_count])) layer_1 = tf.matmul(fingerprint_input, weights_1) + bias_1 layer_1 = tf.nn.relu(layer_1) layer_2 = tf.matmul(layer_1, weights_2) + bias_2 layer_2 = tf.nn.relu(layer_2) layer_3 = tf.matmul(layer_2, weights_3) + bias_3 layer_3 = tf.nn.relu(layer_3) logits = tf.matmul(layer_3, weights_out) + bias_out if is_training: return logits, dropout_prob else: return logits It takes the input size as fingerprint_size and the labels size as well as label_count. It has three hidden layers with 128 neurons each. I'm following the TensorFlow example on a speech data set, which provides a framework for everything else. In the documentation, all I needed to do is to include my own neural network architecture and my method should have those arguments defined and return the logits. When I trained another predefined architecture, with the same inputs and output, the neural network trains. But this one is not training. Here is one predefined architecture: def create_single_fc_model(fingerprint_input, model_settings, is_training): if is_tra…
downvote count: 0
answer count: 1
tagged with: neural-network
tagged with: machine-learning
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50210698
has comment: http://stackoverflow.com/comment/87438004

http://stackoverflow.com/comment/87331584
comment on: http://stackoverflow.com/a/50154826
score: 1
type: Comment
type: AnswerComment
has text: *There's an entire website dedicated to python **older** & **old** style formats: https://pyformat.info/, they don't have the new string interpolation style yet

http://stackoverflow.com/comment/87167118
comment on: http://stackoverflow.com/q/50075351
type: QuestionComment
has text: Looks like the line is still something your not expecting. Clearly there are more than 3 items in the line. I suggest you print the first line to debug this, see what is actually contained `importance_ranking`. I'm not sure if you are using a `dict` or a `dataframe`, but check the shape of your data.
score: 0
type: Comment

http://stackoverflow.com/a/78280106
score: 0
has body: Any Python (or non Python) PDF editor like PyPDF has the ability to add (and remove) the OPTIONAL permission flags. Thus nothing different to using any PDF editor. The core of the Question was I also need to request that the viewers can't modify this document, even if they has the opening password. And that is OPTIONAL per the standard. Acrobat "Viewers" will respect and block their abilities based on ADOBE flags, but other viewers optionally per Open PDF licenced code and PDFs. Do not have to respect those flags, once the password is supplied to open and decrypt the file for viewing. All PDFs are editable with or without flags and with or without signature locking. To use or edit a restricted file simply open (with the "User Password" for descrambling in the viewer) in any Alternative editing viewer, that does not use Adobe code. To edit or remove signatures you may need to use a GUI or Binary editor. Answer To ensure Adobe flags, do not let a user edit an Adobe PDF, then like many .gov or .org sites, request that the user only use Acrobat Reader, or a similar viewer like Chromium Edge.
type: Answer
answers question: http://stackoverflow.com/q/50217131

http://stackoverflow.com/a/50144111
answers question: http://stackoverflow.com/q/50143946
type: Answer
has body: I figured out what was wrong, in case anyone will ever want to do this: for k in k_range: knn = KNeighborsClassifier(n_neighbors=k) model = knn.fit(X_train, Y_train) y_predict_proba = model.predict_proba(X_test).tolist() probabilities = np.array(y_predict_proba)[:, 1] fpr, tpr, _ = roc_curve(Y_test, probabilities) roc_auc = auc(fpr, tpr) color = ['blue', 'orange', 'red', 'green', 'coral', 'grey', 'indigo', 'gold', 'lime', 'olive', 'pink', 'navy', 'magenta', 'yellow', 'tomato', 'turquoise', 'yellowgreen', 'maroon', 'lightblue'] plt.plot(fpr, tpr, color=color[k - 1], lw=1, label='ROC (area = %f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.legend(loc="lower right") plt.show()
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50143946
score: 1

http://stackoverflow.com/q/50180414
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50180593
tagged with: python
has body: I have a class that generates an indefinite amount of data objects. This class has a subprocess for this generation of data. Since this subprocess needs to use a pool of workers, it is non daemonic. Now the problem is that this Process will never finish it's work (because that is what it is designed to do), so when the main process finishes it will be unable to join and thus python will never quit. I therefore have to somehow terminate it reliably at the end of main. This has proven to be more tricky than I expected, because I cannot rely on the destructor of the class AND python processes have per default not timeout on their join method. A hacky workaround was to implement a cleanup function that is called at the very end and terminates the worker but that is obviously not a good solution since one could easily forget to call it. DO you have any suggestions how else this may be solved? Regards, Fabian Here is a minimalistic example: from builtins import range from builtins import object from multiprocessing import Process from multiprocessing import Queue from multiprocessing import Pool from collections import deque def transform(x): return x / 10 class SomeName(object): def __init__(self): self.was_started = False def start(self): print("started") def produce(target_queue, num_processes): print("producer started") ctr = 0 pool = Pool(num_processes) results = deque() for i in range(num_processes): item = ctr ctr += 1 results.append(pool.apply_async(transform, args=(item,))) while True: target_queue.put(results.popleft().get()) item = ctr ctr += 1 results.append(pool.apply_async(transform, args=(item,))) self.queue = Queue(4) self.process = Process(target=produce, args=(self.queue, 4)) self.process.daemon = False self.process.start() self.was_started = True def __next__(self): if not self.was_started: self.start() return self.queue.get() if __name__ == "__main__": a = SomeName() [print(next(a)) for _ in range(20)]
score: 0
has title: Terminate non-daemon python background Process when Program completes
has answer: http://stackoverflow.com/a/50180470
tagged with: multiprocessing
type: Question

http://stackoverflow.com/q/50078361
type: Question
has answer: http://stackoverflow.com/a/63089107
answer count: 2
score: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52429324
downvote count: 0
favorite count: 0
tagged with: plot
tagged with: networkx
has body: I'm using Plotly's Python interface to generate a network. I've managed to create a network with my desired nodes and edges, and to control the size of the nodes. I am desperately looking for help on how to do the following: add node labels add edge labels according to a list of weights control the edge line width according to a list of weights All this without using the "hovering" option, as it has to go in a non-interactive paper. I'd greatly appreciate any help! Plotly's output | In case this fails, the figure itself | matrix.csv This is my code (most is copy-pasted from the Plotly tutorial for Networkx): import pandas as pd import plotly.plotly as py from plotly.graph_objs import * import networkx as nx matrix = pd.read_csv("matrix.csv", sep = "\t", index_col = 0, header = 0) G = nx.DiGraph() # add nodes: G.add_nodes_from(matrix.columns) # add edges: edge_lst = [(i,j, matrix.loc[i,j]) for i in matrix.index for j in matrix.columns if matrix.loc[i,j] != 0] G.add_weighted_edges_from(edge_lst) # create node trace: node_trace = Scatter(x = [], y = [], text = [], mode = 'markers', marker = Marker( showscale = True, colorscale = 'YIGnBu', reversescale = True, color = [], size = [], colorbar = dict( thickness = 15, title = 'Node Connections', xanchor = 'left', titleside = 'right'), line = dict(width = 2))) # set node positions pos = nx.spring_layout(G) for node in G.nodes(): G.node[node]['pos']= pos[node] for node in G.nodes(): x, y = G.node[node]['pos'] node_trace['x'].append(x) node_trace['y'].append(y) # create edge trace: edge_trace = Scatter(x = [], y = [], text = [], line = Line(width = [], color = '#888'), mode = 'lines') for edge in G.edges(): x0, y0 = G.node[edge[0]]['pos'] x1, y1 = G.node[edge[1]]['pos'] edge_trace['x'] += [x0, x1, None] edge_trace['y'] += [y0, y1, None] edge_trace['text'] += str(matrix.loc[edge[0], edge[1]])[:5] # size nodes by degree deg_dict = {deg[0]:int(deg[1]) for deg in list(G.degree())} for node, degree in enumerate(deg_dict): node_tra…
upvote count: 5
tagged with: plotly
tagged with: python
has title: Customizing a Networkx graph (or Scatter) with Python Plotly

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/50116405
tags question: http://stackoverflow.com/q/50147612
type: Tag
tags question: http://stackoverflow.com/q/50091588
tags question: http://stackoverflow.com/q/50219994

http://stackoverflow.com/comment/87176437
type: Comment
type: QuestionComment
score: 8
comment on: http://stackoverflow.com/q/50080233
has text: What have you tried? BTW: this are not valid integers, I'm assuming you are turning them into strings. It is also a very bad idea to use python types as a variable name, e.g. `list`.

http://stackoverflow.com/a/50199713
has body: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version try to disabe the SSL Certificate Check for The Site https://pypi.python.org/simple/pysocks/ or There Are A 404 Not Found Or An 403 Forbidden In The Site
type: Answer
answers question: http://stackoverflow.com/q/50198752
score: 0
has comment: http://stackoverflow.com/comment/87416346

http://stackoverflow.com/comment/87473962
score: 0
type: Comment
has text: I was trying to bypass the resource object. But this works too. Thanks.
comment on: http://stackoverflow.com/a/50202183
type: AnswerComment

http://stackoverflow.com/comment/87347126
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50163445
has text: With no prior knowledge? Impossible.
score: 1

flask
tags question: http://stackoverflow.com/q/50189490
tags question: http://stackoverflow.com/q/50120775
tags question: http://stackoverflow.com/q/50158969
tags question: http://stackoverflow.com/q/50089690
tags question: http://stackoverflow.com/q/50210036
tags question: http://stackoverflow.com/q/50109466
tags question: http://stackoverflow.com/q/50162274
tags question: http://stackoverflow.com/q/50138445
tags question: http://stackoverflow.com/q/50168932
tags question: http://stackoverflow.com/q/50086001
tags question: http://stackoverflow.com/q/50160087
tags question: http://stackoverflow.com/q/50198753
tags question: http://stackoverflow.com/q/50163249
tags question: http://stackoverflow.com/q/50219452
tags question: http://stackoverflow.com/q/50078664
tags question: http://stackoverflow.com/q/50160009
tags question: http://stackoverflow.com/q/50172305
tags question: http://stackoverflow.com/q/50091379
tags question: http://stackoverflow.com/q/50195313
tags question: http://stackoverflow.com/q/50189438
tags question: http://stackoverflow.com/q/50185926
tags question: http://stackoverflow.com/q/50223446
tags question: http://stackoverflow.com/q/50225864
tags question: http://stackoverflow.com/q/50160746
tags question: http://stackoverflow.com/q/50189486
tags question: http://stackoverflow.com/q/50172635
tags question: http://stackoverflow.com/q/50218190
tags question: http://stackoverflow.com/q/50214180
tags question: http://stackoverflow.com/q/50134780
tags question: http://stackoverflow.com/q/50161843
tags question: http://stackoverflow.com/q/50082951
tags question: http://stackoverflow.com/q/50091265
tags question: http://stackoverflow.com/q/50105499
tags question: http://stackoverflow.com/q/50108907
tags question: http://stackoverflow.com/q/50104362
tags question: http://stackoverflow.com/q/50083889
tags question: http://stackoverflow.com/q/50103361
tags question: http://stackoverflow.com/q/50217672
tags question: http://stackoverflow.com/q/50187320
tags question: http://stackoverflow.com/q/50084280
tags question: http://stackoverflow.com/q/50087728
tags question: http://stackoverflow.com/q/50222250
tags question: http://stackoverflow.com/q/50156408
tags question: http://stackoverflow.com/q/50096827
tags question: http://stackoverflow.com/q/50180980
tags question: http://stackoverflow.com/q/50186237
tags question: http://stackoverflow.com/q/50186010
tags question: http://stackoverflow.com/q/50143672
tags question: http://stackoverflow.com/q/50182833
tags question: http://stackoverflow.com/q/50213683
tags question: http://stackoverflow.com/q/50114648
tags question: http://stackoverflow.com/q/50088793
tags question: http://stackoverflow.com/q/50129149
tags question: http://stackoverflow.com/q/50105057
tags question: http://stackoverflow.com/q/50146815
tags question: http://stackoverflow.com/q/50120694
tags question: http://stackoverflow.com/q/50226243
tags question: http://stackoverflow.com/q/50113323
tags question: http://stackoverflow.com/q/50181122
tags question: http://stackoverflow.com/q/50112759
tags question: http://stackoverflow.com/q/50083331
tags question: http://stackoverflow.com/q/50137259
tags question: http://stackoverflow.com/q/50198678
tags question: http://stackoverflow.com/q/50121432
tags question: http://stackoverflow.com/q/50190164
tags question: http://stackoverflow.com/q/50087442
tag name: flask
tags question: http://stackoverflow.com/q/50087103
tags question: http://stackoverflow.com/q/50133484
tags question: http://stackoverflow.com/q/50086974
tags question: http://stackoverflow.com/q/50152641
tags question: http://stackoverflow.com/q/50211209
tags question: http://stackoverflow.com/q/50158459
tags question: http://stackoverflow.com/q/50167920
tags question: http://stackoverflow.com/q/50086585
tags question: http://stackoverflow.com/q/50113222
tags question: http://stackoverflow.com/q/50121124
tags question: http://stackoverflow.com/q/50195277
tags question: http://stackoverflow.com/q/50191352
tags question: http://stackoverflow.com/q/50162128

http://stackoverflow.com/comment/87347571
has text: Sorry* within a file within a folder on the same level as `FolderB`, i.e. `Project/Directory/$CWD.py`
comment on: http://stackoverflow.com/q/50164550
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87264641
comment on: http://stackoverflow.com/a/50123016
score: 0
has text: @Null-Hypothesis Thanks, that was a typo.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87405364
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50191395
has text: @vzone, I can't remove it because "others have invested time and efforts into answering it". And yes, once again, you were right, i have another 'test' lib hidden in `/home/nathan/.anaconda3/lib/python3.6/test/__init__.py`, well at least now, I know how to check what module I'm actually loading thanks to you ^^. I'll change my answer in order to reflect that.

http://stackoverflow.com/comment/87307981
comment on: http://stackoverflow.com/a/50144841
type: AnswerComment
score: 0
type: Comment
has text: Thank you! I ended up doing something very similar. I think my mistake was honestly misunderstanding how to use ".extend"

http://stackoverflow.com/q/50086583
type: AnsweredQuestion
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50243491
has title: How to ragged partition a list in Python?
has comment: http://stackoverflow.com/comment/87493944
score: 1
upvote count: 3
linked to: http://stackoverflow.com/q/312443
downvote count: 2
tagged with: partition
has comment: http://stackoverflow.com/comment/87189236
has answer: http://stackoverflow.com/a/50086609
has comment: http://stackoverflow.com/comment/87194403
has body: Is there a built-in Python function such that with vals=[1,2,3,4,5] then foo(vals,2) gives [[1,2],[3,4],[5]] I am looking for the behaviour that Wolfram Language gives with Partition[Range@5, UpTo@2] {{1, 2}, {3, 4}, {5}}
tagged with: wolfram-mathematica
has comment: http://stackoverflow.com/comment/87194156
favorite count: 0
has comment: http://stackoverflow.com/comment/87189177
has comment: http://stackoverflow.com/comment/87194962
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50086625
has comment: http://stackoverflow.com/comment/87189062
possible better answer: http://stackoverflow.com/a/50086609
has comment: http://stackoverflow.com/comment/87481556
tagged with: python
has comment: http://stackoverflow.com/comment/87194851
has comment: http://stackoverflow.com/comment/87189556
accepted answer: http://stackoverflow.com/a/50243491

http://stackoverflow.com/a/50201814
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50201787
has body: All you have to do is slap a return on the front. def prune(tree): return [prune(branch) for branch in tree if branch != []] If you wanted to decompose the list comprehension—and there's no real reason to—it'd be: def prune(tree): for branch in tree: if branch != []: yield prune(branch) Or: def prune(tree): branches = [] for branch in tree: if branch != []: branches.append(prune(branch)) return branches
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50201787

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/50150568
tags question: http://stackoverflow.com/q/50075375
type: Tag
tags question: http://stackoverflow.com/q/50110395

http://stackoverflow.com/comment/87473538
has text: The expected date is always the nearest to (t - 1 mth) so: 1991-03-13 -> 1991-02-13, 1991-02-27 -> 1991-01-30 etc.
score: 0
comment on: http://stackoverflow.com/q/50227956
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87470592
has text: 1) `print` is not a constructor (so what's with the title?); and 2) constructors generally should not have side-effects
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50226663
type: QuestionComment

http://stackoverflow.com/comment/87262743
has text: Do you mean `range(len(walk))` instead of `range(walk)`? You also have a typo in the outer `for` loop in which you write `walks` instead of `walk`.
type: Comment
comment on: http://stackoverflow.com/q/50122358
type: QuestionComment
score: 0

http://stackoverflow.com/a/50179784
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50129464
has body: Taking into account that you are using Python client library, use print() function to obtain the desired results. I don’t know if you are testing the application locally or you have deployed it. If you are testing the application locally: print() function output can be found in the cloud shell. If you have deployed the application: go to the GCP console, App Engine and services. Select the service in which you have deployed your application. In the right side click on tools and select "Logs". This will redirect the page to your app logs. A more precise logging can be defined using the Stackdriver Logging for Python. The warning level can be defined. This can help you manage your application or identify events of interest. Find an example code here. You might find useful Stackdriver Logging agent, an application based on fluentd that runs on your virtual machine (VM) instances. The Logging agent is pre-configured to send logs from VM instances to Stackdriver Logging. There are source and configuraiton files available for redis. If you want a more general vision, App Engine flexible environment logs official documentation can help you to understand the different available logs.

http://stackoverflow.com/comment/87423579
score: 0
type: Comment
type: QuestionComment
has text: Which columns identify the row you want to update?
comment on: http://stackoverflow.com/q/50203341

http://stackoverflow.com/q/50092084
favorite count: 0
type: Question
tagged with: numpy
has body: Lets say i generate an image this way: import cv2 import numpy as np im = cv2.imread('target.jpg') zzo = np.zeros(im.shape) shp = (int(im.shape[0]),int(0.5*im.shape[1]),int(im.shape[2])) zz = np.zeros(shp) oo = 255*np.ones(shp) cct = np.concatenate((zz,oo),1) cv2.imshow('image',cct) cv2.waitKey(0) cv2.destroyAllWindows() The result is an image that is half white and half black. How can i randomize the locations of the black and white pixels? I've tried using the numpy permutation and shuffle functions but this doesn't appear to do anything to the image. The variable im is a 3D-array and randomizing the positions of the pixels requires moving an object that has three values per pixel (R,G,B) so pixel one is im[0,0,:], pixel two is im[0,1,:] and so on
tagged with: pixel
has answer: http://stackoverflow.com/a/50092387
possible better answer: http://stackoverflow.com/a/50092369
downvote count: 0
has answer: http://stackoverflow.com/a/50092835
has answer: http://stackoverflow.com/a/50092369
has title: randomizing location of black pixels in an image
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50092387
answer count: 3
upvote count: 3
score: 3
tagged with: python
tagged with: image-processing

http://stackoverflow.com/a/50117801
has body: you tryed to write on the start of the script #coding: UTF-8 ??
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50116967

generator
tags question: http://stackoverflow.com/q/50204495
type: Tag
tags question: http://stackoverflow.com/q/50119668
tags question: http://stackoverflow.com/q/50091553
tags question: http://stackoverflow.com/q/50177296
tags question: http://stackoverflow.com/q/50133385
tag name: generator
tags question: http://stackoverflow.com/q/50176304
tags question: http://stackoverflow.com/q/50129607
tags question: http://stackoverflow.com/q/50100235
tags question: http://stackoverflow.com/q/50185509

http://stackoverflow.com/comment/87340840
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50161375
score: 0
has text: Personally, I think this feature needs more spotlight, for instance you should be able to read directly from a `.json` file instead of having to load a json file into a dictionary then pass that into this function.

http://stackoverflow.com/a/50089032
score: 1
type: Answer
has body: Although you will not use the boundingRect() to detect the collision you must return a QRect that is the minimum size that covers the shape, for this we can use the boundingRect() method of QPainterPath, besides it is not necessary to overwrite the shape QGraphicsRectItem. class RectItem(QGraphicsRectItem): def __init__(self, *args): super().__init__(*args) self.setFlag(QGraphicsItem.ItemIsMovable) self.setPen(QPen(Qt.cyan)) class CurveItem(QGraphicsItem): def __init__(self): super().__init__() self.path = self._setupPath() def paint(self, painter, styles, widget=None): painter.drawPath(self.path) def boundingRect(self): return self.path.boundingRect() def shape(self): return self.path def _setupPath(self): path = QPainterPath() path.moveTo(0, 0) path.cubicTo(99, 0, 50, 50, 99, 99) path.cubicTo(0, 99, 50, 50, 0, 0) return path class Scene(QGraphicsScene): def __init__(self): super().__init__() self.curve_item = CurveItem() self.rect_item = RectItem(-50, -50, 25, 25) self.addItem(self.curve_item) self.addItem(self.rect_item) def mouseMoveEvent(self, e): print(self.collidingItems(self.rect_item, mode=Qt.IntersectsItemShape)) super().mouseMoveEvent(e)
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87199371
accepted answer of: http://stackoverflow.com/q/50086893
answers question: http://stackoverflow.com/q/50086893

http://stackoverflow.com/comment/87202875
type: QuestionComment
has text: Read this: https://stackoverflow.com/questions/37680981/how-can-i-retrieve-data-from-a-qtablewidget
score: 0
comment on: http://stackoverflow.com/q/50093086
type: Comment

memoization
type: Tag
tag name: memoization
tags question: http://stackoverflow.com/q/50108641

http://stackoverflow.com/q/50083466
type: UnansweredQuestion
tagged with: arrays
has title: Best data structure for version control
has comment: http://stackoverflow.com/comment/87182815
tagged with: python
tagged with: data-structures
has comment: http://stackoverflow.com/comment/87182820
has comment: http://stackoverflow.com/comment/87183024
has comment: http://stackoverflow.com/comment/87182839
score: 0
has answer: http://stackoverflow.com/a/50083574
answer count: 1
has comment: http://stackoverflow.com/comment/87182878
has body: I've a dynamic array of 10^7 512-bit elements in which elements can be added, deleted and interchanged with each other. Every time, a user manipulates the array, I want to record the changes in a space-efficient way such that I'm able to get the final version without needing to evaluate all the previous versions. Which is the best data structure for doing that? An expensive way is to store all the versions of the array: [1,5,7,3,8,2] [1,4,5,7,3,8,2] [1,5,4,7,3,8,2] [1,4,5,3,7,8,2] [2,4,5,3,7,8,1] Another way (this would require to compute every version to find the current state): [1,5,7,3,8,2] Add 4 between 1 and 5 Switch 4 with 5 Switch 3 with 7 Switch 1 with 2 Is there an space-efficient alternative that solves the problem?! Thank You!
has comment: http://stackoverflow.com/comment/87182854
has comment: http://stackoverflow.com/comment/87185669
type: Question
has comment: http://stackoverflow.com/comment/87182921

http://stackoverflow.com/q/50104617
tagged with: many-to-many
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has body: I have these models (simplified): class Product(TimeStampedModel): product_id = models.AutoField(primary_key=True, ) shop = models.ForeignKey('Shop', related_name='products', to_field='shop_name', on_delete=models.CASCADE) category = models.ForeignKey('Category', related_name='products', to_field='category_name', on_delete=models.SET_NULL) brand = models.ForeignKey('Brand', related_name='products', to_field='brand_name', on_delete=models.CASCADE) class Brand(models.Model): brand_name = models.CharField(max_length=50) shops = models.ManyToManyField('Shop', related_name='shops') categories = models.ManyToManyField('Category', related_name='categories') class Category(models.Model): category_name = models.CharField(max_length=128) shops = models.ManyToManyField('Shop') class Shop(models.Model): shop_name = models.CharField(max_length=30) In admin I am trying manually to change a Category for bunch of selected Products (I have a custom function for that). But here I see 2 problems: 1) Must be updated M2M relation in Brand-&gt;Category, if there was no Brand with this Category. 2) Must be updated M2M relation in Category-&gt;Shop, if there was not this selected Category in the Shop. How to do this in the best way? I know that this might be some kind of Django signals use, specially m2m_changed, but I can't understand who is emitter of the signal, and who is receiver, and how to update multiple tables after change in 1 table.
has title: Many-to-Many update, Django signals
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: signals
tagged with: django
tagged with: python

http://stackoverflow.com/q/50184386
duplicate of: http://stackoverflow.com/q/8687018
has body: Because of this answer, it might be necessary to do this: path = r"D:\Temp\abc[def]\ # (i have many others to process) path = path.replace('[', '[[]').replace(']', '[]]') # now we can use glob here with path However, the first replace gets mixed up with the second replace, and the result is not what is expected, i.e. D:\Temp\abc[[]def[]]\. The only solution I found is to use a temporary character ~ to avoid the 2 replace to be mixed up with each other: path = path.replace('[', '[[~').replace(']', '[]]').replace('~', ']') Is there a nice way to use 2 replacements without the first having effect on the second?
type: AnsweredQuestion
has title: Use 2 string replace without the first having effect on the second
has comment: http://stackoverflow.com/comment/87386228
score: 0
has comment: http://stackoverflow.com/comment/87386110
answer count: 1
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/8687018
has comment: http://stackoverflow.com/comment/87386106
linked to: http://stackoverflow.com/q/2595119
accepted answer: http://stackoverflow.com/a/50184418
tagged with: python
has answer: http://stackoverflow.com/a/50184418

http://stackoverflow.com/comment/87302770
type: QuestionComment
has text: You probably need to write your own generator, which yields a dictionary `batch_dict={'inputLayerName' : X_train, 'outputLayerName' : Y_train}`, where `input/outputLayerName` should be the same as the one you used to define your network input/output, i.e. `net_in = Input(shape=(xxx), name='inputLayerName')`.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50141766

http://stackoverflow.com/a/50184282
type: Answer
has body: Another approach that is much nicer, is to use properties import random class Card: def __init__(self): self.value = 0 def shuffle(self): self.value = random.randint(1, 13) @property def face_value(self): faces = {1: "Ace", 2: "two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen", 13: "King"} return faces[self.value] def __str__(self): return self.face_value def deal_hand(): card = Card() print("Your 5 hand card is") for i in range(5): card.shuffle() print(card) deal_hand() output: Your 5 hand card is Seven Eight Ace Seven Ace
has comment: http://stackoverflow.com/comment/87385978
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50182966
has comment: http://stackoverflow.com/comment/87386035
answers question: http://stackoverflow.com/q/50182966

http://stackoverflow.com/comment/87265676
type: AnswerComment
comment on: http://stackoverflow.com/a/50106542
score: 0
has text: @McBraunie This function does that. Do you have any problems with this approach?
type: Comment

http://stackoverflow.com/q/50143481
has comment: http://stackoverflow.com/comment/87407421
has title: join based on more than 1 column in a pandas dataframe
has comment: http://stackoverflow.com/comment/87305485
tagged with: dataframe
tagged with: python
score: 0
answer count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/23508351
type: Question
has comment: http://stackoverflow.com/comment/87305182
type: UnansweredQuestion
has body: I have a data frames(df1) with two columns(e.g. A and A_NEW). A is supposed to be a default join key between df1 and another data frame (df2). I want to join df1 and df2 in a way that if there is no match between df1.A and df2.key, then join based on df1.A_NEW and and df2.key. Imagine following scenario: It means value of join attribute could be either in df1.A or df1.A_NEW but our priority is df1.A. If there is no match between df1.A and df2.key, then df1.A_NEW should be checked with df2.key. I appreciate if you could help me with inner join and left outer join scenarios.

http://stackoverflow.com/q/50153993
has comment: http://stackoverflow.com/comment/87325743
possible better answer: http://stackoverflow.com/a/50154328
type: AnsweredQuestion
score: 2
has title: Retrieving data from xml file to mysql database
answer count: 2
has answer: http://stackoverflow.com/a/50154328
tagged with: xml-parsing
upvote count: 2
tagged with: mysql-python
downvote count: 0
tagged with: elementtree
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87328254
has body: I have to retrieve the data from xml file and has to enter into the database. There was no error when I run my python file but the data is not entering into the database. I am unable to find where I went wrong. It would be very helpful if anyone could help me. Here is my python code, from xml.etree import ElementTree import mysql.connector dom = ElementTree.parse('profile.xml') ticker = dom.findall('TICKER') name = dom.findall('NAME') address = dom.findall('ADDRESS') phone = dom.findall('PHONE') website = dom.findall('WEBSITE') sector = dom.findall('SECTOR') industry = dom.findall('INDUSTRY') full_time = dom.findall('FULL_TIME') bus_summ = dom.findall('BUS_SUMM') ticker_list = [t.text for t in ticker] name_list = [t.text for t in name] add_list = [t.text for t in address] phn_list = [t.text for t in phone] site_list = [t.text for t in website] sec_list = [t.text for t in sector] ind_list = [t.text for t in industry] emp_list = [t.text for t in full_time] sum_list = [t.text for t in bus_summ] db = mysql.connector.Connect(host = 'localhost', user = 'root', password ='root' , database = 'nldb_project') cur = db.cursor() query = "INSERT INTO profiles(`prof_ticker`,`name`,`address`,`phonenum`,`website`,`sector`,`industry`,full_time`,`bus_summ`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)" sqltuples = [(t,n,a,p,s,sec,i,e,su) for t,n,a,p,s,sec,i,e,su in zip(ticker_list,name_list,add_list,phn_list,site_list,sec_list,ind_list,emp_list,sum_list)] cur.executemany(query,sqltuples) I am using python 3.6.5 version. Here is my xml code, <?xml version="1.0"?> AAPL Apple Inc. <ADDRESS>1 Infinite Loop;Cupertino, CA 95014;United State 408-996-1010 http://www.apple.com Technology Consumer Electronics <FULL_TIME>100,000</FULL_TIME> <BUS_SUMM>Apple</BUS_SUMM> <SOURCE>https://finance.yahoo.com/quote/AAPL/profile?p=AAPL T AT and T Inc. <ADDRESS>208 South Akard Street;Dallas, TX 75202;United States 210-821-4105 http://www.att.com Communication Services Telecom Services <FULL_TIME>254,000</F…
accepted answer: http://stackoverflow.com/a/50169867
tagged with: python
has answer: http://stackoverflow.com/a/50169867

http://stackoverflow.com/comment/87423151
has text: sorry, I mean `recall_score`.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50203106

http://stackoverflow.com/comment/87167015
has text: Then post that attempt and the error as well. In particular, you only want the last two columns, so something like `_,a,b` looks like it would work.
score: 0
comment on: http://stackoverflow.com/q/50075351
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87307168
comment on: http://stackoverflow.com/q/50144414
type: Comment
type: QuestionComment
has text: I think numpy should provide unsigned ints. I would try np.array(array).astype(np.uint8)
score: 0

http://stackoverflow.com/a/50155978
has comment: http://stackoverflow.com/comment/87329795
score: 10
answers question: http://stackoverflow.com/q/50155886
type: Answer
upvote count: 10
has body: Here's how to get a list of email addresses for active users: emails = User.objects.filter(is_active=True).values_list('email', flat=True) If you want to exclude empty email addresses, you can do it like this: emails = User.objects.filter(is_active=True).exclude(email='').values_list('email', flat=True)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50155886
has comment: http://stackoverflow.com/comment/87329689

http://stackoverflow.com/a/50083610
upvote count: 1
has comment: http://stackoverflow.com/comment/87183053
answers question: http://stackoverflow.com/q/50083582
score: 1
has body: Your input is obviously generated by calling just printing out Python lists (or calling str or repr on them). This particular example can be handled by using literal_eval: with open("input.txt") as fp: for line in fp: obj = ast.literal_eval(line) corpus.append(obj[3]) However, that won't work for all Python list displays in general. And when it doesn't work… well, there's not much you can do in general. But you can just literal_eval until you get an error, and then, for each error, laboriously work out how to pre-process things to work around it. The right thing to do is generate output that's actually parseable, like JSON, and then you can just parse it trivially.
has comment: http://stackoverflow.com/comment/87183015
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87167133
has text: *facepalm* so the issue is with number? If number is a list, then list slicing with variables would work?
type: QuestionComment
comment on: http://stackoverflow.com/q/50074919
score: 0
type: Comment

http://stackoverflow.com/q/50132627
type: Question
possible better answer: http://stackoverflow.com/a/50132678
tagged with: iterator
has answer: http://stackoverflow.com/a/50132739
tagged with: python-3.5
has body: I have this code: a = ['animal', 'dog', 'car', 'bmw', 'color', 'blue'] a_iter = iter(a) print(a) print(a_iter) print(dict(zip(a,a))) print(dict(zip(a_iter,a_iter))) and output is: ['animal', 'dog', 'car', 'bmw', 'color', 'blue'] &lt;list_iterator object at 0x7f2d98b756d8&gt; {'dog': 'dog', 'car': 'car', 'animal': 'animal', 'color': 'color', 'blue': 'blue', 'bmw': 'bmw'} {'car': 'bmw', 'color': 'blue', 'animal': 'dog'} I do not understad, why the zip works differently with a_iter than a. What does iter() do, list is iterable, so why use iter()? Could anybody explain me this with some nice example? I googled about it but I still do not understand it.
score: 6
tagged with: python
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/87283268
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/50132678
accepted answer: http://stackoverflow.com/a/50132843
has title: What does iter() do to list?
favorite count: 0
has answer: http://stackoverflow.com/a/50132843

persistence
tags question: http://stackoverflow.com/q/50165242
tag name: persistence
type: Tag

http://stackoverflow.com/comment/87455329
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50218877
type: QuestionComment
has text: @roganjosh using subprocesses is the best way ive found so far to do it. im not sure how to have it loop through the function successfully multiple times

http://stackoverflow.com/comment/87335390
type: AnswerComment
comment on: http://stackoverflow.com/a/50156333
score: 0
type: Comment
has text: Thank you for the answer! I've updated the driver but I still get the same issue

http://stackoverflow.com/q/50129135
tagged with: python-3.6
has body: I've encountered one peculiar issue I just can't understand. I've been working on a code in PyCharm, using Python 3.6 (Windows 10) and I've imported few modules for that objective like so: import requests from bs4 import BeautifulSoup import time import lxml For few days now I've been coding having no problems, I've run my code several times to test it and everything been going well until suddenly, without changing anything in the interpreter or any other setting, the modules seem to generate a lot of import errors such as: ImportError: cannot import name 'BeautifulSoup' AttributeError: module 'requests' has no attribute 'get' This is so weird, suddenly I can't run my code and all my work is halted. I've been looking up the internet and saw that usually this happens if you call one of your files in a same name as a module (for example, naming my file bs4.py), I'm afraid this is not the case here, I made sure my file is named in a unique name which doesn't exist anywhere on said libraries. I couldn't find any other solution for this. Can anyone help me figure this one out?
has comment: http://stackoverflow.com/comment/87759629
tagged with: python-import
answer count: 0
tagged with: pycharm
has title: Sudden module imports issues
score: 1
linked to: http://stackoverflow.com/q/48093363
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87276356
favorite count: 0
type: Question
tagged with: importerror
has comment: http://stackoverflow.com/comment/87276790
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87276294
tagged with: python

http://stackoverflow.com/a/50222445
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50222055
type: Answer
has body: You can try this: np.where(p &gt; np.random.rand(1000), 1, 0)

http://stackoverflow.com/comment/87305123
score: 0
type: Comment
type: QuestionComment
has text: Yes, it should be the same order if there is nothing extremely special in your code. Try it out yourself.
comment on: http://stackoverflow.com/q/50143102

http://stackoverflow.com/comment/87341987
type: AnswerComment
comment on: http://stackoverflow.com/a/50161586
score: 0
has text: Your code incorrectly assumes that `list2[-1]` corresponds to the length of the output lists. That was just a coincidence, and it has been changed to a different number now to make that more obvious.
type: Comment

http://stackoverflow.com/comment/87637789
comment on: http://stackoverflow.com/a/50282803
score: 1
type: Comment
type: AnswerComment
has text: Yes, I calculated them, starting with figuring out the center point for the 3 "major" colors. I named these major because they span a larger range of the hue values before what my eye could discern as a different color. It ended up dividing up pretty nicely with a hue range of 40 for the major colors and 20 for the 3 minor colors, covering the hue space of 180. The monochrome values are a bit more subjective.

http://stackoverflow.com/comment/87220520
type: Comment
has text: on my machine `"python.pythonPath": "python"` and `"python.envFile": "${workspaceFolder}/.env"` hope that helps
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50093335

http://stackoverflow.com/comment/87461558
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50221779
has text: one tiny thing, you can probably remove `if len(res)>1:`. the loop `for num in res[1:]:` will just do nothing if `res` has length 1 or 0. This tiny change probably won't make much difference.
type: Comment

http://stackoverflow.com/q/50160774
accepted answer: http://stackoverflow.com/a/50161242
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50161242
favorite count: 0
type: Question
score: 5
upvote count: 5
has title: pandas wide_to_long suffix parameter
tagged with: python
type: AnsweredQuestion
has body: I have a question about a parameter when using wide_to_long in pandas. There is parameter called suffix that I do not understand. In the documentation it says: suffix : str, default ‘\d+’ A regular expression capturing the wanted suffixes. ‘\d+’ captures numeric suffixes. Suffixes with no numbers could be specified with the negated character class ‘\D+’. You can also further disambiguate suffixes, for example, if your wide variables are of the form Aone, Btwo,.., and you have an unrelated column Arating, you can ignore the last one by specifying suffix=’(!?one|two)’ New in version 0.20.0. Question: What can be used for suffix? And I found someone uses suffix like this when using wide_to_long: suffix='.' What does it do?
tagged with: pandas

http://stackoverflow.com/q/50080520
downvote count: 0
tagged with: django
tagged with: python
has body: I am getting data from an API and saved in models.py as part of learning Django. I got data and it is saved in db as it is. [u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT'] Now when I try to access this data in template I getting this list only and not able to show it in a user friendly manner. I have tried: {% for data in datalist.items %} {{data}} {% endfor %} But result output in template html will be [u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT'] I need something like RASH ERYTHEMATOUS, PAIN ,FEELING HOT ..... Edited: Further details I get some data from API. I convert API json to json.loads(data) and save it in models.py Now in API a particular sub set is saved in models.py as [u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT'] because json.loads() converts json data to python readable format. I have saved it in models.py I can retrieve this data in template but its coming as [u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT'] Now I cannot display it by removing [u' Update: Nothing worked. Tried following code and it did the magic. def reactiondata(self): return self.reactions.replace("[",'').replace("u",'').replace("'",'').replace(']','').split(',')
score: 2
has title: Django-Python list saved in DB how to access in template?
tagged with: django-templates
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50080574
type: Question
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/50089293
has comment: http://stackoverflow.com/comment/87195411
downvote count: 0
accepted answer: http://stackoverflow.com/a/50089483
has comment: http://stackoverflow.com/comment/87194797
upvote count: 1
score: 1
has body: Hey i have troubles with my code, my entry isn't displayed, there is an error in my code but i don't see where. If someone can display the big frame on top and the entry on the bottom just tell me how :) from tkinter import * root = Tk() root['bg']='white' root.title('Next Note') root.minsize(800, 500) root.maxsize(800,500) frame = Frame(root, bg='light blue', height=300, width = 780 ) frame.grid(row=1, column=1, padx=10, pady=30) frame.grid_propagate(0) text = StringVar() text_entry = Entry(root, textvariable=text, bg='white', border=1, width = 100) text_entry.grid(row=2, column=2, padx=50, pady=750,) text_entry.grid_propagate(0) root.mainloop()
has answer: http://stackoverflow.com/a/50089483
has comment: http://stackoverflow.com/comment/87195044
favorite count: 0
has comment: http://stackoverflow.com/comment/87194734
tagged with: tkinter
has title: Python - Tkinter My Entry isn't displayed
type: Question
has comment: http://stackoverflow.com/comment/87194908
has comment: http://stackoverflow.com/comment/87195548
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/87194689
has comment: http://stackoverflow.com/comment/87195261
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87194558
has comment: http://stackoverflow.com/comment/87194990
has comment: http://stackoverflow.com/comment/87194819

http://stackoverflow.com/a/50146282
has body: import re my_string='I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny' match = lambda x: True if len(re.split('(Destiny){1}', x)) == 3 else False repl = lambda x: str.replace(x,'Destiny','TAG:{Destiny:Destiny}') if match(x) else x l =re.split(r'({.*?})',my_string) replaced=[repl(i) for i in l] print(''.join(replaced)) output I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny:Destiny}
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50145412

http://stackoverflow.com/comment/87309686
has text: I think it just looks up num in its namespace and finds the class variable
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50145679
type: Comment

http://stackoverflow.com/q/50155284
has answer: http://stackoverflow.com/a/50155696
answer count: 4
downvote count: 2
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50157029
favorite count: 0
type: Question
has body: So the program should take a number and then should print this number using text. print("Enter your number") Number = int(input()) def number_to_text_ones(ones): if ones == 1: print("one") elif ones == 2: print("two") elif ones == 3: print("three") elif ones == 4: print("four") elif ones == 5: print("five") elif ones == 6: print("six") elif ones == 7: print("seven") elif ones == 8: print("eight") elif ones == 9: print("nine") def number_to_text_tens(tens): if tens == 2: print("twenty ") elif tens == 3: print("thirty ") elif tens == 4: print("fourry ") elif tens == 5: print("fifty ") elif tens == 6: print("sixty ") elif tens == 7: print("seventy ") elif tens == 8: print("eighty ") elif tens == 9: print("ninety ") def number_to_text_hundreds(hundreds): if hundreds == 1: print("one hundred") elif hundreds == 2: print("two hundreds") elif hundreds == 3: print("three hundreds") elif hundreds == 4: print("four hundreds") elif hundreds == 5: print("five hundreds") elif hundreds == 6: print("six hundreds") elif hundreds == 7: print("seven hundreds") elif hundreds == 8: print("eight hundreds") elif hundreds == 9: print("nine hundreds") if Number == 0: print("zero") elif Number == 10: print("ten") elif Number == 11: print("eleven") elif Number == 12: print("twelve") elif Number == 13: print("thirteen") elif Number == 14: print("fourteen") elif Number == 15: print("fifteen") elif Number == 16: print("sixteen") elif Number == 17: print("seventeen") elif Number == 18: print("eighteen") elif Number == 19: print("nineteen") if Number &lt; 10: Result = Number % 10 number_to_text_ones(Result) elif (Number &gt;= 20 and Number &lt; 100): First = Number // 10 Second = (Number - (First * 10)) % 10 Result = First * 10 + Second number_to_text_tens(First) number_to_text_ones(Second) elif (Number &gt;= 100 and Number &lt; 1000): First = Number // 100 Second = (Number - (First * 100)) // 10 Third = (Number - (First * 100) - (Second * 10)) % 10 Result = First * 100 + Second * 10 + Third numbe…
has answer: http://stackoverflow.com/a/50155556
has answer: http://stackoverflow.com/a/50155361
has comment: http://stackoverflow.com/comment/87328344
linked to: http://stackoverflow.com/q/60208
tagged with: python
score: -1
has title: How to have 2 outputs from 2 different functions in one line?

http://stackoverflow.com/q/50189486
downvote count: 2
answer count: 1
tagged with: javascript
tagged with: python
tagged with: jquery
tagged with: python-requests
tagged with: flask
has answer: http://stackoverflow.com/a/50191586
has comment: http://stackoverflow.com/comment/87396180
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87396320
has body: This is my java script for connecting flask using ajax but it is showing 404 error.I don't understand where I am getting wrong The flask script to connecting above java script.I am not able to connect use the flask json result into java script.It is not able to connect,I guess problem with fetching of data from flask # webapp app = Flask(__name__, template_folder='./') @app.route('/') def index(): return render_template('index.html') @app.route('/prediction', methods=['POST', 'GET']) def prediction(): if request.form != None and 'message' in request.form: msg = request.form['message'] response = pred(str(msg)) return jsonify(response) else: # Through chatbot #msg = request.args.get(['message']) response = pred(str(request.get_json['message'])) return jsonify(response) if __name__ == '__main__': app.debug = True app.run()
has title: Update flask without refresh
upvote count: 0
type: UnansweredQuestion
score: -2

sparse-matrix
tags question: http://stackoverflow.com/q/50196129
tag name: sparse-matrix
tags question: http://stackoverflow.com/q/50114617
type: Tag
tags question: http://stackoverflow.com/q/50224636
tags question: http://stackoverflow.com/q/50162257
tags question: http://stackoverflow.com/q/50190718
tags question: http://stackoverflow.com/q/50107592

http://stackoverflow.com/a/51070284
answers question: http://stackoverflow.com/q/50195331
type: Answer
has body: This is expected behaviour. matplotlib won't accept unknown keyword arguments. Making my_fake_kwarg an explicit keyword argument won't fix things. With def valid_mpl(my_fake_kwarg=None, **kwargs): do_something_with(my_fake_kwarg) fig, ax = plt.subplots() ax.plot([1,2,3], [-3, -2, -1], **kwargs) return fig, ax valid_mpl(my_fake_kwarg=True) still results in kwargs = {'my_fake_kwarg': True}. You could remove it from kwargs after you're done with it. def valid_mpl(**kwargs): fig, ax = plt.subplots() if 'my_fake_kwarg' in kwargs: del kwargs['my_fake_kwarg'] ax.plot([1,2,3], [-3, -2, -1], **kwargs) return fig, ax Or create a new dictionary to unpack into ax.plot. def valid_mpl(**kwargs): fig, ax = plt.subplots() fake_kwargs = ['my_fake_kwarg'] plot_kwargs = {k: v for k, v in kwargs.items() if k not in fake_kwargs} ax.plot([1,2,3], [-3, -2, -1], **plot_kwargs) return fig, ax
accepted answer of: http://stackoverflow.com/q/50195331
has comment: http://stackoverflow.com/comment/89982355
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/87462172
has text: @SAndrew What I think happens is that you create a connection in the very beginning and if it is inactive for >60sec the server cuts it off. If you query every 5 min it's ok to create a new connection every time, so yes, moving creation of `Elasticsearch` object (and hence the connection) inside the loop should solve your problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50213782
score: 0

http://stackoverflow.com/a/50075327
has comment: http://stackoverflow.com/comment/87187138
answers question: http://stackoverflow.com/q/50075291
score: 1
downvote count: 0
type: Answer
upvote count: 1
has body: Because you didn't indent your code correctly. It should look probably like this: for i in range(0,5): if i==0 : b=b.append(1) else: result=(b[i-1]+1) b.append(result) return(result) where the body of the for loop is indented, and so do the bodies of the if and else statements, relatively to their respected statements.

http://stackoverflow.com/comment/87319339
comment on: http://stackoverflow.com/q/50150722
type: QuestionComment
has text: Try removing the margins? `ax.margins(0,0)`
score: 0
type: Comment

http://stackoverflow.com/a/50116516
upvote count: 4
has comment: http://stackoverflow.com/comment/87260413
downvote count: 0
answers question: http://stackoverflow.com/q/50105860
has body: I agree with cdlane that it would be better to avoid Tkinter-level event binding where possible, but I thought it might also be interesting to approach the problem without altering the overall design much. My solution only requires an additional import: from collections import deque And a new version of movearound: pending = deque() def movearound(event): x = event.x y = event.y pending.append((x,y)) if len(pending) == 1: while pending: x,y = pending[0] turtle.goto(x,y) pending.popleft() As I indicated in my comments, goto can call movearound if the window's event queue is backed up, and this can cause a stack overflow or race conditions that make the turtle move in unusual ways. This approach aims to prevent arbitrarily deep recursion, by only letting the topmost instance of movearound call goto. if len(pending) == 1: should only succeed for nonrecursive calls; all recursive calls will see a queue larger than that. The while pending: loop works through all the built-up events, handling them in the order they arrived. The result: a turtle that dutifully follows the path of the cursor, albeit at its own turtley pace:
type: Answer
score: 4

http://stackoverflow.com/q/50141696
tagged with: kaggle
tagged with: python
has body: I am currently building a DNN for the Titanic Dataset classification. During that process, I get the following error: InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [1,5] and labels shape [5] My code can be found here: https://github.com/isaac-altair/Titanic-Dataset/blob/master/Titanic%2BProject.ipynb I tried reshaping logits using the np.reshape(logits, (-1, 1)), but it would not work. Thanks
score: 0
answer count: 0
has title: Titanic Dataset. Logits and Labels of different shape error
has comment: http://stackoverflow.com/comment/87303375
has comment: http://stackoverflow.com/comment/87304991
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/87303609
has comment: http://stackoverflow.com/comment/87305200
type: UnansweredQuestion

http://stackoverflow.com/q/50137024
type: AnsweredQuestion
has body: I have a DataFrame stats with a Multindex and 8 samples (only two shown here) and 8 genes for each sample. In[13]:stats Out[13]: ARG/16S \ count mean std min sample gene Arnhem IC 11.0 2.319050e-03 7.396130e-04 1.503150e-03 Int1 11.0 7.243040e+00 6.848327e+00 1.364879e+00 Sul1 11.0 3.968956e-03 9.186019e-04 2.499074e-03 TetB 2.0 1.154748e-01 1.627663e-01 3.816936e-04 TetM 4.0 1.083125e-04 5.185259e-05 5.189226e-05 blaOXA 4.0 4.210963e-06 3.783235e-07 3.843571e-06 ermB 4.0 4.111081e-05 7.894879e-06 3.288865e-05 ermF 4.0 2.335210e-05 4.519758e-06 1.832037e-05 Basel Aph3a 4.0 7.815592e-06 1.757242e-06 5.539389e-06 IC 11.0 5.095161e-03 5.639278e-03 1.302205e-03 Int1 12.0 1.333068e+01 1.872207e+01 4.988048e-02 Sul1 11.0 1.618617e-02 1.988817e-02 2.970397e-03 I'm trying to calculate the p-value (Students t-test) for each of these samples, comparing each of the genes between them. I've used scipy.stats.ttest_ind_from_stats but I managed to get the p-values for the different samples for one gene and only those of the samples neighboring each other. Experiments = list(values1_16S['sample'].unique()) for exp in Experiments: if Experiments.index(exp)&lt;len(Experiments)-1: second = Experiments[Experiments.index(exp)+1] else: second = Experiments[0] tstat, pvalue = scipy.stats.ttest_ind_from_stats(stats.loc[(exp,'Sul1')]['ARG/16S','mean'], stats.loc[(exp,'Sul1')]['ARG/16S','std'], stats.loc[(exp,'Sul1')]['ARG/16S','count'], stats.loc[(second,'Sul1')]['ARG/16S','mean'], stats.loc[(second,'Sul1')]['ARG/16S','std'], stats.loc[(second,'Sul1')]['ARG/16S','count']) d.append({'loc1':exp, 'loc2':second, 'pvalue':pvalue}) stats_Sul1 = pd.DataFrame(d) stats_Sul1 How can I get the pvalues between ALL samples? And is there a way to do this for all genes at once without running the code one by one for each gene?
accepted answer: http://stackoverflow.com/a/50143281
has comment: http://stackoverflow.com/comment/87318922
tagged with: pandas
has answer: http://stackoverflow.com/a/50143281
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87331711
upvote count: 6
tagged with: scipy
has title: Calculate pvalue from pandas DataFrame
type: Question
has comment: http://stackoverflow.com/comment/87301387
answer count: 1
score: 6
downvote count: 0
favorite count: 0
tagged with: statistics

http://stackoverflow.com/comment/87168540
score: 0
type: AnswerComment
has text: thank you for your answer.I have a question, how can I connect input button & done method?
comment on: http://stackoverflow.com/a/50076052
type: Comment

http://stackoverflow.com/comment/87344740
comment on: http://stackoverflow.com/q/50163192
type: QuestionComment
score: 1
has text: Mmmm, how indicative is the image of the images you have to process? Is it actually the pattern or the colour you want to remove? I mean if someone produces some code that removes yellow pixels are you going to say *"Oh sometimes the grid is red, but it's always a grid"*. Can you clarify if the colours may be different? Or the pattern may be different? What I mean is, can I leverage the colour? Why not just make solid green image anyway? I feel you are not telling us the whole story here...
type: Comment

http://stackoverflow.com/a/50162628
answers question: http://stackoverflow.com/q/50155925
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87365567
has comment: http://stackoverflow.com/comment/87354817
upvote count: 4
has body: You can use pandas categorical to create the dummy variables, or, simpler, use the formula interface where patsy transforms all non-numeric columns to the dummy variables, or other factor encoding. Using the formula interface in this case (same as lower case ols in statsmodels.formula.api) shows the result below. Patsy sorts levels of the categorical variable alphabetically. 'Friday' is missing in the list of variables and has been selected as reference category. &gt;&gt;&gt; res = sm.OLS.from_formula('A ~ B + weekday', df).fit() &gt;&gt;&gt; print(res.summary()) OLS Regression Results ============================================================================== Dep. Variable: A R-squared: 0.301 Model: OLS Adj. R-squared: 0.029 Method: Least Squares F-statistic: 1.105 Date: Thu, 03 May 2018 Prob (F-statistic): 0.401 Time: 15:26:02 Log-Likelihood: -97.898 No. Observations: 26 AIC: 211.8 Df Residuals: 18 BIC: 221.9 Df Model: 7 Covariance Type: nonrobust ======================================================================================== coef std err t P&gt;|t| [0.025 0.975] ---------------------------------------------------------------------------------------- Intercept -1.4717 19.343 -0.076 0.940 -42.110 39.167 weekday[T.Monday] 2.5837 9.857 0.262 0.796 -18.124 23.291 weekday[T.Saturday] -6.5889 9.599 -0.686 0.501 -26.755 13.577 weekday[T.Sunday] 9.2287 9.616 0.960 0.350 -10.975 29.432 weekday[T.Thursday] -1.7610 10.321 -0.171 0.866 -23.445 19.923 weekday[T.Tuesday] 2.6507 9.664 0.274 0.787 -17.652 22.953 weekday[T.Wendesday] -6.9320 9.911 -0.699 0.493 -27.754 13.890 B 0.4047 0.258 1.566 0.135 -0.138 0.948 ============================================================================== Omnibus: 1.039 Durbin-Watson: 2.313 Prob(Omnibus): 0.595 Jarque-Bera (JB): 0.532 Skew: -0.350 Prob(JB): 0.766 Kurtosis: 3.007 Cond. No. 638. ============================================================================== Warnings: [1] Standard Errors assume that the covariance matri…
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50155925
score: 4

http://stackoverflow.com/q/50170321
score: 1
has comment: http://stackoverflow.com/comment/87358698
has comment: http://stackoverflow.com/comment/87358389
favorite count: 0
has comment: http://stackoverflow.com/comment/87358665
type: Question
has comment: http://stackoverflow.com/comment/87358849
tagged with: tkinter
answer count: 0
has title: tkinter how to attach scrollbar to listbox using place?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87358833
downvote count: 0
has body: hi i want to attach scrollbar to listbox using place but it does not show up in the program my code: txt = Listbox(root, width = 60, height = 25,bd = 0, relief = SUNKEN) lb2 = Listbox(root, width = 15, height = 25,bd=0) txt.place(relx=0.4, rely=0.45, width = 360, height = 400, anchor=CENTER) lb2.place(relx=0.87, rely=0.45,anchor=CENTER ) scrollbar = Scrollbar(frame, orient="vertical") scrollbar.config(command=txt.yview) scrollbar.place(x=400,rely=0.45, width=10, height = 100, anchor = "center") txt.config(yscrollcommand=scrollbar.set) if i run the program, i can't see the scrollbar. Edited : sorry here's my full code from tkinter import * root = Tk() root.geometry("500x600") frame = Frame(root) frame.pack() #l1 = Label(root, text="Enter Message ") l2 = Label(root, text="Enter Your Name ",font=("squarefont", 25)) ent = Entry(root, state='disabled',bd=1,borderwidth = 0,highlightthickness=0) ent1 = Entry(root, borderwidth = 0,highlightthickness=0) btn = Button(root, text="send",state='disabled',font=(None, 25),borderwidth = 0,highlightthickness=0) btn1 = Button(root, text="Ok",borderwidth = 0,highlightthickness=0,font=(None, 15)) txt = Listbox(root, width = 60, height = 25,bd = 0, relief = SUNKEN) lb2 = Listbox(root, width = 15, height = 25,bd=0) txt.place(relx=0.4, rely=0.45, width = 360, height = 400, anchor=CENTER) lb2.place(relx=0.87, rely=0.45,anchor=CENTER ) scrollbar = Scrollbar(frame, orient="vertical") scrollbar.config(command=txt.yview) scrollbar.place(x=400,rely=0.45, width=10, height = 100, anchor = "center") txt.config(yscrollcommand=scrollbar.set) btn.place(relx = 0.87, rely =0.87, width = 90, height = 90, anchor=CENTER) ent.place(relx=0.4, rely =0.87, width = 360, height = 90, anchor=CENTER) btn1.place(relx =0.9, rely =0.08, anchor="center") l2.place(relx =0.6, rely =0.08, anchor="e") ent1.place(relx =0.6, rely =0.08, height = 30, anchor="w") ent1.focus_set() root.title("Messenger") root.mainloop()
upvote count: 1
has comment: http://stackoverflow.com/comment/87358380
tagged with: python
has comment: http://stackoverflow.com/comment/87358039
has comment: http://stackoverflow.com/comment/87358885
has comment: http://stackoverflow.com/comment/87358529
has comment: http://stackoverflow.com/comment/87366940
has comment: http://stackoverflow.com/comment/87358577

http://stackoverflow.com/q/50148951
has answer: http://stackoverflow.com/a/50149056
score: 0
answer count: 2
has title: How to skip the Index
has comment: http://stackoverflow.com/comment/87315974
has answer: http://stackoverflow.com/a/50149054
has comment: http://stackoverflow.com/comment/87317705
type: Question
tagged with: python
type: UnansweredQuestion
has body: #main program while True: ReadValue = Func03Modbus(1,70,40);#slave,start,number of registers x3 = struct.pack('&gt;HH',abs(ReadValue[3]),abs(ReadValue[2])) pressure = struct.unpack('&gt;f', x3) print pressure[0] c3 = struct.pack('&gt;HH',abs(ReadValue[5]),abs(ReadValue[4])) purity = struct.unpack('&gt;f', c3) print purity[0] hrs = int(ReadValue[30]) mins= int(ReadValue[31]) timein =float(str(ReadValue[30])+"."+str(ReadValue[31])) print timein r=requests.get("http://api.thingspeak.com/update api_key=5RMT************&amp;field4="+str(pressure[0])+"&amp;field5="+str(purity[0])+"&amp;field1="+str(ReadValue[i])+"&amp;field2="+str(mins)+"&amp;field3="+str(timein))) print str(ReadValue[30]) time.sleep(15) While running the above program it stops running with returning following error: Traceback (most recent call last): File "/home/pi/v1.py", line 123, in x3 = struct.pack('>HH',abs(ReadValue[3]),abs(ReadValue[2])); IndexError: tuple index out of range I want my program to run continuously even when it returns error. I want to skip the error and to run the program continuously. How can I do that ?

http://stackoverflow.com/q/50154897
type: Question
has body: I have a code which lists out all the tcp connections: import psutil for connection in (psutil.net_connections(kind='tcp')): print connection[5] However, I need to list out the freshly added as well. I would, then, run the script which would run the code in the while(1) loop and keep on checking the new connections.
tagged with: python
tagged with: psutil
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50155351
score: 0
has answer: http://stackoverflow.com/a/50155351
answer count: 1
has title: How do I list out the new TCP connections using Python?

http://stackoverflow.com/comment/87428612
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50205755
has text: I see, so if I did not include the beginning ^ and end $, the "do not include operator [^]" would not count the string regardless of where the : and / are, not only at the end?
score: 0

http://stackoverflow.com/a/50090882
score: 0
answers question: http://stackoverflow.com/q/50090810
type: Answer
has body: You'll want to learn about the Python file handling API. This is useful in all kinds of contexts, even for things that aren't strictly files. It's also good to know because it maps pretty directly to *nix's actual file handling operations, which will be useful in C and many other languages as well: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files If you want to store each user's password in a separate file, you can always just open it "w" (write mode), but if you want to be able to store them all in one file, you'll need to learn about how to search through and change particular lines, etc. Essentially, you'll be implementing your own file-backed database API. Sounds like a great learning project!

http://stackoverflow.com/q/50202606
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87422053
tagged with: selenium-webdriver
downvote count: 2
has comment: http://stackoverflow.com/comment/87422212
has comment: http://stackoverflow.com/comment/87422088
has body: My problem is that I am trying to get the text of the element, which fills up with HTML content dynamically. Here is HTML source code. The last div: Fills with HTML code when the mouse enters the first div: How can I get the text of this element using Selenium WebDriver?
upvote count: 1
answer count: 1
tagged with: selenium
favorite count: 0
type: Question
tagged with: python-3.x
has title: Locate text which loads dynamically Python Selenium WebDriver
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/50202738

http://stackoverflow.com/q/50091272
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50091497
has answer: http://stackoverflow.com/a/50091497
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50091511
has title: python pandas read_excel: sep parameter available?
has answer: http://stackoverflow.com/a/50091511
score: 6
tagged with: python
upvote count: 6
has body: I'm trying to read a .xlsx into a pandas dataframe using pd.read_excel("C:/..."). The problem is I only get one column which include all the data seperated by ",". |---| "Country","Year","Export" | |---|---------------------------| | 0 | Canada,2017,3002 | | 1 | Bulgaria,2016,3960 | | 2 | Germany,2015,3818 | But this is not the format that I want... I'd like to get three columns like the table below. |---| "Country" | "Year" | "Export" | |---|--------------|----------| -----------| |1 | Canada | 2017 | 3002 | |2 | Bulgaria | 2016 | 3960 | |3 | Germany | 2015 | 3818 | So i am looking for the sep=',' or delimiter=',' parameter as contained in pd.read_csv. I allready worked through the documentation of pandas.read_excel but have not found a parameter which handle this problem... Thanks!
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/87350340
comment on: http://stackoverflow.com/q/50165614
score: 0
type: Comment
type: QuestionComment
has text: what's device_id column? Doesn't look like your dataframe has it

http://stackoverflow.com/comment/87423805
score: 0
comment on: http://stackoverflow.com/q/50203321
has text: columns are showing and this precipitation column is also one of the column. But the issue is at the end. When i assign X=df[X_COLS].values, then this error is showing
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87261392
score: 0
type: Comment
type: AnswerComment
has text: How do you suggest re-organizing the dataframes?
comment on: http://stackoverflow.com/a/50120072

http://stackoverflow.com/q/50131596
has comment: http://stackoverflow.com/comment/87284388
has comment: http://stackoverflow.com/comment/87284562
answer count: 0
has comment: http://stackoverflow.com/comment/87282414
has body: I am trying to work with two huge lists using the multiprocessing module of python.To share the data between these processes a manager.dict() object. Here is a code snippet. def my_function(item, list_two, return_dict): for val in list_two: # Do some I/O operation and DB connect operations and # get modified values of variables item and val new_value = item + val return_dict[item] = new_value if __name__ == "__main__": procs = [] manager = multiprocessing.Manager() return_dict = manager.dict() list_one = [1, 2, 3, 5.....] # len(list_one) = 120 list_two = ['a', 'b', 'c', .......] # len(list_two) = 800 for item in list_one: proc = Process(target=my_function, args=(str(item), list_two, return_dict)) procs.append(proc) proc.start() for proc in procs: proc.join() print(return_dict) Now since I am using Process object it creates processes equal to the number of items in my list_one and joins them. I execute this program and meanwhile, I execute top command to see that there are about 80 users logged in. But as soon as the number of users increases say 125, the same program breaks saying that error: can't start new thread. multiprocessing.cpu_count() = 16 I even tried to break list_one into batches of 10 and execute for those batches. But unfortunately, it is processing the first batch only. It doesn't work on remaining batches. So, why is the program breaking, is it because it cannot create so many threads as there are more users or because it cannot perform these many I/O operations parallelly? Using Python Version - 2.6 EDIT: Posting Traceback Process SyncManager-1: Traceback (most recent call last): File "/usr/lib64/python2.6/multiprocessing/process.py", line 232, in _bootstrap self.run() File "/usr/lib64/python2.6/multiprocessing/process.py", line 88, in run self._target(*self._args, **self._kwargs) File "/usr/lib64/python2.6/multiprocessing/managers.py", line 525, in _run_server server.serve_forever() File "/usr/lib64/python2.6/multiprocessing/managers.py", line 158,…
has comment: http://stackoverflow.com/comment/87435685
has comment: http://stackoverflow.com/comment/87284046
has comment: http://stackoverflow.com/comment/87284187
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/87283861
has comment: http://stackoverflow.com/comment/87284363
has comment: http://stackoverflow.com/comment/87282660
has comment: http://stackoverflow.com/comment/87435568
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/87282514
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87282693
tagged with: python
has comment: http://stackoverflow.com/comment/87439425
has comment: http://stackoverflow.com/comment/87283915
has title: Can not create new thread using python multiprocessing module
score: 0

http://stackoverflow.com/comment/87446540
score: 0
comment on: http://stackoverflow.com/q/50214155
type: Comment
type: QuestionComment
has text: @swenzel thank you a lot, that works for me :)

conv-neural-network
tags question: http://stackoverflow.com/q/50140155
tags question: http://stackoverflow.com/q/50178499
tags question: http://stackoverflow.com/q/50093581
tags question: http://stackoverflow.com/q/50081333
tags question: http://stackoverflow.com/q/50186035
tags question: http://stackoverflow.com/q/50079585
tags question: http://stackoverflow.com/q/50174656
tags question: http://stackoverflow.com/q/50133649
tags question: http://stackoverflow.com/q/50105143
tags question: http://stackoverflow.com/q/50209452
tags question: http://stackoverflow.com/q/50209661
tags question: http://stackoverflow.com/q/50182263
type: Tag
tags question: http://stackoverflow.com/q/50201024
tags question: http://stackoverflow.com/q/50190571
tags question: http://stackoverflow.com/q/50109629
tags question: http://stackoverflow.com/q/50141766
tags question: http://stackoverflow.com/q/50109718
tags question: http://stackoverflow.com/q/50149446
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/50144597
tags question: http://stackoverflow.com/q/50156010

http://stackoverflow.com/comment/87172991
type: QuestionComment
score: 0
has text: And you're on Windows and didn't generate this file yourself (deliberately making some assumptions)?
comment on: http://stackoverflow.com/q/50078374
type: Comment

selenium
tags question: http://stackoverflow.com/q/50155658
tags question: http://stackoverflow.com/q/50223735
tags question: http://stackoverflow.com/q/50218124
tags question: http://stackoverflow.com/q/50123527
tags question: http://stackoverflow.com/q/50074995
tags question: http://stackoverflow.com/q/50113359
tags question: http://stackoverflow.com/q/50172324
tags question: http://stackoverflow.com/q/50204841
tags question: http://stackoverflow.com/q/50128136
tags question: http://stackoverflow.com/q/50185236
tags question: http://stackoverflow.com/q/50209580
tags question: http://stackoverflow.com/q/50206758
tags question: http://stackoverflow.com/q/50134380
tags question: http://stackoverflow.com/q/50136361
tags question: http://stackoverflow.com/q/50220166
tags question: http://stackoverflow.com/q/50115238
tags question: http://stackoverflow.com/q/50080859
tags question: http://stackoverflow.com/q/50130778
tags question: http://stackoverflow.com/q/50107183
tags question: http://stackoverflow.com/q/50168663
tags question: http://stackoverflow.com/q/50082612
tags question: http://stackoverflow.com/q/50117377
tags question: http://stackoverflow.com/q/50132755
tags question: http://stackoverflow.com/q/50188930
tags question: http://stackoverflow.com/q/50154940
tags question: http://stackoverflow.com/q/50155780
tags question: http://stackoverflow.com/q/50102792
tags question: http://stackoverflow.com/q/50096474
tags question: http://stackoverflow.com/q/50114703
tags question: http://stackoverflow.com/q/50209216
tags question: http://stackoverflow.com/q/50200308
tags question: http://stackoverflow.com/q/50143413
tags question: http://stackoverflow.com/q/50193478
tags question: http://stackoverflow.com/q/50132257
tags question: http://stackoverflow.com/q/50195971
tags question: http://stackoverflow.com/q/50202606
tags question: http://stackoverflow.com/q/50087048
tags question: http://stackoverflow.com/q/50151189
tags question: http://stackoverflow.com/q/50162457
tags question: http://stackoverflow.com/q/50124877
type: Tag
tags question: http://stackoverflow.com/q/50139506
tags question: http://stackoverflow.com/q/50205073
tags question: http://stackoverflow.com/q/50093119
tags question: http://stackoverflow.com/q/50091420
tags question: http://stackoverflow.com/q/50149422
tags question: http://stackoverflow.com/q/50155229
tags question: http://stackoverflow.com/q/50162027
tag name: selenium
tags question: http://stackoverflow.com/q/50145236
tags question: http://stackoverflow.com/q/50111457
tags question: http://stackoverflow.com/q/50186398
tags question: http://stackoverflow.com/q/50111282
tags question: http://stackoverflow.com/q/50181286
tags question: http://stackoverflow.com/q/50184850
tags question: http://stackoverflow.com/q/50166782
tags question: http://stackoverflow.com/q/50096393
tags question: http://stackoverflow.com/q/50184692
tags question: http://stackoverflow.com/q/50135960
tags question: http://stackoverflow.com/q/50081520
tags question: http://stackoverflow.com/q/50113232
tags question: http://stackoverflow.com/q/50093985

http://stackoverflow.com/comment/87303375
score: 1
type: Comment
type: QuestionComment
has text: Fixed the error by writing "logits = tf.reshape(logits, [-1, 1])". I will post more if I have anymore errors.
comment on: http://stackoverflow.com/q/50141696

http://stackoverflow.com/comment/87370127
has text: Why not read each file with `json.load()` and use the result to extend an initialy empty array? (provided they contain *correct* JSON...)
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50176471

http://stackoverflow.com/comment/87301450
type: Comment
has text: Consider: What would happen if someone entered invalid input? What would your program do? It would print a message, set the `no` or `file` variable to `None`, and continue to execute. Is that correct error handling?
type: QuestionComment
comment on: http://stackoverflow.com/q/50141558
score: 1

http://stackoverflow.com/q/50178954
answer count: 1
favorite count: 0
tagged with: swig
score: 1
has comment: http://stackoverflow.com/comment/99882421
tagged with: python
has comment: http://stackoverflow.com/comment/99883842
has title: SWIG: Passing a std::vector< std::vector <double> > pointer to python
has answer: http://stackoverflow.com/a/50179025
tagged with: c++
type: Question
has body: I'm using SWIG to call a C++ program from python with three arguments. The last argument is also being used for the return value. analysis.i %module coverage %{ //#include "../SeqMCMC/src/funeval_base.hpp" #include "coverage.hpp" %} %include "std_vector.i" void coverage(std::vector&lt;double&gt; *Pypar, std::vector&lt;std::vector&lt;double&gt; &gt; *Pyxpass, std::vector&lt;std::vector&lt;double&gt; &gt; *Pyypass); coverage.hpp #ifndef _COVERAGE_ #define _COVERAGE_ #include&lt;vector&gt; void coverage(std::vector&lt;double&gt; *Pypar, std::vector&lt;std::vector&lt;double&gt;&gt; *Pyxpass, std::vector&lt;std::vector&lt;double&gt;&gt; *Pyypass); #endif coverage.cpp #include "isofuneval.hpp" #include "funeval_base.hpp" #include &lt;boost/numeric/ublas/vector.hpp&gt; #include &lt;boost/numeric/ublas/matrix.hpp&gt; void coverage (std::vector&lt;double&gt; *Pypar, std::vector&lt;std::vector&lt;double&gt;&gt; *Pyxpass, std::vector&lt;std::vector&lt;double&gt;&gt; *Pyypass){ //Convert the par, xpass and ypass vectors as ublas boost::numeric::ublas::vector&lt;double&gt; par((*Pypar).size()); boost::numeric::ublas::matrix&lt;double&gt; xpass((*Pyxpass).size(),(*Pyxpass)[0].size()); boost::numeric::ublas::matrix&lt;double&gt; ypass((*Pyypass).size(),(*Pyypass)[0].size()); for (size_t i = 0; i &lt; (*Pypar).size(); i++){ par(i) = (*Pypar)[i]; } for (size_t i = 0; i &lt; (*Pyxpass).size(); i++){ for (size_t j = 0; j &lt;(*Pyxpass)[0].size(); j++){ xpass(i,j) = (*Pyxpass)[i][j] ;} } for (size_t i = 0; i &lt; (*Pyypass).size(); i++){ for (size_t j = 0; j &lt;(*Pyypass)[0].size(); j++){ ypass(i,j) = (*Pyypass)[i][j];} } isofuneval CoveragePlot; CoveragePlot.function(par, xpass, ypass); //These should actually be references and or pointers if I expect ypass to have the result for (size_t i = 0; i &lt; (*Pyypass).size(); i++){ for (size_t j = 0; j &lt;(*Pyypass)[0].size(); j++){ (*Pyypass)[i][j] = ypass(i,j) ; } } } It compiles, and the module loads, but when I run it: import _coverag…
downvote count: 0
upvote count: 1
type: UnansweredQuestion

indexing
tags question: http://stackoverflow.com/q/50176262
tags question: http://stackoverflow.com/q/50182600
tags question: http://stackoverflow.com/q/50124679
tags question: http://stackoverflow.com/q/50184575
tags question: http://stackoverflow.com/q/50117750
tag name: indexing
tags question: http://stackoverflow.com/q/50119207
type: Tag
tags question: http://stackoverflow.com/q/50083493
tags question: http://stackoverflow.com/q/50157098
tags question: http://stackoverflow.com/q/50085411
tags question: http://stackoverflow.com/q/50206517
tags question: http://stackoverflow.com/q/50134181
tags question: http://stackoverflow.com/q/50180644
tags question: http://stackoverflow.com/q/50127658
tags question: http://stackoverflow.com/q/50133876
tags question: http://stackoverflow.com/q/50172078
tags question: http://stackoverflow.com/q/50194338
tags question: http://stackoverflow.com/q/50159175

http://stackoverflow.com/comment/87263630
type: Comment
type: QuestionComment
score: 0
has text: Why the dot after `session=tf.Session().` ?
comment on: http://stackoverflow.com/q/50122440

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/50202701
tags question: http://stackoverflow.com/q/50143660
type: Tag
tags question: http://stackoverflow.com/q/50202415
tags question: http://stackoverflow.com/q/50136563
tags question: http://stackoverflow.com/q/50107190
tags question: http://stackoverflow.com/q/50102423
tags question: http://stackoverflow.com/q/50187537
tags question: http://stackoverflow.com/q/50173419
tags question: http://stackoverflow.com/q/50176189
tags question: http://stackoverflow.com/q/50219084
tags question: http://stackoverflow.com/q/50111745
tags question: http://stackoverflow.com/q/50169308
tags question: http://stackoverflow.com/q/50126843
tags question: http://stackoverflow.com/q/50120247
tags question: http://stackoverflow.com/q/50120806
tags question: http://stackoverflow.com/q/50144359
tags question: http://stackoverflow.com/q/50129708
tags question: http://stackoverflow.com/q/50153319
tags question: http://stackoverflow.com/q/50088143
tags question: http://stackoverflow.com/q/50152210
tags question: http://stackoverflow.com/q/50139400
tags question: http://stackoverflow.com/q/50130605
tag name: csv
tags question: http://stackoverflow.com/q/50083806
tags question: http://stackoverflow.com/q/50196511
tags question: http://stackoverflow.com/q/50182797
tags question: http://stackoverflow.com/q/50122828
tags question: http://stackoverflow.com/q/50179852
tags question: http://stackoverflow.com/q/50118909
tags question: http://stackoverflow.com/q/50164511
tags question: http://stackoverflow.com/q/50179101
tags question: http://stackoverflow.com/q/50106226
tags question: http://stackoverflow.com/q/50117209
tags question: http://stackoverflow.com/q/50085655
tags question: http://stackoverflow.com/q/50205842
tags question: http://stackoverflow.com/q/50214084
tags question: http://stackoverflow.com/q/50165263
tags question: http://stackoverflow.com/q/50144570
tags question: http://stackoverflow.com/q/50107166
tags question: http://stackoverflow.com/q/50110549
tags question: http://stackoverflow.com/q/50091174
tags question: http://stackoverflow.com/q/50107263
tags question: http://stackoverflow.com/q/50103918
tags question: http://stackoverflow.com/q/50217771
tags question: http://stackoverflow.com/q/50181734
tags question: http://stackoverflow.com/q/50079133
tags question: http://stackoverflow.com/q/50109643
tags question: http://stackoverflow.com/q/50142569
tags question: http://stackoverflow.com/q/50202268
tags question: http://stackoverflow.com/q/50103582
tags question: http://stackoverflow.com/q/50084013
tags question: http://stackoverflow.com/q/50115896
tags question: http://stackoverflow.com/q/50172287
tags question: http://stackoverflow.com/q/50138353
tags question: http://stackoverflow.com/q/50152548
tags question: http://stackoverflow.com/q/50125055
tags question: http://stackoverflow.com/q/50210715
tags question: http://stackoverflow.com/q/50120877
tags question: http://stackoverflow.com/q/50090662
tags question: http://stackoverflow.com/q/50161002
tags question: http://stackoverflow.com/q/50216787
tags question: http://stackoverflow.com/q/50097521
tags question: http://stackoverflow.com/q/50113803
tags question: http://stackoverflow.com/q/50137671
tags question: http://stackoverflow.com/q/50104837
tags question: http://stackoverflow.com/q/50147510
tags question: http://stackoverflow.com/q/50222314
tags question: http://stackoverflow.com/q/50101543
tags question: http://stackoverflow.com/q/50091133
tags question: http://stackoverflow.com/q/50194521
tags question: http://stackoverflow.com/q/50151228
tags question: http://stackoverflow.com/q/50105687
tags question: http://stackoverflow.com/q/50086338
tags question: http://stackoverflow.com/q/50132352
tags question: http://stackoverflow.com/q/50226334
tags question: http://stackoverflow.com/q/50158920
tags question: http://stackoverflow.com/q/50166782
tags question: http://stackoverflow.com/q/50113009
tags question: http://stackoverflow.com/q/50091475

http://stackoverflow.com/a/50115795
type: Answer
has body: You can do this: web_stats['new_column'] = [2,4,6,8,10,12]
accepted answer of: http://stackoverflow.com/q/50115766
score: 1
answers question: http://stackoverflow.com/q/50115766
type: AcceptedAnswer
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/87362981
type: QuestionComment
has text: `existing_alpha_models.append('foo')`?
comment on: http://stackoverflow.com/q/50172358
type: Comment
score: 0

http://stackoverflow.com/q/50187032
has comment: http://stackoverflow.com/comment/87391937
tagged with: python
possible better answer: http://stackoverflow.com/a/50187316
has comment: http://stackoverflow.com/comment/87390779
answer count: 4
has answer: http://stackoverflow.com/a/50187415
upvote count: 2
has answer: http://stackoverflow.com/a/50187339
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50187339
has title: How do I quickly find the last number of elements matching some criterion in numpy?
has body: Suppose I have some array: x = numpy.array([1, 2, 3, 4, 5, 1, 1, 1]) And I want to find the number of consecutive 1s at the end of the array. One way to do this is with a loop: i = len(x) - 1 while x[i] == 1: i = i - 1 Now I can look at i and work out the number of 1s in the back of x. However, in my real-world example x can be very large, as can the number of 1s, so I want a solution that: Doesn't use loops, and Doesn't traverse the whole array
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50187316
favorite count: 0
has answer: http://stackoverflow.com/a/50187372
type: Question
tagged with: numpy

http://stackoverflow.com/q/50222730
has answer: http://stackoverflow.com/a/50223238
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/50223004
possible better answer: http://stackoverflow.com/a/50222986
has title: Building a dictionary from a three dimensional array with Python
tagged with: python
tagged with: sorting
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50222817
answer count: 4
has comment: http://stackoverflow.com/comment/87464061
type: AnsweredQuestion
tagged with: python-2.7
has body: I am currently having a problem to sort my 3d array data into different dictionaries based on the first column of the array. I want to check the first column of the array and make a dictionary with the names of the strings in it. I would also like to make a two dimensional array with the values on the same row. My data looks like like something like that: allValues=[["str1","str1","str1","str1","str1","str1","str1","str2","str2","str2","str2","str2"],[1,2,3,4,5,6,7,8,9,10,11,12],[1,2,3,4,5,6,7,8,9,10,11,12]] And my aim is: allValuesDict = {'str1': [[1,2,3,4,5,6,7], [1,2,3,4,5,6,7]], 'str2': [[8,9,10,11,12], [8,9,10,11,12]]}
score: 1
has comment: http://stackoverflow.com/comment/87481274
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50222986
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50222817

http://stackoverflow.com/q/50110350
tagged with: atom-editor
answer count: 2
has body: So, right now I beginning to look into AI programming and for that I will need to work heavily with Python. Atom is my go-to editor for all of my web-development projects and I was wondering if I can use it to save and run python projects as well.
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87238014
has comment: http://stackoverflow.com/comment/87238070
favorite count: 0
type: Question
has title: Can a Python program be run through Atom text-editor?
has answer: http://stackoverflow.com/a/50110444
has answer: http://stackoverflow.com/a/50110387
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87238122
upvote count: 1
tagged with: python

http://stackoverflow.com/q/50158796
type: AnsweredQuestion
score: 0
answer count: 1
has body: I am building a Django app that works with a text-heavy database, and it counts some predefined phrases within the text. It does not count the number of records that contain the phrases, but it counts the frequency within one record. And here is where i am stuck: Django does count and find phrases if i add the string directly: frequency = 'Search this text for me, please'.count('this text') When i use this logic with a model Manager, "count" does not work, and gives the error: Typeerror: count() takes 1 positional argument but 2 were given This is my code in model.py class MyModelManager(models.Manager): def get_queryset(self): qs = super(MyModelManager, self).get_queryset().values_list('mytext').count('this text') return qs class MyModel(models.Model): mytext = models.TextField() ... objects = MyModelManager() Can you please suggest me how should i continue? Am i on the right track or should i apply a totally different approach to make this working? Thanks!
type: Question
tagged with: django-managers
tagged with: word-count
tagged with: word-frequency
has answer: http://stackoverflow.com/a/50159093
accepted answer: http://stackoverflow.com/a/50159093
has title: Word frequency count within record with Django model Manager
tagged with: django
tagged with: python

http://stackoverflow.com/comment/87225266
type: AnswerComment
comment on: http://stackoverflow.com/a/50103981
type: Comment
has text: Could I ask what the difference between this pd.wide_to_long is and the one in the question I linked?
score: 0

http://stackoverflow.com/comment/87628115
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50189497
score: 0
has text: @BenjaVR I want is as csv only , Like I want to start from scratch , Not already one converted to pandas dataframe.

http://stackoverflow.com/q/50092647
has title: I deleted data from the dictionary and write dictionary's data to text file and got key error?
tagged with: dictionary
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87201878
has comment: http://stackoverflow.com/comment/87201537
has body: I have a text file which looks like this: myFiles.txt Dell 2015 A14523 Sam Sony 2014 A74256 John Acer 2018 A45656 Mark Sony 2007 S12345 James I want to delete the data when I give index as input so, I convert the text file into dictionary. By this way, I got indexes for my text file. But when I delete any data from the dictionary and write rest of data to text file a key error occur. Because when I delete data from the dictionary,indexes remains the same For example: I have created 4 rows with for different key i.e. 1,2,3 and 4 When I delete the data from index 2 then dictionary indexes remains unchanged, I left with 1,3 and 4 and when I rewrite the data to text file it will give key error. How can I delete data from text file. I am new to python.Help me to solve it def deleteFunction(self): ownerListDic = {} num = 1 with open("myFiles.txt", "r") as oy: for line in oy: li = line.strip().split() ownerListDic[num] = {"name": li[0], "purchase": li[ 1], "bluePlate": li[2], "owner": li[3]} num += 1 # enter the record id to delete from the text file indexId = int(input("Enter record ID: ")) if indexId in ownerListDic: # prompting to confirm the user you are going to delete # this data print(("You arev about to delete " + ''.join(ownerListDic[indexId]['name'] + " " + ownerListDic[indexId]['purchase'] + " " + ownerListDic[indexId]["bluePlate"] + " " + ownerListDic[indexId]['owner'])) + " .") # ask user to delete the data delete = input( "Do you wish to delete this record (Y/N): ").upper() # if yes then data will delete if delete == "Y": ownerListDic.pop(indexId, None) num=1 with open("myFiles.txt", 'w') as log: for dataValue in ownerListDic.values(): log.write(ownerListDic[num]['name'] + "\t" + ownerListDic[num]['purchase'] + "\t" + ownerListDic[num]["bluePlate"] + "\t" + ownerListDic[num]['owner'] + "\n") num += 1 # after deletion this message will print print("Record deleted.")
has comment: http://stackoverflow.com/comment/87201865
tagged with: python

http://stackoverflow.com/comment/87215663
type: Comment
comment on: http://stackoverflow.com/a/50090809
type: AnswerComment
has text: Please take a look into the migration guide, they have a detailed explanation. They have changed the types. Instead of python data types like torch.FloatTensor all pytorch tensors are now form type 'torch.Tensor'. Instead you should use now dtype, same as it is used in numpy. But take a look at the guide, if you have any questions left just ask :)
score: 1

http://stackoverflow.com/comment/87435628
type: QuestionComment
comment on: http://stackoverflow.com/q/50208954
has text: I experienced a similar problem, and it turned out that the problem was related to the email address used as "From:" to log server errors in production (by default it is `root@localhost`and it's set by the SERVER_EMAIL setting). Ref: https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-SERVER_EMAIL
score: 0
type: Comment

http://stackoverflow.com/comment/87426782
score: 2
has text: I don't understand what this answer has to do with this question.
type: Comment
comment on: http://stackoverflow.com/a/50202738
type: AnswerComment

http://stackoverflow.com/a/66885097
score: 0
has body: For anyone who did not get the exact label by following the above 2 answers Well I tried each of the above two answers, but it did not gave the exact label. So what I did was to copy and paste the whole code from https://github.com/tensorflow/models/blob/master/research/object_detection/utils/visualization_utils.py After copying all the code to my jupyter notebook, I changed some part of the original code. It was to return the detected label along with image array inside the visualize_boxes_and_labels_on_image_array() function So, part of the code for visualize_boxes_and_labels_on_image_array() function should look like this: def visualize_boxes_and_labels_on_image_array( image, boxes, classes, scores, category_index, instance_masks=None, instance_boundaries=None, keypoints=None, keypoint_scores=None, keypoint_edges=None, track_ids=None, use_normalized_coordinates=False, max_boxes_to_draw=20, min_score_thresh=.5, agnostic_mode=False, line_thickness=4, mask_alpha=.4, groundtruth_box_visualization_color='black', skip_boxes=False, skip_scores=False, skip_labels=False, skip_track_ids=False): """Overlay labeled boxes on an image with formatted scores and label names. This function groups boxes that correspond to the same location and creates a display string for each detection and overlays these on the image. Note that this function modifies the image in place, and returns that same image. Args: image: uint8 numpy array with shape (img_height, img_width, 3) boxes: a numpy array of shape [N, 4] classes: a numpy array of shape [N]. Note that class indices are 1-based, and match the keys in the label map. scores: a numpy array of shape [N] or None. If scores=None, then this function assumes that the boxes to be plotted are groundtruth boxes and plot all boxes as black with no classes or scores. category_index: a dict containing category dictionaries (each holding category index `id` and category name `name`) keyed by category indices. instance_masks: a uint8 numpy array of …
has comment: http://stackoverflow.com/comment/125421072
type: Answer
answers question: http://stackoverflow.com/q/50077353
has comment: http://stackoverflow.com/comment/125426379

http://stackoverflow.com/comment/87413778
has text: Some boundary cases I can imagine are 1) the real part is at the very end, the virtual part is at the beginning; 2) every odd element is real, every even element is virtual.
type: AnswerComment
comment on: http://stackoverflow.com/a/50198446
score: 0
type: Comment

http://stackoverflow.com/q/50154076
score: 0
answer count: 0
tagged with: sql
linked to: http://stackoverflow.com/q/7053652
has body: Trying to do this python code that generates random numbers to do addition and multiplication operations based on the user input. I need help on how to run each function only five times and then go back to the menu again. Thank you so much :(( Also, everytime the answer prints, it generates "None" below the line. How do I get rid of that? import random ## def of menu: options_menu function ## def options_menu(): print ("a &gt; Addition") print ("m &gt; Multiplication") print ("q &gt; Quit") ## end of options_menu function ## ## def of addition function ## def addition_option(): int_a = random.randint(1,100) int_b = random.randint(1,9) addition_operation = int(input (str(int_a) + " + " + str(int_b) + " = ")) addition_result = int_a + int_b if addition_operation == addition_result: print ("Correct") else: print ("Incorrect. The correct answer is " + str(addition_result)) ## end of addition function ## ## def of multiplication function ## def multiplication_option(): int_a = random.randint(1,100) int_b = random.randint(1,9) multiplication_operation = int(input (str(int_a) + " x " + str(int_b) + " = ")) multiplication_result = int_a * int_b if multiplication_operation == multiplication_result: print ("Correct") else: print ("Incorrect. The correct answer is " + str(multiplication_result)) ## end of multiplication function ## ## def of quit function ## def quit_option(): print ("Good bye!") return quit_option() ## end of quit function ## ##### MAIN PROGRAM #### #print the menu options_menu() user_choice = input("Enter command (a/m/q): ") while True: if user_choice == "a": print(addition_option()) elif user_choice == "m": print(multiplication_option()) elif user_choice == "q": print(quit_option())
has comment: http://stackoverflow.com/comment/87325672
duplicate of: http://stackoverflow.com/q/7053652
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87325688
tagged with: python
has title: For Loop Implementation + RandInt

http://stackoverflow.com/a/69407955
downvote count: 0
upvote count: 1
has body: Here is the Example Code: query = session.query(Region.name).all() query = map(lambda t: t[0], query) query = list(query) print(query)
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50154436

http://stackoverflow.com/q/50192897
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50193126
has body: class Score(pygame.Surface): pygame.font.Font.render(Text, antialias, color, Background) I am trying to make a code that will implement a Text file that gets on to my pygame surface. I want It to show up on the top right hand corner of the screen. My issue is that i have no understanding what the antialias does and what do I put on the antialias code spot. Do I put an Int or some sort of String. Here is more of the code to show just to give you an idea of what i'm going for. I hope this helps to get my answer. import pygame from pygame.locals import * from sys import exit class Ball(pygame.Surface): """ A bouncy ball """ x = 320 y = 0 speedx = 0 speedy = 250 def get_top(self): return self.y def get_bottom(self): return self.y + self.get_height() def get_left(self): return self.x def get_right(self): return self.x + self.get_width() def is_hit(self, paddle): if self.get_bottom() &gt;= paddle.get_top(): if self.get_right() &gt;= paddle.get_left(): if self.get_left() &lt;= paddle.get_right(): if self.get_top() &lt;= paddle.get_top(): self.speedy = self.speedy * -1 self.y = self.y - 3 if paddle.motion == "Left": self.speedx -= 20 if paddle.motion == "Right": self.speedx += 20 class Paddle(pygame.Surface): """ A Paddle """ x = 200 y = 260 motion = "None" def get_top(self): return self.y def get_bottom(self): return self.y + self.get_height() def get_left(self): return self.x def get_right(self): return self.x + self.get_width() class Score(pygame.Surface): pygame.font.Font.render("name.png", if __name__ == "__main__": pygame.init() infoObject = pygame.display.Info() screen_w = 640 screen_h = 480 screen = pygame.display.set_mode((screen_w, screen_h), 0, 32) clock = pygame.time.Clock() screencolor = (0,255,255) color = (255, 0, 0) color2 = (0,0,255) radius = 7 pos = (radius,radius) screen.fill(screencolor) wipe = pygame.Surface((screen_w,screen_h)) pygame.draw.rect(wipe, screencolor, pygame.Rect(0,0,screen_w,screen_h)) paddle = Paddle((70,10)) pygame.draw.rect(paddle, colo…
tagged with: pygame
tagged with: pygame-surface
tagged with: initialization
has comment: http://stackoverflow.com/comment/87403331
accepted answer: http://stackoverflow.com/a/50193104
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50193104
upvote count: 2
tagged with: fonts
has answer: http://stackoverflow.com/a/50193126
downvote count: 0
has title: What Does The antialias mean in this Font render code for pygame mean?

datetime
tags question: http://stackoverflow.com/q/50109695
tags question: http://stackoverflow.com/q/50082441
tags question: http://stackoverflow.com/q/50097741
tag name: datetime
tags question: http://stackoverflow.com/q/50191062
tags question: http://stackoverflow.com/q/50209102
tags question: http://stackoverflow.com/q/50117750
tags question: http://stackoverflow.com/q/50175035
tags question: http://stackoverflow.com/q/50176122
tags question: http://stackoverflow.com/q/50157773
tags question: http://stackoverflow.com/q/50188123
tags question: http://stackoverflow.com/q/50122268
tags question: http://stackoverflow.com/q/50182568
tags question: http://stackoverflow.com/q/50219969
tags question: http://stackoverflow.com/q/50225050
type: Tag
tags question: http://stackoverflow.com/q/50132941
tags question: http://stackoverflow.com/q/50092673
tags question: http://stackoverflow.com/q/50134463
tags question: http://stackoverflow.com/q/50177211
tags question: http://stackoverflow.com/q/50211016
tags question: http://stackoverflow.com/q/50133185
tags question: http://stackoverflow.com/q/50222042
tags question: http://stackoverflow.com/q/50201517
tags question: http://stackoverflow.com/q/50131744
tags question: http://stackoverflow.com/q/50101384
tags question: http://stackoverflow.com/q/50171434
tags question: http://stackoverflow.com/q/50096909
tags question: http://stackoverflow.com/q/50106363
tags question: http://stackoverflow.com/q/50164229
tags question: http://stackoverflow.com/q/50116971
tags question: http://stackoverflow.com/q/50188207
tags question: http://stackoverflow.com/q/50158588
tags question: http://stackoverflow.com/q/50160560
tags question: http://stackoverflow.com/q/50106651

http://stackoverflow.com/a/50159161
score: 0
has comment: http://stackoverflow.com/comment/87355312
answers question: http://stackoverflow.com/q/50158617
has comment: http://stackoverflow.com/comment/87355139
has body: This is your corrected code, i = 0 while i &lt; 7: i += 1 if i == 6: i = 0 It reaches 0 on reaching 6. Lot's of syntax Error fixed.
type: Answer
has comment: http://stackoverflow.com/comment/87339356

http://stackoverflow.com/comment/87360736
comment on: http://stackoverflow.com/q/50171619
score: 0
has text: Hi @Kevin "texoutput" does not appear in the python code. I think "tex" refers to LaTex I am using. The code works on another computer but I get this error message on new computer
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50281197
type: Answer
accepted answer of: http://stackoverflow.com/q/50177976
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50177976
score: 3
has body: The problems with your example are mostly caused by some poor naming in the QsciScintilla APIs. The foldLine and foldAll methods should really be called toggleFoldLine and toggleFoldAll, because they actually undo the previous state. This means, for instance, that if two successive lines have the same fold level, calling foldLine twice will result in no net changes. In the implementation below, I have used the more explicit Scintilla messages so that only the lines which really require folding are affected. I have also changed the keyboard shortcuts to match the defaults in SublimeText: class Foo(QsciScintilla): def __init__(self, parent=None): ... QShortcut(QKeySequence("Ctrl+K, Ctrl+J"), self, self.fold_by_level) QShortcut(QKeySequence("Ctrl+K, Ctrl+0"), self, self.fold_by_level) ... def fold_by_level(self, level=0): SCI = self.SendScintilla if level: level += 0x400 MASK = QsciScintilla.SC_FOLDLEVELNUMBERMASK for line in range(self.lines()): foldlevel = SCI(QsciScintilla.SCI_GETFOLDLEVEL, line) &amp; MASK print('line=%i, level=%i' % (line + 1, foldlevel), end='') if foldlevel == level: line = SCI(QsciScintilla.SCI_GETFOLDPARENT, line) if SCI(QsciScintilla.SCI_GETFOLDEXPANDED, line): print(', foldline:', line + 1, end='') SCI(QsciScintilla.SCI_FOLDLINE, line, QsciScintilla.SC_FOLDACTION_CONTRACT) print() else: SCI(QsciScintilla.SCI_FOLDALL, QsciScintilla.SC_FOLDACTION_EXPAND)
upvote count: 3

http://stackoverflow.com/q/50170020
type: Question
tagged with: python
tagged with: pytest-django
has body: I have VOUCHERED_PEOPLE in the base.py And I need to test it by dummy I have read this in order to get settings.VOUCHERED_PEOPLE being patched, but it does not work in Django2 utils.py from django.conf import settings def get_voucher_people(mobile_phone: str) -&gt; typing.Dict[str, typing.Union[str, int]]: """Read name from base.py""" for record in settings.VOUCHERED_PEOPLE: if record['mobile_phone'] == mobile_phone: return record return None base.py VOUCHERED_PEOPLE = [{...}, {...}] tests.py with patch('poinkbackend.apps.vouchers.utils.settings', VOUCHERED_PEOPLE=dummy): from pprint import pprint import ipdb; ipdb.set_trace() give_voucher(sarit.userprofile, True) Attempt1: with patch.object(settings, 'VOUCHERED_PEOPLE') as mock_settings: mock_settings.return_value = dummy This does not work. settings.VOUCHERED_PEOPLE is a function. I have to execute it to get dummy by settings.VOUCHERED_PEOPLE() Problem: patch does not work. It is not change value to be my dummy Question: Where am I wrong?
has title: patch django.conf settings does not mutate the value
tagged with: mocking
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50170271
tagged with: django
tagged with: patch
has answer: http://stackoverflow.com/a/50170271
answer count: 1

http://stackoverflow.com/q/50121192
tagged with: msys2
tagged with: windows
has body: When I run msys2.exe and launch a Python program, nothing gets printed to the terminal unless either enough text is printed such that the buffer automatically flushes, or if I run sys.stdout.flush(). In order to fix this, I have to launch msys2 with msys2_shell.cmd -defterm. Defterm works fine in all ways, except for that it's really ugly. So, I'm hoping that there's a way to fix the mintty terminal such that it does not buffer output from my programs.
tagged with: python
has comment: http://stackoverflow.com/comment/87266731
has title: How can I set up my msys2 terminal to not buffer output?
has comment: http://stackoverflow.com/comment/87266690
score: 2
tagged with: bash
answer count: 0
upvote count: 2
tagged with: mintty
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion

min
type: Tag
tags question: http://stackoverflow.com/q/50089508
tag name: min

http://stackoverflow.com/comment/87304058
score: 2
has text: The `with` statement is exception safe. Your alternate use is not.
comment on: http://stackoverflow.com/q/50142921
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50217722
favorite count: 0
has comment: http://stackoverflow.com/comment/87452480
has comment: http://stackoverflow.com/comment/87454575
has comment: http://stackoverflow.com/comment/87463020
has answer: http://stackoverflow.com/a/50217779
has comment: http://stackoverflow.com/comment/87452535
score: 0
type: Question
has comment: http://stackoverflow.com/comment/87452556
type: UnansweredQuestion
has title: Code skips IF statement and goes straight to ELSE statement
has comment: http://stackoverflow.com/comment/87455354
answer count: 1
has comment: http://stackoverflow.com/comment/87454987
has comment: http://stackoverflow.com/comment/87452381
has comment: http://stackoverflow.com/comment/87452488
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87454492
has comment: http://stackoverflow.com/comment/87452546
downvote count: 1
has comment: http://stackoverflow.com/comment/87452522
has body: //IF statment is completely skipped, but when i remove the ELSE statement, the IF statement works? if fname != '' and lname != '' and user != '' and rank != '' and password != '' and firenum != '' and phonenum != '' and phoneconfirm != '' and admin != '': if phonenum == phoneconfirm and len(phonenum) == int(10): get = AllPersonnel.query.filter_by(agencyid=current_user.agencyid).all() for i in get: if phonenum == i.phonenum: all = [] all.append({'error' : 'ERROR: Phone number already exists in database'}) return jsonify(all) else: pers = AllPersonnel(name.upper(), rank.upper(), firenum, phonenum, username, password, admin.upper(), agencyid, agencyname.upper(), availability, avtimestamp, enat, enattimestamp, taskavailbility, avtimetsamptask, plusdate) db.session.add(pers) db.session.commit() all = [] all.append({'success' : 'SUCCESS: FireFighter added to database!'}) return jsonify(all) This is my other code that works for my other program. phoneemp = EmsaEmp.query.all() for num in phoneemp: if phonenum == num.phonenum: allexist = ('ERROR: Phone Number Already Exists In Database. Please Use The Help Desk or Contact a Supervisor. Thanks') return render_template('register.html', allexist=allexist) else: print('Success') ans = '' name = (fname + ' ' + lname) emp = EmsaEmp(name.upper(), title.upper(), phonenum, ans) db.session.add(emp) db.session.commit() This is what i ended up doing and it works now. if phonenum == phoneconfirm and len(phonenum) == int(10): get = AllPersonnel.query.filter_by(agencyid=current_user.agencyid).all() for i in get: if phonenum == i.phonenum: all = [] all.append({'error' : 'ERROR: Phone number already exists in database'}) return jsonify(all) for u in get: if phonenum != i.phonenum: pers = AllPersonnel(name.upper(), rank.upper(), firenum, phonenum, username, password, admin.upper(), agencyid, agencyname.upper(), availability, avtimestamp, enat, enattimestamp, taskavailbility, avtimetsamptask, plusdate) db.session.add(pers) db.session.commit() …

http://stackoverflow.com/comment/87184680
type: QuestionComment
comment on: http://stackoverflow.com/q/50084497
has text: as it is clear , WHY there is so much timing difference.
score: 0
type: Comment

http://stackoverflow.com/comment/87284363
score: 0
has text: Running 120 subprocesses might not be optimal in terms of speed, but it shouldn't cause the error that's being described, so I think that's a bit of a red herring. Can try stripping your code back so it's essentially launching 120 subprocesses with the manager and passing the big list? And then start halving the list size to see if you can launch N subprocesses successfully. And then see if N > 0 or 1.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50131596

http://stackoverflow.com/a/53457860
score: 0
has body: I run into same error when setting up python, keras and anything between. Background: I installed anaconda and followed instructions by https://www.youtube.com/watch?v=z0qhKP2liHs and instruction to downgrade to python 3.6 by http://docs.anaconda.com/anaconda/user-guide/faq/#how-do-i-get-the-latest-anaconda-with-python-3-5 Running from Jupyter I run into same problem as author I was able to solve my problem by: - uploading pandas version for python 3.6 per https://docs.anaconda.com/anaconda/packages/py3.6_win-64/ then I run python from command line .. it worked then I tested with PyCharm .. it worked Appears that either Anaconda&amp;Jupyter combination did not work or selecting pandas version did the job.
type: Answer
answers question: http://stackoverflow.com/q/50089668

http://stackoverflow.com/comment/87432212
has text: Also , if there are multiple subdirectories with similar files matching the patterns ,the script is not able to iterate over them
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50172195
type: AnswerComment

http://stackoverflow.com/comment/87266717
type: QuestionComment
score: 0
type: Comment
has text: @Nathan Only colored grid squares in pairs of four.
comment on: http://stackoverflow.com/q/50124231

http://stackoverflow.com/q/50111591
has comment: http://stackoverflow.com/comment/87240548
tagged with: python
has title: Why is TypeError: __init__() takes 1 positional argument but 2 were given when running sql commands
answer count: 2
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87240854
has comment: http://stackoverflow.com/comment/87240820
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87241005
has answer: http://stackoverflow.com/a/66621983
downvote count: 0
tagged with: mysql
upvote count: 1
has answer: http://stackoverflow.com/a/57589711
has comment: http://stackoverflow.com/comment/87241180
favorite count: 0
type: Question
has body: import mysql.connector conn = mysql.connector.connect(host='localhost', user='root', password='root', database='nlidb') cur = conn.cursor() stmt = "create table statistics(sno int(5), stat_ticker varchar(10) primary key, marketcap varchar(10), enterprise_value varchar(10), return_on_assets varchar(10), total_cash varchar(10), operating_cash_flow varchar(10), levered_free_cash_flow varchar(10), total_debt varchar(10), current_ratio varchar(10), gross_profit varchar(10), profit_margin varchar(10))" cur.execute(stmt) I am trying to create a table in my database but it is giving me this error. Traceback (most recent call last): File "G:/python/NLIDB/nlidb/database.py", line 3, in &lt;module&gt; conn = mysql.connector.connect('localhost', user='root', password='root', database='nlidb') File "G:\python\NLIDB\venv\lib\site-packages\mysql\connector\__init__.py", line 179, in connect return MySQLConnection(*args, **kwargs) File "G:\python\NLIDB\venv\lib\site-packages\mysql\connector\connection.py", line 57, in __init__ super(MySQLConnection, self).__init__(*args, **kwargs) TypeError: __init__() takes 1 positional argument but 2 were given Can anyone help me out this?? Thanks in advance.

http://stackoverflow.com/comment/87230115
has text: Possible duplicate of [python for-loop only executes once?](https://stackoverflow.com/questions/41933378/python-for-loop-only-executes-once)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50106176
type: QuestionComment

http://stackoverflow.com/a/50115240
score: 1
has comment: http://stackoverflow.com/comment/106783752
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50114827
has body: The legend is not on because plt wasn't instructed to label the plots. Add something like this to obtain labels in the legend "label='Plot 1'" in your plot line: chart = plt.bar(index, data, bar_width, color='blue',edgecolor='black', label='Plot 1') chart = plt.bar(index+bar_width, data2, bar_width, color='red', edgecolor='black', label='Plot 2') chart = plt.bar(index+2*bar_width, data, bar_width, color='green', edgecolor='black', label='Plot 3') This gets you legends.
has comment: http://stackoverflow.com/comment/87253175
type: Answer
has comment: http://stackoverflow.com/comment/87256280

http://stackoverflow.com/comment/87426921
comment on: http://stackoverflow.com/a/50204905
has text: Yeah, I was thinking you had a different point, I will revise my answer.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50087407
has title: Replace string in sentence using another column and POS tag
has comment: http://stackoverflow.com/comment/87190851
linked to: http://stackoverflow.com/q/50085252
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87194750
type: Question
has body: How to replace string in sentence using another column and POS tag? I want to replace string in col2 as POS tag from col1 For example: col1 col2 output mtmb2 MTMB2 is a my sentence NNP is a my sentence mmm2 Your MmM2 is my sentence Your NNP is my sentence bbb2 Your sentence is bbb2 Your sentence is NN I try use @YOLO solution: ## import libraries from nltk import word_tokenize, pos_tag, pos_tag_sents ## tag the sentece df['col2'] = df['col2'].apply(word_tokenize).apply(pos_tag) ## this function does the magic def get_vals(lst): op = [] for i, v in enumerate(lst): if i == 0: op.append(v[1]) else: op.append(v[0]) return ' '.join(op) ## apply the function df['col2'] = df['col2'].apply(get_vals) print(df) col1 col2 0 aaa1 NNP is a great friend 1 abb2 NN is a very good friend But this solution working only if word to replace is on first index...
score: 0
has comment: http://stackoverflow.com/comment/87190905
tagged with: pandas
has comment: http://stackoverflow.com/comment/87194931
tagged with: python

http://stackoverflow.com/q/50075351
accepted answer: http://stackoverflow.com/a/50075796
has comment: http://stackoverflow.com/comment/87167005
has comment: http://stackoverflow.com/comment/87166950
has comment: http://stackoverflow.com/comment/87166972
has comment: http://stackoverflow.com/comment/87167314
has comment: http://stackoverflow.com/comment/87167118
type: AnsweredQuestion
has title: trying to grab all column values that aren't equal to 0.000000 in python 3
linked to: http://stackoverflow.com/q/1479776
has comment: http://stackoverflow.com/comment/87167015
tagged with: anaconda
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/87167577
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has body: I have a dataset shown below and I am trying to grab each name in the feature column where the importance column is not equal to 0.000000 and put them straight into a list to use straight away. I have tried a few methods but the main two which show promise are as follows: Method 1 new_features = [] for i in importance_ranking['importance']: if i &gt; 0.000000: new_features.append(i) new_features method 1 just grabs me all of the values of the importance column, but I want the feature column value instead so I tried method 2 Method 2 features_to_use = [] for x,y in importance_ranking: if y &gt; 0.000000: features_to_use.append(x) features_to_use method 2 throws me the error as follows: method 2 error ValueError Traceback (most recent call last) &lt;ipython-input-1181-d1ec4f141ff9&gt; in &lt;module&gt;() 1 features_to_use = [] ----&gt; 2 for x,y in importance_ranking: 3 if y &gt; 0.000000: 4 features_to_use.append(x) 5 ValueError: too many values to unpack (expected 2) any help is greatly appreciated method 3 and error features_to_use = [] for s,x,y in importance_ranking: if y &gt; 0.000000: features_to_use.append(x) features_to_use --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-1182-8ed92369130e&gt; in &lt;module&gt;() 1 features_to_use = [] ----&gt; 2 for s,x,y in importance_ranking: 3 if y &gt; 0.000000: 4 features_to_use.append(x) 5 ValueError: too many values to unpack (expected 3) Dataset **feature importance** 1 src_bytes 0.541433 18 count 0.160338 30 dst_host_diff_srv_rate 0.074743 53 service_bgp 0.066960 31 dst_host_same_src_port_rate 0.045040 28 dst_host_srv_count 0.027176 9 num_compromised 0.016684 25 diff_srv_rate 0.008991 58 service_pm_dump 0.008533 62 service_auth 0.008270 29 dst_host_same_srv_rate 0.006760 2 dst_bytes 0.005153 33 dst_host_serror_rate 0.004642 6 hot 0.003985 32 dst_host_srv_diff_host_rate 0.003330 35 dst_host_rerror_rate 0.002923 34 dst_host_srv_s…
has comment: http://stackoverflow.com/comment/87167073
has answer: http://stackoverflow.com/a/50075723
possible better answer: http://stackoverflow.com/a/50075723
has comment: http://stackoverflow.com/comment/87167528
has comment: http://stackoverflow.com/comment/87167257
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50075796

http://stackoverflow.com/comment/87199138
type: AnswerComment
has text: Oh. I changed your "line" to "row" in the `for` loop.... for no particular reason except i find it tidy.
score: 0
comment on: http://stackoverflow.com/a/50090903
type: Comment

http://stackoverflow.com/a/50136360
downvote count: 0
score: 4
has body: Bokeh's palettes are simply a list of HTML colors. You can create your own one. For example, picking the list from https://www.w3schools.com/colors/colors_shades.asp: myReds = [ '#000000', '#080000', '#100000', '#180000', '#200000', '#280000', '#300000', '#380000', '#400000', '#480000', '#500000', '#580000', '#600000', '#680000', '#700000', '#780000', '#800000', '#880000', '#900000', '#980000', '#A00000', '#A80000', '#B00000', '#B80000', '#C00000', '#C80000', '#D00000', '#D80000', '#E00000', '#E80000', '#F00000', '#F80000', '#FF0000'] Then replace Reds9 by myReds: [...] exp_cmap = LinearColorMapper(palette=myReds, low = min(flowers["petal_length"]), high = max(flowers["petal_length"])) [...]
answers question: http://stackoverflow.com/q/50111925
type: Answer
upvote count: 4

http://stackoverflow.com/a/50232606
accepted answer of: http://stackoverflow.com/q/50114356
type: Answer
has comment: http://stackoverflow.com/comment/87548488
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87533572
answers question: http://stackoverflow.com/q/50114356
has comment: http://stackoverflow.com/comment/87569243
has body: I have come across similar while running JMeter stress tests from a windows machine. This should happen due to port limitations set up by windows as standard. There are 5000 default ports as per their docs. You may try increasing this value using this guide
has comment: http://stackoverflow.com/comment/87532858

http://stackoverflow.com/comment/87238396
score: 0
has text: Thank you for this! This certainly does work within the limited parameters I provided, so I apologize for not providing further details from the outset. The function, ideally, will be able to take in two input variables (x, y) where x is the number of rows/columns and y is the size of the individual, smaller grids within the larger whole.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50106542

http://stackoverflow.com/a/50193328
has comment: http://stackoverflow.com/comment/87411149
upvote count: 13
answers question: http://stackoverflow.com/q/50193159
has comment: http://stackoverflow.com/comment/87405378
type: AcceptedAnswer
downvote count: 0
has body: Basing my answer on a function from SO you can do it like this: Interestingly this answer is also 2x as fast as MaxU and Amis answer for a dataset with +500 rows. My bet is that the bottleneck is str.extract(). But something is clearly strange. import pandas as pd import re #https://stackoverflow.com/questions/33997361 def dms2dd(s): # example: s = """0°51'56.29"S""" degrees, minutes, seconds, direction = re.split('[°\'"]+', s) dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60); if direction in ('S','W'): dd*= -1 return dd df = pd.DataFrame({'CPO': {0: 'Raya', 1: 'Raya'}, 'Latitude': {0: '0°51\'56.29"S', 1: '1°23\'39.29"S'}, 'Longitude': {0: '101°26\'46.29"E', 1: '101°35\'30.45"E'}, 'PKO': {0: 'X', 1: 'X'}, 'ParentCompany': {0: 'Incasi', 1: 'Incasi'}}) df['Latitude'] = df['Latitude'].apply(dms2dd) df['Longitude'] = df['Longitude'].apply(dms2dd) printing df returns: CPO Latitude Longitude PKO ParentCompany 0 Raya -0.865636 101.446192 X Incasi 1 Raya -1.394247 101.591792 X Incasi Update: To correct your mistake you could do something in the lines of: m = df['Latitude'].str[-2] != '"' df.loc[m, 'Latitude'] = df.loc[m, 'Latitude'].str[:-1] + '"' + df.loc[m, 'Latitude'].str[-1] Full example: import re s1 = """0°51'56.29"S""" s2 = """0°51'56.29S""" df = pd.Series((s1,s2)).to_frame(name='Latitude') m = df['Latitude'].str[-2] != '"' df.loc[m, 'Latitude'] = df.loc[m, 'Latitude'].str[:-1] + '"' + df.loc[m, 'Latitude'].str[-1] print(df)
accepted answer of: http://stackoverflow.com/q/50193159
score: 13
has comment: http://stackoverflow.com/comment/87405293
type: Answer

xcode
tag name: xcode
tags question: http://stackoverflow.com/q/50212388
type: Tag

http://stackoverflow.com/comment/87256937
comment on: http://stackoverflow.com/q/50119119
has text: @jedwards the flag idea worked, thank you so much :)
score: 0
type: Comment
type: QuestionComment

ocr
tags question: http://stackoverflow.com/q/50158014
tags question: http://stackoverflow.com/q/50169850
tags question: http://stackoverflow.com/q/50117524
tags question: http://stackoverflow.com/q/50185383
tag name: ocr
type: Tag

http://stackoverflow.com/a/50103961
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50097048
downvote count: 1
upvote count: 0
has comment: http://stackoverflow.com/comment/87273513
type: Answer
score: -1
has body: Such a solution works for me. numbers = list() for i in range(0, 3): inputNr = int(input("Enter a number: ")) if(inputNr == -99): break numbers.append(inputNr) #Then we take all of the numbers and calculate the sum and avg on them sum = 0 for j, val in enumerate(numbers): sum += val print("The total sum is: " + str(sum)) print("The avg is: " + str(sum / len(numbers)))
has comment: http://stackoverflow.com/comment/87324691
has comment: http://stackoverflow.com/comment/87320346
accepted answer of: http://stackoverflow.com/q/50097048
has comment: http://stackoverflow.com/comment/87327207

http://stackoverflow.com/q/50161002
has answer: http://stackoverflow.com/a/50671578
accepted answer: http://stackoverflow.com/a/50671578
has title: Python write multiple numpy array to csv file
has comment: http://stackoverflow.com/comment/87341185
has comment: http://stackoverflow.com/comment/87350438
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/87360619
tagged with: numpy
type: AnsweredQuestion
score: 0
has body: I am trying to add features of multiple images by converting them from raw data format to .csv. I have read and displayed features of two images via print function but during addition of contents to csv, i am only able to add single numpy array. I want to add few thousand images in same csv. Below is printed output, but csv only shows one array (having features of single image). Image showing code and output
answer count: 1
type: Question

http://stackoverflow.com/comment/87479898
type: Comment
comment on: http://stackoverflow.com/a/50230390
type: AnswerComment
has text: @atomAltera `runserver` is a development server and should not be used in production
score: 0

http://stackoverflow.com/q/50074690
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/87165970
score: 33
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/70122450
upvote count: 33
has answer: http://stackoverflow.com/a/73025967
tagged with: django-settings
has answer: http://stackoverflow.com/a/55842863
accepted answer: http://stackoverflow.com/a/50075525
has title: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
has answer: http://stackoverflow.com/a/65706051
tagged with: django
has answer: http://stackoverflow.com/a/50075525
tagged with: python
has body: I'm trying to make MongoDB and Django get on with each other the way I want them to. That's the error I'm getting when trying to import viewsets from rest_framework_mongoengine. The whole error looks like this: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. It doesn't find settings.py or what? If so I can't figure out why! Namely, say, why did this problem not appear with other modules then? Here are my INSTALLED APPS INSTALLED_APPS = [ 'rest_framework', 'rest_framework_mongoengine', 'mongoengine.django.mongo_auth', 'rest_framework.authtoken', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'core', 'core.essences.user', 'core.essences.user.authentication', 'core.essences.test_result', ]
has comment: http://stackoverflow.com/comment/87165800
type: AnsweredQuestion
tagged with: restframeworkmongoengine
has answer: http://stackoverflow.com/a/59020345
has answer: http://stackoverflow.com/a/70122450
has answer: http://stackoverflow.com/a/63214403

http://stackoverflow.com/comment/87349321
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50162090
has text: @eyllanesc I'm closer to a solution. I found that QMovie does have QMovie.setScaledSize() which scales the image reader. So instead of scaling the label, I scale the movie and then call QLabel.adjustSize() to fit the label to the movie. It is a little "jumpy" but it does work. I'll post my code in a bit.
score: 1

http://stackoverflow.com/q/50172329
score: 0
has title: Find in value elasticsearch Response
answer count: 0
has comment: http://stackoverflow.com/comment/87361959
type: Question
has comment: http://stackoverflow.com/comment/87361743
type: UnansweredQuestion
has body: I have merged list of ids. I want to do it on one search. I am doing ES search like: self._test_search.with_ids(idsWithOtherIds).search() Then I am iterating over one 1st part: for test in tests: if test.id in ids: But in this for loop I need to get some data from other part of results. How can I do it ? EDIT: idsWithVectorsCids = idsForVectors + ids and in for loop I need to take result from ES from idsForVectors.
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/87361941

countvectorizer
type: Tag
tag name: countvectorizer
tags question: http://stackoverflow.com/q/50152386

http://stackoverflow.com/a/54084424
score: 17
downvote count: 0
answers question: http://stackoverflow.com/q/50087098
upvote count: 17
has body: I solved this issue by typing the following command, pip install --user &lt;package_name&gt; Example, pip install --user tensorflow NOTE: You should not enter your own username for this command. Please enter with '--user'.
type: Answer

http://stackoverflow.com/q/50206582
type: Question
type: UnansweredQuestion
has title: Error converting RDD row to a dataframe with pyspark
tagged with: pyspark
has comment: http://stackoverflow.com/comment/87430541
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50208921
has comment: http://stackoverflow.com/comment/87430701
downvote count: 0
tagged with: apache-spark
upvote count: 1
score: 1
has body: I wrote a function that I want to apply to a dataframe, but first I have to convert the dataframe to a RDD to map. Then I print so I can see the result: x = exploded.rdd.map(lambda x: add_final_score(x.toDF())) print(x.take(2)) The function add_final_score takes a dataframe, which is why I have to convert x back to a DF before I pass it through. However, it give me this error that toDF is not in the list: Py4JJavaError Traceback (most recent call last) &lt;ipython-input-491-11e7b77ecf3f&gt; in &lt;module&gt;() 42 # StructField('segmentName', StringType(), True)]) 43 # x = exploded.rdd.map(lambda y: y.toDf()) ---&gt; 44 print(x.take(2)) ~/spark-2.3.0-bin-hadoop2.7/python/pyspark/rdd.py in take(self, num) 1356 1357 p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts)) -&gt; 1358 res = self.context.runJob(self, takeUpToNumLeft, p) 1359 1360 items += res ~/spark-2.3.0-bin-hadoop2.7/python/pyspark/context.py in runJob(self, rdd, partitionFunc, partitions, allowLocal) 999 # SparkContext#runJob. 1000 mappedRDD = rdd.mapPartitions(partitionFunc) -&gt; 1001 port = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions) 1002 return list(_load_from_socket(port, mappedRDD._jrdd_deserializer)) 1003 ~/spark-2.3.0-bin-hadoop2.7/python/lib/py4j-0.10.6-src.zip/py4j/java_gateway.py in __call__(self, *args) 1158 answer = self.gateway_client.send_command(command) 1159 return_value = get_return_value( -&gt; 1160 answer, self.gateway_client, self.target_id, self.name) 1161 1162 for temp_arg in temp_args: ~/spark-2.3.0-bin-hadoop2.7/python/pyspark/sql/utils.py in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---&gt; 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() ~/spark-2.3.0-bin-hadoop2.7/python/lib/py4j-0.10.6-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 318 raise Py4JJavaError( 319 "An error occurred while calling {0}{1}{2}.\n". --&gt; 320 format(target_id, ".…
answer count: 1
linked to: http://stackoverflow.com/q/40667879
favorite count: 0

http://stackoverflow.com/comment/87280977
has text: Works the same way
comment on: http://stackoverflow.com/a/50130905
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87346696
comment on: http://stackoverflow.com/a/50163154
score: 0
type: AnswerComment
type: Comment
has text: OHHHH that's the reason! I'm still new to coding and understanding function is still challenging. Thank you so much!

http://stackoverflow.com/a/50095187
type: Answer
has comment: http://stackoverflow.com/comment/87207443
has comment: http://stackoverflow.com/comment/87271769
upvote count: 6
score: 6
has body: As you have mentioned: All my convolutions are 5x5 windows, 1x1 stride, with (from 1st one to last one) 32, 64, 128 and 256 features. I am using leaky ReLUs and 2x2 max pooling. FC layers are composed of 64 and 3 neurones. So, the memory consumption of your network goes like : Input: 640x640x3 = 1200 (in KB) C1: 636x636x32 = 12.5 MB (stride=1 worked) P1: 635x635x32 = 12.3 MB (stride=1 worked) C2: 631x631x64 = 24.3 MB P2: 630x630x64 = 24.2 MB C3: 626x626x128 = 47.83 MB P3: 625x625x128 = 47.68 MB C4: 621x621x256 = 94.15 MB P4: 620x620x256 = 93.84 MB FC1: 64 = 0.0625 KB (negligible) FC2: 3 = 0.003 KB (negligible) Total for one image = ~ 358 MB For batch of 56 image = 56 x 358 ~19.6 GB That's why your network does not run on 6 GB. Try with some higher stride or lower sized image to adjust it into 6 GB space. And it should work. You can refer this to better understand memory consumption calculation.
has comment: http://stackoverflow.com/comment/87245466
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87271337
downvote count: 0
has comment: http://stackoverflow.com/comment/87207395
accepted answer of: http://stackoverflow.com/q/50093581
has comment: http://stackoverflow.com/comment/87275552
answers question: http://stackoverflow.com/q/50093581

http://stackoverflow.com/comment/87447339
comment on: http://stackoverflow.com/q/50215279
score: 2
type: Comment
type: QuestionComment
has text: It may be composition, but it still results in exactly 1 function and not 2.

http://stackoverflow.com/comment/87388790
type: QuestionComment
has text: Thanks for advice
comment on: http://stackoverflow.com/q/50185839
score: 0
type: Comment

http://stackoverflow.com/q/50165501
tagged with: python
possible better answer: http://stackoverflow.com/a/50165755
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50165755
has answer: http://stackoverflow.com/a/61064098
has title: Generate random list of timestamps in python
tagged with: random
downvote count: 0
tagged with: timedelta
favorite count: 0
type: Question
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/50165564
tagged with: time
accepted answer: http://stackoverflow.com/a/50165564
has answer: http://stackoverflow.com/a/56887160
has body: I'm trying to generate random list of 24hr timestamps. I can generate one sample of date and time between the set range using the code below. I'm hoping to generate multiple samples (e.g. 10 samples) Also, the date component isn't a priority for me. If i could drop that and just generate random 24hr timestamps that would be good. Most threads I've found only consider generate random dates. I can find anything that concerns time. import random import time from datetime import datetime def randomDate(start, end): frmt = '%d-%m-%Y %H:%M:%S' stime = time.mktime(time.strptime(start, frmt)) etime = time.mktime(time.strptime(end, frmt)) ptime = stime + random.random() * (etime - stime) dt = datetime.fromtimestamp(time.mktime(time.localtime(ptime))) return dt random_datetime = randomDate("20-01-2018 13:30:00", "23-01-2018 04:50:34") print(random_datetime) Output: 2018-01-21 03:33:55

http://stackoverflow.com/comment/87170598
type: QuestionComment
has text: @OwenHempel I add some infos.If you know something, please help me.
score: 0
comment on: http://stackoverflow.com/q/50077168
type: Comment

http://stackoverflow.com/comment/87381362
type: AnswerComment
score: 0
type: Comment
has text: Thanks for your answer.... I don't use Anaconda... I installed it in the console directly and then program with Pycharm... What you say I've tried and it does not work for the very good reasons mentioned above by @tdelaney in the comments....
comment on: http://stackoverflow.com/a/50182045

http://stackoverflow.com/q/50217553
tagged with: python
has comment: http://stackoverflow.com/comment/87452637
has comment: http://stackoverflow.com/comment/87453454
has title: Kalman Filtering_1-dimensional_Python
tagged with: numpy
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87452782
answer count: 1
has body: I try to use Kalman filtering for my one dimensional data. So, assume that I have the following dataset: Variable 250.1 248.5 262.3 265.3 270.2 I do know that there is a noise in my data and hence, I want to clean this data by using Kalman filtering. Which way can produce the most efficient result for me? I run the following code: from pykalman import KalmanFilter import numpy as np kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]], observation_matrices = [[0.1, 0.5], [-0.3, 0.0]]) measurements = np.asarray([(250.1),(248.5),(262.3),(265.3), (270.2)]) kf = kf.em(measurements, n_iter=5) (filtered_state_means, filtered_state_covariances)=kf.filter(measurements) (smoothed_state_means, smoothed_state_covariances)=kf.smooth(measurements) As you can see, I try to use pykalman, however I cannot install this module. I try to use easy_install pykalman direction, and the error is invalid syntax. Another problem is, I have a huge data set, so I have more than one hundred thousand rows in my variable column. So, I cannot write all observations one by one.
has comment: http://stackoverflow.com/comment/87453054
has answer: http://stackoverflow.com/a/50237588
has comment: http://stackoverflow.com/comment/87452056
type: Question
tagged with: kalman-filter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87452937
linked to: http://stackoverflow.com/q/43377626

http://stackoverflow.com/comment/87218663
score: 1
comment on: http://stackoverflow.com/q/50101064
type: Comment
type: QuestionComment
has text: u can use `pip install django-markdown`

http://stackoverflow.com/a/50183021
has body: ([k]*size for k, size in enumerate(train_sizes)) is a generator expression, which means it evaluates to an iterator, not a sequence. np.array wants sequences; if you give it an iterator, it treats it as a sequence of one object, the iterator itself, which is not very useful. (That's what keras is complaining about—it's expecting an array of numbers, and you've given it an array of iterator objects.) But np.array will take lists, and you can trivially turn a generator expression into a list comprehension by using brackets instead of parens (or in addition to parens, where the extra parens are optional): np.array([[k]*size for k, size in enumerate(train_sizes)]) Or, if you don't want to waste time and memory building that list, you can use np.fromiter, but that's a bit tricky to use for 2D arrays, and your sequence is small enough that I wouldn't worry about converting it to a list here.
answers question: http://stackoverflow.com/q/50182860
accepted answer of: http://stackoverflow.com/q/50182860
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/a/50121135
type: Answer
has comment: http://stackoverflow.com/comment/87298709
has comment: http://stackoverflow.com/comment/87259982
answers question: http://stackoverflow.com/q/50118811
score: 1
has comment: http://stackoverflow.com/comment/87262831
has comment: http://stackoverflow.com/comment/87264198
downvote count: 0
upvote count: 1
has body: There is no mechanism to prevent the handling of the event by the widget, when both the canvas and a canvas item both are bound to an event. From the canonical documentation: If bindings have been created for a canvas window using the bind command, then they are invoked in addition to bindings created for the canvas's items using the bind widget command. The bindings for items will be invoked before any of the bindings for the window as a whole. Since the binding for the item is invoked first, one solution is to use a variable that the widget binding can use to know it should ignore the event. Another solution would be to not bind to the canvas items, and let all handling come from the binding to the widget. Within the bound function you can ask the canvas which item was clicked, and then do the item-specific function if something was clicked on. Here's an example of the second technique: import tkinter as tk import random def on_click(event): current = event.widget.find_withtag("current") if current: item = current[0] color = canvas.itemcget(item, "fill") label.configure(text="you clicked on item with id %s (%s)" % (item, color)) else: label.configure(text="You didn't click on an item") root = tk.Tk() label = tk.Label(root, anchor="w") canvas = tk.Canvas(root, background="bisque", width=400, height=400) label.pack(side="top", fill="x") canvas.pack(fill="both", expand=True) for color in ("red", "orange", "yellow", "green", "blue", "violet"): x0 = random.randint(50, 350) y0 = random.randint(50, 350) canvas.create_rectangle(x0, y0, x0+50, y0+50, outline="black", fill=color) canvas.bind('&lt;ButtonPress-1&gt;', on_click) root.mainloop()
has comment: http://stackoverflow.com/comment/87262478
has comment: http://stackoverflow.com/comment/87260400

http://stackoverflow.com/q/50091174
favorite count: 0
possible better answer: http://stackoverflow.com/a/50091254
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50091254
has title: csv writer to stdout throws error in with block
has answer: http://stackoverflow.com/a/50091296
linked to: http://stackoverflow.com/q/41738098
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50091296
tagged with: http://stackoverflow.com/tag/csv
score: 1
has body: How to force csv.writer() to accept stdout inside with block? I this works ok: with (open(output, "w")) if output != 'stdout' else stdout as file: this is also fine: file = csv.writer(open(output, "w") if output != 'stdout' else stdout) but when I try this: with csv.writer(open(output, "w") if output != 'stdout' else stdout) as file: I get AttributeError: __exit__ How to make this with block work please? I am looking for solution like ruby solution but for python.
downvote count: 0
tagged with: stdout
has comment: http://stackoverflow.com/comment/87198683

http://stackoverflow.com/comment/87245965
comment on: http://stackoverflow.com/a/50114301
type: Comment
has text: or just `return next((grade for s, grade in grades if size <= s), None)`?
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87413211
type: QuestionComment
score: 0
has text: What do you want to "convert"? It is already RDF ...
comment on: http://stackoverflow.com/q/50195872
type: Comment

http://stackoverflow.com/comment/87488212
type: QuestionComment
comment on: http://stackoverflow.com/q/50229091
has text: He is talking about not closing after `tf.InteractiveSession()`
score: 1
type: Comment

http://stackoverflow.com/comment/87187688
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50084943
score: 0
has text: I tried with your answer sir.But when key 'c' is pressed, page2 is not displayed. key 'e' is working well. sir, if you dont mind, can you please edit and send the whole program for me sir. plz!!

http://stackoverflow.com/q/50183503
has answer: http://stackoverflow.com/a/50183546
type: Question
type: UnansweredQuestion
tagged with: facebook
tagged with: python
has body: I'm trying to create a very simple Facebook app (using the Python SDK) that does nothing more than post to its own page. The eventual app will make one post per day, and that's all it will do. (Please note that I am a novice programmer, and this is in part a learning exercise for me.) My initial test code looks like this, and it successfully posts to the page: import facebook token = 'XXXXX' graph = facebook.GraphAPI(access_token = token, version = "2.1") graph.put_object(parent_object='me', connection_name='feed', message='Test post to page') The catch is that it only works if I plug in a value for token that is a valid page access token. For testing, I can get one from the Graph API Explorer, but obviously I'd like my app to be able to get one each time it runs, using its own credentials (e.g. app ID and app secret). I have been searching for a way to do this with the Python SDK, but I have had no luck finding out how, in part because most apps are much more complicated (involving user logins and so forth). I don't see Is there a simple way to do this, or is the problem more complicated than I think it is?
has title: Getting a Facebook page access token for a simple app (Python)
score: 0
answer count: 1

in-place
tags question: http://stackoverflow.com/q/50224226
tag name: in-place
type: Tag

http://stackoverflow.com/q/50227128
has body: I want to sort values in specific column by using python code when I click th "Çiz" button right side. However it sorts according to first element if numbers are double or more. I realize that it accepts values as string. I look many questions in websites there is no answer for me. I do not want to write a script, there must be a solution for sorting because it seems so easy. It is my script from Qt 5.10, here. Here is my script - I wrote 0 for sorting acccording to first column: QTableWidget.sortItems(0, QtCore.Qt.AscendingOrder) But it accepts values as string not number value. Actually there is a script when user click header it sorts values but I do not want to had user clicked the header: QTableWidget.setSortingEnabled(True)
duplicate of: http://stackoverflow.com/q/11938459
has comment: http://stackoverflow.com/comment/87473340
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/13074035
duplicate of: http://stackoverflow.com/q/50047673
tagged with: qtablewidget
linked to: http://stackoverflow.com/q/13074035
answer count: 1
tagged with: python
has title: How to sort QTableWidget column values?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11938459
tagged with: pyqt
has answer: http://stackoverflow.com/a/50228964
upvote count: 7
accepted answer: http://stackoverflow.com/a/50228964
downvote count: 1
score: 6
tagged with: pyqt5

http://stackoverflow.com/comment/87407903
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50191742
score: 0
has text: Pls check my response. Doesn't seem to work with my implementation.

http://stackoverflow.com/q/50227399
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87472638
tagged with: python
has comment: http://stackoverflow.com/comment/87472253
has title: find all method not storing complete number in the list, when '+919888098880' is entered
tagged with: regex
has body: #! /usr/bin/python3 #Find indian phone number in the text entered. print('Enter text:') para = input() #user's input import re phonenumreg = re.compile(r'[(\+91)|(0)]?[6-9]\d{9}') no = phonenumreg.findall(para) print(no) #print list when I enter '+917087708705' and the list prints ['+9170877087'] but works fine for '7087708705' and '07087708705' can someone explain me why?
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87472307
has answer: http://stackoverflow.com/a/50227555
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87247021
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50114898
has text: sorry, there is mistake, it should be iter1 instead of a, and iter2 instead of b.
type: Comment

http://stackoverflow.com/q/50105094
has title: Python: upload large files S3 fast
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/76490401
upvote count: 16
has answer: http://stackoverflow.com/a/50118024
accepted answer: http://stackoverflow.com/a/50118024
tagged with: python
tagged with: boto3
has answer: http://stackoverflow.com/a/50111108
possible better answer: http://stackoverflow.com/a/50111108
has comment: http://stackoverflow.com/comment/87228721
has comment: http://stackoverflow.com/comment/87244558
type: AnsweredQuestion
answer count: 3
downvote count: 0
has body: I am trying to upload programmatically an very large file up to 1GB on S3. As I found that AWS S3 supports multipart upload for large files, and I found some Python code to do it. (link ) My point: the speed of upload was too slow (almost 1 min). Is there any way to increase the performance of multipart upload. Or any good library support S3 uploading
tagged with: upload
has comment: http://stackoverflow.com/comment/87243867
score: 16
favorite count: 0
type: Question

http://stackoverflow.com/comment/87310855
has text: Yes it is out of scope. Because you have defined variable fname in load_file() and once that function has been called and exited, other functions might not know about fname() because of scope.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50146327
score: 1

http://stackoverflow.com/comment/87242381
type: Comment
comment on: http://stackoverflow.com/a/50112159
has text: It is as I had thought. This is an issue with the way the python library handles the OS environment passed along with command. Read [this](https://stackoverflow.com/questions/24788292/intermittent-oserror-errno-7-argument-list-too-long-with-short-command-12) article as it will explain better than I can
type: AnswerComment
score: 0

http://stackoverflow.com/q/50208007
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50208064
accepted answer: http://stackoverflow.com/a/50208064
answer count: 2
has body: I have following df - id score 222.0 0.0 222.0 0.0 222.0 1.0 222.0 0.0 222.0 1.0 222.0 1.0 222.0 1.0 222.0 0.0 222.0 1.0 222.0 -1.0 416.0 0.0 416.0 0.0 416.0 2.0 416.0 0.0 416.0 1.0 416.0 0.0 416.0 1.0 416.0 1.0 416.0 0.0 416.0 0.0 895.0 1.0 895.0 0.0 895.0 0.0 895.0 0.0 895.0 0.0 895.0 0.0 895.0 0.0 895.0 0.0 895.0 0.0 895.0 0.0 I want to calculate mode for same value of id for score column. Something Like this- id score 222.0 1.0 416.0 0.0 895.0 0.0 My tried like this- df['score'] = df.mode()['score'] But I am getting following output - id score 222.0 0.0 222.0 NaN 222.0 NaN 222.0 NaN 222.0 NaN 222.0 NaN 222.0 NaN 222.0 NaN 222.0 NaN 222.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 416.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN 895.0 NaN What is wrong here?
has title: Calculate mode of a column in Pandas using other column with same row values
tagged with: python
type: AnsweredQuestion
tagged with: pandas-groupby
downvote count: 0
possible better answer: http://stackoverflow.com/a/50208245
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50208245

http://stackoverflow.com/q/50209179
accepted answer: http://stackoverflow.com/a/50442667
type: Question
has answer: http://stackoverflow.com/a/50442667
has title: Read emails from axigen server using python
answer count: 1
tagged with: email
downvote count: 0
upvote count: 1
favorite count: 0
has body: Is there any implemented library or solution to read emails(get attachments too) from an Axigen server using Python? I've done it before with the email library and the gmail api but i cannot find any documentation on axigen. Is there any difference or you could connect just like you would do to any other imap or pop3 server? Any hit would be useful, Thank you!
type: AnsweredQuestion
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87435469

http://stackoverflow.com/q/50135823
tagged with: templates
tagged with: string
type: Question
has answer: http://stackoverflow.com/a/50136004
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: string template substitution: each and every occurrence must be substituted
score: 0
has body: I have the following MWE: import string class MyTemplate(string.Template): delimiter = '$' pattern = r''' \$(?: (?P&lt;escaped&gt;\$)| (?P&lt;named&gt;[_a-z][_a-z0-9]*)\$| (?P&lt;braced&gt;[_a-z][_a-z0-9]*)\$| (?P&lt;invalid&gt;) ) ''' data1="max=$max$ min=$min$" data2="max=$max$ " print MyTemplate(data1).substitute({"max":"10","min":"1"}) print MyTemplate(data2).substitute({"max":"10","min":"1"}) print MyTemplate(data1).substitute({"max":"10"}) Of the 3 prints, I want that the only acceptable case is the first; the last one raise an exception, but the second simply writes: max=10 How can I detect this case (more values than placeholder)? Is it possible to verify that a value is substituted only once? Thanks!

http://stackoverflow.com/q/50092818
favorite count: 0
type: Question
tagged with: network-programming
type: UnansweredQuestion
has title: Sum weights of neighbors nodes in python
has comment: http://stackoverflow.com/comment/87201907
tagged with: python
score: -4
downvote count: 4
tagged with: weighted
upvote count: 0
answer count: 1
has body: I need to sum the total weights of a neighbors node. For example, I have a node (1) where its neighbors are (2) and (4). Its edges has a weight: (1-2 , weight = 3) and (1-4, weight = 5). Then, I need the result of sum weights (8). I tried: sum_tot = [] for neigh in G.neighbors(1): sum_tot.append(G[1][neigh]['weight']) sum(sum_tot) But results 0 Any ideas for python programming?
has answer: http://stackoverflow.com/a/50092907

http://stackoverflow.com/comment/87254494
score: 0
has text: Too much code, please provide a [Complete, Minimal, Verifiable Example](https://stackoverflow.com/help/mcve)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50115630

http://stackoverflow.com/comment/87339303
has text: @Patricks Artner thank you but it is more complicated
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50160069

http://stackoverflow.com/comment/87243622
comment on: http://stackoverflow.com/q/50113282
has text: Can you figure out which elements are problematic _before_ you run out of memory?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50113257
score: 2
has comment: http://stackoverflow.com/comment/87243798
has comment: http://stackoverflow.com/comment/87255148
favorite count: 0
has answer: http://stackoverflow.com/a/74648587
tagged with: python-3.x
tagged with: linux
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/73375720
answer count: 2
downvote count: 0
tagged with: pip
linked to: http://stackoverflow.com/q/49489569
tagged with: python
type: UnansweredQuestion
has body: Good morning, I use Linux Void with Openbox and SpaceFm. I would like to update the pip, but uninstalling the installed version (9.0.3) fails: is there a solution? I also tried the "python3 -m pip install --upgrade pip" command with the same result. This is the terminal output. Thank you. $ pip install --upgrade pip Collecting pip Downloading https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl (1.3MB) 100% |████████████████████████████████| 1.3MB 280kB/s Installing collected packages: pip Found existing installation: pip 9.0.3 Uninstalling pip-9.0.3: Exception: Traceback (most recent call last): File "/usr/lib/python3.6/shutil.py", line 544, in move os.rename(src, real_dst) OSError: [Errno 18] Collegamento tra dispositivi non valido: '/usr/lib/python3.6/site-packages/pip' -&gt; '/tmp/pip-xsteet9f-uninstall/usr/lib/python3.6/site-packages/pip' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3.6/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/lib/python3.6/site-packages/pip/req/req_set.py", line 778, in install requirement.uninstall(auto_confirm=True) File "/usr/lib/python3.6/site-packages/pip/req/req_install.py", line 754, in uninstall paths_to_remove.remove(auto_confirm) File "/usr/lib/python3.6/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/usr/lib/python3.6/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/usr/lib/python3.6/shutil.py", line 556, in move rmtree(src) File "/usr/lib/python3.6/shutil.py", line 480, in rmtree _rmtree_safe_fd(fd, path, onerror) File "/usr/lib/python3.6/shutil.py", line 418, in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) File …
has title: Error when trying to update pip

http://stackoverflow.com/a/53050694
downvote count: 0
score: 4
has body: This stackoverflow post has an answer, although the steps are a bit different. Install the ipykernel in your virtual environment: pipenv install ipykernel Start shell with: pipenv shell Set name so Atom Hydrogen can recognize: python -m ipykernel install --user --name=name-that-atom-hydrogen-will-list Start Atom (from within pipenv shell) and when you run code (control-enter), Atom should list python kernels to use (including name-that-atom-hydrogen-will-list)
accepted answer of: http://stackoverflow.com/q/50162216
type: Answer
answers question: http://stackoverflow.com/q/50162216
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/50164605
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50164024
type: Answer
upvote count: 1
has body: Your traceback mentions Process Process-42:, so there are at least 42 processes being created. You're creating a process for every CSV file, which is not useful and is probably causing the memory error. Your problem can be solved much more simply using multiprocessing.Pool.map. The worker function can also be shortened greatly: def worker(f): with open(f) as infile: return Counter(line.strip().split(",")[1] for line in infile) def main(): pool = multiprocessing.Pool() result_list = pool.map(worker, [f for f in files if f.endswith('.csv')]) Passing no arguments to the pool means it'll create as many processes as you have CPU cores. Using more may or may not increase performance.
has comment: http://stackoverflow.com/comment/87358036
accepted answer of: http://stackoverflow.com/q/50164024
score: 1

http://stackoverflow.com/q/50077228
has body: I am learning pyqt5 and somehow I can't use fcitx in the text box created by QTextEdit or QLineEdit although fcitx works normally with other Qt apps like goldendict or kate. But later I found out that fcitx also doesn't work with another Qt app named Retext which uses Qt 5.10. Maybe this has something to do with the latest version of Qt or so I think. Here's my code, just a simple textbox and nothing else: import PyQt5.QtWidgets as QtWidgets import sys class App(QtWidgets.QWidget): def __init__(self): super().__init__() self.text = QtWidgets.QTextEdit() self.initUI() def initUI(self): vbox = QtWidgets.QVBoxLayout() vbox.addWidget(self.text) self.setLayout(vbox) self.show() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) ex = App() sys.exit(app.exec_())
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87173479
tagged with: python
has title: Can't use fcitx with self-written Qt app
score: 2
tagged with: fcitx
upvote count: 2
tagged with: pyqt
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50087899

http://stackoverflow.com/comment/87640799
type: Comment
comment on: http://stackoverflow.com/a/50286917
has text: You can just add to all vectors (which can be represented as lists) one element and set its value to 1 for locations and 0 otherwise.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50107909
type: Question
has title: python: cannot import name beam_runner_api_pb2
tagged with: apache-beam
tagged with: python
has comment: http://stackoverflow.com/comment/87233920
has answer: http://stackoverflow.com/a/50108335
tagged with: python-2.7
score: 0
has body: I am relatively new to Python and Beam and I have followed the Apache Beam - Python Quickstart (here) to the last letter. My Python 2.7 virtual environment was created with conda. I cloned the example from https://github.com/apache/beam When I try to run python -m apache_beam.examples.wordcount --input sample_text.txt --output counts I get the following error /Users/name/anaconda3/envs/py27/bin/python: cannot import name beam_runner_api_pb2 (which after searching I understand means that there is a circular import) I have no idea where to begin. Is this a bug or something wrong with my setup. (I have now tried redoing the example in three different virtual environments - all with the same result)
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/50077443
tagged with: python
has title: (Microbit) Player position resets after function completes
upvote count: 1
score: 1
favorite count: 0
type: Question
has body: I've been working on a program for the Microbit inspired by some basic blocks script I saw a few years back. The functionality of the AI controlled pixel and the player controlled pixel work as intended--which one annoying, and game breaking bug--the player ship resets to its spawn position whenever the AI ship completes its function. I suspect this is because I have an assigned position for the ship in the beginning of the code, where it is then modified in the function itself. Removing this results in an error where a variable is not referenced--however, I cannot leave the problem alone. I welcome any guidance. The code is below. from microbit import * import random enemyXpos = 4 playerXpos = 2 while True: display.set_pixel(enemyXpos,0,4) display.set_pixel(playerXpos,4,6) def laser(laserXpos, laserYpos): laserXpos = playerXpos laserYpos = 3 for i in range (4): display.set_pixel(laserXpos,laserYpos,9) if laserYpos &gt; 0: display.set_pixel(laserXpos,laserYpos,0) laserYpos -= 1 display.set_pixel(laserXpos,laserYpos,9) if laserYpos == 0 and laserXpos == enemyXpos: display.show(all_booms, delay=200) score = score + 1 continue elif laserYpos == 0: display.set_pixel(bombXpos,bombYpos,0) laserYpos = newlaserYpos sleep (200) def enemy_left(enemyXpos, playerXpos): enemyXpos = 4 for i in range (4): display.clear() enemyXpos -= 1 display.set_pixel(enemyXpos,0,4) display.set_pixel(playerXpos,4,6) if button_a.is_pressed() and button_b.is_pressed(): laser(laserXpos,laserYpos) elif button_a.is_pressed() and playerXpos &gt; 0: playerXpos -= 1 elif button_b.is_pressed() and playerXpos &lt; 4: playerXpos += 1 sleep(200) def enemy_right(enemyXpos, playerXpos): enemyXpos = 0 for i in range (4): display.clear() enemyXpos += 1 display.set_pixel(enemyXpos,0,4) display.set_pixel(playerXpos,4,6) if button_a.is_pressed() and button_b.is_pressed(): laser(laserXpos,laserYpos) elif button_a.is_pressed() and playerXpos &gt; 0: playerXpos -= 1 elif button_b.is_pressed() and playerXpos &lt; 4: p…
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50088265
upvote count: 4
has comment: http://stackoverflow.com/comment/87192993
answers question: http://stackoverflow.com/q/50087271
downvote count: 0
has body: It depends on what other datasets you have however here is one approach : Just blindly cut out one second snippets from your audio then perform some judgement as to whether each audio snippet file is actually a single spoken digit. For each input audio file define a one second window which you pluck out and save into its own file then slide this window further into the audio file and again pluck out the next snippet into its own file. Since we want one second clips and we do not know where in the source input file our digits lay, once the first window snippet is saved only slide say 100ms over and pluck out the next window. So for each input audio file we will create a succession of overlapping snippets each with its starting point only 100ms separated from previous snippet. To perform this easily use command line tool ffmpeg https://ffmpeg.org/ffmpeg.html https://ffmpeg.org/ffmpeg-utils.html#time-duration-syntax input_audio=audio_from_your_dataset.wav output_audio=output/aaa ffmpeg -i $input_audio -ss 0 -t 1 -acodec copy ${output_audio}.0.00.wav ffmpeg -i $input_audio -ss 0.20 -t 1 -acodec copy ${output_audio}.0.20.wav ffmpeg -i $input_audio -ss 0.40 -t 1 -acodec copy ${output_audio}.0.40.wav ffmpeg -i $input_audio -ss 0.60 -t 1 -acodec copy ${output_audio}.0.60.wav ffmpeg -i $input_audio -ss 0.80 -t 1 -acodec copy ${output_audio}.0.80.wav ffmpeg -i $input_audio -ss 1.00 -t 1 -acodec copy ${output_audio}.1.00.wav ffmpeg -i $input_audio -ss 1.20 -t 1 -acodec copy ${output_audio}.1.20.wav in above the parm -ss defines starting point of snippet in seconds ... so 0.60 will start 600ms into the file ... parm -t defines length of window in seconds so its output will be ./output/aaa.0.00.wav ./output/aaa.0.20.wav ./output/aaa.0.40.wav ./output/aaa.0.60.wav ./output/aaa.0.80.wav ./output/aaa.1.00.wav ./output/aaa.1.20.wav issue above on command line ... its not limited to just wav, other codecs are OK too ... now you have several one second snippet audio files plucked from…
type: Answer
score: 4

http://stackoverflow.com/q/50157754
favorite count: 0
accepted answer: http://stackoverflow.com/a/50158107
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87333798
answer count: 2
score: 6
upvote count: 6
tagged with: python
tagged with: vectorization
has title: numpy summing matrix-rows by indices
has answer: http://stackoverflow.com/a/50158107
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50158239
downvote count: 0
has answer: http://stackoverflow.com/a/50158239
has comment: http://stackoverflow.com/comment/87333892
has body: I have 3 matrices (np arrays): A is of shape (n,m) ; B is of shape (m,k); and C is of shape (n,k) Matrix C has only values from the set {-1,0,1} and it's an "indicator" of some sort: if C[i,j]==1 then I want to add the i-th row of A to the j-th column of b; and if C[i,j]==(-1) then subtract (0 does nothing). It can easily be done with loops, but I'm wondering if there's a vectorized way to do it that might be faster? example code: C = np.array([[-1, 0, 0, 0, 1], [ 0, 0, 0, 0, -1], [ 0, 0, 0, 0, -1], [-1, 0, 0, 1, 1]]) a,b = np.where(C==1) #here a=[0,3,3] and b=[4,3,4] A[a,:] = [[0, 1, 2, 3, 4, 5, 6], [3, 3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3, 3]] B[:,b] += A[a] #B is all 0.0 before expected result: array([[ 0., 0., 0., 3., 3.], [ 0., 0., 0., 3., 4.], [ 0., 0., 0., 3., 5.], [ 0., 0., 0., 3., 6.], [ 0., 0., 0., 3., 7.], [ 0., 0., 0., 3., 8.], [ 0., 0., 0., 3., 9.]]) actual result: array([[ 0., 0., 0., 3., 3.], [ 0., 0., 0., 3., 3.], [ 0., 0., 0., 3., 3.], [ 0., 0., 0., 3., 3.], [ 0., 0., 0., 3., 3.], [ 0., 0., 0., 3., 3.], [ 0., 0., 0., 3., 3.]])

http://stackoverflow.com/q/50169580
tagged with: python
type: Question
tagged with: tensorflow-estimator
has comment: http://stackoverflow.com/comment/91084940
answer count: 0
tagged with: deep-learning
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: tensorflow
favorite count: 0
has body: I am currently using the resnet training code from the official models branch of tensorflow and I am facing an issue with respect to the device placement of input_fn when invoked from the Estimator. The default device placement is always CPU when input_fn is invoked from _call_input_fn inside the Estimator class - [r1.8 source]. with ops.device('/cpu:0'): return input_fn(**kwargs) Although the official documentation recommends the input data pipeline to be placed on the CPU so that the GPU is used only for training, there can be scenarios where one needs to perform a forward inference during the data loading phase. For example, during adversarial attacks to perturb the input image by computing the gradients with respect to the input. Is there a way to override the explicit CPU device placement for input data loading when using Estimators?
has title: Tensorflow - How to use GPU for input_fn with Estimator

http://stackoverflow.com/comment/87318065
has text: [This](https://nedbatchelder.com/text/names1.html) is the best explanation of how Python names work that I know of.
score: 3
comment on: http://stackoverflow.com/q/50150055
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50137918
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87322888
has comment: http://stackoverflow.com/comment/87318806
has comment: http://stackoverflow.com/comment/87294320
has body: The source is obviously getting removed via some other control path than stop(). The only candidate I can think of here (from the code you’ve provided) is the self._check_price method. If you’re returning False/GLib.SOURCE_REMOVE from that, you should also unset self.timeout_id: def _check_price(self): … self.timeout_id = 0 return GLib.SOURCE_REMOVE
type: Answer
answers question: http://stackoverflow.com/q/50137029
has comment: http://stackoverflow.com/comment/87319935
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50137029

http://stackoverflow.com/q/50219359
possible better answer: http://stackoverflow.com/a/50219446
upvote count: 1
has answer: http://stackoverflow.com/a/50219446
has answer: http://stackoverflow.com/a/50219463
has body: I have a csv file with only one column, an example of a cell is: "What is the capital of France?1)Lille 2)Paris OK3)Nice" I am trying to divide each sentence by separating the statement from all the individual possible answers. Is there an efficient way to do this?
favorite count: 0
type: Question
has title: Python - Splitting a single csv cell into multiple cells
accepted answer: http://stackoverflow.com/a/50219408
downvote count: 0
has answer: http://stackoverflow.com/a/50219493
has answer: http://stackoverflow.com/a/50219408
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: pandas
score: 1

http://stackoverflow.com/comment/87380391
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50181536
has text: if you have no access to B or C servers , you cannot do it.

http://stackoverflow.com/comment/113424405
score: 1
has text: Note that the thread safety guide has moved to: https://github.com/googleapis/google-api-python-client/blob/master/docs/thread_safety.md
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/55282616

http://stackoverflow.com/comment/104671532
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50229639
has text: @Oysiyl did you manage to sovle this ?
score: 0

http://stackoverflow.com/comment/87300098
comment on: http://stackoverflow.com/a/50137968
score: 0
type: Comment
has text: I have edited my answer clarifying that problem was in not defining those variables into the `tf.Graph` before initializing them.
type: AnswerComment

http://stackoverflow.com/comment/87309063
type: AnswerComment
comment on: http://stackoverflow.com/a/50145071
has text: @ViralPatel What is your desired output after removing the brackets?
score: 0
type: Comment

http://stackoverflow.com/comment/87389650
type: Comment
score: 0
has text: i added an example
type: QuestionComment
comment on: http://stackoverflow.com/q/50162357

http://stackoverflow.com/a/50205861
has body: Python's sqlite library probably is installed. Try: import sqlite3 in the Python shell. If you want to be able to use sqlite's CLI program, you need to install it. Download here. Use the Windows version obviously.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/87429020
accepted answer of: http://stackoverflow.com/q/50205804
answers question: http://stackoverflow.com/q/50205804
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87492566
downvote count: 0
has comment: http://stackoverflow.com/comment/122932028

http://stackoverflow.com/comment/87445697
type: Comment
has text: Vivek,The data is not pickled. Both models get the exact same data. @MikeMcKerns Indeed, that is exactly what i mean.
score: 0
comment on: http://stackoverflow.com/q/50213578
type: QuestionComment

http://stackoverflow.com/q/50175216
has comment: http://stackoverflow.com/comment/87367755
answer count: 1
has body: how can I execute a query without doing like this specially if a parameters wasn't provided? def query_fetch(self, sql_query, params=None, fetchall=True, *args): with self.cursor.execute(sql_query) if params is None else self.cursor.execute(sql_query, params): row = self.cursor.fetchall() if fetchall else self.cursor.fetchone() r = [d for d in row] return r
score: 0
type: Question
has comment: http://stackoverflow.com/comment/87367467
has comment: http://stackoverflow.com/comment/87375092
has answer: http://stackoverflow.com/a/50178912
has title: pyodbc cursor execute with or without params
tagged with: python
type: UnansweredQuestion
tagged with: pyodbc

http://stackoverflow.com/q/50195855
answer count: 1
tagged with: fft
type: Question
has title: Frequency Domain Relu: How to compute sum of diracs where spatial domain values are positive?
type: UnansweredQuestion
has body: I'm attempting to implement the frequency domain ReLu as detailed in: http://cs231n.stanford.edu/reports/2015/pdfs/tema8_final.pdf The formula that is confusing me is on the bottom left of page 4. I am not confident that I am computing the sum of the FFT of the dirac function properly. Am I interpreting this formula incorrectly? import numpy as np import matplotlib.pyplot as plt img = np.array([[-1.0,2.3],[5,7.8]]) # Dirac is essentially the shifting matrix # So create the 2d shifting matrix values N = 2 x = np.arange(0, N, 1) y = np.arange(0, N, 1) xm, ym = np.meshgrid(x, y) shiftMat = np.exp(1j * ((2.0 * np.pi)) * (xm + ym)) # Set equal to shift mat # In this trivial example I know that [0,0] is only negative position # So set to 0 and compute sum of all positions in which f(x) &gt; 0 as detailed in paper freqRelu = shiftMat freqRelu[0,0] = 0 freqRelu = np.sum(freqRelu) # Fourier Convolution and IFFT imgFFT = np.fft.fft2(img) freqR = np.multiply(imgFFT,freqRelu) reluedFreq = np.real(np.fft.ifft2(freqR)) # Spatial Relu For Comparision reluedImg = img reluedImg[0,0] = 0 plt.subplot(121) plt.imshow(reluedImg) plt.subplot(122) plt.imshow(reluedFreq) plt.show() print(np.allclose(reluedFreq,reluedImg)) print(reluedFreq) print(reluedImg)
has answer: http://stackoverflow.com/a/50864913
tagged with: python
tagged with: relu
score: 0

http://stackoverflow.com/comment/87299961
type: AnswerComment
has text: Hi again @mhrtsh! Seems that you can add some variables to the `tf.Graph` after starting `tf.Session`, my bad. Anyway, the problem was trying to initialize through `sess.run()` some variables not previously defined into the `tf.Graph`. Typical approach in Tensorflow is to first define the `tf.Graph` and then start a `tf.Session`.
type: Comment
comment on: http://stackoverflow.com/a/50137968
score: 0

http://stackoverflow.com/q/50121287
has body: I want my pub/sub to store only the last available message on the channel, and dump all prior ones that wouldn't have been consumed because of the consumer being too slow (or paused). ZMQ has the CONFLATE option, but does RabbitMQ have a similar option on Python (pika)? The publisher updates at 50Hz, while some subscribers cannot process quite that fast (between 10 to 50Hz). I don't want them to process the oldest message in queue (which means processing data that is already outdated); it must process only the last available message when it's ready to consume.
tagged with: messaging
tagged with: pika
has comment: http://stackoverflow.com/comment/87263862
has title: Is there a RabbitMQ/pika equivalent to ZMQ's CONFLATE option?
tagged with: python
tagged with: rabbitmq
has comment: http://stackoverflow.com/comment/87267219
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50124625
has answer: http://stackoverflow.com/a/50124625
answer count: 1
has comment: http://stackoverflow.com/comment/87261763
type: Question

http://stackoverflow.com/comment/87227770
has text: Could you please post your code so we can take a look?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50105305

http://stackoverflow.com/q/50137670
type: Question
linked to: http://stackoverflow.com/q/40950310
has answer: http://stackoverflow.com/a/50137955
has comment: http://stackoverflow.com/comment/87293730
score: 0
tagged with: python
has body: I am dealing with a very dirty data that has different kinds of character that I need to remove. Below is just a snapshot. I just want it remove only these characters from the starting character, however it removes all the characters in the col1. Data is in data frame: col1: , Matt R, Carl A _ Hello, World_ ). My Name is ). 'Amy' . My name is 'Matt' ., My name is 'Clark' My name is 'Amy' #clean row Code: articles[col1].str.replace(",","") articles[col1].str.replace("_","") articles[col1].str.replace(").","") articles[col1].str.replace(".","") articles[col1].str.replace(".,","")
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50138180
answer count: 2
has answer: http://stackoverflow.com/a/50138180
has title: python replace first character with ""
has comment: http://stackoverflow.com/comment/87293994
possible better answer: http://stackoverflow.com/a/50137955

http://stackoverflow.com/comment/87334399
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50158035
has text: It is not very easy as they are both in huge files that I import.
type: Comment

http://stackoverflow.com/comment/123257172
has text: True! this is elegant, shortest, simplest.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/66650120

http://stackoverflow.com/comment/88625775
has text: switched to casperjs :)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50140480
type: QuestionComment

http://stackoverflow.com/q/50203732
has answer: http://stackoverflow.com/a/68618970
has comment: http://stackoverflow.com/comment/87424438
tagged with: data-science
favorite count: 0
type: Question
has body: How to compare column names of 2 different Pandas data frame. I want to compare train and test data frames where there are some columns missing in test Data frames??
tagged with: python
possible better answer: http://stackoverflow.com/a/68618970
upvote count: 16
has comment: http://stackoverflow.com/comment/87424458
tagged with: numpy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50203789
answer count: 2
has comment: http://stackoverflow.com/comment/87424387
tagged with: pandas
has answer: http://stackoverflow.com/a/50203789
has title: Compare column names of Pandas Dataframe
has comment: http://stackoverflow.com/comment/87424415
downvote count: 0
score: 16
tagged with: machine-learning

http://stackoverflow.com/comment/87201936
type: Comment
has text: I don't see where `T` is generated at all, so can't test your claim there. But the question is: what do you want to do with the zero pixels? Also: is your indenting wrong in the code? Can't understand what it does!
type: QuestionComment
comment on: http://stackoverflow.com/q/50092730
score: 0

http://stackoverflow.com/comment/87295458
type: QuestionComment
has text: I see you have a COMMA after mint , I think inizialization is not ok .
comment on: http://stackoverflow.com/q/50138520
score: 0
type: Comment

http://stackoverflow.com/a/70286197
type: Answer
has body: This is a very old question, however, it is very related to my recent research topic. Aechlys provides alternatives to solve your problems, which is great. Let me clarify it more clearly. Neural networks can be divided into two sorts according to the size of input length: one is fixed-size and the other is varying-size. For fixed-size, the most common example is MLP. Traditionally, it is insensitive to the position of your model input. In other words, you assume that the order of your input features does not matter. For instance, you use age, sex, education to predict the salary of a person. These characteristics can be placed in positions of your MLP. For varying-size, model architectures include RNN, LSTM, Transformer. They are specifically designed for sequential data like texts and time series. These sorts of data have a natural order within their data points. They can perfectly deal with vary-size inputs. To summarize, you might use the wrong model to deal with signals with MLP. The optimal choice is to adopt RNN/Transformer.
answers question: http://stackoverflow.com/q/50216691
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87358430
type: AnswerComment
comment on: http://stackoverflow.com/a/50170302
has text: Well, at least it seems to work :) Now I have to understand it, give me some time to get my head around it, then I'll accept it. Thank you!
score: 0
type: Comment

http://stackoverflow.com/comment/87383588
type: Comment
type: QuestionComment
has text: I had to change chmod of /usr/local/lib/python3.5/dist-packages/.
score: 0
comment on: http://stackoverflow.com/q/50182155

http://stackoverflow.com/comment/87377396
comment on: http://stackoverflow.com/a/50180068
score: 0
type: Comment
type: AnswerComment
has text: I agree, though where you used `if line`, I would use `if line is not None` as if the value in the dictionary is falsey, it will fail the check even though the value was found. I think it's fair to make the assumption that the value in the dictionary's not `None` (if it is you'll probably want to just access the value and catch any exceptions), but it could very well be Falsey in many situations (e.g. having value `0`).

http://stackoverflow.com/a/50141226
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87300839
upvote count: 1
has comment: http://stackoverflow.com/comment/87300865
has comment: http://stackoverflow.com/comment/87300892
has comment: http://stackoverflow.com/comment/87300785
type: Answer
has body: As Daniel pointed out, you need to re-render the form. The basics of HTTP Form Post are: If the form is valid: save + do a HttpResponseRedirect If the form is not valid; re-render the same template with the errors Change your function to: def update(request, id): item = get_object_or_404(BookEntry, id=id) if request.method == "POST": form = UpdateForm(request.POST, instance=item) # print template error_messages = { 'error': form.errors, } if form.is_valid(): print(form.cleaned_data) post = form.save(commit=False) post.save() return HttpResponseRedirect(reverse('bms:index'), id) return render(request, 'index.html',{'form':form}) # Form invalid case is handled here; the form is reused from above; form.errors is available in the template now else: pass # Handle GET requests here
answers question: http://stackoverflow.com/q/50140945
accepted answer of: http://stackoverflow.com/q/50140945
score: 1

http://stackoverflow.com/q/50206542
accepted answer: http://stackoverflow.com/a/52174245
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52174245
answer count: 2
downvote count: 0
tagged with: django-forms
favorite count: 0
tagged with: image-gallery
type: Question
upvote count: 2
has body: I am using a modelformset_factory method with forms containing only an ImageField. The Model the forms are based on contains a user field that has a many-to-one relationship with a User Model that extends AbstractUser(See Extending User Model with Abstract User). Currently, each instance of a user has a correlating User Profile, but I would also like to allow the user to upload a gallery of images to their profile. models.py class Gallery(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='user_gallery', blank=True, null=True) def create_gallery(sender, **kwargs): if kwargs['created']: user_gallery = Gallery.objects.create(user=kwargs['instance']) user_gallery.save(); post_save.connect(create_gallery, sender=User) forms.py class GalleryForm(forms.ModelForm): image = forms.ImageField(label='FormImage') class Meta: model = Gallery fields = ['image'] views.py def EditProfile(request): GalleryFormSet = modelformset_factory(Gallery, form=GalleryForm, extra=3, max_num=3) if request.method == "POST": formset = GalleryFormSet(request.POST, request.FILES) if formset.is_valid(): for form in formset.cleaned_data: my_image = form['image'] photo = Gallery(user=request.user, image=my_image) photo.save() return render(request, 'user_handler/editprofile.html', {'formset': formset}) else: formset = GalleryFormSet() return render(request, 'user_handler/editprofile.html', {'formset': formset}) Template &lt;form id="post_form" method="post" action="" enctype="multipart/form-data"&gt; {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{form.image}} &lt;img src="{{form.image.url}}"/&gt; {% endfor %} &lt;input type="submit" name="submit" value="Submit" /&gt; &lt;/form&gt; The problem I'm have is that using {{ form.image }} produces this result: ... and using {{ form.image.url }} within an image's source tag produces absolute nothing at all. When I inspect the element I contain it in, it states the s…
possible better answer: http://stackoverflow.com/a/59282922
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/59282922
has title: How can I get the url of a Django ImageField?

http://stackoverflow.com/a/64375427
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50213271
type: Answer
has body: Sadly there are indeed very broken systems as @Steffen Ullrich explains (even though they claim to be industry standards) which aren't capable of handling fragmented TCP frames. Since my application/script is rather isolated and self-contained, I used the simpler workaround based on @Roeften 's answer which applies TCP_CORK to all connections. Warning: this workaround makes sense only in situations when you don't risk breaking any other functionality relying on requests. requests.packages.urllib3.connection.HTTPConnection.default_socket_options = [(6,3,1)]

http://stackoverflow.com/comment/87464454
has text: It iterated over the string `'upper left'` which yielded characters, and it took the first four because there's four plots.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50223388
score: 1

http://stackoverflow.com/comment/87485766
score: 0
comment on: http://stackoverflow.com/q/50175564
type: Comment
type: QuestionComment
has text: @jmh I followed the "Install Python from Source" [here](http://stackabuse.com/install-python-on-mac-osx/)

http://stackoverflow.com/a/50162207
upvote count: 2
has body: Rather than adjust the count attribute directly, just append to it 50 times to get a full list. def test_append_full(self): a = List() for i in range(50): a.append(i) with self.assertRaises(AssertionError): a.append(0) This ensures your test does not depend on any implementation-specific details of how you cap the list size. Suppose that you changed List.append to count down from 50 instead of counting up from 0? This test doesn't care; it will test for the AssertionError no matter how you decide to raise it. Note that assertions can be disabled at run-time; they are more appropriate for debugging. Instead, define your own exception to be raised when an attempt is made to append to a full list: class ListFullError(RuntimeError): pass def append(self,item): if self.count &gt; 50: raise ListFullError self.array[self.count] = item self.count += 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50162089
score: 2

http://stackoverflow.com/comment/87325846
score: 0
type: Comment
type: AnswerComment
has text: Just make sure that you transform your 'train_x' and 'train_y' into numpy arrays and that 'train_x' has only 2 columns
comment on: http://stackoverflow.com/a/50138740

http://stackoverflow.com/q/50096645
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61197320
has comment: http://stackoverflow.com/comment/87221761
has comment: http://stackoverflow.com/comment/87210775
has body: I have a 3D volume data stored in an 3-dimension array with background value 0 and volume value 1. Now I want to get arbitrary section planes of this volume. I read the answer here:How can an almost arbitrary plane in a 3D dataset be plotted by matplotlib? But it seems that the accepted answer was wrong, it generates mapped coordinates of xoy plane but not the slice coordinates. So how to get the correct shape of the slice plane? Are there any methods of transforming the mapped shape to original shape? Thanks!
linked to: http://stackoverflow.com/q/14138899
tagged with: python
tagged with: slice
score: 2
type: AnsweredQuestion
has title: Arbitrary Slice of 3D Array in Python
linked to: http://stackoverflow.com/q/11282988
upvote count: 3
answer count: 1
tagged with: arrays
accepted answer: http://stackoverflow.com/a/61197320
downvote count: 1

http://stackoverflow.com/q/50192763
tagged with: text-classification
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50192796
has title: python sklearn pipiline fit: "AttributeError: lower not found"
has answer: http://stackoverflow.com/a/50192796
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: svm
has body: I'm trying to classify sveveral text data into 3 categories using sklearn. But I'm getting "AttributeError: lower not found" when running. Code: train, test = train_test_split(df, random_state=42, test_size=0.3, shuffle=True) X_train = train.contents X_test = test.contents Y_train = train.category Y_test = test.category clf_svc = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfVectorizer(tokenizer=',', use_idf=True, stop_words="english")), ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)), ]) clf_svc = clf_svc.fit(X_train, Y_train) predicted_svc = clf_svc(X_test) print(np.mean(predicted_svc == Y_test)) Dataframe (df) consists of 2 columns: contents (long text data) and categories (text data). contents are scraped texts thus contain tens or hundreds of words, and categories are single words such as "A", "B". I've already checked past questions in stackoverflow but I could not solve this error occuring. I'd be very glad to know the solution, or problems in the code itself. Any advice and answers will be greatly appreciated. Thanks in advance.
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87430661
answer count: 1
tagged with: scikit-learn

adaboost
tag name: adaboost
type: Tag
tags question: http://stackoverflow.com/q/50143759

http://stackoverflow.com/comment/87508081
type: Comment
type: QuestionComment
has text: Wasn't sure at the time if that had done the trick, or if another problem was related. I've undeleted it.
comment on: http://stackoverflow.com/q/50093030
score: 0

http://stackoverflow.com/a/66116924
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50109243
has body: I had similar issue. Solution is to use LATERAL sqlalchemy method: subquery = select([student_list.c.project_id, student_list.c.student_list_id])\ .where(student_list.c.project_id == project.project_id)\ .limit(1)\ .lateral('students') query = select([project.c.project_name, subquery.c.project_id, subquery.c.student_list_id])\ .select_from(project.join(subquery))
downvote count: 0

http://stackoverflow.com/comment/87385440
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50183106
type: Comment
has text: Whenever I'm trying to import it to another program I get this: line 9, in deal self.value(random.randint(1,13)) AttributeError: 'Card' object has no attribute 'value'

http://stackoverflow.com/comment/87181240
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50082563
has text: If I print it then it works
type: Comment

http://stackoverflow.com/comment/87232984
score: 0
type: Comment
type: QuestionComment
has text: `\btheparticularword\b` (before that check `str.split` (with help from `str.strip`) would suffice).
comment on: http://stackoverflow.com/q/50107838

http://stackoverflow.com/q/50191185
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/87400548
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: I have this dataframe: cnpj Porte 0 453232000125 1 11543123000156 2 345676 3 121234561023456 'cnpj' is currently as float. If cnpj has '0001' in it, I want to classify 'Porte' as A. So it looks like this: cnpj Porte 0 453232000125 A 1 11543123000156 A 2 345676 3 121234561023456 I'm trying: df['Porte'].loc[(df['cnpj'].astype(int).astype(str).str.contains('0001'))]='A' But it gets me this error: TypeError: cannot convert the series to &lt;class 'int'&gt; How could I do that?
possible better answer: http://stackoverflow.com/a/50191316
accepted answer: http://stackoverflow.com/a/50191212
tagged with: python
has answer: http://stackoverflow.com/a/50191316
has answer: http://stackoverflow.com/a/50191212
has answer: http://stackoverflow.com/a/50191404
has title: Convert float column into string and test presence of string in Pandas

http://stackoverflow.com/a/50190838
has comment: http://stackoverflow.com/comment/87406056
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87403362
has body: You probably want to use beta.pdf, as with: import numpy as np from scipy import stats from scipy.optimize import curve_fit import matplotlib.pyplot as plt n = 21 x = np.linspace(0, 1, n) y = stats.beta.pdf(x, 2.5, 15, 0.3) + np.random.normal(scale=0.1, size=n) p0 = [2.0, 10.0, 0.5] popt, pcov = curve_fit(stats.beta.pdf, x, y, p0) print(popt) You may also find lmfit (https://lmfit.github.io/lmfit-py/) useful. For this, you would have to wrap stats.beta.pdf, but this gives you a lot more flexibility in putting bounds on parameters or fixing them: from lmfit import Model def beta_fcn(x, alpha, beta, loc): return stats.beta.pdf(x, alpha, beta, loc) bmodel = Model(beta_fcn) params = bmodel.make_params(alpha=2, beta=10., loc=0.5) params['alpha'].min = 1.0 result = bmodel.fit(y, params, x=x) print(result.fit_report()) with plt.style.context("ggplot"): fig, ax = plt.subplots() ax.plot(x, y, 'o') ax.plot(x, result.best_fit) ax.set_ylabel("Density") ax.set_xlabel("$x$") plt.show() This will print out Model Model(beta_fcn) Fit Statistics # fitting method = leastsq # function evals = 75 # data points = 21 # variables = 3 chi-square = 0.06244742 reduced chi-square = 0.00346930 Akaike info crit = -116.177008 Bayesian info crit = -113.043441 Variables alpha: 2.50445306 +/- 0.06843391 (2.73%) (init = 2) beta: 14.9105872 +/- 0.31198655 (2.09%) (init = 10) loc: 0.29906057 +/- 0.00190835 (0.64%) (init = 0.5) Correlations (unreported correlations are &lt; 0.100) C(alpha, beta) = 0.894 C(alpha, loc) = -0.834 C(beta, loc) = -0.564 (and, to be clear, the best fit values and uncertainties will be the same from the curve_fit example above) and a plot of
has comment: http://stackoverflow.com/comment/87405488
score: 1
accepted answer of: http://stackoverflow.com/q/50182681
downvote count: 1
answers question: http://stackoverflow.com/q/50182681
has comment: http://stackoverflow.com/comment/87406431
type: Answer
has comment: http://stackoverflow.com/comment/87405653
upvote count: 2

http://stackoverflow.com/a/50194605
accepted answer of: http://stackoverflow.com/q/50190480
has body: Your limit setting works correctly. You made mistake while debugging. As Mikhail Gerasimov pointed in the comment, you put your print() call in wrong place - it must be inside session.get() context. In order to be confident that limit is respected, I tested your code against simple logging server - and test shows that the server receives exactly that number of connections that you set in TCPConnector. Here is the test: import asyncio import aiohttp loop = asyncio.get_event_loop() class SilentServer(asyncio.Protocol): def connection_made(self, transport): # We will know when the connection is actually made: print('SERVER |', transport.get_extra_info('peername')) async def get_images(url, session): chunk_size = 100 # This log doesn't guarantee that we will connect, # session.get() will freeze if you reach TCPConnector limit print(f'CLIENT | Making request to {url}') async with session.get(url=url) as r: while True: chunk = await r.content.read(chunk_size) if not chunk: break urls = [f'http://127.0.0.1:1337/{x}' for x in range(20)] conn = aiohttp.TCPConnector(limit=3) session = aiohttp.ClientSession(connector=conn, loop=loop) async def test(): await loop.create_server(SilentServer, '127.0.0.1', 1337) await asyncio.gather(*(get_images(url, session=session) for url in urls)) loop.run_until_complete(test())
type: AcceptedAnswer
downvote count: 0
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/50190480
type: Answer

http://stackoverflow.com/a/50180839
answers question: http://stackoverflow.com/q/50172958
has body: thanks for the answers. For one reason or another they both did not work, but they were useful. I found a solution, ancient, not very elegant, but working: import pandas as pd data = pd.read_csv('enummixed.txt', header = None, low_memory=False) data = data.drop(data.columns[[0]],axis=1) for i in data.index: k=0 for j in range(0,15): if (data.iloc[i,j]==data.iloc[i,j+16]) is True: k+=1 if k==15: print(data.loc[i], file=open("symmetric_ne.txt", "a"))
type: Answer
score: 0

http://stackoverflow.com/q/50074803
has comment: http://stackoverflow.com/comment/87165894
type: Question
has title: How to handle the download response received from a server in javascript
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4545311
tagged with: django
has comment: http://stackoverflow.com/comment/87165895
tagged with: ajax
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I try to send a download request to the server using ajax, and then the backend confirms that the current user has permission to download the current file and decides whether to send an error message or download the file to the browser. However, browsers can only handle error messages but cannot process download response, I have no ideal to solve this problem This the ajax code: &lt;script type="text/javascript"&gt; function fdownload(file_pk){ $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ url:"{% url 'file_download' %}", type:"POST", data:{"file_pk":file_pk}, success:function(error_message){ if(error_message == "true"){ $.Pop('you have no permission to download this file！',{Animation:'showSweetAlert'}); } else{ ....... } }, }); } This is backend code: def download_util(download_file): file=open(download_file.file.path,'rb') response =FileResponse(file) response['Content-Type']='application/octet-stream' response['Content- Disposition']='attachment;filename='+"".join(download_file.file.name.split('/')[-1:]).encode('utf-8').decode('ISO-8859-1') return response def file_download(request): file_pk = request.POST["file_pk"] download_file = get_object_or_404(models.Download_file,pk = file_pk) user_group = [] file_group = [] if request.user.is_authenticated: for e in get_object_or_404(User,username = request.user).groups.all(): user_group.append(e.name) for e in download_file.download_permission.all(): file_group.append(e.name) if 'anyone' in file_group or list_in(user_group,file_group): return download_util(download_file) else: return HttpResponse('true')

http://stackoverflow.com/comment/87182079
has text: the only difference is that randint is inclusive of 100, randrange is not. randrange shouldn't be outputting decimals.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50083093

http://stackoverflow.com/comment/87399180
comment on: http://stackoverflow.com/a/50188006
type: Comment
score: 0
has text: I haven't used Tornado so far, but I could take a look for some other tutorials.
type: AnswerComment

http://stackoverflow.com/comment/87405927
comment on: http://stackoverflow.com/q/50194338
score: 0
type: Comment
has text: I only have rel and eta. I only know that eta has the same size of the number of zeros in rel. Since rel contains 6 zeros, eta has size 6. I don't know where the eta elements come from...
type: QuestionComment

http://stackoverflow.com/comment/87406858
type: QuestionComment
score: 8
type: Comment
has text: These two columns are constant and have a standard deviation of 0. Hence you are dividing by 0. Hence NaN.
comment on: http://stackoverflow.com/q/50194821

http://stackoverflow.com/a/50078850
has body: Here are the steps to achieve this. Add loading button with hidden class. When you click update Product button, following things should happen. $(".update_button").on("click", function(e){ $(".loading_button").show(); // show loading button $(".update_button").hide(); // hide update button $.ajax({}) // send ajax request to update product, on success, hide loader and show update button });
type: Answer
answers question: http://stackoverflow.com/q/50078543
score: 0

http://stackoverflow.com/comment/87477166
type: QuestionComment
type: Comment
has text: yeah, I mentioned those points while suggesting the solutions.. try the perl one..
score: 0
comment on: http://stackoverflow.com/q/50229641

http://stackoverflow.com/q/50110269
upvote count: 2
tagged with: curve
has title: Find tangent line satisfying certain requirements to curve equation with optimizer?
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: optimization
has body: I have what seems to be a relatively simplistic geometric optimization question, but one in which I have absolutely no experience. I have a bunch of data that I am fitting a spline through to find its equation, such as the below, And this is the equation I fit to the dots, with the code, import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline plt.figure(figsize=(6.5, 4)) plt.axis([0.017,.045,.0045,.014]) plt.scatter(x,y,color='orange') spl = UnivariateSpline(x, y) plt.plot(xs, spl(xs), 'b', lw=3) plt.show() And what I want to do is find the equation of a line, y = mx + b, with a certain y-intercept a that hits the blue curve at some tangent point. So, for example, if my line has to pass through y=.006, what is the slope b of its line that makes it hit the blue line's tangent? I though about doing a regular optimization over the derivatives of the curve at a large amount of points, but I am unsure how to set this up in a rigorous way.
type: Question
tagged with: derivative
score: 1
has comment: http://stackoverflow.com/comment/87237819
downvote count: 1
has comment: http://stackoverflow.com/comment/87237831
favorite count: 0
has comment: http://stackoverflow.com/comment/87237828
has comment: http://stackoverflow.com/comment/87237811

http://stackoverflow.com/comment/87244181
type: Comment
type: QuestionComment
score: 0
has text: I did try it, i got a fully black image.
comment on: http://stackoverflow.com/q/50092730

http://stackoverflow.com/comment/121214519
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/68581985
has text: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

http://stackoverflow.com/comment/87212253
type: Comment
type: QuestionComment
has text: I would suggest to make list box or links for each row, on click of which you can launch `OptionMenu` or just a grid with `entry` or labels having all those details.
comment on: http://stackoverflow.com/q/50097889
score: 1

http://stackoverflow.com/q/50099765
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87228239
has body: I just found out that mapping a list is in e.g. Python and Haskell is done like this: newlist = map(function, somelist) In e.g. Kotlin and Dart it is done like this: newlist = somelist.map(function) I am wondering what advantages each solution has over the other? The Python/Haskell implementation is more "functional" isn´t it?
has answer: http://stackoverflow.com/a/50100082
tagged with: map-function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50100065
has answer: http://stackoverflow.com/a/50100098
tagged with: python
tagged with: haskell
upvote count: 4
tagged with: kotlin
answer count: 4
downvote count: 4
score: 0
tagged with: functional-programming
has answer: http://stackoverflow.com/a/50100359
has title: map() as class member versus map() as independent function?
has comment: http://stackoverflow.com/comment/87221425

http://stackoverflow.com/comment/87470761
comment on: http://stackoverflow.com/a/50225479
type: Comment
has text: LineCollection fixed it. Thank you for the help.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50218124
type: Question
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50230564
tagged with: selenium
tagged with: web-crawler
has title: Selecting an option from an optgroup with selenium and python
has body: I would like to choose a value from this optgroup which should then give me a dropdown of links. Search all text Buyer Farmer/Rancher Farmers Market Fishery Food Bank Here is my code so far: driver = webdriver.Chrome('/path/to/chromedriver') driver.get("https://foodmarketmaker.com/main/mmsearch") iframe = driver.find_element_by_tag_name("iframe") driver.switch_to.frame(iframe) select = Select(driver.find_element_by_class_name("select2-hidden- accessible")) select.select_by_value("bt:Farmer/Rancher") links = driver.find_elements_by_tag_name('a') print(links) for link in links: print(link.get_attribute('href')) I either get an exception that the element does not exist, or when I access by index, i get an ElementNotVisibleException due to the aria-hidden attribute being true. Is there any way around this?
has answer: http://stackoverflow.com/a/50219197
favorite count: 0
has comment: http://stackoverflow.com/comment/87454330

http://stackoverflow.com/a/50133991
has comment: http://stackoverflow.com/comment/87286238
has body: This error raise usually when you trying to assign a instance.id instead of instance. In the django, you are need to saaign a instance to all the ForeignKey fields. Instance Ex: mat = Material.objects.all()[0]
answers question: http://stackoverflow.com/q/50133816
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50227625
tagged with: python
has body: In pandas, I want to map strings to integers, but strangely, the other column covert strings to integers as I wanted, but one column convert strings to floats, and one level doesn't convert correctly and it becomes NaN, the code: data2['post'].map({'集体企业人员':0, '在岗职工':1, '农电工':2}) 0 0.0 1 0.0 2 0.0 3 1.0 4 1.0 5 1.0 6 1.0 7 0.0 8 0.0 9 0.0 10 NaN 11 1.0 12 1.0 13 1.0 14 NaN 15 1.0 16 0.0 17 0.0 18 NaN 19 1.0 20 NaN 21 1.0 22 1.0 23 1.0 24 1.0 25 1.0 26 1.0 27 1.0 28 0.0 How can I deal with it?
accepted answer: http://stackoverflow.com/a/50227676
type: AnsweredQuestion
tagged with: pandas
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
score: -1
type: Question
has title: how to map string to integer in python
has answer: http://stackoverflow.com/a/50227676

http://stackoverflow.com/q/50166813
accepted answer: http://stackoverflow.com/a/50168178
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: global-variables
has answer: http://stackoverflow.com/a/50168178
tagged with: tensorflow
type: Question
has title: What variables does global_variables_initializer() do the initialization?
has body: In tensorflow, after I use cell.zero_state() to initialize the cell state and hidden state, I should initialize the global variables or the RNN cell won't run. However, I wonder how does it globalize(initialize variables range?) and what variables does it globalize(bias? weight? activation function?) ? enter link description here I think the parameters that should initialize is non other than: weight, bias, activation function in each neuron. What does the global_variables_initializer actually do? Thanks a lot!

http://stackoverflow.com/a/50180763
upvote count: 2
score: 2
downvote count: 0
has body: Since you commented that you have control over the format of the file, changing it to proper CSV format (with or without headers) will be much easier than coming up with a custom ad-hoc solution. African elephant,6654.000,5712.000,-999.0,-999.0,3.3,38.6,645.0,3,5,3 African giant pouched rat,1.000,6.600,6.3,2.0,8.3,4.5,42.0,3,1,3 Arctic Fox,3.385,44.500,-999.0,-999.0,12.5,14.0,60.0,1,1,1 Arctic ground squirrel,.920,5.700,-999.0,-999.0,16.5,-999.0,25.0,5,2,3 Asian elephant,2547.000 4603.000,2.1,1.8,3.9,69.0,624.0,3,5,4 Baboon,10.550,179.500,9.1,.7,9.8,27.0,180.0,4,4,4 Then all you have to do is import csv with open('test_files/test.csv') as f: lines = list(csv.reader(f)) print(lines) # [['African elephant', '6654.000', '5712.000', '-999.0', '-999.0', '3.3', '38.6', '645.0', '3', '5', '3'], # ['African giant pouched rat', '1.000', '6.600', '6.3', '2.0', '8.3', '4.5', '42.0', '3', '1', '3'], # ['Arctic Fox', '3.385', '44.500', '-999.0', '-999.0', '12.5', '14.0', '60.0', '1', '1', '1'], # ['Arctic ground squirrel', '.920', '5.700', '-999.0', '-999.0', '16.5', '-999.0', '25.0', '5', '2', '3'], # ['Asian elephant', '2547.000 4603.000', '2.1', '1.8', '3.9', '69.0', '624.0', '3', '5', '4'], # ['Baboon', '10.550', '179.500', '9.1', '.7', '9.8', '27.0', '180.0', '4', '4', '4']]
answers question: http://stackoverflow.com/q/50180465
type: Answer

http://stackoverflow.com/comment/102944292
type: Comment
type: AnswerComment
score: 4
has text: Such a bummer that the easiest method requires writing the init yourself, this defeating one if the biggest wins dataclasses brings to the table!
comment on: http://stackoverflow.com/a/58283543

http://stackoverflow.com/comment/87396268
comment on: http://stackoverflow.com/q/50189726
score: 0
type: Comment
has text: Look at str.format() instead.
type: QuestionComment

http://stackoverflow.com/comment/87267218
comment on: http://stackoverflow.com/q/50124526
type: QuestionComment
type: Comment
score: 0
has text: The only syntax error in this code is in the first line. When the first line's indentation is fixed, it runs without problems. You'll have to post a [mcve].

http://stackoverflow.com/comment/87418669
comment on: http://stackoverflow.com/a/50200792
has text: Do you know what this means? ValueError Traceback (most recent call last) <ipython-input-94-3c6057213311> in <module>() 1 E = np.zeros((n**2,nvar)) ----> 2 E[:n**2,:n**2] = np.diag(np.ones(n**2)) 3 b = np.zeros(n**2).reshape(n**2,-1) 4 b[:n**2] = M.reshape(n**2,-1) 5 ValueError: could not broadcast input array from shape (225,225) into shape (225,15)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87253553
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50086001
has text: @GrahamDumpleton i don't configure the python-home option of WSGIDaemonProcess,i added two options in the movie.wsgi: sys.path.insert(0, '/home/virtualenvs/movie-3QK-yS3b/lib/python3.6/site-packages/') sys.path.insert(0, '/data/movie') it works
score: 0

http://stackoverflow.com/comment/87464551
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50222720
has text: @jwodder @scnerd Several domain areas that I'm trying to learn here. Mostly OpenStack and the API, so I stumbled across the Python example and went with it. I will look for `python requests` examples and see if I can work it out. Thanks for your responses.
score: 0

http://stackoverflow.com/comment/87490449
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50220277
type: AnswerComment
has text: Worked like a charm, thanks again! Answer accepted as well.

http://stackoverflow.com/a/50101041
answers question: http://stackoverflow.com/q/50090714
score: 1
type: Answer
has body: As you can see in the documentation, torch.LongTensor uses the data type '64-bit integer (signed)'. So what you are seeing in your output is actually an integer, it's only the exponential notation.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87219052

http://stackoverflow.com/q/50121110
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50121150
accepted answer: http://stackoverflow.com/a/50121150
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/988228
has body: i have a file that looks like so: {"Apples": 14, "Bananas": 14, "Pineapples": 0, "Pears": 8} im trying to figure out how i can read this file in and be able to use it so that i can for example reduce the "apples" value to lower i.e 13 from 14
has title: how to read and manipulate a dictionary and file python 2.7
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87259930
score: 1
duplicate of: http://stackoverflow.com/q/988228
answer count: 1

http://stackoverflow.com/q/50135334
downvote count: 0
has comment: http://stackoverflow.com/comment/87288779
has answer: http://stackoverflow.com/a/71371974
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53276928
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87289290
has comment: http://stackoverflow.com/comment/91293762
tagged with: pipenv
possible better answer: http://stackoverflow.com/a/52871751
has comment: http://stackoverflow.com/comment/87296510
upvote count: 20
answer count: 5
accepted answer: http://stackoverflow.com/a/50166693
tagged with: python
has comment: http://stackoverflow.com/comment/87347533
has body: Today, I installed Pipenv via pip install pipenv As mentioned in the documentation I went to a test directory and created a new virtual environment using pipenv shell and tried to install a package via pipenv install numpy I got the following error message: Installing numpy… ⠧ Error: An error occurred while installing numpy! Traceback (most recent call last): File "/Users/florian/.local/share/virtualenvs/test-bJfQ6Jzk/bin/pip", line 7, in &lt;module&gt; from pip._internal import main ModuleNotFoundError: No module named 'pip._internal' This error occurs even after reinstalling pipenv, deleting all files and recreate the environment. It also had no impact if I ran pipenv install numpy inside or outside the environment. Python 3.6.3 Pipenv 11.10.1 Thank you in advance.
has answer: http://stackoverflow.com/a/50166693
has answer: http://stackoverflow.com/a/73743813
has comment: http://stackoverflow.com/comment/87351143
has comment: http://stackoverflow.com/comment/87288684
type: AnsweredQuestion
score: 20
linked to: http://stackoverflow.com/q/49940813
has answer: http://stackoverflow.com/a/52871751
has title: Pipenv-Error: ModuleNotFoundError: No module named 'pip._internal'
duplicate of: http://stackoverflow.com/q/49940813

http://stackoverflow.com/comment/87328765
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50155571
has text: What you mean by "showing sth on display"?
type: Comment

http://stackoverflow.com/comment/87302427
has text: I'd upvote but it's not letting me. Mods negged me hard when I asked a question they didn't like. Sorry man.
comment on: http://stackoverflow.com/a/50141452
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87268316
type: Comment
comment on: http://stackoverflow.com/a/50124958
type: AnswerComment
score: 1
has text: [This might be helpful in understanding how cmdlets/functions in a pipeline behaves in PowerShell](https://stackoverflow.com/questions/48522415/are-the-cmdlets-in-a-pipeline-executing-in-parallel/48523475#48523475)

http://stackoverflow.com/comment/87183738
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50083839
has text: @RayToal My interpretation of the question (which I admit could be wrong) is that `myFunction` returns False for values of `x` less than some number `N`, and returns True for all values of `x` greater than or equal to `N`. And the goal is to find `N`. So a binary search can be used to find `N` while calling `myFunction` no more than 35 times. But `next` will do a linear search, and could call `myFunction` up to 34 billion times.

http://stackoverflow.com/q/50141544
tagged with: python
has answer: http://stackoverflow.com/a/50143559
accepted answer: http://stackoverflow.com/a/50143559
tagged with: apache-kafka
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
has title: Kafka to Pandas dataframe without Spark
favorite count: 0
type: Question
score: 5
upvote count: 5
answer count: 1
has body: I am reading streaming data from a kafka topic and I want to store some parts of it in a pandas dataframe. from confluent_kafka import Consumer, KafkaError c = Consumer({ 'bootstrap.servers': "###", 'group.id': '###', 'default.topic.config': { 'auto.offset.reset': 'latest' } }) c.subscribe(['scorestore']) while True: msg = c.poll(1.0) if msg is None: continue if msg.error(): if msg.error().code() == KafkaError._PARTITION_EOF: continue else: print(msg.error()) break print('Received message: {}'.format(msg.value().decode('utf-8'))) c.close() The received message is a json { "messageHeader" : { "messageId" : "4b604b33-7256-47b6-89d6-eb1d92a282e6", "timestamp" : 152520000, "sourceHost" : "test", "sourceLocation" : "test", "tags" : [ ], "version" : "1.0" }, "id_value" : { "id" : "1234", "value" : "333.0" } } I am trying to create a dataframe that will have the timestamp, id and value columns, for example timestamp id value 0 152520000 1234 333.0 Is there a way to accomplish this without parsing the json message and appending the values I need row by row to the dataframe?
downvote count: 0

http://stackoverflow.com/a/50181495
type: Answer
has comment: http://stackoverflow.com/comment/101134835
has comment: http://stackoverflow.com/comment/87384130
has comment: http://stackoverflow.com/comment/87380274
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50180980
downvote count: 0
has comment: http://stackoverflow.com/comment/101059138
has body: One way to approach this would be to create two routes - one that starts the counter and and that returns the count itself. Note, I've added "threaded=True" to allow multiple calls to be made. from flask import Flask app = Flask(__name__) @app.route('/') def main(): """Say hello""" global index_counter print(index_counter) return "Hello World: %s" % str(index_counter) @app.route('/counter') def counter(): global index_counter index_counter = 0 while True: index_counter += 1 if __name__ == '__main__': app.run(threaded=True) Now, you can first invoke: http://localhost/counter This will start the counter. And then at any point you can invoke: http://localhost And the should print out the counter value.

http://stackoverflow.com/q/50147410
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50147532
has answer: http://stackoverflow.com/a/50147518
linked to: http://stackoverflow.com/q/12265451
accepted answer: http://stackoverflow.com/a/50147495
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: This is a part of our assignments for Computer Programming in high school. These are the instructions. https://prospect.schoolloop.com/file/1407107943880/1376109333800/2888156401519472863.pdf def c7(): myList = [7, 10, 94, 2, 54, 2, 19, 4, 11] print (myList) valueToSearch = int(input("Enter the value to search for: ")) for n in range(0, len(myList)): if valueToSearch == myList[n]: print (myList[n], "is in index", n) elif (n == len(myList)-1) and (valueToSearch != myList[n]): print ("No matches") For example: &gt;&gt;&gt; c7() [7, 10, 94, 2, 54, 2, 19, 4, 11] Enter the value to search for: 1 No matches &gt;&gt;&gt; c7() [7, 10, 94, 2, 54, 2, 19, 4, 11] Enter the value to search for: 7 (7, 'is in index', 0) No matches The last line "No matches" is unexpected when the input is 7.
score: 0
has comment: http://stackoverflow.com/comment/87313085
has answer: http://stackoverflow.com/a/50147497
possible better answer: http://stackoverflow.com/a/50147497
has answer: http://stackoverflow.com/a/50147495
has title: Elif statement printing when it shouldn't
type: Question

http://stackoverflow.com/comment/87476720
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50229671
has text: I added an edit. `add_word()` in the original code is using global variables, and the arguments `self` and `var` were going unused. Also, `self` is generally a keyword used in class methods, not in functions.
type: Comment

http://stackoverflow.com/q/50224772
favorite count: 0
has comment: http://stackoverflow.com/comment/87467215
tagged with: python-3.x
type: AnsweredQuestion
tagged with: algorithm
has answer: http://stackoverflow.com/a/50224959
possible better answer: http://stackoverflow.com/a/50224959
tagged with: python
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/87467194
has body: I have to design an algorithm that compares two sorted lists of the same length and return the number of common values between them. So if I have two lists a = [2, 9, 15, 27, 36, 40] and b = [9, 11, 15, 23, 36, 44], the algorithm should return the value of 3 as 9, 15 and 36 are present in both lists. I know that there might be an easier to do with using sets, but since I'm trying to learn data structures and algorithms I'd prefer to do it the longer(harder way). My current code uses any array merge algorithm which is non-working at the moment as I'm still confused as to r1 and r2, though i think they would be the right most element in the array, but I don't know how to get that. eg. r1 = 40 (from list a), and r2 = 44 (from list b)? global a a = [2, 9, 15, 27, 36, 40] global b b = [9, 11, 15, 23, 36, 44] global c c = [] def merge (a1, a, r1, a2, b, r2, c, list3): i = a j = b k = c r1 = r2 = while i &lt;= r1 and j &lt;= r2: if a1[i]&lt;=a2[j]: a3[k] = a1[i] i += 1 elif a3[k] &gt;= a2[j]: j += 1 k += 1 while i &lt;= r1: a3[k] = a1[i] i += 1 k += 1 while j &lt;= r2: a3[k] = a2[j] j += 1 k += 1 Thank you for the help and feedback.
type: Question
has comment: http://stackoverflow.com/comment/87467554
answer count: 3
has answer: http://stackoverflow.com/a/50226521
tagged with: array-merge
accepted answer: http://stackoverflow.com/a/50226521
has comment: http://stackoverflow.com/comment/87467128
downvote count: 0
has answer: http://stackoverflow.com/a/50227609
has title: Python algorithm to compare two sorted lists and count how many elements are the same
has comment: http://stackoverflow.com/comment/87467291

http://stackoverflow.com/a/50181068
answers question: http://stackoverflow.com/q/50180704
type: Answer
has body: Just realized a typo was the issue. Oopsies..
score: 0
has comment: http://stackoverflow.com/comment/87384579

http://stackoverflow.com/q/50225723
downvote count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/87469459
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/50243790
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87469538
tagged with: gradient-descent
has answer: http://stackoverflow.com/a/78737891
possible better answer: http://stackoverflow.com/a/78737891
has comment: http://stackoverflow.com/comment/87472203
tagged with: python
tagged with: mini-batch
tagged with: import
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50243790
answer count: 2
score: 5
has title: Is there a Python library where I can import a gradient descent function/method?
has body: One way to do gradient descent in Python is to code it myself. However, given how popular a concept it is in machine learning, I was wondering if there is a Python library that I can import that gives me a gradient descent method (preferably mini-batch gradient descent since it's generally better than batch and stochastic gradient descent, but correct me if I'm wrong). I checked NumPy and SciPy but couldn't find anything. I have no experience with TensorFlow but looked through their online API. I found tf.train.GradientDescentOptimizer, but there is no parameter that lets me choose a batch size, so I'm rather fuzzy on what it actually is. Sorry if I sound naive. I'm self-learning a lot of this stuff.

http://stackoverflow.com/a/73450108
score: 0
has body: A solution has been discussed, but not yet implemented. IDLE Shell - input() blocks output from another thread #83905. It seems the only way to work around it using IDLE is to launch IDLE with a '-n' command line option to stop IDLE from launching its subprocess.
type: Answer
answers question: http://stackoverflow.com/q/50108354

http://stackoverflow.com/a/50194321
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50183277
has body: Here's something that I think does what you desire. To test it I had to create some sample input data since you don't have any in your question—which is what is going on at the very beginning of the snippet. For each time range interval, it creates a separate "bucket" which contains the corresponding time values within the time range. Note that some time values may end up being place in two buckets since the interval ranges overlap. from pprint import pprint import random random.seed(42) # Create same "random" sequence each run for testing. # First create some test data. INTERVAL = 0.02 # 20 ms start = 37913 times = [] nvalues = 2, 3, 4, 2, 1 # Number of values in each interval. for i, nvalue in enumerate(nvalues): lowerbounds = start + i*INTERVAL upperbounds = start + (i+1)*INTERVAL for _ in range(nvalue): times.append(random.uniform(lowerbounds, upperbounds)) print('There are {} time values:'.format(len(times))) times.sort() # Put into ascending order. pprint(times) #======= # Split the times up into "buckets" of values depending on their range. HALF_INTERVAL = INTERVAL / 2 brackets = [] print() print('Time brackets:') st = int(min(times)) for i in range(4): begin = round(st + i*HALF_INTERVAL, 6) end = round(begin + INTERVAL, 6) brackets.append((begin, end)) print(' ', begin, end) buckets = [[] for _ in range(len(brackets))] # Create empty buckets. for t in times: # Put each time in the cooresponding bucket of times. for i, (begin, end) in enumerate(brackets): if begin &lt;= t &lt;= end: buckets[i].append(t) print() print('Stored in corresponding interval bucket:') for i, bracket in enumerate(brackets): print('bucket[{}]: range: {!r}, values: {}'.format( i, bracket, buckets[i])) Sample Output: There are 12 time values: [37913.0005002151, 37913.01278853597, 37913.02446421476, 37913.025500586366, 37913.03472942428, 37913.04173877665, 37913.048438436395, 37913.05353398975, 37913.05784359135, 37913.060595944386, 37913.064372759494, 37913.09010710576] Time brackets: 37…
answers question: http://stackoverflow.com/q/50183277
type: Answer
has comment: http://stackoverflow.com/comment/87651628
has comment: http://stackoverflow.com/comment/87651862
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/50093149
has body: Change X = df_cryptoindependent_variables for X = df_crypto[independent_variables] independent_variables is already a list, so no need to put double brackets.
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50093130
has comment: http://stackoverflow.com/comment/87202434
accepted answer of: http://stackoverflow.com/q/50093130
type: AcceptedAnswer

http://stackoverflow.com/a/50422753
has comment: http://stackoverflow.com/comment/87912586
answers question: http://stackoverflow.com/q/50184145
type: Answer
has body: So I am wondering if your input is not in int32 format then this will not work anymore. Meaning: [[0.0], [0.0], [0.0], [0.0], [0.0]] if the position 4 data is 31.11 for example instead of 31. Then it can no longer work?
has comment: http://stackoverflow.com/comment/87872440
score: 0

qwidget
tag name: qwidget
type: Tag
tags question: http://stackoverflow.com/q/50161900

http://stackoverflow.com/comment/87390029
type: AnswerComment
has text: I have tried this `for key in y: k = "{0}".format(key) z = "{0}".format(key) + ".csv" k.to_csv(z, sep=',')` but it fails.
comment on: http://stackoverflow.com/a/50185562
score: 0
type: Comment

http://stackoverflow.com/a/50076040
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50075719
score: 4
answers question: http://stackoverflow.com/q/50075719
downvote count: 0
has comment: http://stackoverflow.com/comment/87214764
has body: You can simply overwrite the values of your image with the values of your logo. Your image is a WxHx3 array, and your logo is W1xH1x3, assuming W &lt; W1 and H &lt; H1. Having said that, you can simply: background[offset[0]:offset[0]+img_w,offset[1]:offset[1]+img_h] = img A simple test: import cv2 import numpy background = numpy.zeros((100,100,3)) img = numpy.ones((10,10,3)) offset = numpy.array((10,10)) background[offset[0]:offset[0]+img.shape[0],offset[1]:offset[1]+img.shape[1]] = img cv2.imshow("test", background) cv2.waitKey(0) cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/87249464
has comment: http://stackoverflow.com/comment/87278284
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50139032
score: 0
has comment: http://stackoverflow.com/comment/87315962
has comment: http://stackoverflow.com/comment/87299225
has comment: http://stackoverflow.com/comment/87296932
tagged with: utf-8
has title: string split function in python
has comment: http://stackoverflow.com/comment/87325624
has body: I am using : Python 2.6.6 I have the following sample code. scnd_dic.txt, contains Chinese char; I have problem with output of split. Is there any way to see Chinese char in the result of split instead of unicode? print(line): 勀 KE4 print(line.split() ): [u'\xe5\x8b\x80', 'KE4'] u'\xe5\x8b\x80' vs 勀; import codecs with codecs.open('scnd_dic.txt', 'r', encoding='utf-8') as f: #d = dict(line.rstrip().split(None, 1) for line in f) for line in f: print(line) print(line.split() ) in side scnd_dic.txt, there are some rows like following: 勀 KE4 垸 HUAN2 昇 SHENG1 洩 XIE4 犇 BEN1 缐 XIAN4 Output: 勀 KE4 [u'\xe5\x8b\x80', u'KE4'] 垸 HUAN2 [u'\xe5\x9e\xb8', u'HUAN2'] 昇 SHENG1 [u'\xe6\x98\x87', u'SHENG1'] 洩 XIE4 [u'\xe6\xb4\xa9', u'XIE4'] 犇 BEN1 [u'\xe7\x8a\x87', u'BEN1'] 祕 MI4 [u'\xe7\xa5\x95', u'MI4'] 缐 XIAN4
type: Question
has comment: http://stackoverflow.com/comment/87301802
tagged with: split
has comment: http://stackoverflow.com/comment/87297203
tagged with: encoding
has comment: http://stackoverflow.com/comment/87316902
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50156913
answer count: 1
has comment: http://stackoverflow.com/comment/87326323
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87329396
has comment: http://stackoverflow.com/comment/87297095
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50151469
duplicate of: http://stackoverflow.com/q/3344115
has comment: http://stackoverflow.com/comment/103530130
has title: How to protect python scripts?
answer count: 1
upvote count: 1
tagged with: python
type: UnansweredQuestion
score: -2
has body: When I prepared to distribute my first python application several years ago, I had to face a problem: how to obfuscate python scripts so no clear code shown to my customer?
type: Question
linked to: http://stackoverflow.com/q/3344115
downvote count: 3
has answer: http://stackoverflow.com/a/50151470
favorite count: 0

http://stackoverflow.com/q/50202238
answer count: 21
downvote count: 0
has answer: http://stackoverflow.com/a/58488461
has answer: http://stackoverflow.com/a/55713417
has answer: http://stackoverflow.com/a/58250822
tagged with: python-requests
tagged with: chardet
favorite count: 0
possible better answer: http://stackoverflow.com/a/53032616
type: Question
has answer: http://stackoverflow.com/a/56289848
has title: Python (pip) - RequestsDependencyWarning: urllib3 (1.9.1) or chardet (2.3.0) doesn't match a supported version
has answer: http://stackoverflow.com/a/54557853
has answer: http://stackoverflow.com/a/59405150
has answer: http://stackoverflow.com/a/53032616
linked to: http://stackoverflow.com/q/49768770
has answer: http://stackoverflow.com/a/53283374
score: 116
has answer: http://stackoverflow.com/a/58250912
has answer: http://stackoverflow.com/a/54747174
has answer: http://stackoverflow.com/a/56286650
linked to: http://stackoverflow.com/q/49881448
upvote count: 116
has answer: http://stackoverflow.com/a/58649233
has answer: http://stackoverflow.com/a/77215664
has answer: http://stackoverflow.com/a/64781424
tagged with: pip
has answer: http://stackoverflow.com/a/56170328
tagged with: python
has answer: http://stackoverflow.com/a/74203213
has answer: http://stackoverflow.com/a/52715820
has answer: http://stackoverflow.com/a/57401964
has answer: http://stackoverflow.com/a/55504365
type: AnsweredQuestion
has body: I found several pages about this issue but none of them solved my problem. Even if I do a : pip show I get : /usr/local/lib/python2.7/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.9.1) or chardet (2.3.0) doesn't match a supported version! RequestsDependencyWarning) Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module> load_entry_point('pip==1.5.6', 'console_scripts', 'pip')() File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 480, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2691, in load_entry_point return ep.load() File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2322, in load return self.resolve() File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2328, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 74, in <module> from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/usr/lib/python2.7/dist-packages/pip/vcs/mercurial.py", line 9, in <module> from pip.download import path_to_url File "/usr/lib/python2.7/dist-packages/pip/download.py", line 22, in <module> import requests, six File "/usr/local/lib/python2.7/dist-packages/requests/__init__.py", line 90, in <module> from urllib3.exceptions import DependencyWarning ImportError: cannot import name DependencyWarning What I did : pip install --upgrade chardet but as explain up, it gaves me the same error. so I did : sudo apt remove python-chardet and unistalling all his dependecies. After I reinstall it -> the same :'( I did the same for python-pip. After reinstalling it -> the same. Here are the lines about urllib3 and chardet versions needed : extract of /usr/local/lib/python2.7/dist-packages/requests/__init__.py : # Check urllib3 for compatibility. major, minor, pa…
accepted answer: http://stackoverflow.com/a/50212636
has answer: http://stackoverflow.com/a/56131895
tagged with: urllib3
has answer: http://stackoverflow.com/a/50212636

http://stackoverflow.com/comment/87443237
type: Comment
comment on: http://stackoverflow.com/q/50211040
score: 1
has text: I tried the exact code in jupyter and it worked like a charm.I think the issue is with some settings in spyder since i am using spyder
type: QuestionComment

http://stackoverflow.com/q/50228061
has comment: http://stackoverflow.com/comment/88049356
score: 0
has comment: http://stackoverflow.com/comment/87473335
answer count: 0
has comment: http://stackoverflow.com/comment/87473383
has comment: http://stackoverflow.com/comment/87475810
type: Question
has comment: http://stackoverflow.com/comment/87473285
has body: When debugging Python code, Chinese variables are displayed as Unicode.
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/87473649
has title: When debugging python code, Chinese variables are displayed as Unicode
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50084207
has comment: http://stackoverflow.com/comment/87192364
type: Answer
has comment: http://stackoverflow.com/comment/87191514
accepted answer of: http://stackoverflow.com/q/50084022
has comment: http://stackoverflow.com/comment/87191121
score: 0
has comment: http://stackoverflow.com/comment/87190686
has body: Assuming your language is C-like, f 2 is not a valid function call; it must be written f(2). But your grammar says: Rule 5 function_call -&gt; ID function_call_args Rule 6 function_call_args -&gt; expression which certainly allows f 2 (which is an ID followed by an expression). On the other, that grammar does not allow f() nor f(1,2). (The third production function_call_args -&gt; function_call is redundant since you have function_call_args -&gt; expression and expression -&gt; function_call. Redundant productions create parsing conflicts, so I left it out.) What you need function_call to be is something pretty similar to function_definition, with explicit parentheses and an optional list of expressions.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50084022
has comment: http://stackoverflow.com/comment/87190443

http://stackoverflow.com/q/50110351
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87308186
has comment: http://stackoverflow.com/comment/87349969
linked to: http://stackoverflow.com/q/48289129
has comment: http://stackoverflow.com/comment/87310571
duplicate of: http://stackoverflow.com/q/48289129
has body: In making some half polar scatter plots with matplotlib, I found that the figures contained far more white space than the same data plotted on a Cartesian plot. The problem seems to be that the PolarAxes class assumes a data ratio of 1, even for a half polar plot, and I can't find a way to change it. There is a get_data_ratio operation, but no set_data_ratio. I marked the 4 corners of the axis in each case with A# and the four corners of the figure with F# to highlight the problem. In the polar case, the axis corners are nowhere near the corners of the range of the graph, so the vertical extent of the graph limits its overall size. Can anyone give me guidance on how to adjust the axis to conform more closely to the range of the graph? The code I used to generate both graphs, based on the matplotlib polar example is below. import argparse import numpy as np import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description='Plot max particle temperature at initial particle location') parser.add_argument('--polar', action='store_true', help='use polar grid') args = parser.parse_args() polar = args.polar # Fixing random state for reproducibility np.random.seed(19680801) # Compute radius and theta N =100 r = 2 * np.random.rand(N) theta = np.pi * np.random.rand(N) area = 100 * r**2 colors = theta # Compute Cartesian x = r*np.cos(theta) y = r*np.sin(theta) # Choose polar or cartesian plot if polar: coor1=theta coor2=r else: coor1=x coor2=y # Create rectangular figure fig=plt.figure(figsize=(10,5)) # Create Axis if polar: ax = plt.axes(polar=True) ax.set_thetamin(0) ax.set_thetamax(180) else: ax = plt.axes() # Plot data c = ax.scatter(coor1, coor2, c=colors, cmap='hsv') # Set limits if polar: ax.set_rlim(0,2) else: plt.axis('scaled') plt.xlim(-2,2) plt.ylim(0,2) ax.annotate('A1',xy=(0, 0),xycoords='axes fraction',horizontalalignment='center', verticalalignment='center') ax.annotate('A2',xy=(1, 0),xycoords='axes fraction',horizontalalignment='center', verticalalig…
tagged with: polar-coordinates
tagged with: matplotlib
tagged with: python
type: Question
score: 0
has title: How can I adjust Axes sizes in matplotlib polar plots?
answer count: 0
has comment: http://stackoverflow.com/comment/87350065

http://stackoverflow.com/a/50187616
downvote count: 0
answers question: http://stackoverflow.com/q/50187485
type: Answer
score: 2
upvote count: 2
has body: You could use a regular expression: import re word = re.sub(r'.(.)', r'-\1', "monkey")

http://stackoverflow.com/comment/87307690
has text: I tried inlining it and renaming it and realized that the issue was gone for some reason. Though I'm not sure what the reason is, I have accepted your answer :)
comment on: http://stackoverflow.com/a/50134204
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50126788
accepted answer: http://stackoverflow.com/a/50126935
downvote count: 1
type: AnsweredQuestion
tagged with: non-greedy
score: 3
has body: I am working with transcripts and having trouble with matching patterns in non-greedy fashion. It is still grabbing way too much and looks like doing greedy matches. A transcript looks like this: >> John doe: Hello, I am John Doe. >> Hello, I am Jane Doe. >> Thank you for coming, we will start in two minutes. >> Sam Smith: [no audio] Good morning, everyone. To find the name of speakers within >> (WHATEVER NAME):, I wrote pattern=re.compile(r'&gt;&gt;(.*?):') transcript='&gt;&gt; John doe: Hello, I am John Doe. &gt;&gt; Hello, I am Jane Doe. &gt;&gt; Thank you for coming, we will start in two minutes. &gt;&gt; Sam Smith: [no audio] Good morning, everyone.' re.findall(pattern, transcript) I expected 'John Doe' and 'Sam Smith', but it is giving me 'John Doe' and 'Hello, I am Jane Doe. &gt;&gt; Thank you for coming, we will start in two minutes. &gt;&gt; Sam Smith' I am confused because .*? is non-greedy, which (I think) should be able to grab 'Sam Smith'. How should I fix the code so that it only grabs whatever in >> (WHATEVER NAME):? Also, I am using Python 3.6. Thanks!
has comment: http://stackoverflow.com/comment/87271729
possible better answer: http://stackoverflow.com/a/50127365
has comment: http://stackoverflow.com/comment/87271533
tagged with: python
tagged with: regex
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50126935
upvote count: 4
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/87271720
tagged with: regex-greedy
has title: Python regex non-greedy acting like greedy
has answer: http://stackoverflow.com/a/50127365

http://stackoverflow.com/a/50220971
has comment: http://stackoverflow.com/comment/87489965
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87489398
answers question: http://stackoverflow.com/q/50220860
upvote count: 1
has comment: http://stackoverflow.com/comment/87504027
has comment: http://stackoverflow.com/comment/87502685
has body: Specify the --no-binary flag. To use sdist for cryptography: pip install --no-binary cryptography cryptography To use sdist for everything: pip install --no-binary :all: cryptography
accepted answer of: http://stackoverflow.com/q/50220860
has comment: http://stackoverflow.com/comment/87493352
has comment: http://stackoverflow.com/comment/87503480
has comment: http://stackoverflow.com/comment/87492337
type: Answer
has comment: http://stackoverflow.com/comment/87489727
has comment: http://stackoverflow.com/comment/87492133
has comment: http://stackoverflow.com/comment/87502516

http://stackoverflow.com/a/50076000
type: Answer
has comment: http://stackoverflow.com/comment/87169730
score: 0
answers question: http://stackoverflow.com/q/50075940
has comment: http://stackoverflow.com/comment/87168298
has body: agree with @MasonStedman you should do soemthing like this something like &lt;div class="left"&gt; &lt;input type="checkbox"&gt; &lt;p&gt;{{ item.name }}&lt;/p&gt; &lt;p&gt;{{ item.email }}&lt;/p&gt; &lt;input type="hidden" name="delete_ids[]" value="{{item.id}}" /&gt; &lt;/div&gt;

http://stackoverflow.com/a/50112569
answers question: http://stackoverflow.com/q/50112265
score: 3
upvote count: 3
downvote count: 0
has body: The exception you catch is of TypeError and not ValueError. If you want to catch the exception, replace ValueError by TypeError or leave it blank (you will henceforth catch all exceptions). Note that you should not try to use ns or url in the except block since they are undefined. The other solution to do is: if elem is not None: ns, url = elem nsmap[ns] = url
has comment: http://stackoverflow.com/comment/87244537
type: Answer
has comment: http://stackoverflow.com/comment/87242275

http://stackoverflow.com/a/50151487
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/133453110
accepted answer of: http://stackoverflow.com/q/50151417
has comment: http://stackoverflow.com/comment/87321028
upvote count: 12
has body: We can do something like this that works for any generic array - def islandinfo(y, trigger_val, stopind_inclusive=True): # Setup "sentients" on either sides to make sure we have setup # "ramps" to catch the start and stop for the edge islands # (left-most and right-most islands) respectively y_ext = np.r_[False,y==trigger_val, False] # Get indices of shifts, which represent the start and stop indices idx = np.flatnonzero(y_ext[:-1] != y_ext[1:]) # Lengths of islands if needed lens = idx[1::2] - idx[:-1:2] # Using a stepsize of 2 would get us start and stop indices for each island return list(zip(idx[:-1:2], idx[1::2]-int(stopind_inclusive))), lens Sample run - In [320]: y Out[320]: array([1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]) In [321]: islandinfo(y, trigger_val=1)[0] Out[321]: [(0, 2), (8, 9), (16, 19)] In [322]: islandinfo(y, trigger_val=0)[0] Out[322]: [(3, 7), (10, 15)] Alternatively, we can use diff to get the sliced comparisons and then simply reshape with 2 columns to replace the step-sized slicing to give ourselves a one-liner - In [300]: np.flatnonzero(np.diff(np.r_[0,y,0])!=0).reshape(-1,2) - [0,1] Out[300]: array([[ 0, 2], [ 8, 9], [16, 19]])
type: Answer
has comment: http://stackoverflow.com/comment/108111745
score: 12
has comment: http://stackoverflow.com/comment/87324499
answers question: http://stackoverflow.com/q/50151417

http://stackoverflow.com/comment/87449169
has text: what's the error ? please run `makemigrations` & `migrate` if you changed the related_name
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50215819
score: 0

http://stackoverflow.com/q/50120860
has comment: http://stackoverflow.com/comment/87274318
tagged with: python
has comment: http://stackoverflow.com/comment/87263191
type: Question
has comment: http://stackoverflow.com/comment/87262823
answer count: 0
upvote count: 2
score: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88165798
tagged with: spotify
downvote count: 0
has title: Controlling the Spotify desktop app using Pywinauto in Windows
has body: Is there a way to control the Spotify desktop app using pywinauto? Tutorials only show examples with simple apps like Notepad which have windows with titles. The Spotify app window doesnt have a title and I dont know how to create the window specification object in this situation,or to control anything in spotify. I can open the Spotify app using the code below but thats about how far I go. from pywinauto.application import Application app = Application().start('Spotify.exe') I am trying to specify and select a playlist on the left side panel of the Spotify windows app which contains saved playlists, then select play on any random song from the playlist window that pops up on the right.I tried to click on a playlist name called 'New Music' on the left panel by using the following code, which is still incomplete as I need another argument to specifically reference the playlist I need: app.window(control_type='TextControl').click() The only useable values I got from Inspect.exe for the item listed as "New Music" are Name:New Music, ControlType:TextControl, ProcessId:3680, and a list of Ancestors. I couldnt use the ProcessId since every other playlist uses the same id and couldnt use the Name since it wont be a valid argument.
tagged with: pywinauto
favorite count: 0
has comment: http://stackoverflow.com/comment/87861886
has comment: http://stackoverflow.com/comment/87715757
has comment: http://stackoverflow.com/comment/87272476

http://stackoverflow.com/comment/87456332
has text: Hey again and sorry for the very late response! i managed to fix the error i was getting and completely forgot to come here.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50163814
type: Comment

http://stackoverflow.com/comment/87259055
score: 3
has text: @ImportanceOfBeingErnest I just noticed the other answer, however, this response provides 1. Example data 2. markers in the style as the OP wished 3. an example output
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50120732

http://stackoverflow.com/comment/87427105
type: QuestionComment
comment on: http://stackoverflow.com/q/50204440
score: 0
has text: @DavidFarrugia I have tried using the import google and the search method but that only gives u the url of the results
type: Comment

http://stackoverflow.com/a/50175727
has body: You can try threading. I've made changes below to the code and tested it here, and it worked. from tkinter import * from threading import Thread import os import sys import time import threading # NEW master = Tk() master.geometry("500x500") master.resizable(False,False) def tryout(): sign2.config(text = "AAA") for x in range(5): print(x) time.sleep(1) sign2.config(text = "BBB") for x in range(5): print(x) time.sleep(1) sign2.config(text = "CCC") def close_window(): master.destroy() sys.exit() def thread(): # NEW threading.Thread(target=tryout).start() # NEW sign1 = Label(master, text = "VNA GUI").grid(pady=10, padx=10) sign2 = Label(master, text = "Choose option to continue") sign2.grid(pady=10, padx=10, ipadx=50) Button(master, text='Exit', command=close_window).grid(pady=10, padx=20) butTest = Button(master, text='test', command=thread) # Changed butTest.grid(pady=10, padx=20) master.mainloop( )
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87431876
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50175555

http://stackoverflow.com/q/50181878
answer count: 2
has answer: http://stackoverflow.com/a/50181975
possible better answer: http://stackoverflow.com/a/50181975
has answer: http://stackoverflow.com/a/50182008
accepted answer: http://stackoverflow.com/a/50182008
linked to: http://stackoverflow.com/q/932069
type: Question
has comment: http://stackoverflow.com/comment/87381817
has title: Dynamically loading objects from list of python files
tagged with: python
has body: I'm wondering if I have some python scripts in a folder that will have common functionality like method names but different functionality can by dynamically imported. These python scripts will be in a single folder but I don't know how many their will be. I'd like to have a script look in the folder, get a list of the scripts and create objects for each of them.
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87437059
has text: What should I see if I execute the code above ?. I just get a Frame with a very small square in the center with a 'X' inside
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50209797
type: QuestionComment

http://stackoverflow.com/comment/127341684
type: AnswerComment
score: 1
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
comment on: http://stackoverflow.com/a/72063834
type: Comment

http://stackoverflow.com/a/50192119
type: AcceptedAnswer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50191826
downvote count: 0
type: Answer
has body: A vectorised approach is possible via numpy.searchsorted together with numpy.argsort: import numpy as np A = np.array(['a', 'b', 'c', 'd']) B = np.array(['d', 'b', 'a', 'c']) xsorted = np.argsort(B) res = xsorted[np.searchsorted(B[xsorted], A)] print(res) [2 1 3 0]
accepted answer of: http://stackoverflow.com/q/50191826

http://stackoverflow.com/comment/87349482
score: 0
has text: @express_v2 I still don't understand what you're asking. If you want to click and get a result for each thing in `link_click`, just do `for thing in link_click:` then `course_select = thing.click()` and then whatever you want to do with each `course_select`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50165568

http://stackoverflow.com/q/50216844
has answer: http://stackoverflow.com/a/50220641
has comment: http://stackoverflow.com/comment/87475398
tagged with: python
has comment: http://stackoverflow.com/comment/87473533
has comment: http://stackoverflow.com/comment/87513767
has comment: http://stackoverflow.com/comment/87452402
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/87454215
has body: I'm trying to read the tables from a [web page][1] into pandas DataFrames. pandas.read_html returns a list of empty tables because the tables from the HTML are indeed empty. They're probably populated dynamically. Someone suggested that the data source could to be an [XML][3] that looks like this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> Content ID Unique identifier for use of tool Product Type 1. sample name 2. sample name 3. sample name 4. sample name 5. sample name 6. sample name 7. Accessories Sub Category Name of checkbox item and announcement subhead Published Date Text type - not Date Spell out month name completely Description Enter a full description Special Notes To appear under recommendation table Product Image Enter entire URL path to image or provide the image through email. Announcement URL Enter file name, no spaces Product URL Enter full URL Product SKU Enter product number being discontinued Product Description Enter product description for original product Replacement Product SKU Enter product number to replace discontinued product Only use this column when multiple country skus are not needed Replacement Product Description Enter product description for replacement product Only use this column when multiple country skus are not needed Custom Header 1 Use these custom headers to build a dynamic table. Used primarily for multiple skus per country Custom Header 2 Use these custom headers to build a dynamic table. Used primarily for multiple skus per country Custom Header 3 Use these custom headers to build a dynamic table. Used primarily for multiple skus per country Custom Header 4 Use these custom headers to build a dynamic table. Used primarily for multiple skus per country Custom Header 5 Use these custom headers to build a dynamic table. Used primarily for multiple skus per country Custom Header 6 Use these custom headers to build a dynamic table. Used primarily for multiple skus per country 1 1 xx sample namexx June 1, 2011 xx S…
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/943739
has comment: http://stackoverflow.com/comment/87506049
tagged with: pandas
has comment: http://stackoverflow.com/comment/87452024
upvote count: 2
score: 1
linked to: http://stackoverflow.com/q/13287490
has title: Convert XML to DataFrames
has comment: http://stackoverflow.com/comment/87451905
answer count: 1
has comment: http://stackoverflow.com/comment/87452360
has comment: http://stackoverflow.com/comment/87451647
downvote count: 1
accepted answer: http://stackoverflow.com/a/50220641
has comment: http://stackoverflow.com/comment/87451455
favorite count: 0
tagged with: xslt
type: Question
has comment: http://stackoverflow.com/comment/87451367
has comment: http://stackoverflow.com/comment/87513710

http://stackoverflow.com/q/50206036
has comment: http://stackoverflow.com/comment/87451919
tagged with: python
tagged with: amazon-web-services
tagged with: ubuntu
has body: I am a newbie. I am running python web application on AWS-Ubuntu. My goal is to access this app from the browser with IP address. I have configured Apache web server. Below are my conf and wsgi file. .conf file &lt;VirtualHost *:80&gt; ServerName 13.58.200.92 ServerAdmin admin@13.58.200.92 WSGIDaemonProcess catalog threads=5 WSGIProcessGroup catalog WSGIScriptAlias / /var/www/catalog/catalog.wsgi &lt;Directory /var/www/catalog/Catalog/&gt; Order allow,deny Allow from all &lt;/Directory&gt; Alias /static /var/www/catalog/Catalog/static &lt;Directory /var/www/catalog/Catalog/static/&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined .wsgi file #!/usr/bin/python3.5 import sys import os import logging logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) sys.path.insert(0,"/var/www/catalog/") sys.path.append('/var/www/catalog/Catalog') from Catalog import Employee as application application.secret_key = 'super' catalog.py #!/usr/bin/env python3 from flask import Flask, render_template, url_for, request, redirect, jsonify from flask import flash from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Department, Employee, User from flask_httpauth import HTTPBasicAuth # Anti Forgery State Token Code from flask import session as login_session import random import string # Import for 'Gconnect' step from oauth2client.client import flow_from_clientsecrets, FlowExchangeError import httplib2 import json from flask import make_response import requests auth = HTTPBasicAuth() CLIENT_ID = json.loads(open('/var/www/catalog/Catalog/client_secrets.json', 'r').read())['web']['client_id'] app = Flask(__name__) # Connect to Database and create database session engine = create_engine('postgresql://empcat:empcat@localhost/emp_catalog') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() @app.r…
score: 2
answer count: 0
downvote count: 0
has title: TypeError: 'module' object is not callable for all the def function():
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: apache

http://stackoverflow.com/q/50082324
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50181779
has title: Python3.4 termios modification
has comment: http://stackoverflow.com/comment/87180651
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to figure out how to use the termios calls to configure the tty. Below I am playing with baudrate. I am able to call tcgetattr, change the values, see that they have changed in a print before I send them. However tcsetattr followed by tcgetattr shows that the hardware is not getting them. I tried changing to su in case it was a permissions thing but that made no difference. I see that it is possible for the termios structure to be locked and unlocked by writing a special termios structure. How do I test it to see if it is locked, and if so, how do I unlock it? import os import termios def TestTTY(tty): fd = os.open(tty,os.O_RDWR | os.O_NONBLOCK) if fd: if os.isatty(fd): tios = termios.tcgetattr(fd) print("From tcgetattr") print(tios) #try to set the baud to B38400 tios[2] &amp;= ~termios.CBAUD tios[2] |= termios.B38400 print("To tcsetattr") print(tios) termios.tcsetattr(fd,termios.TCSANOW,tios) print("Readback tcgetattr") print(termios.tcgetattr(fd)) os.close(fd) TestTTY("/dev/ttyS0") From tcgetattr [0, 0, 6321, 0, 4097, 4097, [b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', 0, 0, b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00']] To tcsetattr [0, 0, 2239, 0, 4097, 4097, [b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', 0, 0, b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00']] Readback tcgetattr [0, 0, 6321, 0, 4097, 4097, [b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', 0, 0, b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00']]
tagged with: termios

http://stackoverflow.com/comment/87294339
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50136727
has text: What I (we?) are trying to say is that your input data as shown in your snippet (`players`, `rounds`, etc.) look incomplete. You would need 24 values to define your tensor, while you are providing only 9 (`0...8`). If `[7, 8]` are the values of the 2 actions taken by player `0` for round `2`, raise `4`; what about the actions for the other players / raises / rounds?

http://stackoverflow.com/comment/87384088
score: 0
type: Comment
type: QuestionComment
has text: @BryanOakley I use it as in the code of the edited section of my question, but gives me the same behavior
comment on: http://stackoverflow.com/q/50181025

http://stackoverflow.com/q/50105687
score: 3
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87229028
has answer: http://stackoverflow.com/a/50764787
tagged with: python
has title: Find and write to next blank cell in a column
type: Question
tagged with: python-3.x
answer count: 2
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87231614
has answer: http://stackoverflow.com/a/50763976
has body: I need to find and write to next blank cell. import csv with open(r'C:\\filepath\file.txt', 'r') as input_file: reader = csv.reader(input_file) with open (r'C:\filepath\file.csv', 'a', newline = '') as output_file: writer = csv.writer(output_file) for row in reader: content = [i.split('~') for i in row] for row1 in content: con = [len(k.split('*')) for k in row1] conn = [m.split('*') for m in row1] for b in conn: if con[0] &gt; 4: if (b[0] == 'NM1' and b[1] == '82' and b[2] == '1' ): writer.writerow([b[3]] + [b[4]]) print ( b[3] + b[4] ) elif (b[0] == 'GS' ): writer.writerow(['','','',b[2]]) print(b[2]) Seeking to get the output as shown in pic above. Right now in the first row only 'App1' is printing then in second row the names etc. Input File I am using as below. : ISA*16* 00 0*T*&gt;~ GS*IN*APP1*0999~ HPT*1*2~ SE*21*0001~ GE*1*145~ NM1*82*1*Tiger1a*Test1*K****~ NM1*82*1*Lion1a*Test2*K****~ NM1*82*1*Elephant1a*Test3*K****~ ISA*16* 00 0*T*&gt;~ GS*IN*APP2*0999~ HPT*1*2~ SE*21*0001~ GE*1*145~ NM1*82*1*Tiger1a*Test4*K****~ ISA*16* 00 0*T*&gt;~ GS*IN*APP1*0999~ HPT*1*2~ SE*21*0001~ GE*1*145~ NM1*82*1*Tiger1a*Test4*K****~ NM1*82*1*Lion1a*Test5*K****~ NM1*82*1*Elephant1a*Test6*K****~ ISA*16* 00 0*T*&gt;~ GS*IN*APP10999~ HPT*1*2~ SE*21*0001~ GE*1*145~ NM1*82*1*Tiger1a*Test7*K****~ [![enter image description here][2]][2]
favorite count: 0
has comment: http://stackoverflow.com/comment/87228632
upvote count: 3

http://stackoverflow.com/comment/119627196
has text: I am having the same problem but I am on ubuntu which doesn't have a raspi-config. What are my options?
type: Comment
comment on: http://stackoverflow.com/a/63988765
type: AnswerComment
score: 0

http://stackoverflow.com/comment/98484680
score: 2
type: Comment
comment on: http://stackoverflow.com/a/52974437
type: AnswerComment
has text: as recall and precision have two scores i) In terms of -ve value ii) In terms of +ve value So you need to pass one of these value in pos_label so that function can return score in terms of that pos label

http://stackoverflow.com/comment/87312679
type: Comment
comment on: http://stackoverflow.com/q/50147095
score: 0
has text: i get this error bulk_create() got an unexpected keyword argument 'kode_pem'
type: QuestionComment

http://stackoverflow.com/a/50097260
upvote count: 1
answers question: http://stackoverflow.com/q/50097024
score: 1
has body: You've got two options: Casting the column type (or even the whole dataframe): df[column] = df[column].astype(int) Or using numpy's floor method (for positive floats as in your example) df[column] = np.floor(df[column])
downvote count: 0
type: Answer

http://stackoverflow.com/q/50133186
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I need to get the size of an image, but to call an image I'm not using img=open'rectangle.png' instead I'm using filename1 = askopenfilename(filetypes=[("image","*.png")]) but I get this error : width, height = background.size TypeError: 'int' object is not iterable This is my code : import tkFileDialog from tkFileDialog import askopenfilename # Open dialog box from PIL import Image import cv2 import numpy filename1 = askopenfilename(filetypes=[("image","*.png")]) filename2 = askopenfilename(filetypes=[("image","*.png")]) img=cv2.imread(filename1,1) background=cv2.imread(filename2,1) offset = numpy.array((10,10)) background[offset[0]:offset[0]+img.shape[0],offset[1]:offset[1]+img.shape[1]]=img width, height = background.size print('width = ', width) print('height = ',height) cv2.imshow("Added Image", background) cv2.waitKey(0)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87284481
tagged with: python
has title: Get the size of an image in python
tagged with: image
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87290617

http://stackoverflow.com/a/58494505
score: 2
answers question: http://stackoverflow.com/q/50194364
upvote count: 2
downvote count: 0
type: Answer
has body: The returned value is the transaction hash on the blockchain. When transacting (i.e., when using "transact" rather than "call") the blockchain gets modified, and the library you are using returns the transaction hash. During that process you must have paid ether in order to be able to modify the blockchain. However, operating in read-only mode costs no ether at all, so there is no need to specify gas. Discounting the "0x" at the beginning, ethereum addresses have a length of 40, but in your test you are using a 39-character-long address, so there is a missing a "1" there. Meaning, tests are correct, you have an error in your input. Both return_true and return_address should be marked as view in Solidity, since they are not actually modifying the state. I'm pretty sure you get a warning in remix. Once you do that, there is no need to access both methods using "transact" and paying ether, and you can do it using "call" for free. In case you need to access the transaction hash after using transact you can do so calling the .hex() method on the returned HexBytes object. That'll give you the transaction hash as a string, which is usually way more useful than as a HexBytes.

http://stackoverflow.com/comment/87456073
score: 0
type: Comment
has text: That's rather outside the scope of this question, I think. Play around with it for a while and ask a new question if you get stuck.
comment on: http://stackoverflow.com/a/50219497
type: AnswerComment

http://stackoverflow.com/comment/87308931
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50145004
has text: thanks! Could you please explain how you calculated that probability too?! Or at least give me a hint/reference so I can find out how to do so if you do not mind?!

http://stackoverflow.com/a/66327473
has body: You can use the function clean_lat_long() from the library DataPrep. Install it with pip install dataprep. from dataprep.clean import clean_lat_long df = pd.DataFrame({"Latitude": ["0°51'56.29''S", "1°23'39.29''S", "0°19'56.63''N"], "Longitude": ["101°26'46.29''E", "101°35'30.45''E", "99°22'56.36''E"]}) df2 = clean_lat_long(df, lat_col="Latitude", long_col="Longitude", split=True) df2 Latitude Longitude Latitude_clean Longitude_clean 0 0°51'56.29''S 101°26'46.29''E -0.8656 101.4462 1 1°23'39.29''S 101°35'30.45''E -1.3942 101.5918 2 0°19'56.63''N 99°22'56.36''E 0.3324 99.3823
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50193159

http://stackoverflow.com/q/50091118
answer count: 1
tagged with: web-scraping
has body: I am trying to scrape the link to the banner image (bigger image) from this link: https://allevents.in/pune/filmmaking-workshop/20001033616713 . For that I tried with these two commands both of which returned an empty list. response.xpath('//img[@class="event-banner-image"]/@src').extract() response.xpath('//*[@class="event-banner-image"]/@src').extract() I am using Scrapy with Python.
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/87202197
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87207627
accepted answer: http://stackoverflow.com/a/50097815
has title: Banner image couldn't be scraped
has answer: http://stackoverflow.com/a/50097815

http://stackoverflow.com/comment/87343993
type: QuestionComment
score: 0
has text: I'm confused by this statement "imported : tensorflow and tensorflow-gpu". Did you install tensorflow with `pip install tensorflow` or `pip install tensorflow-gpu`?
comment on: http://stackoverflow.com/q/50160889
type: Comment

http://stackoverflow.com/comment/87432698
type: QuestionComment
score: 0
has text: you can't use this, you have to do Yocto's way
type: Comment
comment on: http://stackoverflow.com/q/50097648

http://stackoverflow.com/comment/87305965
comment on: http://stackoverflow.com/q/50143759
type: QuestionComment
has text: Yes, it is 10 fold Cross Validation (10-CV) @HarisNadeem
score: 1
type: Comment

http://stackoverflow.com/comment/87435233
score: 0
has text: I need a little more help from you on the same solution given by you above. I have to implement the same in a tree where at every node I have to compare words of the document with their siblings documents and keep those words at every node having more than 60% count at that node and less than 40% count at its siblings node. In the original question, if the tree is big and B and C also has childrens and also A has other childs also like D,E then how can this be done. Kindly help me with this. It is very important and urgent for me. Thanks.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50172885

http://stackoverflow.com/a/50084684
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87186366
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50083055
answers question: http://stackoverflow.com/q/50083055
has body: The first application of _test_fn will return range(1,4), which is [1,2,3]. The second application will return range(5,7), which is [5,6]. Tensorflow will then attempt to put all of these into one tensor, i.e. [[1,2,3],[5,6]]. This is not a valid tensor since the two rows have different lengths, so this code crashes. What are you trying to achieve exactly?
has comment: http://stackoverflow.com/comment/87187189
type: AcceptedAnswer

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/50116836
tags question: http://stackoverflow.com/q/50209009
tags question: http://stackoverflow.com/q/50152428
type: Tag

http://stackoverflow.com/a/50084258
score: 2
answers question: http://stackoverflow.com/q/50082095
type: Answer
has body: You can use pandas.Series.str.count to count the number of times in each row a pattern is encountered. df.names.str.count('John').sum() 3 In this example, it matches OP's output. However, this would produce different results if John appeared more than once in one row. Suppose we had this df instead: df names 0 John John 1 John M John M 2 Mike John Mike John 3 Audrey Audrey 4 Andrew Andrew Then my answer produces df.names.str.count('John').sum() 6 While Wen's answer produces df.names.str.contains('John').sum() 3
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87619455
comment on: http://stackoverflow.com/a/50301348
type: Comment
has text: NB for step 2: "install your package" is a valid way of setting up `sys.path` :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87220704
comment on: http://stackoverflow.com/a/50098910
score: 0
type: Comment
has text: Thanks for your reply. I already did this approach and it worked. But, I was looking for a way to transform the data while reading the csv-file.
type: AnswerComment

http://stackoverflow.com/a/50118327
has body: Do you want a/X^2 or a/X? You ask for one but your example shows the other. for col in col_list: new_col = 'new_' + col df[new_col] = df[col] / (df['X']**2) will give you what you ask for, if what you want is actually a/X adjust accordingly.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50118240
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87315658
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50148570
has text: Good catch -- I actually had just copied another (but very similar) query from my Python code. I edited the question to have the right code which includes the intentional order_by. This query directly in psql: `SELECT transactions.stall, transactions.purchased_date, transactions.expiry_date FROM transactions WHERE transactions.expiry_date > '2016-01-01 00:00:00.000Z' AND transactions.purchased_date < '2019-01-01 00:00:00.000Z' ORDER BY transactions.purchased_date;` has a response time of 5457.151 ms (00:05.457) so slightly slower, but not 15 min, so it doesn't seem to be the issue here

http://stackoverflow.com/q/50146481
has comment: http://stackoverflow.com/comment/87311344
has body: import pandas as pd import re df1 = pd.DataFrame({"Greetings": ["Greetings to you too", "hi", "hello", "hey", "greetings", "sup", "what's up", "yo"]}) df2 = pd.DataFrame({"Farewell": ["GoodBye", "See you", "Bye", "Laters"]}) frames = [df1, df2] df3=pd.concat(frames, axis=1, join='outer', copy=True) sentence = 'hi' for index, row in df3.iterrows(): if index&gt;0: if sentence.lower() in df3.iloc[index,:].values: print(df3.iloc[index].values) This gives me an output of: ['hi' 'See you'] The end purpose is to basically iterate through all columns from 2nd row onwards to look for keyword match (which is why I put: if index>0) and if it finds a match, then to output by default the first item of that column (in this case "Greetings to you too" which is df3.iloc[0,0] in this scenario. Hence I need help to add additional line of code, so that the result output after running the code will look like this: "Greetings to you too" Could someone help please.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87312453
has title: Python Pandas Dataframe loop iteration
score: 0
has comment: http://stackoverflow.com/comment/87311951
tagged with: for-loop
tagged with: pandas
has comment: http://stackoverflow.com/comment/87311664
answer count: 1
has comment: http://stackoverflow.com/comment/87311250
tagged with: iteration
has answer: http://stackoverflow.com/a/50147701
type: Question

http://stackoverflow.com/q/50126232
has body: This is built upon a previous question Solve a simple packing combination with dependencies, although there is no need to check out that question to understand this one. This question asks about the fastest ways to count the number of linear extensions of a partially ordered set. Such an partially ordered list can be visualized as the feasibility of a packing configuration, given arbitrary ordering of the objects. The question is than equivalent to what are the possible ordering of all the blocks handed to you for you to achieve the shown packing configuration, if the blocks cannot be moved once placed? In this example, all blocks ABCDEFG need to be laid down,dependencies for A,B,C,D: set{}, E: set{A,B},F: set{B,C} G: set{C,D}. You can get all possibilities of completing the partially ordered set by checking all permutations of 7 blocks and count the number that meets the dependencies. A faster alternative is provided by גלעד ברקן in the previous post who used a graph structure that terminate further search into a branch if the dependencies are not met in nodes already explored. nodes = { 'A': { 'neighbours': ['B','C','D','E','F','G'], 'dependency': set()}, 'B': { 'neighbours': ['A','C','D','E','F','G'], 'dependency': set()}, 'C': { 'neighbours': ['A','B','D','E','F','G'], 'dependency': set()}, 'D': { 'neighbours': ['A','B','C','E','F','G'], 'dependency': set()}, 'E': { 'neighbours': ['C','D','F','G'], 'dependency': set(['A','B'])}, 'F': { 'neighbours': ['A','D','E','G'], 'dependency': set(['B','C'])}, 'G': { 'neighbours': ['A','D','E','G'], 'dependency': set(['C','D'])}, } def f(key, visited): if len(visited) + 1 == len(nodes): return 1 if nodes[key]['dependency'] and not nodes[key]['dependency'].issubset(visited): return 0 result = 0 for neighbour in nodes[key]['neighbours']: if neighbour not in visited: _visited = visited.copy() _visited.add(key) result += f(neighbour, _visited) return result print 2 * f('A', set()) + 2 * f('B', set()) # exploiting symmetry My qu…
tagged with: poset
has comment: http://stackoverflow.com/comment/87290018
type: Question
tagged with: graph
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87281930
downvote count: 0
has title: Number of ways to go through a partially ordered set
favorite count: 0
tagged with: combinations
score: 2
has comment: http://stackoverflow.com/comment/87289513
has comment: http://stackoverflow.com/comment/87287801
tagged with: algorithm
linked to: http://stackoverflow.com/q/49948256
has comment: http://stackoverflow.com/comment/87289101
tagged with: python

http://stackoverflow.com/q/50201024
downvote count: 0
upvote count: 1
tagged with: keras
has body: I train CNN model with keras library with numbers of epoch is 25. Can I run model in first time with 10 epochs then save model with these lines of code: model.fit_generator(training_set, steps_per_epoch = 100000, epochs = 10, validation_data = test_set, validation_steps = 40000) from keras.models import load_model model.save('my_model.h5') Then I restart python and continue to run the next 15 epochs with the same dataset like the code bellow: model = load_model('my_model.h5') model.fit_generator(training_set, steps_per_epoch = 100000, epochs = 15, validation_data = test_set, validation_steps = 40000) Is it sufficient to continue training ? Or I have to do any other step to continue the job. I am very appreciated with any support.
has title: Continue train CNN with saved model in keras
tagged with: conv-neural-network
tagged with: deep-learning
score: 1
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50202278
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/87411149
comment on: http://stackoverflow.com/a/50193328
type: Comment
score: 0
has text: @Funkeh-Monkeh Is it only one row? I'd manually go in and change it to the correct value in that case. In other case, if you are sure everything else is correct I added an updated code you could run before you apply the functions.
type: AnswerComment

http://stackoverflow.com/comment/87201577
type: AnswerComment
comment on: http://stackoverflow.com/a/50091576
has text: That's possible: see "mixed strategy" at the end.
score: 0
type: Comment

http://stackoverflow.com/a/50091897
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87199991
answers question: http://stackoverflow.com/q/50091625
type: Answer
has comment: http://stackoverflow.com/comment/87200102
has body: There is no truly global namespace in python. You need to have a common module everyone imports. Its best if the common module has few side effects (e.g., importing another module that could create circular dependencies). main.py is a particularly poor container because its the top level script and isn't a module at all. Other importers would get a different main as a module. So you could create config.py VERBOSE = True SAMPLINGRATE = 44100 and all of your modules simply do from config import *

http://stackoverflow.com/comment/87281734
has text: Where did you write the code? and can you also share it, we can help you get unstuck more easily if you can share the code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50130947

http://stackoverflow.com/comment/87325626
comment on: http://stackoverflow.com/q/50152946
score: 0
has text: Yes. That why I groupBy the target dataframe.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87468455
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50224741
has text: Thx again. I’ll check it out and CRON might work too. I’ll investigate.
type: Comment

http://stackoverflow.com/a/50127741
answers question: http://stackoverflow.com/q/50127167
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50127167
type: Answer
score: 1
has body: Modify the bar function like this - def bar(row): b = row['B'] c = row['C'] d = row['D'] a = row['A'] e, f = myClass.foo( a, b, c, d ) row['E'] = e row['F'] = f row['G'] = e+f return row And then call it like this - df = df.apply(bar, axis = 1) Output A B C D E F G 0 2018-03-26 16:56:05.352316 X 100 26.11 0.0 0.0 0.0 1 2018-03-26 18:30:25.972228 X 100 26.10 0.0 0.0 0.0 2 2018-03-26 19:07:37.321565 Y 150 26.20 0.0 0.0 0.0 3 2018-03-28 16:15:07.450381 Y 50 26.20 0.0 0.0 0.0 4 2018-03-28 19:59:34.827558 X 100 26.06 0.0 0.0 0.0 5 2018-03-29 16:55:41.329606 X 57 26.09 0.0 0.0 0.0
type: AcceptedAnswer

http://stackoverflow.com/a/50101120
score: 1
answers question: http://stackoverflow.com/q/50100941
downvote count: 0
upvote count: 1
has body: I think using regex is probably a good way to go (using str.findall): import pandas as pd df = pd.DataFrame(list_fs) df['Timestamp_ordered'] = df[0].str.findall('\d{4}-\d{2}-\d{2} \d{2}:\d{2}').apply(pd.Series) df['FilePath'] = df[0].str.findall('(\w{4}://.*)').apply(pd.Series) # Sort and get rid of old column df = df'Timestamp_ordered', 'FilePath'.sort_values('Timestamp_ordered') Which returns: &gt;&gt;&gt; df Timestamp_ordered FilePath 0 2017-08-25 12:10 hdfs://filepath=2011-01-31 16%3A06%3A09.0 1 2017-08-29 14:12 hdfs://filepath=2011-02-28 10%3A00%3A00 2 2017-08-29 14:20 hdfs://filepath=2011-03-31 10%3A00%3A00 3 2017-08-29 14:32 hdfs://filepath=2011-04-30 10%3A00%3A00 5 2017-08-29 15:02 hdfs://filepath=2011-05-31 10%3A00%3A00 6 2017-08-29 15:06 hdfs://filepath=2011-06-30 10%3A00%3A00 7 2017-08-31 10:38 hdfs://filepath=2011-07-31 10%3A00%3A00 8 2017-08-31 10:42 hdfs://filepath=2011-08-31 10%3A00%3A00 9 2017-08-31 11:08 hdfs://filepath=2011-09-30 10%3A00%3A00 10 2017-08-31 11:11 hdfs://filepath=2011-10-31 10%3A00%3A00 11 2017-08-31 11:15 hdfs://filepath=2011-11-30 10%3A00%3A00 12 2017-08-31 11:16 hdfs://filepath=2011-12-31 10%3A00%3A00 4 2018-02-20 13:57 hdfs://filepath=2011-05-31 08%3A00%3A00
type: Answer

sqlalchemy
tags question: http://stackoverflow.com/q/50138426
tags question: http://stackoverflow.com/q/50204056
tags question: http://stackoverflow.com/q/50103662
tags question: http://stackoverflow.com/q/50187867
tags question: http://stackoverflow.com/q/50141058
tags question: http://stackoverflow.com/q/50156520
tags question: http://stackoverflow.com/q/50107541
tags question: http://stackoverflow.com/q/50119679
tags question: http://stackoverflow.com/q/50119510
tags question: http://stackoverflow.com/q/50168339
tags question: http://stackoverflow.com/q/50162849
tags question: http://stackoverflow.com/q/50198753
tags question: http://stackoverflow.com/q/50163249
tags question: http://stackoverflow.com/q/50107615
tags question: http://stackoverflow.com/q/50229353
tags question: http://stackoverflow.com/q/50219352
tags question: http://stackoverflow.com/q/50123090
tags question: http://stackoverflow.com/q/50117707
tags question: http://stackoverflow.com/q/50105499
tags question: http://stackoverflow.com/q/50152754
tags question: http://stackoverflow.com/q/50215752
tags question: http://stackoverflow.com/q/50187065
tags question: http://stackoverflow.com/q/50131361
tags question: http://stackoverflow.com/q/50187320
tags question: http://stackoverflow.com/q/50143656
tags question: http://stackoverflow.com/q/50207758
tags question: http://stackoverflow.com/q/50171288
tags question: http://stackoverflow.com/q/50199949
tags question: http://stackoverflow.com/q/50172936
tags question: http://stackoverflow.com/q/50132456
tags question: http://stackoverflow.com/q/50076774
tags question: http://stackoverflow.com/q/50114648
tags question: http://stackoverflow.com/q/50142629
tags question: http://stackoverflow.com/q/50109243
tags question: http://stackoverflow.com/q/50197609
tags question: http://stackoverflow.com/q/50121432
tags question: http://stackoverflow.com/q/50190164
tags question: http://stackoverflow.com/q/50109344
tags question: http://stackoverflow.com/q/50092605
tags question: http://stackoverflow.com/q/50174325
tags question: http://stackoverflow.com/q/50085222
tags question: http://stackoverflow.com/q/50162128
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/50223179
tags question: http://stackoverflow.com/q/50148570
type: Tag
tags question: http://stackoverflow.com/q/50212104

http://stackoverflow.com/comment/87342139
comment on: http://stackoverflow.com/a/50162043
score: 0
type: AnswerComment
has text: df['Reg_cat'] should be empty and d is kinda the code you gave me... Sorry I'm quite new to data science
type: Comment

http://stackoverflow.com/comment/87419905
has text: `tensordot` effectively does an outer product on the dimensions that aren't summed, producing in your case `(5, 10, 10, 10, 10, 10, 10).`. The desired values are embedded in there as some sort of diagonal, but it's calculating a lot more values than you need. With some axis swapping `mutmul` could perform the desired calc, since it's outer dimensions `go-along-for-the-ride`. But `einsum` is easiest to use.
type: QuestionComment
comment on: http://stackoverflow.com/q/50201244
type: Comment
score: 0

http://stackoverflow.com/comment/87231692
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50106934
score: 0
has text: I'm sorry I was looking at my code snippet. In OP's code certainly an exception raised from `connections.cursor()` is catched, and in that case `cursor` will be undefined at the `except:` block

http://stackoverflow.com/a/51516857
score: 1
answers question: http://stackoverflow.com/q/50113163
upvote count: 1
downvote count: 0
type: Answer
has body: And, I don't get why we have to just put in that code as we don't even specify the file that was being downloaded. cred = credentials.Certificate('path/to/serviceAccountKey.json') Let's say that: 'path/to/serviceAccountKey.json' is path to file-you-just-downloaded.json

http://stackoverflow.com/a/50162229
score: 0
has body: Can the Python script just insert a NULL value when the value isn't available? So: INSERT INTO myTable (FirstName, email, phone) VALUES("Bob", "bob@gmail.com", NULL)
has comment: http://stackoverflow.com/comment/87342420
type: Answer
answers question: http://stackoverflow.com/q/50162167
has comment: http://stackoverflow.com/comment/87342647
has comment: http://stackoverflow.com/comment/87342362

http://stackoverflow.com/comment/87481477
type: AnswerComment
comment on: http://stackoverflow.com/a/50224982
type: Comment
score: 0
has text: Thanks a lot for introducing numba. I like it since it make the code readable and easy to maintain

http://stackoverflow.com/comment/87340308
type: Comment
comment on: http://stackoverflow.com/a/50146326
score: 0
type: AnswerComment
has text: @Wen This is great! Could you add this into your answer?

http://stackoverflow.com/comment/87437256
score: 0
type: Comment
type: AnswerComment
has text: @smci the only things I have not mentioned are related to pip. I tried command suggested in [this post](https://stackoverflow.com/a/3452888/4999991) using pip to upgrade/update itself and other packages. It took ages to update everything but the problem still persists. I tried the `conda update conda` command again on my work computer today and the exact same thing happened.
comment on: http://stackoverflow.com/a/50190086

http://stackoverflow.com/q/50124901
has comment: http://stackoverflow.com/comment/87268033
tagged with: python
has answer: http://stackoverflow.com/a/50124956
has comment: http://stackoverflow.com/comment/87268005
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/10660435
answer count: 3
tagged with: while-loop
has answer: http://stackoverflow.com/a/50124966
has title: join a list of of sentences into phrases
score: 1
accepted answer: http://stackoverflow.com/a/50124913
possible better answer: http://stackoverflow.com/a/50124956
has answer: http://stackoverflow.com/a/50124913
downvote count: 1
tagged with: append
has body: I have a list of song lyric strings that looks like this: [' Extending a life\n', 'With total resistance\n', 'To fatal disease\n', 'Future methods of science.\n', 'Replacing what is real\n', 'By using technology\n', 'Population control\n', 'Selecting those who will breed.\n', 'A specific type of form\n', 'Chosen for the unborn.\n', 'A mind without emotion\n', 'Progressive anatomy.\n'] I.e. each lyric ends with a newline character, and some end in a period and a new line character. What I would like to do is produce a list that looks like this: [' Extending a life\n With total resistance\n To fatal disease\n Future methods of science.\n', 'Replacing what is real\n By using technology\n Population control\n Selecting those who will breed.\n', 'A specific type of form\n Chosen for the unborn.\n', 'A mind without emotion\n Progressive anatomy.\n'] I.e. Each value of the new list is a complete lyric string with a period at the end of each complete lyric. I have an idea on how to do go about this for only one section of lyrics: def random_lyrics(song): i = 1 formatted_song = [] formatted_song.append(song[0][1:]) while i &lt;= len(song)-1: if song[i][len(song[i])-2] == '.': formatted_song[0] += song[i] break else: formatted_song[0] += song[i] i +=1 This code works for individual sections of lyrics that need to be joined in the format described above. I am having a hard time generalizing this function to work on the entire original list of song lyrics. Any advice would be appreciated. **Note that the lyrics passed into the function are ordered correctly, i.e. ordered according to the song.
favorite count: 0
type: Question
tagged with: for-loop
upvote count: 2

http://stackoverflow.com/q/50130234
tagged with: python
has body: import os import datetime from flask import Flask, render_template, redirect, url_for # from database import DatabaseConnection # from models import kayıt from forms import LoginForm import psycopg2 as p conn=p.connect(dbname='app_db', user='postgres', host='localhost', password='samet', port=5432) conn.autocommit=True cur=conn.cursor() conn'and line psycopg2.OperationalError: could not connect to server: Connection refused use; postgresql:9.6.5 python:3 If I only run postgre with the info, but it is not running in python thank you Sorry, I should have explained a little more clearly. I'm dealing with a docker. And I have 3 containers, but I am trying to use python container via PostgreSQL. I want to use psycopg2 for this. But I am getting such an error. My login information is correct. I checked.
upvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/88931760
type: Question
linked to: http://stackoverflow.com/q/48422824
answer count: 2
type: UnansweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/87278620
downvote count: 1
tagged with: docker
tagged with: postgresql
tagged with: docker-compose
has answer: http://stackoverflow.com/a/50130449
has title: psycopg2.OperationalError: could not connect to server: Connection refused
has answer: http://stackoverflow.com/a/50971072

http://stackoverflow.com/q/50081220
type: Question
tagged with: boolean
has answer: http://stackoverflow.com/a/50081360
upvote count: 2
has answer: http://stackoverflow.com/a/50081339
possible better answer: http://stackoverflow.com/a/50081339
has answer: http://stackoverflow.com/a/50081403
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
answer count: 5
score: 1
accepted answer: http://stackoverflow.com/a/50081403
tagged with: python
has answer: http://stackoverflow.com/a/50084076
has body: I have the following columns in my dataframe: W1 W2 W3 W4 L1 L2 L3 L4 0 6 6 3 6 7 3 6 7 Nan Nan Nan 6 Nan Nan Nan I want to add four columns to this dataframe, SET1 .. SET4 that are: 1.0 if Wi > Li and neither are Nan 0.0 if Wi &lt; Li and neither are Nan nan if either Wi or Li are Nan In the example above, the output should be: SET1 SET2 SET3 SET4 0.0 0.0 1.0 0.0 1.0 Nan Nan Nan I use the following code to apply the first 2 bullets, but am struggling to deal with NaN properly. for i in range(1,5): wincol = "W" + str(i) losecol = "L" + str(i) setcol = "SET" + str(i) matches_df[setcol] = matches_df[wincol] &gt; matches_df[losecol] matches_df[setcol] = matches_df[setcol].astype(float)
has answer: http://stackoverflow.com/a/50081372
tagged with: nan
has title: Pandas - generate value if column is larger and not null

http://stackoverflow.com/q/50180453
has comment: http://stackoverflow.com/comment/87378618
has comment: http://stackoverflow.com/comment/87378143
type: Question
has comment: http://stackoverflow.com/comment/87378107
has answer: http://stackoverflow.com/a/50181030
has title: How to detect a declared variable that is never used?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87380009
has comment: http://stackoverflow.com/comment/87378108
has comment: http://stackoverflow.com/comment/87378114
upvote count: 2
has body: In Python, I think a common potential error is to misspell a variable name on assignment, then when you wish to use the correctly spelled version of the variable, you don't get the behavior you anticipated. For example: my_variable = "Hello" my_varible = "World" print (my_variable) The intent was to assign a new value to my_variable, but because there was a typo, the program prints "Hello" when the intent was "World". I have tried ``pylint,pychecker, andpyflakes`, but either I'm using the tools incorrectly, or they don't provide a warning for this scenario. So the question is, does a publicly available tool exist that will detect unused variables that have been assigned once and return a warning? The ideal tool would tell me that I declared my_varible at line 2 and never used it later.
has answer: http://stackoverflow.com/a/50181634
score: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/87379206
has comment: http://stackoverflow.com/comment/87378061
linked to: http://stackoverflow.com/q/59123415
favorite count: 0
has comment: http://stackoverflow.com/comment/87378095

http://stackoverflow.com/q/50106021
favorite count: 0
has body: I have some quarter level data for finance deals, so a pretty big dataset. I now want to add the following values to a new column repeated over and over: [-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12] The column should then look something like this: A -12 -11 -10 ... 11 12 -12 -11 ... 11 12 So basically just that list repeating over and over until the last row of my Dataframe. I hope this question is clear enough.
type: AnsweredQuestion
score: 3
answer count: 3
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/50106242
has answer: http://stackoverflow.com/a/50106184
tagged with: dataframe
type: Question
has title: Adding a column of repeating values to dataframe
downvote count: 0
possible better answer: http://stackoverflow.com/a/50106184
tagged with: python
has answer: http://stackoverflow.com/a/50106073
accepted answer: http://stackoverflow.com/a/50106073

http://stackoverflow.com/q/50187537
has answer: http://stackoverflow.com/a/50188334
upvote count: 1
tagged with: python
has body: I want to print csv content from remote url, but I get this: Error Traceback (most recent call last) in () ----> 1 for row in cr: 2 print(row) Error: iterator should return strings, not int (did you open the file in text mode?) My code is: import csv import urllib3 medals_url = "http://winterolympicsmedals.com/medals.csv" http = urllib3.PoolManager() r = http.request("GET", medals_url) r.status response = r.data cr = csv.reader(response) for row in cr: print(row) Thanks in advance.
has comment: http://stackoverflow.com/comment/87391845
accepted answer: http://stackoverflow.com/a/50187699
linked to: http://stackoverflow.com/q/32400867
tagged with: urllib3
has answer: http://stackoverflow.com/a/50187699
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50188334
has comment: http://stackoverflow.com/comment/87391911
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/8515053
score: 1
favorite count: 0
has title: How to print a csv content from remote url using python 3.x?
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/87391900
has comment: http://stackoverflow.com/comment/87391955
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50107573
has body: I am brand new to FreeCAD and fairly new to python in general. I have a project going on in which I have a list of several hundred (x,y) coordinates stored in two columns in an Excel doc. These points define a slice of an elevation profile. What I'm needing to do is draw a line/shape in FreeCAD using these points that can then be extruded into an extended version of this shape. Since the data is currently in excel, I'm leaning towards using pandas to access it, but I'm open to other ideas. The problem I'm having with this line of thinking so far is that I can't figure out a way to access pandas from inside FreeCAD, so I've been attempting to use Winpython(2.7.10) through the Spyder ide to import FreeCAD(0.16) and pandas into the same script. I've tried adding both the Freecad/bin and Freecad/lib folders to my path (using this recommended method https://www.freecadweb.org/wiki/Embedding_FreeCAD/en), but have yet to have any success importing. The error is: "DLL load failed: The specified procedure could not be found." .... Searching around, I can't seem to find FreeCad.dll or FreeCAD.so anywhere in my install, yet FreeCAD runs normally when used independently. To summarize: Wanting to run FreeCAD through an external python console in order to access excel data through pandas (which doesn't seem to be available within FreeCAD itself). In doing so, I get an error and FreeCAD isn't accessible. It might be a version compatibility issue, or something more complex. If you made it here, thank you for taking the time to read through my fairly complex/niche problem. Please feel free to suggest any more elegant alternatives, as I said, I'm new to this and likely haven't come across all possible solutions. Thank you
tagged with: freecad
score: 0
has title: Using Pandas with FreeCAD
tagged with: pandas
has answer: http://stackoverflow.com/a/50299214
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50109370
has comment: http://stackoverflow.com/comment/87236748
tagged with: viterbi
upvote count: 0
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/13519030
has answer: http://stackoverflow.com/a/50110737
favorite count: 0
type: Question
tagged with: shortest-path
tagged with: longest-path
tagged with: algorithm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87238550
has title: K longest paths in a DAG
tagged with: python
score: -2
has body: I want to find K longest paths in a Directed Acyclic Graph (DAG). I have read few articles about it but I couldn't find any actual code that has implemented it. Can somebody help me with a python or pseudo code? Here is one interesting algorithm explanation: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3009499/

http://stackoverflow.com/a/61021158
score: 2
upvote count: 2
downvote count: 0
has body: You're probably going to be better off building from a pandas image instead of base python. This will make iteration must faster and easier, because you won't ever have to reinstall pandas. I like amancevince/pandas ( https://hub.docker.com/r/amancevice/pandas/tags ). There are Alpine and Debian images available for every pandas tag, although I think they may all be python 3.7 now.
answers question: http://stackoverflow.com/q/50190676
type: Answer

http://stackoverflow.com/q/50210594
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
tagged with: python-3.x
has title: the function of 'bounding_boxes' and 'min_object_covered' in tf.image.sample_distorted_bounding_box?
score: 1
has body: How parameters 'bounding_boxes' and 'min_object_covered' control the generation of a single randomly distorted bounding box for an image in tf.image.sample_distorted_bounding_box? I have read the function in tensorflow api, but I still can not understand the proplem. Maybe I need a intuitive example.
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50107082
tagged with: python
type: Question
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50107301
downvote count: 0
answer count: 1
tagged with: pip
favorite count: 0
has title: Does pyenv uninstall remove all packages installed via pip?
has body: I want to remove some older versions and I'm wondering do I have to remove all of the packages installed via pip first, then do a pyenv uninstall [version]?
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50107301
upvote count: 7
score: 7
tagged with: pyenv

gmail
type: Tag
tags question: http://stackoverflow.com/q/50187007
tags question: http://stackoverflow.com/q/50204828
tags question: http://stackoverflow.com/q/50127690
tag name: gmail
tags question: http://stackoverflow.com/q/50200617

http://stackoverflow.com/comment/87313836
type: QuestionComment
comment on: http://stackoverflow.com/q/50147760
type: Comment
score: 2
has text: @PhillipsKruman list comprehensions are great when your desired result is a list. Here there is no point in creating a list of `None` (which is what `foo.remove(i)` returns. You don't even store the result.

http://stackoverflow.com/comment/87281289
comment on: http://stackoverflow.com/q/50113359
score: 0
has text: @Zhivko.Kostadinov not working
type: Comment
type: QuestionComment

http://stackoverflow.com/a/69965027
score: 9
upvote count: 9
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50214773
has body: As pointed out, the currently accepted solution displays the correct HTML5 widget, but the value returned from the widget in the frontend will not be accepted by the field validation in the backend. A working solution is to use a datetime-local widget as well as a custom DateTimeField recognizing the datetime format: from django import forms class DateTimeLocalInput(forms.DateTimeInput): input_type = "datetime-local" class DateTimeLocalField(forms.DateTimeField): # Set DATETIME_INPUT_FORMATS here because, if USE_L10N # is True, the locale-dictated format will be applied # instead of settings.DATETIME_INPUT_FORMATS. # See also: # https://developer.mozilla.org/en-US/docs/Web/HTML/Date_and_time_formats input_formats = [ "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%dT%H:%M", ] widget = DateTimeLocalInput(format="%Y-%m-%dT%H:%M") class Form(forms.Form): my_datetime_field = DateTimeLocalField()

http://stackoverflow.com/q/50226004
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: How to count number of rows in a group in pandas group by ID?
favorite count: 0
tagged with: pandas
score: 1
duplicate of: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/87469320
type: Question
has body: I am an R user and learning python pandas. I am wondering how to covert to a data frame of count number of products that per agent has in Python Pandas. Data: EVT_ID CUST_KEY AGT_KEY product_group 0 1-2U 4624429 6088722 Other_product 1 1-2B 4588790 5443951 Cold 2 1-2T 4368207 6343767 Hot 3 1-2G 4615587 6294539 Warm Convert : AGT_KEY other_product Cold Hot warm 1-2U 1 0 0 0 1-2B 0 1 0 0 1-2T 0 0 1 0 1-2G 0 0 0 1 R code: df&lt;-as.data.frame(mydata%&gt;%group_by(AGT_KEY)%&gt;%count(product_group)%&gt;% spread(product_group,n)) Python i wrote: num_offers_agent_level=agents'ADE_AGT_CO_REP_KEY','Offer_group3'.pivot_table(index=['ADE_AGT_CO_REP_KEY'],columns='Offer_group3',aggfunc='count')
answer count: 0
linked to: http://stackoverflow.com/q/47152691

http://stackoverflow.com/comment/87299844
comment on: http://stackoverflow.com/a/50139372
score: 1
type: Comment
has text: Apologies! New here. I can't figure out why they are different, but I get the same results as you did once I drop the rows with empty values.
type: AnswerComment

http://stackoverflow.com/comment/126536021
has text: or even shorter Path(filepath).parent
type: Comment
comment on: http://stackoverflow.com/a/70028298
type: AnswerComment
score: 6

http://stackoverflow.com/q/50125014
linked to: http://stackoverflow.com/q/24653950
has title: XHTML Parsing using minidom
upvote count: 2
tagged with: minidom
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87268297
tagged with: http://stackoverflow.com/tag/xhtml
downvote count: 0
has comment: http://stackoverflow.com/comment/87268366
tagged with: python
has comment: http://stackoverflow.com/comment/87268319
has comment: http://stackoverflow.com/comment/87268452
score: 2
answer count: 1
has body: I want to parse this to get the weather report. Using python minidom Cloudy 57°F 14°C now i cant just getElementsByTagName("h4") because i will be doing this parse on alot of different weather websites so the amount of h4's tag might be different on each website. But, all of the info i need no matter what state i choose will all be under id="current-temp-cont" I currently am working with something like this but i keep import sys import xml.dom.minidom document = xml.dom.minidom.parse(sys.argv[1]) weather = document.getElementById("current-temps-cont") weatherReal = weather.getElementsByTagName("h4") print(weatherReal) ~ When i run i get. Can someone explain what im missing or if im approaching this the wrong way? Traceback (most recent call last): File "x.py", line 7, in <module> weatherReal = weather.getElementsByTagName("h4") AttributeError: 'NoneType' object has no attribute 'getElementsByTagName'
tagged with: parsing
has comment: http://stackoverflow.com/comment/87280284
favorite count: 0
has comment: http://stackoverflow.com/comment/87268591
type: Question
has answer: http://stackoverflow.com/a/50129574

http://stackoverflow.com/a/50241949
accepted answer of: http://stackoverflow.com/q/50146815
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50146815
type: Answer
has body: After looking for a long time, was able to answer my own question by looking on the web. I had the following: First: Last: Email: It turns out that closing a div will close a form tag so rows were being dynamically added outside the form. By moving the form directive outside of the div, I started getting multiple values when the form was submitted I also eventually found a more detailed answer at Form Issue (closing itself early in table)
score: 0

audio
tags question: http://stackoverflow.com/q/50156917
tags question: http://stackoverflow.com/q/50198977
tags question: http://stackoverflow.com/q/50134790
tags question: http://stackoverflow.com/q/50159721
tags question: http://stackoverflow.com/q/50119444
tags question: http://stackoverflow.com/q/50090404
tags question: http://stackoverflow.com/q/50087271
type: Tag
tags question: http://stackoverflow.com/q/50139417
tags question: http://stackoverflow.com/q/50212416
tag name: audio

http://stackoverflow.com/comment/87406575
comment on: http://stackoverflow.com/q/50194711
type: QuestionComment
type: Comment
has text: How could you not be able to find anything online? This is literally the first thing about `Entry` and `Text` in the docs.
score: 1

http://stackoverflow.com/comment/87240893
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50111828
score: 0
has text: Use shell=True but remove the comma after `python3`.

http://stackoverflow.com/comment/87224742
type: QuestionComment
type: Comment
has text: @user3605780 Since your grouping first, and then performing a `.diff()` you get far more `NaN` values than you think you are getting. Within EVERY group, the first row is `NaN` for the diff, not just the first row of your 10 row `df`.
score: 0
comment on: http://stackoverflow.com/q/50103295

http://stackoverflow.com/a/50132549
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50132383
has body: Use list compressions: In [4]: [[b in a for a in y] for b in x] Out[4]: [[True, False, False, True, False], [False, True, False, False, False], [False, False, False, False, False]] Testing the timing: %timeit print([[b in a for a in y] for b in x]) &lt;lots of printing&gt; 228 µs ± 5.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit for i in x: print([i in x for x in y]) &lt;lots of printing&gt; 492 µs ± 4.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) So half the time.
answers question: http://stackoverflow.com/q/50132383
has comment: http://stackoverflow.com/comment/87283211
type: Answer
has comment: http://stackoverflow.com/comment/87282962
has comment: http://stackoverflow.com/comment/87283266
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87283435
downvote count: 0

http://stackoverflow.com/comment/87418575
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50200985
has text: Have you spent time pouring over the `good_morning` documentation? did you try to get it to work for just one `tick` before iterating over `dataa`?
type: Comment

http://stackoverflow.com/comment/87329551
type: Comment
type: QuestionComment
has text: I think it would work but I was looking for a Python built-in module, so it may be exploitable by any user.
comment on: http://stackoverflow.com/q/50145116
score: 0

http://stackoverflow.com/comment/87220748
type: Comment
has text: You many want to look at [sqlites-serialized-mode](https://stackoverflow.com/questions/7850025/sqlites-serialized-mode)
comment on: http://stackoverflow.com/q/50101816
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87318539
type: Comment
has text: @Aran-Fey your last sentence nails it. I couldn't state it better: modifying the variable vs the object.
type: AnswerComment
comment on: http://stackoverflow.com/a/50150242
score: 0

http://stackoverflow.com/a/50233035
has comment: http://stackoverflow.com/comment/87484111
answers question: http://stackoverflow.com/q/50227577
type: Answer
accepted answer of: http://stackoverflow.com/q/50227577
has comment: http://stackoverflow.com/comment/87484442
score: 0
has body: This is my solution that can be used as example: from Tkinter import * from time import sleep def run_script(): text = StringVar() l = Label(master, textvariable=text, fg='blue').grid(row=6) text.set('calling my function1') master.update() sleep(2) text.set('end of function1') def call_report(): run_script() if __name__ == '__main__': master = Tk() username = Entry(master, name='username', width=30) password = Entry(master, name='password', show='*', width=30) username.grid(row=0, column=1, padx=10, pady=(10,2)) password.grid(row=1, column=1, padx=10, pady=2) button = Button(master, text='start script', command=lambda: call_report()) button.grid(row=6, column=1, sticky=W, pady=10) master.mainloop() I've changed text to textvariable in Label, and I added master.update(). In this way it force the GUI to redraw. Just to test if the GUI was changing, I tested with sleep. It is possible to update more time (for example before calling a function).
type: AcceptedAnswer

http://stackoverflow.com/a/50083663
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Yes, Python supports multiple inheritance: class indigestion(): def burp(self): return " ".join("burp" for _ in range(int(self))) class int_with_indigestion(int, indigestion): pass class float_with_indigestion(float, indigestion): pass n = int_with_indigestion(13) print(n ** 2) print(n.burp()) f = float_with_indigestion(5.3) print(f ** 2) print(f.burp()) USAGE &gt; python3 test.py 169 burp burp burp burp burp burp burp burp burp burp burp burp burp 28.09 burp burp burp burp burp &gt;
answers question: http://stackoverflow.com/q/50083589
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50083589

http://stackoverflow.com/comment/87374859
type: Comment
comment on: http://stackoverflow.com/q/50178578
has text: http://ipyparallel.readthedocs.io/en/latest/magics.html
type: QuestionComment
score: 1

http://stackoverflow.com/q/50224587
tagged with: qt
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50230486
answer count: 1
has comment: http://stackoverflow.com/comment/87466908
has body: The "supports" bubble acts similar to a tool tip, when button is clicked it appears next to a button. How is this bubble created? it allows widgets to be placed inside itself. Is this a widget by itself or some sort of float layout? I am new to QT and couldn't figure out how to approach this, which widget to use to achieve this?
upvote count: 8
favorite count: 0
score: 8
type: Question
has title: Approach to Create Floating Box UI in QT
has answer: http://stackoverflow.com/a/50230486
tagged with: python
has comment: http://stackoverflow.com/comment/102261717

http://stackoverflow.com/comment/87407892
type: Comment
comment on: http://stackoverflow.com/q/50195402
type: QuestionComment
has text: Perhaps you're looking for [`%run`](https://stackoverflow.com/questions/11744181/running-python-script-inside-ipython)?
score: 0

http://stackoverflow.com/comment/87268717
has text: @EuniceTT, No problem. Please feel free to accept (green tick on left) if this helped.
type: Comment
comment on: http://stackoverflow.com/a/50125110
type: AnswerComment
score: 0

http://stackoverflow.com/q/50112726
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87244479
tagged with: shopify
has comment: http://stackoverflow.com/comment/87244249
has title: Shopify App OAuth Error Whitelisted URL if user is not logged in
has comment: http://stackoverflow.com/comment/89583071
has body: My app was working two weeks ago. If the user is already logged in, I am not getting this error. But, if user is not logged in, I am getting that Redirect URI Whitelisted error. On checking the issue, I found out that - If user is already logged in, on browser, I am seeing this url - https://vsanalytics.myshopify.com/admin/oauth/request_grant?client_id=&amp;redirect_uri=http%3A%2F%2F54.218.116.25%3A8080%2Flogin%2Ffinalize%2F&amp;scope=write_products%2Cwrite_orders%2Cwrite_customers%2Cread_checkouts%2Cread_price_rules%2Cwrite_price_rules%2Cread_marketing_events%2Cwrite_marketing_events And it is working fine. But, if user is not logged in, I am seeing this - https://vsanalytics.myshopify.com/admin/oauth/request_grant?client_id=70ffd0b9d365026205e5a06a7a55788a&amp;redirect_uri=http%253A%252F%252F54.218.116.25%253A8080%252Flogin%252Ffinalize%252F&amp;scope=write_products%252Cwrite_orders%252Cwrite_customers%252Cread_checkouts%252Cread_price_rules%252Cwrite_price_rules%252Cread_marketing_events%252Cwrite_marketing_events Clearly, redirect uri is double encoded when user is logged in
score: 1
tagged with: python
favorite count: 0
type: Question

shopify
tag name: shopify
tags question: http://stackoverflow.com/q/50112726
type: Tag

http://stackoverflow.com/comment/87379894
comment on: http://stackoverflow.com/q/50180988
score: 0
has text: It's a dataframe with a single column. I've done this with other dataframes with larger values and I didn't have this issue. I don't believe the index column is producing the error
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50087868
downvote count: 0
accepted answer: http://stackoverflow.com/a/50089850
tagged with: python
tagged with: heatmap
has body: I am able to get the radial heatmap in ggplot2 like this How do I get the same using matplotlib? This is a sample df and visualisation, not the data used to create the radial heatmap using ggplot2. import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.DataFrame(np.random.uniform(-1, 1, (24,12))) df.columns = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] sns.heatmap(df, cmap = "coolwarm", cbar = False) EDIT: My data's dimension is the same as the sample df I have provided. I would like to plot the same.
type: AnsweredQuestion
has title: How do I create radial heatmap in matplotlib?
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50089850
has answer: http://stackoverflow.com/a/50088128
possible better answer: http://stackoverflow.com/a/50088128
favorite count: 0
type: Question
answer count: 2
upvote count: 5
score: 5

http://stackoverflow.com/q/50097765
tagged with: python
linked to: http://stackoverflow.com/q/49771837
has comment: http://stackoverflow.com/comment/87260648
has comment: http://stackoverflow.com/comment/87262259
score: 0
has comment: http://stackoverflow.com/comment/87261155
has comment: http://stackoverflow.com/comment/87265605
upvote count: 1
has comment: http://stackoverflow.com/comment/87218720
tagged with: matplotlib
answer count: 1
downvote count: 1
has body: I use the following code import sys from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout, \ QLineEdit, QMessageBox, QInputDialog, QLabel, QHBoxLayout, QGridLayout, QStackedLayout, QFormLayout from PyQt5 import QtCore, QtGui, QtWidgets import time import matplotlib matplotlib.use("TkAgg") from matplotlib.lines import Line2D import matplotlib.animation as animation from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt from matplotlib.figure import Figure # data import numpy as np #import matplotlib.pyplot as plt import pandas as pd import os import csv # percent MW x=['BE2000', 'BE2020', 'BE5000', 'BE6010', 'BE6017', 'BE6020', 'BE6027', 'BE6030', 'BE6050', 'BE6057', 'BE6061', 'BE6062', 'BE6063', 'BE6070', 'BE6073', 'BE6075', 'BE6080', 'BE6090', 'BE7000', 'BE7010'] y=[0.0002716766988612973, 0.005178087393490427, 0.0014053668695097226, 0.3174139251746979, 0.006049724003653125, 0.24824287385322272, 0.0004986331396716525, 0.19624266416568525, 0.13170894569069627, 0.0028535946936992873, 0.0002737864422892905, 0.0011817396106664916, 0.0029533382584451574, 0.03281361420815501, 0.000273411124091493, 0.002558801432193384, 0.027004861403488886, 0.004918720459633545, 0.006030278629435105, 0.0002858345295419518] #figure = plt.figure() H = np.array([[100, 2, 39, 190], [402, 55, 369, 1023], [300, 700, 8, 412], [170, 530, 330, 1]]) Z = np.array([[3, 290, 600, 480], [1011, 230, 830, 0], [152, 750, 5, 919], [340, 7, 543, 812]]) class Window(QDialog): def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init_ self.im = None self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect('button_press_event', self.on_button_press_event) # …
tagged with: pyqt5
has title: Rotate or resize the axis ticks using pyqt5 in python
has comment: http://stackoverflow.com/comment/87260576
has comment: http://stackoverflow.com/comment/87260406
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87261684
has answer: http://stackoverflow.com/a/55216371
has comment: http://stackoverflow.com/comment/87219448
has comment: http://stackoverflow.com/comment/87219062

http://stackoverflow.com/a/50152227
score: 0
has body: First sort the elements of list and then remove duplicate. Find my code and listsfinal represents your answer. links = [['a', 'b', 'c', 'd'], ['c', 'd', 'a', 'b'], ['e', 'f', 'g', 'h'], ['g', 'h', 'e', 'f']] links1=[] for elements in links: elements=sorted(elements) links1.append(elements) # print links1 linksfinal=[list(t) for t in set(tuple(element) for element in links1)] print linksfinal
has comment: http://stackoverflow.com/comment/87340381
type: Answer
answers question: http://stackoverflow.com/q/50151240

http://stackoverflow.com/a/55678557
downvote count: 0
answers question: http://stackoverflow.com/q/50159662
type: Answer
upvote count: 4
score: 4
has body: conda update conda did not work for me, so I will just post my solution here. First, go to python interactive shell, do $ python &gt;&gt; import sysconfig &gt;&gt; print(sysconfig.__file__) This should give you where the file locates for sysconfig. Then what you need to go to that file and edit the source code, for me it was /opt/conda/envs/test/lib/python3.6/sysconfig.py, then find the function and change function signature for _get_sysconfigdata_name, what I did was make check_exists default to True.
has comment: http://stackoverflow.com/comment/132257243

http://stackoverflow.com/comment/87376682
type: QuestionComment
score: 0
has text: Due to floating point rounding, even `np.arange(0.3, 12.5, 0.6).astype(int)` can be produce surprises.
comment on: http://stackoverflow.com/q/50171141
type: Comment

http://stackoverflow.com/q/50192556
linked to: http://stackoverflow.com/q/31728528
has comment: http://stackoverflow.com/comment/87422843
has comment: http://stackoverflow.com/comment/87404074
has comment: http://stackoverflow.com/comment/87422814
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87402695
linked to: http://stackoverflow.com/q/28099892
answer count: 0
has body: So I am trying to get this density plot to work for the given integral. Not sure what I am missing but I am getting this error. Traceback: runfile('F:/PHY 281/Homework/Set 4/tyest3.py', wdir='F:/PHY 281/Homework/Set 4') Traceback (most recent call last): File "", line 1, in runfile('F:/PHY 281/Homework/Set 4/tyest3.py', wdir='F:/PHY 281/Homework/Set 4') File "E:\Programs\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "E:\Programs\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "F:/PHY 281/Homework/Set 4/tyest3.py", line 27, in gb = quad(Jm,0,1e-6) [0] File "E:\Programs\Anaconda\lib\site-packages\scipy\integrate\quadpack.py", line 323, in quad points) File "E:\Programs\Anaconda\lib\site-packages\scipy\integrate\quadpack.py", line 388, in _quad return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit) TypeError: only length-1 arrays can be converted to Python scalars from scipy.integrate import quad import numpy as np import matplotlib.pyplot as plt from numpy import cos,sin,pi lmda = 5e-7 m = 1 def Jm(thta): return (1/pi)*cos(m*thta-x*sin(thta)) xvals = np.linspace(-10*lmda,10*lmda,200) zvals = np.linspace(-20*lmda,20*lmda,200) x,z = np.meshgrid(xvals,zvals) gb = quad(Jm,0,1e-6) [0] plt.figure(figsize=(12,8)) plt.imshow(gb,origin='lower',extent=[-10*lmda,10*lmda,-20*lmda,20*lmda]) cbar = plt.colorbar() cbar.ax.set_ylabel('V/m') cbar.ax.set_xlabel('E') plt.xlabel('x nm') plt.ylabel('y nm') plt.show()
type: UnansweredQuestion
tagged with: physics
has comment: http://stackoverflow.com/comment/87404642
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/87422411
has title: Density plot of integral. TypeError: only length-1 arrays can be converted to Python scalars

http://stackoverflow.com/a/50136304
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50136252
answers question: http://stackoverflow.com/q/50136252
has body: First replace NaNs and then sum per rows: df['MasterID'] = df.fillna('').sum(axis=1) If need specify columns names: df['MasterID'] = df'ID1','ID2'.fillna('').sum(axis=1) print (df) ID1 ID2 MasterID 0 Apple NaN Apple 1 Orange NaN Orange 2 NaN Pear Pear 3 NaN Grape Grape
has comment: http://stackoverflow.com/comment/87290851
type: Answer
has comment: http://stackoverflow.com/comment/87290708
upvote count: 3
score: 3

http://stackoverflow.com/comment/87341449
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50137319
has text: Did this resolve the issue? In short, you should be passing python datetime objects to the `dt` field.
type: Comment

http://stackoverflow.com/a/50148044
answers question: http://stackoverflow.com/q/50146782
has body: Use np.stack with the axis keyword def vectorf(x, y, z): return np.stack((y, x, z), axis = -1)
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50146782
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50100800
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has comment: http://stackoverflow.com/comment/87219250
has body: EDIT: I have solved the issue: the time_zone module requires a paid subscription The aim is to scrape the user's timezone (from IP address) through IPStack. I am able to scrape the data contained in the 'main' section. That is, those that don't require "specify response fields". However, the remainder of the data, such as that contained within 'time_zone', I am having trouble scraping it. I am quite new to scraping, so perhaps I am making an obvious error. The documentation can be found here: https://ipstack.com/documentation. from urllib.request import urlopen import json baseurl = """ http://api.ipstack.com/155.42.107.7 ?access_key=YOUR_ACCESS_CODE &fields=time_zone """ f = urlopen(baseurl) json_string = f.read() parsed_json = json.loads(json_string) timezone_id = parsed_json['time_zone']['id'] f.close() print(timezone_id) The output is: "KEYERROR: 'time_zone'" Thank you, any help would be appreciated!
tagged with: web-scraping
has title: How to scrape time_zone from IPStack?
has comment: http://stackoverflow.com/comment/88115517
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50552474
has answer: http://stackoverflow.com/a/50552474

http://stackoverflow.com/comment/87290025
type: AnswerComment
has text: Hey, I had a go of changing it around, but the problem is it still just prints the same first list over and over. Is this because the inputs arent resetting after each loop?, I guess the "x" in range" should have been a different letter
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50135599

http://stackoverflow.com/comment/87356512
type: AnswerComment
score: 0
has text: The value followed by `b=` is a digital signature value
comment on: http://stackoverflow.com/a/50106742
type: Comment

http://stackoverflow.com/comment/87341367
type: QuestionComment
comment on: http://stackoverflow.com/q/50161754
has text: "I'll be back shortly to post my code." ... where are you going? ;)
type: Comment
score: 3

http://stackoverflow.com/comment/87263926
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50122770
has text: You could wrap the `raw_input` with an `int` call, but that'll throw an exception if the user entered a string that can't be converted (which is fine, I guess, if you catch it).
type: Comment

http://stackoverflow.com/a/50140995
type: Answer
answers question: http://stackoverflow.com/q/50138110
score: 1
upvote count: 1
downvote count: 0
has body: "120 cm" is a string, not an integer, so that's a confusing example. Some ways to find "unexpected" values include: Use "describe" to examine the range of numerical values, to see if there are any far outside of your expected range. Use "unique" to see the set of all values for cases where you expect a small number of permitted values, like a gender field. Look at the datatypes of columns to see whether there are strings creeping in to fields that are supposed to be numerical. Use regexps if valid values for a particular column follow a predictable pattern.

http://stackoverflow.com/q/50122358
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87262635
type: Question
type: AnsweredQuestion
has title: Code is the same as previous lines but gives an error?
score: 1
has body: I keep getting TypeError: 'int' object is not subscriptable within my evenly() function. equall() and gauss() work fine if I comment out the evenly function, and all I did was copy the code from them and used my stepe() function instead of step() or stepn() import numpy as np import matplotlib.pyplot as plt from numpy.random import rand,seed,randn steps = 1 walks = 10000 walk = np.zeros(steps + 1) def step(): if rand() &lt; 0.5: return 1.0 return -1.0 def stepn(): return randn() + 0.5 def stepe(): return (6*(rand()-0.5)) def equall(walks,steps): l = [] for w in range(walks): for s in range(steps): walk[s+1] = walk[s] + step() l.append(walk[steps]) return l def gauss(walks,steps): l = [] for w in range(walks): for s in range(steps): walk[s+1] = walk[s] + stepn() l.append(walk[steps]) return l def evenly(walk,steps): l = [] for w in range(walks): for s in range(steps): walk[s+1] = walk[s] + stepn() l.append(walk[steps]) return l plt.figure(figsize=(10,7)) plt.hist(equall(walks,steps),bins=15) plt.show() plt.hist(gauss(walks,steps),bins=15) plt.show() plt.hist(evenly(walks,steps),bins=15) plt.show()
tagged with: python
accepted answer: http://stackoverflow.com/a/50122411
tagged with: random-walk
favorite count: 0
has answer: http://stackoverflow.com/a/50122411
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/87262743

http://stackoverflow.com/q/50101543
has answer: http://stackoverflow.com/a/50101738
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/50101892
answer count: 4
has answer: http://stackoverflow.com/a/50101596
accepted answer: http://stackoverflow.com/a/50101596
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/87219802
possible better answer: http://stackoverflow.com/a/50101644
has title: converting TXT to CSV python
has comment: http://stackoverflow.com/comment/87219816
has answer: http://stackoverflow.com/a/50101644
downvote count: 1
favorite count: 0
type: Question
has body: I have a txt data. it looks as follows time pos 0.02 1 0.1 2 ... and so on. so the each line is separated with a space. I need to convert it in to a CSV file. like time,pos 0.02,1 0.1,2 0.15,3 How can I do it with python ? This is what I have tried time = [] pos = [] def get_data(filename): with open(filename, 'r') as csvfile: csvFileReader = csv.reader(csvfile) next(csvFileReader) for row in csvFileReader: time.append((row[0].split(' ')[0])) pos.append((row[1])) return

http://stackoverflow.com/q/50194752
has comment: http://stackoverflow.com/comment/87406589
has comment: http://stackoverflow.com/comment/87406771
has answer: http://stackoverflow.com/a/50194790
has comment: http://stackoverflow.com/comment/87406622
tagged with: arrays
accepted answer: http://stackoverflow.com/a/50194798
downvote count: 0
has comment: http://stackoverflow.com/comment/87406863
tagged with: python
upvote count: 7
has body: I have a numpy array like this: candidates = array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1], [1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0]]) And I do not understand what is the difference between candidates[0]: candidates[0] = array([1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0] candidates[0].shape = (34,) And candidates[0:1]: candidates[0:1] = array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0]]) candidates[0:1].shape = (1, 34) because I believe the two should give the exact same results? I mean the later i.e. candidates[0:1] is supposed to represent the first element only, right? So, what is the difference between the two exactly?
linked to: http://stackoverflow.com/q/42882842
has answer: http://stackoverflow.com/a/50194798
has comment: http://stackoverflow.com/comment/87406817
has title: difference between A[0] and A[0:1] numpy arrays in python
type: AnsweredQuestion
answer count: 3
score: 7
linked to: http://stackoverflow.com/q/22053050
possible better answer: http://stackoverflow.com/a/50194777
has comment: http://stackoverflow.com/comment/87406654
has comment: http://stackoverflow.com/comment/87407202
has answer: http://stackoverflow.com/a/50194777
has comment: http://stackoverflow.com/comment/87406683
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/87277565
has text: this works great.
comment on: http://stackoverflow.com/q/50122470
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50213782
linked to: http://stackoverflow.com/q/25908484
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87444932
accepted answer: http://stackoverflow.com/a/50214154
downvote count: 0
has comment: http://stackoverflow.com/comment/87556243
tagged with: elasticsearch
has comment: http://stackoverflow.com/comment/87462172
has comment: http://stackoverflow.com/comment/87445007
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87444911
has answer: http://stackoverflow.com/a/50214154
has body: I have installed elasticsearch python package and I have created a elastic clustere. I am using below python code to send data to elastic cloud: from elasticsearch import Elasticsearch, RequestsHttpConnection import time import datetime es = Elasticsearch(['70.19.172.110:9200'],http_auth=('&lt;username&gt;','&lt;password&gt;')) for x in range(0,5): es.index(index='test', doc_type='json', id=x, body={ 'data1':"Hello World', 'value':325, 'time': datetime.datetime.now() }) print("Data sent {} ".format(x)) time.sleep(60) So as you can see in the code I am sending the data with the interval of 1min time.sleep(60). This works fine and all the 5 data's are in the elasticsearch. Then I changed the time.sleep(60) to time.sleep(300) and it gave me below error: elasticsearch.exceptions.ConnectionTimeout: ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host='70.19.172.110', port=9200): Read timed out. (read timeout=10)) Is there anything which I am doing wrong. Is there any way I can keep connected to the elasticsearch so that I dont't through these types of errors. Thanks.
has title: Read timeout error while using elastic search python package
has comment: http://stackoverflow.com/comment/87444486
has comment: http://stackoverflow.com/comment/87462224
answer count: 1
has comment: http://stackoverflow.com/comment/87444764
tagged with: python

http://stackoverflow.com/q/50154213
answer count: 1
favorite count: 0
type: Question
has title: Drop Repeated Values in Column, Retaining the Row
tagged with: pandas
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50154229
accepted answer: http://stackoverflow.com/a/50154229
has body: I have a problem similar to dropping duplicates, but I need to retain the row that has the repeated value. So essentially, I need to retain the first value and then replace every repetition of it with ''. Col1 Col2 a 1 b 1 c 1 d 2 What I need is: Col1 Col2 a 1 b c d 2 Thanks.
type: AnsweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87465780
comment on: http://stackoverflow.com/q/50224053
type: QuestionComment
type: Comment
has text: You seem to have internet problems (Network is unreachable)
score: 0

http://stackoverflow.com/q/50143360
score: 0
has comment: http://stackoverflow.com/comment/87306933
answer count: 1
linked to: http://stackoverflow.com/q/15821121
type: Question
accepted answer: http://stackoverflow.com/a/50147245
has answer: http://stackoverflow.com/a/50147245
has body: I don't think the other questions on stack overflow that sound like this are actually this question. (I did read several of them.) I downloaded a module, thinkbayes.py. When I'm in IDLE, typing "from thinkbayes import pmf" gives the following. Traceback (most recent call last): File "", line 1, in from thinkbayes import pmf ModuleNotFoundError: No module named 'thinkbayes' I copied thinkbayes.py to many directories where python is installed, and that didn't help. So, I searched online for this and found recommendations like: SET SAVE=%PYTHONPATH% SET PYTHONPATH=. python scripts/doit.py SET PYTHONPATH=%SAVE% (in stack overflow) I tried that (and other recommendations) both in IDLE and in the Windows command-line interface. Neither one recognizes those commands. I changed directories to C: -- no improvement. What am I missing here that everyone else knows? To repeat, I'm trying to get a Python 3 installation to recognize a .py file that I've copied into the 'Scripts' directory, the 'include' directory, etc. Thanks, Sakyataksis
tagged with: windows
tagged with: path
tagged with: python
tagged with: python-idle
has comment: http://stackoverflow.com/comment/87305001
has comment: http://stackoverflow.com/comment/87306842
has comment: http://stackoverflow.com/comment/87311745
has title: IDLE's path, not Windows' path: How do I edit Python's path in MS Windows to include a .py module?
type: AnsweredQuestion

facebook
tags question: http://stackoverflow.com/q/50183503
tags question: http://stackoverflow.com/q/50159067
tag name: facebook
type: Tag
tags question: http://stackoverflow.com/q/50162757
tags question: http://stackoverflow.com/q/50221437
tags question: http://stackoverflow.com/q/50200669

http://stackoverflow.com/comment/87757502
has text: thanks, i use conda now,btw i had tried in elementOS but still failed.
comment on: http://stackoverflow.com/q/50128924
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50088128
has comment: http://stackoverflow.com/comment/87192687
has comment: http://stackoverflow.com/comment/87195649
score: 2
has comment: http://stackoverflow.com/comment/87192539
has comment: http://stackoverflow.com/comment/87195717
type: Answer
has comment: http://stackoverflow.com/comment/87194796
has comment: http://stackoverflow.com/comment/87195401
has comment: http://stackoverflow.com/comment/87195104
answers question: http://stackoverflow.com/q/50087868
has comment: http://stackoverflow.com/comment/87195597
has comment: http://stackoverflow.com/comment/87192517
has body: I would use polar. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) n= 12 rad = np.linspace(0, 10, n) a = np.linspace(0, 2 * np.pi, n) r, th = np.meshgrid(rad, a) z = np.random.rand(n,n) plt.subplot(projection="polar") plt.pcolormesh(th, r, z) plt.plot(a, r, color='k', ls='none',cmap = 'binary') plt.grid() plt.colorbar() plt.show()
upvote count: 2
has comment: http://stackoverflow.com/comment/87195806
downvote count: 0
has comment: http://stackoverflow.com/comment/87193363
has comment: http://stackoverflow.com/comment/87192416

http://stackoverflow.com/comment/87172350
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50077995
has text: yes for all words I get the same number

http://stackoverflow.com/comment/87316235
comment on: http://stackoverflow.com/q/50148321
type: Comment
type: QuestionComment
has text: This could be a place to start: https://stackoverflow.com/questions/49247884/querying-from-microsoft-sql-to-a-pandas-dataframe/49250361#49250361 .
score: 0

http://stackoverflow.com/comment/87422577
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50202870
has text: what if the length of list is something around 10^6? then the nested loop will not be efficient.

http://stackoverflow.com/comment/87297320
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50139250
score: 1
has text: I see a mix of tabs and spaces in the code you posted here on SO; see [this screenshot from your text in Sublime Text, where dots are spaces and dashes are tabs](https://i.sstatic.net/eWSZd.png). Don't do that, configure your editor to only use spaces for indentation.

http://stackoverflow.com/comment/87467008
has text: Entry with 'place_1', 'thing1 and 'ind1' is duplicate. How would you expect it to be resolved? And if I understand correctly, you want trans_id to be the value in your desired output?
score: 0
comment on: http://stackoverflow.com/q/50223432
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50088134
type: Question
has title: Pandas DataFrame - Add Column Containing Conditional Sum of "previous" Rows
type: UnansweredQuestion
has body: I have a dataset of tennis match results as follows: tennis_cols = ['Year','TourNo','MatchNo','Round','Winner','Loser'] tennis_rslts = [ [2018, 1, 1, 'QF', 'PlayerA', 'PlayerB'] ,[2018, 1, 2, 'QF', 'PlayerC', 'PlayerD'] ,[2018, 1, 3, 'QF', 'PlayerE', 'PlayerF'] ,[2018, 1, 4, 'QF', 'PlayerG', 'PlayerH'] ,[2018, 1, 5, 'SF', 'PlayerA', 'PlayerC'] ,[2018, 1, 6, 'SF', 'PlayerE', 'PlayerG'] ,[2018, 1, 7, 'F', 'PlayerA', 'PlayerE'] ] dfTennis=pd.DataFrame(tennis_rslts,columns=tennis_cols) dfTennis Year TourNo MatchNo Round Winner Loser 0 2018 1 1 QF PlayerA PlayerB 1 2018 1 2 QF PlayerC PlayerD 2 2018 1 3 QF PlayerE PlayerF 3 2018 1 4 QF PlayerG PlayerH 4 2018 1 5 SF PlayerA PlayerC 5 2018 1 6 SF PlayerE PlayerG 6 2018 1 7 F PlayerA PlayerE I want to add a column, WinsToDate, which contains the number of wins the winner of this match had before the current match, i.e.: Year TourNo MatchNo Round Winner Loser WinsToDate 0 2018 1 1 QF PlayerA PlayerB 0 1 2018 1 2 QF PlayerC PlayerD 0 2 2018 1 3 QF PlayerE PlayerF 0 3 2018 1 4 QF PlayerG PlayerH 0 4 2018 1 5 SF PlayerA PlayerC 1 &lt;-- PlayerA won MatchNo 1 5 2018 1 6 SF PlayerE PlayerG 1 &lt;-- PlayerE won MatchNo 3 6 2018 1 7 F PlayerA PlayerE 2 &lt;-- PlayerA won MatchNo 1 and 5 My real-world dataset is large enough that iterating through the dataset is too slow. Any ideas how I achieve the result in an efficient manner? Essentially I want to count the number of rows where the Winner matches the row being processed and the MatchNo is less than the current row being processed. ** UPDATE ** I can get a count of the number of times the winner occurs in the Dataframe using: dfTennis['Count'] = list(map(lambda x : len(dfTennis[(dfTennis['Winner'] == x)]), dfTennis['Winner'])) But this counts all occurrences rather than all occurrences before the current row.
tagged with: python
has answer: http://stackoverflow.com/a/50106218
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87192408
answer count: 1
tagged with: dataframe

http://stackoverflow.com/comment/87389762
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50162072
has text: why did i get "recursion error : limit exceded" so ?
type: Comment

http://stackoverflow.com/comment/87201642
comment on: http://stackoverflow.com/q/50092680
score: 0
has text: I know, but I want to access the tuple's[0]
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50085112
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
has body: I am trying to figure out what the best way to communicate between different widgets is, where the widgets are custom classes inheriting from tkinter widgets and I have several frames present (to help with layout management). Consider for example the following simple gui (written for python 3, change tkinter to Tkinter for python 2): from tkinter import Frame,Button,Tk class GUI(Frame): def __init__(self, root): Frame.__init__(self,root) self.upper_frame=Frame(root) self.upper_frame.pack() self.lower_frame=Frame(root) self.lower_frame.pack() self.upper_btn1 = Button(self.upper_frame, text="upper button 1") self.upper_btn2 = Button(self.upper_frame, text="upper button 2") self.upper_btn1.grid(row=0,column=0) self.upper_btn2.grid(row=0,column=1) self.lower_btn = CustomButton(self.lower_frame, "lower button 3") self.lower_btn.pack() class CustomButton(Button): def __init__(self,master,text): Button.__init__(self,master,text=text) self.configure(command=self.onClick) def onClick(self): print("here I want to change the text of upper button 1") root = Tk() my_gui = GUI(root) root.mainloop() The reason I put them in different frames is because I want to use different layout managers in the two different frames to create a more complicated layout. However, I want the command in lower_btn to change properties of eg upper_btn1. However, I can not immediately access upper_btn1 from the instance lower_btn of the customized class CustomButton. The parent of lower_btn is frame2, and the frame2 parent is root (not the GUI instance). If I change the parent of lower_btn to the GUI instance, ie self.lower_btn = CustomButton(self, "lower button") it will not be placed correctly when using pack(). If I change the parent of frame1/frame2 to the GUI instance, ie self.upper_frame=Frame(self) self.upper_frame.pack() self.lower_frame=Frame(self) self.lower_frame.pack() I could in principle access the upper_btn1 from lower_btn by self.master.master.upper_btn1, BUT then the frame1/frame2 are …
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: tkinter-layout
has answer: http://stackoverflow.com/a/56103557
tagged with: oop
has title: Object oriented Tkinter, best way to communicate between widgets in gui with many frames
answer count: 1

http://stackoverflow.com/q/50120301
has comment: http://stackoverflow.com/comment/87258248
has answer: http://stackoverflow.com/a/50120419
has comment: http://stackoverflow.com/comment/87258114
has body: I have a pandas dataframe as below: User ASIN Rating A23VKINWRY6J92 1476783284 5 A3HC4SRK7B2AXR 1496177029 5 AE12HJWB5ODOD B00K2GAUC0 4 AL4RYO265J1G 061579615X 3 I want to generate a dictionary which has 2 columns 'User' and 'ASIN' as keys and third column 'Rating' as the value. Something like below: my_dict[A23VKINWRY6J92][1476783284] = 5 my_dict[A3HC4SRK7B2AXR][1496177029] = 5 my_dict[AE12HJWB5ODOD][B00K2GAUC0] = 4 my_dict[AL4RYO265J1G][061579615X] = 3 How can I do this?
has title: pandas dataframe to_dict two columns as indexes and third as value
tagged with: pandas
has comment: http://stackoverflow.com/comment/87258151
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50120416
has answer: http://stackoverflow.com/a/50120759
has answer: http://stackoverflow.com/a/50120416
favorite count: 0
has answer: http://stackoverflow.com/a/50120720
answer count: 4
type: Question
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50120759
tagged with: python

http://stackoverflow.com/q/50122198
type: Question
has comment: http://stackoverflow.com/comment/87262254
possible better answer: http://stackoverflow.com/a/50122294
has body: I have a Python simple list like this one: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] I want to save it in a csv file that looks like this: 1,2,3,4,5,6,7,8 9,10,11,12,13,14,15,16 How can I do that? I tried: np.savetxt('fname.csv', bbox_form, fmt='%d') But I don't know how to write a new line only after 8 values.
tagged with: format
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/50122294
tagged with: save
accepted answer: http://stackoverflow.com/a/50122403
has comment: http://stackoverflow.com/comment/87262570
has answer: http://stackoverflow.com/a/50122403
has title: Save list values in csv file with Python

http://stackoverflow.com/a/50161031
score: 0
has body: Using the map function might help increase the speed since it makes the computation in parallel import math two52 = 2**52 def crash(x): crash_point = math.floor((100*two52-x)/(two52-x)) return(crash_point/100) crashes_sum = sum(map(crash,range(two52))) expected_crash = crashes_sum/two52
answers question: http://stackoverflow.com/q/50160678
has comment: http://stackoverflow.com/comment/87340051
type: Answer

http://stackoverflow.com/comment/87276702
score: 1
type: QuestionComment
has text: There's a trailing '%' after your css name.
type: Comment
comment on: http://stackoverflow.com/q/50129391

http://stackoverflow.com/comment/87442121
score: 1
type: Comment
has text: JARs don't really provide modular programming, it's more about packaging code. E.g., you cannot make only a part of a JAR public - if you add a JAR to classpath, all its classes become visible to the application. Modules address this issue. Another big point is the dependencies - a module declares/defines its dependencies (incl. dependencies to the modules of the JRE itself) while a JAR doesn't.
type: QuestionComment
comment on: http://stackoverflow.com/q/50212552

http://stackoverflow.com/comment/87404607
score: 0
type: Comment
has text: is there any chance I can also put the numbers in the cells ??
type: AnswerComment
comment on: http://stackoverflow.com/a/50184097

http://stackoverflow.com/q/50153134
has comment: http://stackoverflow.com/comment/87323902
has answer: http://stackoverflow.com/a/65784054
possible better answer: http://stackoverflow.com/a/76430450
type: AnsweredQuestion
answer count: 2
has body: For python, it is two-side test by default: from scipy import stats import numpy as np wt = np.array([71.93636,71.34689,72.2162]) mut = np.array([71.58995,70.82698,70.89562]) t, p = stats.ttest_ind(wt, mut, equal_var=False) print(t,p) I got 2.06163943002 0.108425721876 In Excel, Data tab - Data Analysis - t-Test: Two-Sample Assuming Unequal Variances, I got same value for t, but slightly different value for p (0.1084... vs 0.1082...) Can I ask why?
has answer: http://stackoverflow.com/a/76430450
has comment: http://stackoverflow.com/comment/87342277
has title: Why scipy and Excel generate slightly different p-value for two-sample t-test?
score: 1
has comment: http://stackoverflow.com/comment/87324015
downvote count: 0
upvote count: 1
tagged with: scipy
tagged with: excel
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87342180
tagged with: t-test
tagged with: python
accepted answer: http://stackoverflow.com/a/65784054

http://stackoverflow.com/comment/87419300
type: Comment
comment on: http://stackoverflow.com/a/50200792
score: 0
type: AnswerComment
has text: Do you know how to print matrix size? len(A) does not help.

http://stackoverflow.com/comment/87438383
type: AnswerComment
has text: @SIM Nice. I forgot I was going to look back at that question. I am totally going to put that in my toolbox and reference you of course :-)
score: 0
comment on: http://stackoverflow.com/a/50209744
type: Comment

http://stackoverflow.com/comment/87230781
type: QuestionComment
has text: You mean `b`?..
type: Comment
comment on: http://stackoverflow.com/q/50106715
score: 0

http://stackoverflow.com/comment/87377728
has text: Anyway, what I _think_ you're looking for is a nested zip. Do you know about [`zip`](https://docs.python.org/3/library/functions.html#zip)? If so, do you know how to write a `for` statement inside another `for` statement? (Or, if you prefer, a comprehension with two `for` clauses?) If so, what part are you stuck on?
type: QuestionComment
comment on: http://stackoverflow.com/q/50180242
score: 1
type: Comment

http://stackoverflow.com/comment/87699590
type: Comment
score: 0
type: AnswerComment
has text: @ShitalShah: That example never imports `package1.x`, which contains the invalid `import y`. (Also, the `sys.path` entry added is irrelevant.)
comment on: http://stackoverflow.com/a/50301348

http://stackoverflow.com/q/50086867
score: 1
has comment: http://stackoverflow.com/comment/87189522
downvote count: 0
has answer: http://stackoverflow.com/a/50087238
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87189981
has comment: http://stackoverflow.com/comment/87189724
tagged with: filter
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50088249
has title: Python / Pandas: Dataframe multiple filters
possible better answer: http://stackoverflow.com/a/50087238
has answer: http://stackoverflow.com/a/50088249
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87189800
has comment: http://stackoverflow.com/comment/87189647
type: AnsweredQuestion
answer count: 2
has body: I have the following dataframe which is list of races and results. Date R H Fin Win 0 11182017 1 1 2 0 1 11182017 1 2 1 5 2 11182017 1 3 3 0 3 11182017 2 1 2 0 4 11182017 2 2 1 10 5 11182017 3 1 1 6 6 11182017 3 2 2 0 I want to be able to filter first by race (R) then by horse (H) and return the results. For the dataset above when R = 1 I want to see only H 1 &amp; 2 (ie filter out H 3 for R 1). For R = 2 I want to to see only H 1 (ie filter out H 2 for R 2) and for R =3 I only want to see H 2 (ie filter out H 1 for R 3). I would accomplish this by setting a variable preferably via a prompt. Essentially I am trying to "scratch" certain horses from a particular race Results Example below Date R H Fin Win 0 11182017 1 1 2 0 1 11182017 1 2 1 5 3 11182017 2 1 2 0 6 11182017 3 2 2 0

http://stackoverflow.com/comment/87440287
score: 0
type: Comment
type: QuestionComment
has text: Functions are indeed treated differently, because they form the *behaviour of enum values*, not enum values themselves.
comment on: http://stackoverflow.com/q/50211614

http://stackoverflow.com/q/50113986
type: Question
has body: I would like to call python functions from node.js. I have found python-shell. But as far as I understand it can only run a full python script. I have some logic (loading a huge file) which takes about 2 minutes. I would like to run it and then call python functions from node so that the file is loaded only once. # load a huge file takes 2min model = xyz.load(path) # function using that model def doSomething(id): # some logic using the model return model.get(id) How can I repeatedly call doSomething() without loading the file each time?
has title: Call python function from node.js
answer count: 3
score: 1
tagged with: python
tagged with: node.js
accepted answer: http://stackoverflow.com/a/50247656
has answer: http://stackoverflow.com/a/50114047
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50247656
has answer: http://stackoverflow.com/a/50114097
downvote count: 0
tagged with: node-modules
upvote count: 1
possible better answer: http://stackoverflow.com/a/50114047
favorite count: 0
linked to: http://stackoverflow.com/q/50223084

http://stackoverflow.com/comment/87383790
has text: Oh dang, I tried `normal ! gf` not realizing the space mattered. I'd like to give you two upvotes for those improved solutions, but can only give you one. I'll save the answered for anyone who can explain why `gfgf` is picked up by `gf`
type: Comment
comment on: http://stackoverflow.com/a/50183101
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87346528
score: 0
type: Comment
type: QuestionComment
has text: FWIW, Python already comes with [utilities to escape URLs](https://docs.python.org/dev/library/urllib.parse.html#urllib.parse.quote), no need to do it manually
comment on: http://stackoverflow.com/q/50164258

http://stackoverflow.com/comment/87337762
score: 0
type: AnswerComment
has text: Are you opening it in Excel? Excel will add single quotation marks around the values of a csv if you open it and then save it. It looks the same in Excel, but it's been changed. If you look at the file using a text editor instead, you should be able to see the difference that way. Then the CSV reader will see it differently depending on how it's formatted to read the data. That'd be my first guess.
type: Comment
comment on: http://stackoverflow.com/a/50104566

http://stackoverflow.com/comment/87592884
type: Comment
score: 0
type: AnswerComment
has text: What I meant when I said that you had the wrong Project ID was that you are passing as Project ID a string of the format `newagent/agent/environments...`, while it should only be `newagent`. As you can see in [the documentation](https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/v2beta1/projects.agent.environments.users.sessions.entityTypes/create), the correct format is simply `projects/<Project ID>/agent/sessions/<Session ID>`. That is why I understand that the session path built was wrong. If you print it with `print(session)` it should show something like that format.
comment on: http://stackoverflow.com/a/50237104

http://stackoverflow.com/comment/87382264
has text: This is still going to fail on pretty much any built-in type, not just `type`. It'll fail especially hard for `type`, but it won't work right for other types, either. For example, if you try to copy `int` this way, instances of the result don't support arithmetic, hashing, or pretty much any of the functionality of `int`. The dict-level copy just can't reach deep enough into the C to copy what needs to be copied.
type: Comment
type: AnswerComment
score: 3
comment on: http://stackoverflow.com/a/50176549

http://stackoverflow.com/comment/87412414
type: QuestionComment
has text: This does not work with bar plots. Try using `Axes3d.plot_surface`.
type: Comment
comment on: http://stackoverflow.com/q/50197712
score: 0

http://stackoverflow.com/q/50193149
type: UnansweredQuestion
has title: python ElementTree.Element missing text?
tagged with: python
has body: So, I'm parsing this xml file of moderate size (about 27K lines). Not far into it, I'm seeing unexpected behavior from ElementTree.Element where I get Element.text for one entry but not the next, yet it's there in the source XML as you can see: &lt;!-- language: lang-xml --&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:enumeration value="24"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;UPC12 (item-specific) on cover 2&lt;/xs:documentation&gt; &lt;xs:documentation&gt;AKA item/price; ‘cover 2’ is defined as the inside front cover of a book&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;/xs:enumeration&gt; &lt;xs:enumeration value="25"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;UPC12+5 (item-specific) on cover 2&lt;/xs:documentation&gt; &lt;xs:documentation&gt;AKA item/price; ‘cover 2’ is defined as the inside front cover of a book&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;/xs:enumeration&gt; When I encounter an enumeration tag I call this function: import xml.etree.cElementTree as ElementTree ... def _parse_list_item(xmlns: str, list_id: int, itemElement: ElementTree.Element) -&gt; ListItem: if isinstance(itemElement, ElementTree.Element): if itemElement.attrib['value'] is not None: item_id = itemElement.attrib['value'] # string if list_id == 6 and (item_id == '25' or item_id=='24'): print(list_id, item_id) # &lt;== debug break point here desc = None notes = "" for child in itemElement: if child.tag == (xmlns + 'annotation'): for grandchild in child: if grandchild.tag == (xmlns + 'documentation'): if desc is None: desc = grandchild.text else: if len(notes)&gt;0: notes += " " # add a space notes += grandchild.text or "" if item_id is not None and desc is not None: return Codex.ListItem({'itemId': item_id, 'listId': list_id, 'description': desc, 'notes': notes}) If I place a breakpoint at the print statement, when I get to the enumeration node for "24" I can look at the text for the grandchild nodes and they are as s…
tagged with: http://stackoverflow.com/tag/xml
score: 2
answer count: 2
tagged with: xml-parsing
downvote count: 0
has answer: http://stackoverflow.com/a/50202918
tagged with: elementtree
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50224228
upvote count: 2

http://stackoverflow.com/q/50229772
type: Question
has comment: http://stackoverflow.com/comment/87477719
tagged with: opencv
linked to: http://stackoverflow.com/q/64975918
has comment: http://stackoverflow.com/comment/87477237
has title: opencv install on osx no suitable image error
accepted answer: http://stackoverflow.com/a/50230643
has comment: http://stackoverflow.com/comment/87478143
tagged with: python
has body: I have followed this tutorial to install opencv: https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a I have two different virtual environments setup. On one cv2 works fine. On the other one I get: ImportError: dlopen(/Users/me/.virtualenvs/py3cv/lib/python3.6/site-packages/cv2.so, 2): no suitable image found. Did find: /Users/me/.virtualenvs/py3cv/lib/python3.6/site-packages/cv2.so: mach-o, but wrong architecture /usr/local/Cellar/opencv/3.4.1_5/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so: mach-o, but wrong architecture the working interpreter shows: Python 3.6.4 (default, Dec 25 2017, 14:57:56) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin when I go into python. when I run import ctypes;print(ctypes.sizeof(ctypes.c_void_p)) I get: 8 The breaking one shows: Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin when I run import ctypes;print(ctypes.sizeof(ctypes.c_void_p)): I get: 4 any ideas what is going wrong? output of name -a Darwin MyMBP 17.5.0 Darwin Kernel Version 17.5.0: Fri Apr 13 19:32:32 PDT 2018; root:xnu-4570.51.2~1/RELEASE_X86_64 x86_64
linked to: http://stackoverflow.com/q/1405913
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87477463
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: macos
has answer: http://stackoverflow.com/a/50230643
favorite count: 0

http://stackoverflow.com/q/50106372
has comment: http://stackoverflow.com/comment/87229956
score: 1
has answer: http://stackoverflow.com/a/50106963
answer count: 1
tagged with: python
has body: I work with python 3 and install django-pagseguro. I tried to run command in python shell: from django_pagseguro.urls import pagseguro_urlpatterns and getting error: &gt;&gt;&gt; from django_pagseguro.urls import pagseguro_urlpatterns Traceback (most recent call last): File "C:\Users\patff\AppData\Local\conda\conda\envs\k36\lib\site-packages\django_pagseguro\urls.py", line 3, in &lt;module&gt; from django.conf.urls import patterns, url ImportError: cannot import name 'patterns' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "C:\Users\patff\AppData\Local\conda\conda\envs\k36\lib\site-packages\django_pagseguro\urls.py", line 5, in &lt;module&gt; from django.conf.urls.defaults import patterns, url ModuleNotFoundError: No module named 'django.conf.urls.defaults'
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87230101
has comment: http://stackoverflow.com/comment/87230008
has title: unable to import pagseguro_urlpatterns from django_pagseguro.urls
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django

http://stackoverflow.com/q/50198532
has comment: http://stackoverflow.com/comment/87481613
has body: I have a problem, I need to parse the following dataframe: cluster_name qseqid sseqid pident_x qstart qend sstar send 2 1 seq1_0035_0035 seq13_0042_0035 0.73 42 133 46 189 3 1 seq1_0035_0035 seq13_0042_0035 0.73 146 283 287 389 4 1 seq1_0035_0035 seq13_0042_0035 0.73 301 478 402 503 5 1 seq13_0042_0035 seq1_0035_0035 0.73 46 189 42 133 6 1 seq13_0042_0035 seq1_0035_0035 0.73 287 389 146 283 7 1 seq13_0042_0035 seq1_0035_0035 0.73 402 503 301 478 8 2 seq4_0042_0035 seq2_0035_0035 0.71 256 789 125 678 9 2 seq4_0042_0035 seq2_0035_0035 0.71 802 1056 706 985 10 2 seq4_0042_0035 seq7_0035_0042 0.83 123 745 156 723 12 4 seq11_0035_0035 seq14_0042_0035 0.89 145 647 236 921 13 4 seq11_0035_0035 seq17_0042_0042 0.97 148 623 241 1002 14 5 seq17_0035_0042 seq17_0042_0042 0.94 188 643 179 746 Explanation of the dataframe and blast output: cluster_name : is the cluster where one, two or more paired sequences are present. qseqid : is the name of one sequence sseqid : is the name of another sequence. These make one comparison qseqid vs sseqid pident_x : is the score after the comparison (alignment) of these two sequences, 1 means that they are identical. When blast aligns the two sequence, it gives me coordinates of where my sequences are aligned ("homologous") in my alignment, for example if I have: 10 24 seq1 : AAATTTCCCGGGATGCGATGACGATGAAAAAATTTGG xxxxxxxxx!!!!!!!!!!!!!!!xxxxxxxxxxxxx seq2 : GATGAGATCGGGATGCGATGAGGAGATAGAGATAGAG where x is a difference and ! is a match, blast will give me: qstart (start of the first seq) : 10 qend (endof the first seq) : 24 sstar (start of the second seq) : 10 send (end of the second seq) : 24 Note: this is an example but it does not necessarily begins at 0. and what I actually want is only get within each cluster the maximum pident_x but the issue is that as you can see I can have reversed sequences (if you take a look at the 2,3,4 and 5,6,7 they are the same but reversed) and what I need to do is to keep only one for exemple only the line 2,3…
tagged with: dataframe
tagged with: python
has title: Filtering a dataframe of BLAST sequences to get within each cluster the maximum pident_x
score: 3
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/87583108
upvote count: 3
has comment: http://stackoverflow.com/comment/87486016
downvote count: 0
has answer: http://stackoverflow.com/a/50223639
has comment: http://stackoverflow.com/comment/87454443
has answer: http://stackoverflow.com/a/50198955
favorite count: 0
has comment: http://stackoverflow.com/comment/87454256
type: Question
has comment: http://stackoverflow.com/comment/87480663
type: UnansweredQuestion
tagged with: blast

http://stackoverflow.com/a/61134681
answers question: http://stackoverflow.com/q/50217922
type: Answer
has comment: http://stackoverflow.com/comment/108153818
has body: I use Ruby to control Agilent(keysight) power supply e3631a via RS232 port. I believe I had similiar issue. The symptom was the query commands (like *IDN?) yield no reply and an error code 410 would show up on the device. The issue was that the device cannot send out the data via serial port and so the buffer cannot be cleared up. The fix was that in DCB structure you need to set "DTR_CONTROL_ENABLE". In my case the line control part of dcb looks like "0x00000011". Note that for serial commnication without flow control, normally you do not need to set that. This issue has costed me two days and I hope it will help others.
score: 0

http://stackoverflow.com/comment/87255882
has text: What uses either of these formats? Consider whether translating data on one non-standard format to another non-standard format is a good idea.
score: 0
comment on: http://stackoverflow.com/q/50118834
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50078338
type: Answer
score: -1
has body: It sounds like you want boolean indexing. I'm assuming we're talking about numpy. Note that if you want the values corresponding to zeros in your last column, you just need to negate the boolean logic with ~. import numpy as np # data array A = np.random.random([52,7]) # Make a boolean from your seventh column tf = np.array(A[:,6], dtype=bool) # select values from the fourth column a = A[~tf, 3] # sum them a.sum() # This can be combined into one line if desired. Something like: thesum = A[A[:,6] == 0, 3].sum()
upvote count: 0
answers question: http://stackoverflow.com/q/50078269
downvote count: 1
has comment: http://stackoverflow.com/comment/87173090
has comment: http://stackoverflow.com/comment/87173249
has comment: http://stackoverflow.com/comment/87173202

http://stackoverflow.com/comment/87396313
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50189683
has text: I'd strongly recommend a self-hosted instance of OSRM. If you're on Linux, it's a 10 min setup and generally good enough. What, specifically, are you relying on the Google API to include? Traffic?
type: QuestionComment

http://stackoverflow.com/a/50214281
upvote count: 22
answers question: http://stackoverflow.com/q/50211546
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/134430853
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50211546
has comment: http://stackoverflow.com/comment/122132376
has body: You could try to convert it to hex format. Then it is easy to convert it back to byte format. Sample code to convert bytes to string: hex_str = rnd_bytes.hex() Here is how 'hex_str' looks like: '771296b8' And code for converting it back to bytes: new_rnd_bytes = bytes.fromhex(hex_str) The result is: b'w\x12\x96\xb8' For processing you can use: readable_str = ''.join(chr(int(hex_str[i:i+2], 16)) for i in range(0, len(hex_str), 2)) But never try to encode readable string, here is how readable string looks like: 'w\x12\x96¸' After processing readable string convert it back to hex format before converting it back to bytes string like: hex_str = ''.join([str(hex(ord(i)))[2:4] for i in readable_str])
score: 22
type: Answer

http://stackoverflow.com/comment/87472109
comment on: http://stackoverflow.com/a/50210924
type: Comment
score: 0
type: AnswerComment
has text: Based on suggestions I have decided not to use "exec". Thank you for your reply.

http://stackoverflow.com/a/50186255
score: 0
has comment: http://stackoverflow.com/comment/87445351
answers question: http://stackoverflow.com/q/50170782
has body: UPDATE: Since Jun 2018, this issue does not arise. ORIGINAL ANSWER: Yes Joshua - this was raised as an issue but isn't fixed yet. The workaround is to downgrade from pip 10 to pip 9 -- and then install. This is not ideal. Will try and have a fix soon.
type: Answer

http://stackoverflow.com/comment/125285157
comment on: http://stackoverflow.com/a/65664901
has text: oh thank you, I have been using Brave browser, thinking "yeah this is chrome" but no it's not. downloading actual chrome fixed it. thanks
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/87402466
comment on: http://stackoverflow.com/q/50192737
has text: Well, you are passing in lists, and a list doesn't have a `.start` attribute. Have you read the problem description on Interviewbit properly? Perhaps they are passing in **something different** to represent intervals?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50103656
has comment: http://stackoverflow.com/comment/87224731
has comment: http://stackoverflow.com/comment/87228242
tagged with: numpy
score: 0
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/50105272
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87226549
has comment: http://stackoverflow.com/comment/87225135
has comment: http://stackoverflow.com/comment/87226812
type: Question
has comment: http://stackoverflow.com/comment/87225382
has title: How to vectorize this for loop?
tagged with: matrix
has body: I have a numpy array f with length n and a numpy matrix A with size n x m. I want to break f and A in r pieces f1,...,fr and A1,...,Ar, then make the computations fi*Ai (the vector x matrix multiplication in the mathematical sense) with each fi being a row vector with the number of columns equal the number of rows of Ai. The result will be a row vector 1 x m. The idea is to concatenate all these row vectors to form the matrix B = [ [f1*A1], [f2*A2],..., [fr*Ar] ] (note that this will be a matrix with size r x m). Suppose f and A are already defined. Also suppose the corresponding index of the pieces are in a list [0,d1,...dr]. For example, f1 = f[d[0]:d[1]] and f2 = f[d[1]:d[2]] ). I was using with the following piece of code to solve my problem: B = numpy.zeros([r,m]) for i in range(0,r): lower = d[i] upper = d[i+1] B[i,:] = f[lower:upper].dot(A[lower:upper,:]) The problem is that this piece of code will be computed several times in my program. I heard before that Python for loops are slow and in fact the bottle neck of my code is this part. I can't figure out how to vectorize this but I feel it is possible. I was hoping someone here could show me the way. Thanks.
tagged with: python
has answer: http://stackoverflow.com/a/50105398

http://stackoverflow.com/comment/87306472
comment on: http://stackoverflow.com/a/50136104
type: Comment
type: AnswerComment
has text: instead of installing apt with pip I tried this: https://askubuntu.com/questions/584857/distutilsextra-problem which solved the problem with apt. But now there is another error while executing `pip install -r requirements.txt` the next error is: instead of installing apt with pip I tried this: https://askubuntu.com/questions/584857/distutilsextra-problem which solved the problem with apt. But now there is another error while executing `pip install -r requirements.txt` requests 2.18.4 has requirement certifi>=2017.4.17, but you'll have certifi 0.0.8 which is incompatible.
score: 0

http://stackoverflow.com/comment/87448017
comment on: http://stackoverflow.com/q/50214908
type: Comment
type: QuestionComment
has text: @DSM found the culprit. It was this "Filled_Q1" column which was causing the problem. I first converted the column from "object" data type to "int64", then used strip() method to remove any spaces and now the duplicated method works.
score: 0

http://stackoverflow.com/comment/87398514
type: Comment
score: 0
type: AnswerComment
has text: my god :) if you knew the amount of hours and ugly code i tried to get around this - this programming language is so beautiful. Do have an additional question for dictionaries and lists but better post it as a new question
comment on: http://stackoverflow.com/a/50190753

http://stackoverflow.com/q/50211534
has comment: http://stackoverflow.com/comment/87445333
has comment: http://stackoverflow.com/comment/87474119
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87442925
has comment: http://stackoverflow.com/comment/87443496
tagged with: grid-search
upvote count: 1
tagged with: python
tagged with: data-science
answer count: 0
has comment: http://stackoverflow.com/comment/87442980
has title: Sklearn GridSearchCV Produce very differet numbers for test_score and train_score
has comment: http://stackoverflow.com/comment/87443905
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87440571
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87440720
tagged with: keras
favorite count: 0
has body: I have been running GridSearchCV to find the best hyperparameters for my regression ANN. However, I find it hard to interpret the test_score and train_score values and why they are so unreasonably different. The ANN is created with Keras and MSE is used as loss. If I set the parameter cv=10 the results are reasonable, but when I use cv=3 it is not reasonable and not comparable to if I would do a regular split into test/train sets and run it manually (MSE would be much smaller then). Results for cv=10. {'mean_fit_time': array([ 45.64931359]), 'mean_score_time': array([ 0.88778265]), 'mean_test_score': array([-80.58573808]), 'mean_train_score': array([-54.32416867]), 'param_batch_size': masked_array(data = [25], mask = [False], fill_value = ?), 'param_epochs': masked_array(data = [500], mask = [False], fill_value = ?), 'params': [{'batch_size': 25, 'epochs': 500}], 'rank_test_score': array([1]), 'split0_test_score': array([-79.8304968]), 'split0_train_score': array([-54.1543676]), 'split1_test_score': array([-88.66814966]), 'split1_train_score': array([-52.53867387]), 'split2_test_score': array([-72.68088307]), 'split2_train_score': array([-54.22193575]), 'split3_test_score': array([-65.62303455]), 'split3_train_score': array([-55.11768506]), 'split4_test_score': array([-91.78870671]), 'split4_train_score': array([-53.60385677]), 'split5_test_score': array([-69.70716374]), 'split5_train_score': array([-54.90494821]), 'split6_test_score': array([-72.369327]), 'split6_train_score': array([-55.06327332]), 'split7_test_score': array([-63.47190503]), 'split7_train_score': array([-57.14306102]), 'split8_test_score': array([-61.61434507]), 'split8_train_score': array([-56.35855999]), 'split9_test_score': array([-139.97252682]), 'split9_train_score': array([-50.13532509]), 'std_fit_time': array([ 4.63885948]), 'std_score_time': array([ 0.36701861]), 'std_test_score': array([ 21.97077353]), 'std_train_score': array([ 1.86790488])} If I instead use cv=3 I get extremely large nu…
type: Question

http://stackoverflow.com/comment/87182980
score: 2
type: Comment
type: QuestionComment
has text: If this is part of a homework assignment, or a job, you should at least make sure your teacher or boss or whoever recognizes that they've given you a task that should have been trivial, but is instead painful and brittle, purely because someone else is using Python `repr` as a persistence format, which is a terrible idea and easy to fix at the source.
comment on: http://stackoverflow.com/q/50083582

http://stackoverflow.com/q/50124978
answer count: 1
tagged with: sublimetext3
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50124994
tagged with: python
has title: sublime build system error "can't find '__main__' module in ''"
score: 0
has body: I'm trying to get Sublime3 to work with Python3.6.5 and getting an error message below. /usr/bin/python: can't find '__main__' module in '' [Finished in 0.1s with exit code 1] [shell_cmd: python -u &quot;&quot;] [dir: /Applications/Sublime Text.app/Contents/MacOS] [path:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]

http://stackoverflow.com/q/50136919
has answer: http://stackoverflow.com/a/50137112
tagged with: python
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/50137198
has body: I'm trying to make a writeup on different ways to deal with bad data. right now, I'm working on Null/None/Nan. I want convert random values in an array to Null, and then just print it out, or manipulate it in other ways. I create the data as iris = datasets.load_iris() X = iris.data And can make a random mask with mask = np.random.random(size=X.shape) mask = np.array([[True if y&lt; .9 else False for y in x] for x in mask]) But I don't know how to apply that mask to the data. What I want to do is keep the value in X if the corresponding value in mask is True, otherwise convert it to None the way I do it right now isn't pretty, I feel like a more pythonic way exists i= 0 while i &lt; len(X): j=0 while j &lt; len(X[i]): X[i][j] = X[i][j] if mask[i][j] else None j=j+1 i=i+1 print(X)
downvote count: 1
has answer: http://stackoverflow.com/a/50137117
favorite count: 0
type: Question
tagged with: numpy
has title: python, numpy generate bad data
tagged with: auto-generate
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/87503361
comment on: http://stackoverflow.com/a/50242383
type: AnswerComment
score: 0
has text: Here's the new question - thanks for any help you can give! https://stackoverflow.com/questions/50242843/how-do-i-use-an-aws-sessiontoken-to-read-from-s3-in-pyspark
type: Comment

http://stackoverflow.com/a/52358768
has body: If you declare weights at def build(self, input_shape):, then you have to "use" all the weights after the tf.py_func call. import tensorflow as tf from keras import backend as K from keras.engine.topology import Layer class MultiplyLayer(Layer): def __init__(self, **kwargs): super(MultiplyLayer, self).__init__(**kwargs) def build(self, input_shape): self.filters = self.add_weight(name='Filters', shape=(1, input_shape[1]), initializer='uniform', trainable=True) super(MultiplyLayer, self).build(input_shape) # Be sure to call this at the end def call(self, x): xw = x * self.filters def my_func(x): return 5 * x X = tf.py_func(my_func, [xw], tf.float32) return X + (self.filters - self.filters) def compute_output_shape(self, input_shape): return (input_shape) def get_model(): model = Sequential() model.add(MultiplyLayer(input_shape=(num_features,))) model.add(Dense(128, activation='relu')) model.add(Dropout(0.25)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.4)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model model = get_model() model.summary() model.fit(X_train, y_train_hot, batch_size=batch_size, epochs=epochs, verbose=verbose, validation_data=(X_test, y_test_hot))
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50187667
type: Answer
upvote count: 1

http://stackoverflow.com/q/50227310
tagged with: performance
score: 0
answer count: 3
tagged with: django-models
possible better answer: http://stackoverflow.com/a/50227420
accepted answer: http://stackoverflow.com/a/50227533
type: Question
has answer: http://stackoverflow.com/a/50227420
has answer: http://stackoverflow.com/a/50227533
has body: I have two models named machine and performance, class machine(models.Model): machine_type = models.CharField(null=True, max_length=10) machine_no = models.IntegerField(null=True) machine_name = models.CharField(null=True,max_length=255) machine_sis = models.CharField(null=True, max_length=255) store_code = models.IntegerField(null=True) created = models.DateTimeField(auto_now_add=True) class Performance(models.Model): machine_no = models.IntegerField(null=True) power = models.IntegerField(null=True) store_code = models.IntegerField(null=True) created = models.DateTimeField(auto_now_add=True) For each Machine, there are multiple fields of in Performance Model and I have to find the count of Performance Model's rows in the db which have power = some_integer. Here is what my view looks like: machines = machine.objects.filter(machine_type="G",machine_sis="919") Let's say machine.count() sometimes is 100. For each of this machine I need to calculate the number of machines which have power = 100 in performance model. So what I did first was but was really slow: for obj in machines: print performance.objects.filter(machine_no=obj.machine_no,power=100).count() My second approach was faster than the first approach: for obj in machines: data = performance.objects.filter(machine_no=obj.machine_no,power=100) counter = 0 for p in data: # ***** lets say this loop is called star-loop if p.power == 100: counter +=1 My problem is that the speed is really slow when I have to check 100 machines in Performance model whose power = something. I am not using foreign key in Performance Model because the actual architecture is more complex and I can't use machine number or anything as foreign key because when identifying each machine uniquely I need multiple columns of machine. Also, this project is working in production and I can't take much chance. I am using Django 1.11, Python 2.7 and postresql rds instance. I have increased the network performance buy renting a better instance from aw…
has title: Nested for loop is really slow for query set traversal in Django
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87471825
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50227762

http://stackoverflow.com/comment/87196439
comment on: http://stackoverflow.com/q/50090072
type: QuestionComment
has text: @ekhumoro - I was looking at solution for this and this is the solution some tutorial gave me . I am looking for something that is more logical to remember .
score: 0
type: Comment

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/50205646
type: Tag
tags question: http://stackoverflow.com/q/50084766
tags question: http://stackoverflow.com/q/50183068

http://stackoverflow.com/a/50184546
has body: A bit lengthy, but does what you want: &gt;&gt;&gt; df1 = pd.concat([df.groupby('worker1').sum(), df.groupby('worker2').sum(), df.groupby('worker3').sum()]) &gt;&gt;&gt; df1.groupby(df1.index).sum() earnings Aaron 4573547 Alex 4564552 Alice 10922205 Amanda 7648576 Amy 4573547 Jack 10931200 Matt 3567567 Paul 6357653 Sam 15780695 Tim 7648576 Tony 3567567
answers question: http://stackoverflow.com/q/50170814
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/87353090
type: Comment
comment on: http://stackoverflow.com/q/50167423
type: QuestionComment
has text: Whenever you find yourself writing `map(lambda…`, stop and ask whether this could be a comprehension. `map` is great when you already have a function lying around, but when you're trying to apply an expression and then have to wrap that expression up in a function just so you can pass that function to `map`… that's two extra steps that just cancel each other out.
score: 2

http://stackoverflow.com/comment/87244850
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50113935
type: QuestionComment
has text: If the password is allowed to contain unescaped single quotes, how do we know that on the last line `'asd''asdf'; password 'asdf'` isn't one big password?

http://stackoverflow.com/q/50142116
has comment: http://stackoverflow.com/comment/87303251
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/41772054
has comment: http://stackoverflow.com/comment/87303027
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/50142566
upvote count: 3
has title: Iterate overs values in nested list
has comment: http://stackoverflow.com/comment/87302553
has answer: http://stackoverflow.com/a/50142566
has comment: http://stackoverflow.com/comment/87303028
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50142208
has body: I'm working on scientific data and using a module called pysam in order to get reference position for each unique "object" in my file. In the end, I obtain a "list of lists" that looks like that (here I provide an example with only two objects in the file): pos = [[1,2,3,6,7,8,15,16,17,20],[1,5,6,7,8,20]] and, for each list in pos, I would like to iterate over the values and compare value[i] with value[i+1]. When the difference is greater than 2 (for example) I want to store both values (value[i] and value[i+1]) into a new list. If we call it final_pos then I would like to obtain: final_pos = [[3,6,8,15,17,20],[1,5,8,20]] It seemed rather easy to do, at first, but I must be lacking some basic knowledge on how lists works and I can't manage to iterate over each values of each list and then compare consecutive values together.. If anyone has an idea, I'm more than willing to hear about it ! Thanks in advance for your time ! EDIT: Here's what I tried: pos = [[1,2,3,6,7,8,15,16,17,20],[1,5,6,7,8,20]] final_pos = [] for list in pos: for value in list: for i in range(len(list)-1): if value[i+1]-value[i] &gt; 2: final_pos.append(value[i]) final_pos.append(value[i+1])
has comment: http://stackoverflow.com/comment/87303185
has answer: http://stackoverflow.com/a/50142208
has comment: http://stackoverflow.com/comment/87302882
has comment: http://stackoverflow.com/comment/87302746
tagged with: python

http://stackoverflow.com/a/50202116
score: 1
upvote count: 1
type: Answer
has body: This will do: x = 'Muh kay' x = ' '.join(i.capitalize() for i in x.split())
answers question: http://stackoverflow.com/q/50202010
downvote count: 0

http://stackoverflow.com/a/50080016
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/87175948
type: Answer
has comment: http://stackoverflow.com/comment/87175942
upvote count: 0
has body: loop the same element twice then it will result to duplicate In [6]: [i for i in arr for h in range(2)] Out[6]: [1, 1, 2, 2, 3, 3, 4, 4] Simple one without list comprehension if you have sorted list In [7]: sorted(arr*2) Out[7]: [1, 1, 2, 2, 3, 3, 4, 4]
answers question: http://stackoverflow.com/q/50079921

http://stackoverflow.com/a/50146230
has body: Define instance variable as a part of the class class Test(): needed_file = [] def put(self): print("put") self.needed_file.append('Ninja file') def get(self): print("get") print(self.needed_file)
score: 0
answers question: http://stackoverflow.com/q/50145969
type: Answer

sensors
type: Tag
tags question: http://stackoverflow.com/q/50182991
tag name: sensors

http://stackoverflow.com/q/50204998
tagged with: list
score: 0
answer count: 2
has title: Naming lists based on the names of text files
tagged with: file
has comment: http://stackoverflow.com/comment/87427056
possible better answer: http://stackoverflow.com/a/50205172
type: Question
tagged with: python-3.x
has body: I'm trying to write a function which takes word lists from text files and appends each word in the file to a list, with the same name as the text file. For instance, using the text files Verbs.txt and Nouns.txt would result in all the words in Verbs.txt being in a verbs list and all the nouns in a nounslist. I'm trying to do it in a for loop: def loadAllWords(): fileList = ['Adjectives.txt', 'Adverbs.txt', 'Conjunctions.txt', 'IntransitiveVerbs.txt', 'Leadin.txt', 'Nounmarkers.txt', 'Nouns.txt', 'TransitiveVerbs.txt'] for file in fileList: infile = open(file, 'r') word_type = file[:-4] word_list = [line for line in infile] return word_list Of course, I could do it easily once for each text file: def loadAllWords(): infile = open("Adjectives.txt", "r") wordList = [] wordList = [word for word in infile] return wordList but I'd like my function to do it automatically with each one. Is there a way to do this, or should I just stick with a for loop for each file?
has answer: http://stackoverflow.com/a/50205172
tagged with: for-loop
has answer: http://stackoverflow.com/a/50205030
accepted answer: http://stackoverflow.com/a/50205030
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/87428444
score: 0
has text: Your regex pattern is not valid. Try this pattern: .Bytes.*. This will match any single character before Bytes, and any number (including zero) of characters after Bytes. This probably won't fix your problem completely though. If you want more help, post the rest of your code.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50205576

http://stackoverflow.com/comment/87472831
score: 0
type: AnswerComment
has text: For convention 0.0.0.0 means all ip addresses on local machine, so your socket listen for incoming messages on all network interfaces.
comment on: http://stackoverflow.com/a/50219064
type: Comment

http://stackoverflow.com/comment/87294804
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50137762
type: QuestionComment
has text: There's a much bigger bug in your code: how do you plan to get the user response out? You are throwing out all the references. Once you fix that you will find you can use those same references and the `destroy` method to remove them.

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/50165258
tags question: http://stackoverflow.com/q/50100370
tags question: http://stackoverflow.com/q/50223432
tags question: http://stackoverflow.com/q/50181734
tags question: http://stackoverflow.com/q/50138622
type: Tag

regex
tags question: http://stackoverflow.com/q/50124478
tags question: http://stackoverflow.com/q/50173418
tags question: http://stackoverflow.com/q/50097500
tags question: http://stackoverflow.com/q/50205420
tags question: http://stackoverflow.com/q/50223529
tags question: http://stackoverflow.com/q/50219036
tags question: http://stackoverflow.com/q/50158745
tags question: http://stackoverflow.com/q/50205977
tags question: http://stackoverflow.com/q/50227399
tags question: http://stackoverflow.com/q/50141419
tags question: http://stackoverflow.com/q/50180511
tags question: http://stackoverflow.com/q/50179334
tags question: http://stackoverflow.com/q/50087994
tags question: http://stackoverflow.com/q/50142104
tags question: http://stackoverflow.com/q/50184303
tags question: http://stackoverflow.com/q/50216736
tags question: http://stackoverflow.com/q/50161143
tags question: http://stackoverflow.com/q/50101760
tags question: http://stackoverflow.com/q/50118217
tag name: regex
tags question: http://stackoverflow.com/q/50128747
tags question: http://stackoverflow.com/q/50183725
tags question: http://stackoverflow.com/q/50129974
tags question: http://stackoverflow.com/q/50117433
tags question: http://stackoverflow.com/q/50177941
tags question: http://stackoverflow.com/q/50217926
tags question: http://stackoverflow.com/q/50145945
tags question: http://stackoverflow.com/q/50107838
tags question: http://stackoverflow.com/q/50134687
tags question: http://stackoverflow.com/q/50177113
tags question: http://stackoverflow.com/q/50224015
tags question: http://stackoverflow.com/q/50203857
tags question: http://stackoverflow.com/q/50178228
tags question: http://stackoverflow.com/q/50155573
tags question: http://stackoverflow.com/q/50088926
tags question: http://stackoverflow.com/q/50137307
tags question: http://stackoverflow.com/q/50185421
tags question: http://stackoverflow.com/q/50134178
tags question: http://stackoverflow.com/q/50180881
tags question: http://stackoverflow.com/q/50205692
tags question: http://stackoverflow.com/q/50133637
tags question: http://stackoverflow.com/q/50214691
tags question: http://stackoverflow.com/q/50167232
tags question: http://stackoverflow.com/q/50217875
tags question: http://stackoverflow.com/q/50220146
tags question: http://stackoverflow.com/q/50113590
tags question: http://stackoverflow.com/q/50167708
tags question: http://stackoverflow.com/q/50118909
tags question: http://stackoverflow.com/q/50131539
tags question: http://stackoverflow.com/q/50078281
tags question: http://stackoverflow.com/q/50214938
tags question: http://stackoverflow.com/q/50113754
tags question: http://stackoverflow.com/q/50135220
tags question: http://stackoverflow.com/q/50167021
tags question: http://stackoverflow.com/q/50120395
tags question: http://stackoverflow.com/q/50126788
tags question: http://stackoverflow.com/q/50113935
tags question: http://stackoverflow.com/q/50195954
tags question: http://stackoverflow.com/q/50176471
tags question: http://stackoverflow.com/q/50193802
tags question: http://stackoverflow.com/q/50077264
tags question: http://stackoverflow.com/q/50136046
tags question: http://stackoverflow.com/q/50097910
tags question: http://stackoverflow.com/q/50223742
tags question: http://stackoverflow.com/q/50140586
tags question: http://stackoverflow.com/q/50222734
tags question: http://stackoverflow.com/q/50212950
tags question: http://stackoverflow.com/q/50220129
type: Tag
tags question: http://stackoverflow.com/q/50184102
tags question: http://stackoverflow.com/q/50206354
tags question: http://stackoverflow.com/q/50172878
tags question: http://stackoverflow.com/q/50075317
tags question: http://stackoverflow.com/q/50156908
tags question: http://stackoverflow.com/q/50164830
tags question: http://stackoverflow.com/q/50129589
tags question: http://stackoverflow.com/q/50080854
tags question: http://stackoverflow.com/q/50202010
tags question: http://stackoverflow.com/q/50144074
tags question: http://stackoverflow.com/q/50135505

http://stackoverflow.com/comment/87307057
comment on: http://stackoverflow.com/q/50144366
type: QuestionComment
has text: You _could_ do this, but… Write an import hook. Your hook can insert a `stop_import` callback into builtins that the module being imported can call. Or it can execute the module code statement by statement (ala runpy mode) and build a module manually out of the resulting namespace, which means it can handle a special exceptions (or any exception, if you prefer) as "exit early". If that sounds impossible rather than a fun experiment, you probably don't want to do it.
score: 0
type: Comment

http://stackoverflow.com/a/50077790
downvote count: 5
has comment: http://stackoverflow.com/comment/87171708
upvote count: 0
score: -5
has body: What about .startswith(), it seems to me the easy way of implementing your search.
has comment: http://stackoverflow.com/comment/87173159
answers question: http://stackoverflow.com/q/50077650
type: Answer

http://stackoverflow.com/comment/87452847
comment on: http://stackoverflow.com/q/50217875
type: Comment
type: QuestionComment
has text: What about `len`?
score: 0

http://stackoverflow.com/q/50104598
has body: I am tring to access a new document from a mongo database collection named games by the _id. But for example if I access localhost:5000/solutie/5ae71f3e8e442b090e4c313bit is giving me the error: ValueError: View function did not return a response so it doesn't go through the if and I think I should convert the value of the _id to another type but I don't know how. This is my flask code: @app.route('/solutie/&lt;id&gt;') def solu(id): games = mongo.db.games game_user = games.find_one({'_id' : id}) if game_user: return id This is my mongo database collection named games: { "_id": { "$oid": "5ae71f3e8e442b090e4c313b" }, "sursa1": "nothingfornow", "sursa2": "nothing4now", "corectat": 0, "player2": "test", "player1": "test2", "trimis1": 1, "trimis2": 1 }
tagged with: flask
has title: Flask Pymongo Objectid link not working
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87235801
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/70110866
has answer: http://stackoverflow.com/a/70110473
tagged with: mongodb
answer count: 2
type: UnansweredQuestion
tagged with: pymongo
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87366693
comment on: http://stackoverflow.com/q/50161299
has text: @NathanBlaine oh right.. that did work, thanks
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87220713
comment on: http://stackoverflow.com/q/50101964
has text: I have tried using the melt function but that didnt seem to work
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50195155
has comment: http://stackoverflow.com/comment/87408315
type: Answer
has comment: http://stackoverflow.com/comment/87408332
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/102606035
downvote count: 0
has comment: http://stackoverflow.com/comment/102607393
has body: You need groupby with ffill and bfill themes.groupby('code').apply(lambda x : x.ffill().bfill())
has comment: http://stackoverflow.com/comment/102604015
answers question: http://stackoverflow.com/q/50195148
has comment: http://stackoverflow.com/comment/102608295

http://stackoverflow.com/a/50218049
score: 2
upvote count: 2
has body: This is one way of doing it. Note that this only processes a single block, so you have to extend it to work with multiple blocks: &gt;&gt;&gt; block1 = ['AATTCAT', 'AGTTCAT', 'AATTCGT'] &gt;&gt;&gt; [''.join(b) for b in zip(*(r for r in zip(*block1) if len(set(r)) &gt; 1))] ['AA', 'GA', 'AG'] This basically transposes the 2d array so that you can eliminate the lists when all the letters in the same row (previously in the same column) are the same. Then you re-transpose the result.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50217893
answers question: http://stackoverflow.com/q/50217893
type: Answer
has comment: http://stackoverflow.com/comment/87469243

http://stackoverflow.com/q/50222356
favorite count: 0
linked to: http://stackoverflow.com/q/826948
duplicate of: http://stackoverflow.com/q/25445439
score: 1
has comment: http://stackoverflow.com/comment/87462208
has comment: http://stackoverflow.com/comment/87462232
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87462176
tagged with: python
has title: Python 3.6 string formatting
tagged with: string
downvote count: 1
has body: I have this piece of script which works in python 2.7 but it doesnt on 3.6 with open("points.txt") as myfile: print '{0:10} {1:5}'.format("Exercices","Points") for line in myfile: entry = line.strip().split(",") sum = sum + int(entry[1]) print "{0:^10} {1:^5}".format(entry[0], entry[1]) print "{0:^10} {1:^5}".format("Results",sum) I get a File "points.py", line 18 print '{0:10} {1:5}'.format("Exercices","Points") ^ SyntaxError: invalid syntax Is it because I need to use f string instead? Thanks. Update on Solution I missed the parenthesis.. Correct one is: with open("points.txt") as myfile: print ('{0:10} {1:5}'.format("Exercices","Points")) for line in myfile: entry = line.strip().split(",") sum = sum + int(entry[1]) print("{0:^10} {1:^5}".format(entry[0], entry[1])) print("{0:^10} {1:^5}".format("Results",sum))

http://stackoverflow.com/comment/87417203
type: QuestionComment
has text: As I was posting the path for you, I realized it was not in the correct dir. My bad. Thanks for responding so quickly though. Mods can close this question
comment on: http://stackoverflow.com/q/50200290
score: 0
type: Comment

http://stackoverflow.com/comment/87426299
score: 0
has text: Why don't you just read the json input data and re-write it into csv?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50204585

http://stackoverflow.com/a/50234987
answers question: http://stackoverflow.com/q/50223954
has body: Why don't you turn to RecycleView? It is the widget the contents of which is controlled dynamically by data (which exactrly is a list of dicts), and can handle any combination of widgets inside of it.
type: Answer
score: 0

http://stackoverflow.com/comment/87421228
has text: does this work? Does it do what it is supposed to? What is the question?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50202239
score: 0

http://stackoverflow.com/comment/87215940
type: QuestionComment
has text: what is the output of `type(joblib.load(filename))`?
comment on: http://stackoverflow.com/q/50099623
score: 0
type: Comment

http://stackoverflow.com/comment/107261687
type: QuestionComment
has text: could I ask why you are only using train dataset??
comment on: http://stackoverflow.com/q/50106143
score: 0
type: Comment

http://stackoverflow.com/q/50180632
accepted answer: http://stackoverflow.com/a/50180803
type: Question
tagged with: python-3.x
upvote count: 1
answer count: 1
has title: Infer probability of a specific value from kernel
favorite count: 0
type: AnsweredQuestion
downvote count: 0
score: 1
has body: let's say I have ths simple code that plot the kernel of some data. I would like to extract from this the probability given to a specific value let's say 2, which should be something like 0.145. I know that statistically it is not very relevant but I need this to compute precisely the common area between two distributions. import matplotlib.pyplot as plt import numpy as np from scipy.stats import gaussian_kde data = [1.5]*7 + [2.5]*2 + [3.5]*2 + [4.5]*3 + [5.5]*1 + [6.5]*7 density = gaussian_kde(data) xs = np.linspace(0,8,200) plt.plot(xs,density(xs)) plt.show() Thanks
has answer: http://stackoverflow.com/a/50180803
tagged with: python

http://stackoverflow.com/comment/87307250
comment on: http://stackoverflow.com/a/50144507
has text: Or if you're already working with the output of `~`, then you need to add it to 256, not subtract.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50148111
type: Question
score: 0
answer count: 2
has body: I made a custom method that save session when call get() method in DetailView page. Here's sample of my code. class CustomDetailView(DetailView): model = Jobs template_name = "jobs/job_detail.html" context_object_name = "job" def custom_save_session(self, request): # save session and so on ... I wonder where should I call custom_save_session method. I tried to call it inside get(), get_context_data() and so on. All work well, but I have curiosity what is the best method. Should I call inside get() method? Cause I want to save session data every time get() called. Is there any method that call custom method when every time get() called in DetailView? (I also wonder not only DetailView, but also all CBV in django too)
tagged with: django
has title: Where should I call custom method in django CBV? (DetailView)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50148471
tagged with: python
accepted answer: http://stackoverflow.com/a/50148586
possible better answer: http://stackoverflow.com/a/50148471
has answer: http://stackoverflow.com/a/50148586

http://stackoverflow.com/comment/87185669
type: QuestionComment
has text: @JonathanLeffler ?
score: 0
comment on: http://stackoverflow.com/q/50083466
type: Comment

http://stackoverflow.com/a/50276746
score: 25
accepted answer of: http://stackoverflow.com/q/50185654
downvote count: 0
has comment: http://stackoverflow.com/comment/99927969
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/116920145
upvote count: 25
has body: It seems that cv2.videocode is not a valid OpenCV API either in OpenCV 2.x or OpenCV 3.x. Below is a sample code it works in OpenCV 3 which uses cv2.VideoCapture class. import numpy as np import cv2 # Open a sample video available in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): # print "File Cannot be Opened" while(True): # Capture frame-by-frame ret, frame = vcap.read() #print cap.isOpened(), ret if frame is not None: # Display the resulting frame cv2.imshow('frame',frame) # Press q to close the video windows before it ends if you want if cv2.waitKey(22) &amp; 0xFF == ord('q'): break else: print "Frame is None" break # When everything done, release the capture vcap.release() cv2.destroyAllWindows() print "Video stop" You may check this Getting Started with Videos tutorial for more information. Hope this help.
has comment: http://stackoverflow.com/comment/95687739
type: Answer
answers question: http://stackoverflow.com/q/50185654
has comment: http://stackoverflow.com/comment/99921739
has comment: http://stackoverflow.com/comment/116894901

http://stackoverflow.com/q/50221920
has body: I have csv dataframe like - print(test.loc[1]) outlook sunny temperature mild humidity normal wind weak playtennis yes Name: 1, dtype: object I want to convert this into something like - outlook.sunny.temperature.mild.humidity.normal.wind.weak.playtennis.yes How can I achieve this?
tagged with: machine-learning
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: How can I convert pandas loc indexer to a string?
tagged with: id3
score: 1
has answer: http://stackoverflow.com/a/50222031
tagged with: python
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/50222031
accepted answer: http://stackoverflow.com/a/50222006
has answer: http://stackoverflow.com/a/50222006
downvote count: 0

http://stackoverflow.com/comment/87346744
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50098112
has text: Yes, I do, but same thing in ctypes. I just measure the time elapsed for the outermost python function. My code can be seen at the fork https://github.com/saihv/pybind_examples . Thanks again

http://stackoverflow.com/q/50104095
has comment: http://stackoverflow.com/comment/87225418
has title: Getting Name Error name 'sentence_stream' is not defined
tagged with: nltk
tagged with: python
tagged with: nameerror
upvote count: 0
has comment: http://stackoverflow.com/comment/87277481
downvote count: 2
score: -2
has answer: http://stackoverflow.com/a/50157841
answer count: 1
accepted answer: http://stackoverflow.com/a/50157841
has body: I would like to use trigrams and bigrams because I do not want to use just unigrams. bigramer = gensim.models.Phrases(sentences) model = Word2Vec(bigramer[sentences], workers=num_workers, \ size=num_features, min_count = min_word_count, \ window = context, sample = downsampling) from nltk import bigrams from nltk import trigrams from gensim.models import Phrases from gensim.models.phrases import Phraser trigrams = Phrases(bigrams[sentence_stream]) However, I am having this error. NameErrorTraceback (most recent call last) &lt;ipython-input-161-15b0101c13b1&gt; in &lt;module&gt;() ----&gt; 1 trigrams = Phrases(bigrams[sentence_stream]) NameError: name 'sentence_stream' is not defined
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87225437

http://stackoverflow.com/q/50194338
has body: I have this array: rel=np.array([1,0,0,1,1,0,1,0,1,0,0]) and eta=np.array([2,3,10,16,4,3]) where eta is composed of elements that correspond to 0-elements in rel. In other words, eta[0]=2 is related to rel[1]=0, eta[1]=3 is related to rel[2]=0, eta[2]=10 corresponds to rel[5]=0, and so on. From rel I randomly extract some elements, for example rel_extract=np.array([1,0,0,1,0]) where the null elements are at 1st, 2nd and 4th indexes. How can I create an array named eta_extract using the values in eta considering that eta_extract is made with the same rule of eta? I guess that eta_extract should be eta_extract=array([10,16,3]) Thanks a lot
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/87405855
tagged with: indexing
has comment: http://stackoverflow.com/comment/87406010
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87405985
has comment: http://stackoverflow.com/comment/87405927
accepted answer: http://stackoverflow.com/a/50194613
has comment: http://stackoverflow.com/comment/87405976
has title: Extract elements from a numpy array python
has comment: http://stackoverflow.com/comment/87405959
tagged with: extract
has answer: http://stackoverflow.com/a/50194613
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87460646
comment on: http://stackoverflow.com/a/50210508
type: Comment
has text: Sorry, I meant: I was wondering if Cython's performance would be close to what one would expect from doing this in pure C. I'll definitely try it out
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87237017
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50109822
score: 0
has text: thanks @jhamman, I get this error when I do `da.name = 'new'` `*** AttributeError: cannot set attribute '__xarray_dataarray_variable__' on a 'DataArray' object. Use __setitem__ style assignment (e.g., `ds['name'] = ...`) instead to assign variables.`

http://stackoverflow.com/comment/87316237
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50147944
has text: @BishakhaKumari You can make them appear in next lines by adding a tag. `xstr += ' ' + e + ' '`. Or if you want it to be exactly tabular you can replace p tags with tags and enclose the variable inside tags in the html file. Please share how exactly you want it to look and also sample values in the list if you want full code solution.

http://stackoverflow.com/comment/87167618
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50075703
type: Comment
has text: Possible duplicate of [Mario running across screen too fast in pygame](https://stackoverflow.com/questions/20134955/mario-running-across-screen-too-fast-in-pygame)

http://stackoverflow.com/q/50219578
has comment: http://stackoverflow.com/comment/87456161
possible better answer: http://stackoverflow.com/a/50219666
has answer: http://stackoverflow.com/a/50219642
has title: Rollup of multiple string columns by id - python
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50219666
upvote count: 3
has body: I got following dataframe in Python: d = pd.DataFrame({'id': [1, 1, 1, 2, 2, 3], 'col1': ['normal', 'well', 'normal', 'normal', 'well', 'normal'], 'col2': ['bad', 'normal','normal', 'normal', 'normal', 'bad']}) I would like to rollup by id but keep in columns strings that are other than 'normal' or 'normal' if there is nothing else ('well' or 'bad'). Something like following: result = pd.DataFrame({'id': [1, 2, 3], 'col1': ['well', 'well', 'normal'], 'col2': ['bad', 'normal', 'bad']}) I was thinking about sorting and then using groupby and .first but not sure how to get desired levels on the top in each column.
has answer: http://stackoverflow.com/a/50220062
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50219642

http://stackoverflow.com/q/50162457
tagged with: python-3.x
has title: Handling a slow-loading webpage removing hardcoded delay from my script
possible better answer: http://stackoverflow.com/a/50162967
tagged with: python
accepted answer: http://stackoverflow.com/a/50163204
has answer: http://stackoverflow.com/a/50162967
tagged with: selenium-chromedriver
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: selenium
score: 1
tagged with: web-scraping
upvote count: 1
has body: I've written a script in python in association with selenium to parse some names from a webpage handling the lazyloading method for which the webpage displays it's content upon each scroll to the bottom. My script does it errorlessly. However, the only issue I can't resolve is take out hardcoded delay from my script. I really can't find any idea as to how I can use explicit wait instead of hardcoded delay keeping the logic (applied within the script) as it is to make it more efficient. Thanks in advance for any help. Webpage link This is what I've tried so far (working one): import time from selenium import webdriver driver = webdriver.Chrome() driver.get("find_the_link_above") last_len = len(driver.find_elements_by_class_name("listing__name--link")) new_len = last_len while True: last_len = new_len driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(3) ##I wish to kick out this harcoded delay and use explicit wait in place items = driver.find_elements_by_class_name("listing__name--link") new_len = len(items) if last_len == new_len:break for item in items: print(item.text) driver.quit()
favorite count: 0
has answer: http://stackoverflow.com/a/50163204
type: Question

http://stackoverflow.com/comment/87383627
has text: It looks like the OP wants the key corresponding to the highest value, not the key that's highest in itself.
comment on: http://stackoverflow.com/a/50183074
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87395440
type: Comment
comment on: http://stackoverflow.com/q/50183796
score: 1
type: QuestionComment
has text: You asked [the same question on April 27](https://stackoverflow.com/questions/50065717/heroku-module-not-found). Please [don't repost questions](https://meta.stackexchange.com/a/7054/248627). There, I asked you how you "checked" that a Python module was available using `ls`. That doesn't make much sense. You didn't bother to answer. If you ask questions that don't make sense and don't bother to clarify them we can't help you.

http://stackoverflow.com/q/50091655
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50781468
has comment: http://stackoverflow.com/comment/88130779
score: 0
has body: I am scraping a used car dealer website that has some javascript on the car listing pages hence using scrapy-splash. The car dealer webpages also have infinite scroll until all their cars are listed. The problem i am having is that on some occasions the code below does not let the infinite scroll continue to the end - and i am not sure why - and so i miss some of the cars. I have reduced the Concurrent requests right back to 1 in the Settings file and therefore i know that i at least start to scrap all the car dealers on the start_url page. any ideas i am missing? Settings File code: # -*- coding: utf-8 -*- # Scrapy settings for autotrader1 project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'autotrader1' SPIDER_MODULES = ['autotrader1.spiders'] NEWSPIDER_MODULE = 'autotrader1.spiders' SPLASH_URL = 'http://192.168.99.100:8050/' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'autotrader1 (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) CONCURRENT_REQUESTS = 1 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept':…
tagged with: web-scraping
has title: Scrapy-splash not allowing infinite scroll to complete
tagged with: scrapy
answer count: 1
type: Question
tagged with: scrapy-splash

http://stackoverflow.com/q/50122334
upvote count: 3
tagged with: list
duplicate of: http://stackoverflow.com/q/18041840
has comment: http://stackoverflow.com/comment/87262909
score: 1
duplicate of: http://stackoverflow.com/q/33961445
type: Question
has answer: http://stackoverflow.com/a/50122373
accepted answer: http://stackoverflow.com/a/50122373
downvote count: 2
has comment: http://stackoverflow.com/comment/87262814
has title: Return a list from a list of lists with elements picked by index
duplicate of: http://stackoverflow.com/q/25069497
answer count: 1
has body: Sorry, I don't know how to set a decent title for this problem. I have a function that needs to take a list of lists, e.g. ll = [['a', 'b'], ['c'], ['d', 'e', 'f']] and return ['a', 'c', 'd', 'b', 'e', 'f'] (so, it doesn't just flatten it). I have a feeling it is not as efficient as it could be. def func(lol): ''' Takes a list of lists of varying lengths and creates a single list by taking one by one element from each list respectively. E.g.: ll = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] In: func(ll) Out: [1, 5, 7, 2, 6, 8, 3, 9, 4] ''' arr = [] while lol: for list in lol: try: arr.append(list.pop(0)) except: lol= [list for list in lol if list] return arr What would be a better/faster way to solve this?
linked to: http://stackoverflow.com/q/28395945
tagged with: python
has comment: http://stackoverflow.com/comment/87262826
favorite count: 0
linked to: http://stackoverflow.com/q/952914
duplicate of: http://stackoverflow.com/q/28395945
type: AnsweredQuestion

http://stackoverflow.com/q/50137242
accepted answer: http://stackoverflow.com/a/50138079
has body: I am trying to get a class decorator working. The decorator will add a __init_subclass__ method to the class it is applied to. However, when the method is added to the class dynamically, the first argument is not being bound to the child class object. Why is this happening? As an example: this works, and the static code below is an example of what I'm trying to end up with: class C1: def __init_subclass__(subcls, *args, **kwargs): super().__init_subclass__(*args, **kwargs) print(f"init_subclass -&gt; {subcls.__name__}, {args!r}, {kwargs!r}") Test: &gt;&gt;&gt; D = type("D", (C1,), {}) init_subclass -&gt; D, (), {} However if I add the __init__subclass__ method dynamically, the child class is not being bound to the first argument: def init_subclass(subcls, **kwargs): super().__init_subclass__(**kwargs) print(f"init_subclass -&gt; {subcls.__name__}, {args!r}, {kwargs!r}") def decorator(Cls): Cls.__init_subclass__ = init_subclass return Cls @decorator class C2: pass Test: &gt;&gt;&gt; D = type("D", (C2,), {}) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: init_subclass() missing 1 required positional argument: 'subcls' Why is this happening and how can I do this and get the binding to work the right way?
has answer: http://stackoverflow.com/a/50138079
has title: argument binding for dynamic __init_subclass__ method
tagged with: python
possible better answer: http://stackoverflow.com/a/57809556
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/57809556
upvote count: 3
downvote count: 0
tagged with: metaprogramming
linked to: http://stackoverflow.com/q/36993577
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/50143825
has answer: http://stackoverflow.com/a/50144045
has answer: http://stackoverflow.com/a/50143882
tagged with: cross-validation
tagged with: machine-learning
tagged with: scikit-learn
has title: Reshaping error in multivariate normal function with Numpy - Python
has body: I have this data (c4), I want to use 4-fold cross validation testing on this matrix. The way that I'm splitting the data is as follows: from scipy.stats import multivariate_normal from sklearn.model_selection import KFold import math c4 = np.array([ [5,10,14,18,22,19,21,18,18,19,19,18,15,15,12,4,4,4,3,3,3,3,3,3,3,3,3,3,3,1], [6,9,11,12,10,10,13,16,18,21,20,19,8,5,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3], [4,8,12,17,18,21,21,21,17,16,15,13,7,8,8,7,7,4,4,4,3,3,3,3,4,4,3,3,3,2], [3,7,12,17,19,20,22,20,20,19,19,18,17,16,16,15,14,13,12,9,4,4,4,3,3,3,3,3,2,1], [2,5,8,10,10,11,11,10,13,17,19,20,22,22,20,16,15,15,13,11,8,3,3,3,3,3,3,3,2,1], [4,8,10,11,10,15,15,17,18,19,18,20,18,17,15,13,12,7,4,4,4,4,4,4,4,4,3,3,3,2], [2,8,12,15,18,20,19,20,21,21,23,19,19,16,16,16,14,12,10,7,7,7,7,6,3,3,3,3,2,1], [2,13,17,18,21,22,20,18,18,17,17,15,13,11,8,8,4,4,4,4,4,4,4,4,4,4,4,4,3,1], [6,6,9,14,15,18,20,20,22,20,16,16,15,11,8,8,8,5,4,4,4,4,4,4,4,5,5,5,5,4], [8,13,16,20,20,20,19,17,17,17,17,15,14,13,10,6,3,3,3,4,4,4,3,3,4,3,3,3,2,2], [5,9,17,18,19,18,17,16,14,13,12,12,11,10,4,4,4,3,3,3,3,3,3,3,4,4,3,3,3,3], [4,6,8,11,16,17,18,20,16,17,16,17,17,16,14,12,12,10,9,9,8,8,6,4,3,3,3,2,2,2] ]) kf = KFold(n_splits=4) for train_index, test_index in kf.split(c4): X_train, X_test = c4[train_index], c4[test_index] X_train_mean = np.mean(X_train) X_train_cov = np.cov(X_train.T) v = multivariate_normal(X_train_mean, X_train_cov) res = v.pdf(X_test) print (res) but it didn't work with me, despite that the splitting loop works well with small sample of data. The error message that I got: ValueError: cannot reshape array of size 900 into shape (1,1) Note: the length of all rows is equal. Thanks in advance.
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87306122
has comment: http://stackoverflow.com/comment/87306252
accepted answer: http://stackoverflow.com/a/50144045
downvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87306082
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/50143882

http://stackoverflow.com/comment/87454746
comment on: http://stackoverflow.com/q/50218877
type: Comment
type: QuestionComment
has text: change `result(line).rstrip` to `yield(line).rstrip`
score: 0

http://stackoverflow.com/q/50178248
upvote count: 2
has answer: http://stackoverflow.com/a/50178596
linked to: http://stackoverflow.com/q/50179799
score: 1
has title: Detect color in the middle of image (OpenCV, Python)
downvote count: 1
has comment: http://stackoverflow.com/comment/87383413
has answer: http://stackoverflow.com/a/50178505
favorite count: 0
has comment: http://stackoverflow.com/comment/87374239
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/87374025
has answer: http://stackoverflow.com/a/50178676
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50178539
has answer: http://stackoverflow.com/a/50182588
has comment: http://stackoverflow.com/comment/87373960
tagged with: color-picker
tagged with: python
has body: I have these 3 images (consider "image" the whole square not only the figure inside - this is just for demonstration purposes): What I want to do is detect the colour in the middle (center) of each one. So, having an area (square or circle) in the center and with OpenCV detect which is the colour. Something like a color picker... The purpose is to have 3 values, 3 for each image (BGR). Example: What is the colour in the ROI ? Thanks EDIT Using this code I can find the middle of an image and apply a mask. import cv2 import numpy as np img = cv2.imread("im2.png") height, width, depth = img.shape circle_img = np.zeros((height, width), np.uint8) mask = cv2.circle(circle_img, (int(width / 2), int(height / 2)), 20, 1, thickness=-1) masked_img = cv2.bitwise_and(img, img, mask=circle_img) cv2.imshow("masked", masked_img) cv2.waitKey(0) Now it remains to find BGR of the masked area (visible one...)
tagged with: roi

ipython-parallel
type: Tag
tag name: ipython-parallel
tags question: http://stackoverflow.com/q/50178578

http://stackoverflow.com/a/50111321
accepted answer of: http://stackoverflow.com/q/50111294
has body: If you want to iterate over the lines one by one, you do this: for line in file: do_something_with(line) Your second version isn't working because all you do is reassign the local variable user_input to each line over and over again, so at the end, you just have the last one. You need to actually do something with the line, right there in the loop. Whether that means process it and write some output, or add it to a list or a dict or some other collection for later, depends on what you're trying to do. For example, if you were building a set of all the words in the file, you could do this: words = set() for line in file: words |= set(line.split()) If you want to read the whole file all at once to get a list of all of the lines, on the other hand, you do this: lines = file.readline() … or this: lines = list(file) If you need to loop over the lines multiple times, or access them in arbitrary order, this can be very useful. If not, whatever you wanted to do with lines, you could probably just have done directly with file instead, so you're wasting time and memory building that list. Your code is mixing the two together: for line in file: user_input = file.readline() In other words, for each line in the file, you're trying to read the whole file. This doesn't make any sense. Either do something with each line, or read the whole file just one time.
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87240963
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50111294

http://stackoverflow.com/comment/87397056
score: 0
has text: Thanks Dude @David Eisenstat That was the problem. Please post it as an answer so I can check it. Thanks alot
comment on: http://stackoverflow.com/a/50189936
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87302029
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50141784
has text: It may make more sense to do this transformation at the bytecode level. (If you're at the point where you're putting this level of effort into microoptimizations, though, using something like Cython will probably give you more bang for your buck.)
score: 3

http://stackoverflow.com/comment/87446593
comment on: http://stackoverflow.com/q/50200614
type: Comment
score: 0
has text: You [also posted here](https://ask.libreoffice.org/en/question/154154/best-way-to-run-macro-on-libreoffice-or-openoffice-subform-fill-parameters-event/), and @Ratslinger's answer is a good one.
type: QuestionComment

http://stackoverflow.com/q/50123112
tagged with: pip
accepted answer: http://stackoverflow.com/a/50123301
tagged with: pypi
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50123301
has comment: http://stackoverflow.com/comment/87264572
tagged with: python
has comment: http://stackoverflow.com/comment/87264470
has title: Python packages and default/recommended versions
score: 2
type: AnsweredQuestion
has body: Let's say I have a package MyPackage hosted on Pypi with two versions: 1.0 and 2.0 When a user runs the command pip install MyPackage I want them to download and install 1.0. Is it possible to set a default/recommended package version in this manner? I want to stray away from doing any beta releases i.e. 2.0b1
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50112937
score: 0
answers question: http://stackoverflow.com/q/50104362
has body: If information such as router model, server (Apache/NginX/Node) you will receive much accurate information. The information gathered is only RPi3 and implementation language (not relevant for this question). As others pointed, solution you are looking for is exposing your local port to public. Assuming your stream is accessible at http://192.168.0.1:8080 on your local network. You need to config your router for Port Forwarding/Virtual Server. You goal will be to.. Assign static IP and determine the port number to port forward Added basic auth to the root directory (read on Apache Basic Auth to add basic login prompt) Expose the IP (and port number if different than port 80) to public via DNS Solution below is via noip.com (DNS provider) - free version require confirmation every 30 days. Create no-ip.com account to own a hostname (eg: mycam.ddns.net) Setup no-ip DUC (Dynamic Update Client) so your hostname will tally with your local network IP. Successful setup will allow the example scenario to work by accessing mycam.ddns.net:8080 Done Is DNS required? Your local network IP to outside world (produced by your router) changes intermittently. DNS allows weird number such as 175.143.141.29 today and differently tomorrow to be used like a domain (eg: mycam.ddns.net) Is local static IP required? When your DHCP is renewed (router restarted, different device logging off and on), your IP used by your RPi today (eg: 192.168.0.1) might be 192.168.0.9 on next renewal. Static IP allows 192.168.0.1 to be reserved to a device MAC address (another form of network identity) so it always pointing to the same device on future renewal. Although newer router is much smarter to reserve such IP for such device for longer period. However no-ip DUC might does this for you as it tells the server which IP its currently connected from. Security If you can access it publicly, others will be able to do the same. Proceed with common sense. Alternative setup Due to various setup possibilities, re…
type: Answer

http://stackoverflow.com/comment/87297053
score: 1
has text: Yes, you are right, the text file shows the data correctly. The problem is that Excel ignores the '.' unless it is something like '0,XXX'. The right way to work with .csv files is to use ',' instead of '.' for separating the integer and fractional part from a number. (At least with the European version of Excel).
type: Comment
comment on: http://stackoverflow.com/a/50138645
type: AnswerComment

http://stackoverflow.com/comment/87479637
score: 0
has text: You should read again my messages, I didn't know that you were using visual studio. The problem is also in your DLL source code since with visual studio a long cannot store a pointer on 64bits build
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50197400

http://stackoverflow.com/comment/87234195
type: QuestionComment
score: 0
has text: I edit it and add the error
type: Comment
comment on: http://stackoverflow.com/q/50108003

http://stackoverflow.com/comment/87304624
has text: Instead of guessing, you can also (1) go back to wherever you generated the file (e.g., export from Excel?) and look at what your settings are—or just explicitly re-export as UTF-8, or (2) use `chardet` (and then verify that its output looks reasonable) to make a semi-educated guess instead of a random one.
score: 1
comment on: http://stackoverflow.com/q/50143132
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50179086
answers question: http://stackoverflow.com/q/50176262
has body: In Python variable are ways of referencing objects, not names of the objects. It isn't easy to go from an object to a variable. Also when dealing with multiple objects, it's more natural to put them in lists or dictionaries, rather than assign them to variables. I think this does the same classification: In [95]: SOC = np.array([1, 2, 2, 3, 3, 4]) ...: SOR = np.array([6, 2, 3, 1, 2, 1]) In [96]: items = list(zip(SOC,SOR)) In [97]: items Out[97]: [(1, 6), (2, 2), (2, 3), (3, 1), (3, 2), (4, 1)] In [98]: result = [[] for _ in range(4)] ...: for n,i in enumerate(items): ...: if i[0]&gt;3 and i[1]&gt;3: ...: result[0].append((n,i)) ...: if i[0]&gt;3 and i[1]&lt;=3: ...: result[1].append((n,i)) ...: if i[0]&lt;=3 and i[1]&lt;=3: ...: result[2].append((n,i)) ...: if i[0]&lt;=3 and i[1]&gt;3: ...: result[3].append((n,i)) ...: In [99]: result Out[99]: [[], [(5, (4, 1))], [(1, (2, 2)), (2, (2, 3)), (3, (3, 1)), (4, (3, 2))], [(0, (1, 6))]] result could be converted to characters with: In [100]: np.array(list('ABCDEF')) Out[100]: array(['A', 'B', 'C', 'D', 'E', 'F'], dtype='&lt;U1') In [101]: [[np.array(list('ABCDEF'))[x[0]] for x in y] for y in result] Out[101]: [[], ['F'], ['B', 'C', 'D', 'E'], ['A']] or directly in the first loop: In [102]: result = [[] for _ in range(4)] ...: for n,i in enumerate(items): ...: if i[0]&gt;3 and i[1]&gt;3: ...: result[0].append('ABCDEF'[n]) ...: if i[0]&gt;3 and i[1]&lt;=3: ...: result[1].append('ABCDEF'[n]) ...: if i[0]&lt;=3 and i[1]&lt;=3: ...: result[2].append('ABCDEF'[n]) ...: if i[0]&lt;=3 and i[1]&gt;3: ...: result[3].append('ABCDEF'[n]) ...: ...: In [103]: result Out[103]: [[], ['F'], ['B', 'C', 'D', 'E'], ['A']]
score: 0
has comment: http://stackoverflow.com/comment/87447159
type: Answer
accepted answer of: http://stackoverflow.com/q/50176262
type: AcceptedAnswer

http://stackoverflow.com/comment/87406477
comment on: http://stackoverflow.com/a/50184832
has text: Thank you, again. Your comments are very helpful.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50081243
has comment: http://stackoverflow.com/comment/98305318
type: Answer
has comment: http://stackoverflow.com/comment/87178550
has comment: http://stackoverflow.com/comment/87178615
has comment: http://stackoverflow.com/comment/87181319
downvote count: 0
has comment: http://stackoverflow.com/comment/87191062
upvote count: 3
has comment: http://stackoverflow.com/comment/87178886
score: 3
answers question: http://stackoverflow.com/q/50078142
has body: Here's something that seems like it could accomplish what you want. It's not a full-blown example, but rather just a demonstration of one approach to accomplishing your goal of making a copy. Your question doesn't have any code that actually draws something on a Canvas, so I borrowed some from a tutorial on using tkinter that I found in order to have a Canvas with a few widgets on it for illustration purposes. It produces a window that looks like this that has a single Button and a single Canvas widget containing only three different colored rectangle widgets: Here's the demo code showing how to iterate through all the widgets currently on the Canvas: from pprint import pprint, pformat from tkinter import Button, Tk, Canvas, Frame, BOTH class Example(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.master.title("Colours") self.pack(fill=BOTH, expand=1) button = Button(self, text="Copy", command=self.copy_canvas) button.pack() self.canvas = Canvas(self) self.canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0") self.canvas.create_rectangle(150, 10, 240, 80, outline="#f50", fill="#f50") self.canvas.create_rectangle(270, 10, 370, 80, outline="#05f", fill="#05f") self.canvas.pack(fill=BOTH, expand=1) def copy_canvas(self): # Iterate through all the items in self.canvas and print each # one's type and options (which could be used to recreate it). for id in self.canvas.find_all(): item_type = self.canvas.type(id) options = self.canvas.itemconfigure(id) formatted_options = pformat(options, indent=4) print('id: {}, type: {!r}\n{}'.format( id, item_type, formatted_options)) def main(): root = Tk() ex = Example() root.geometry("400x100+300+300") root.mainloop() if __name__ == '__main__': main() and here's what it prints when the Copy button is pressed: id: 1, type: 'rectangle' { 'activedash': ('activedash', '', '', '', ''), 'activefill': ('activefill', '', '', '', ''), 'activeoutline': ('activeoutline', '', '', '', ''), 'acti…

http://stackoverflow.com/q/50217764
linked to: http://stackoverflow.com/q/37926248
has answer: http://stackoverflow.com/a/50217892
downvote count: 0
tagged with: pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87452563
has comment: http://stackoverflow.com/comment/87452524
answer count: 1
has comment: http://stackoverflow.com/comment/87452482
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87452489
has title: In Python, how to sort a dataframe containing accents?
tagged with: dataframe
tagged with: sorting
has comment: http://stackoverflow.com/comment/87452589
upvote count: 4
has body: I use sort_values to sort a dataframe. The dataframe contains UTF-8 characters with accents. Here is an example: &gt;&gt;&gt; df = pd.DataFrame ( [ ['i'],['e'],['a'],['é'] ] ) &gt;&gt;&gt; df.sort_values(by=[0]) 0 2 a 1 e 0 i 3 é As you can see, the "é" with an accent is at the end instead of being after the "e" without accent. Note that the real dataframe has several columns !
score: 4
tagged with: python

http://stackoverflow.com/comment/87292160
type: Comment
comment on: http://stackoverflow.com/q/50136833
score: 0
has text: Hi @NathanBlaine, That is the result but I believe that's only one page so it might be looping over that same page unfortunately. I'm trying to iterate through the API's url pages (the page changes at Offset +-1 within the url) and then put all of it into a pandas Dataframe.
type: QuestionComment

http://stackoverflow.com/comment/87226185
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50104456
has text: But it will fail if Numberset1 doesn't start with 10, for example if Numberset1 = [11,12,13], or I didn't understand the question.

http://stackoverflow.com/q/50141807
possible better answer: http://stackoverflow.com/a/50142130
has title: Create bars on side of a matriz on python
has answer: http://stackoverflow.com/a/50141883
favorite count: 0
type: Question
tagged with: element
has comment: http://stackoverflow.com/comment/87302375
tagged with: python
accepted answer: http://stackoverflow.com/a/50141883
has body: I want to make a matriz nxn but on the vertical sides I want to put "|" but I can't do it with the code below: def creatematriz(nlines, ncoluns, valor): M = [] for i in range(nlines): line = [] for j in range(ncoluns): line.append(valor) M.append(line) return M def printMatriz(matriz): for line in matriz: for position in line: print(position, end=" ") print("|") def main(): m=creatematriz(20,6,'0') printMatriz(m) main() I want something like this: | 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 | | 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 | | 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 | But I only get: 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 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 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 0 0 0 0 0 0|
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: matrix
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50142130

http://stackoverflow.com/comment/87216987
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/50100235
type: Comment
has text: Can you give a little more of context as to the logic behind the choosing of next1 or next2 to get the next element? Why a simple condition in \_\_next\_\_ would not be sufficient?

http://stackoverflow.com/comment/87220725
has text: there are some cases, for example a kind of "post mortem" debugging, when you add the extra debugging overhead only after an exception is caught (note the the builtin traceback doesn't provide such an information, maye because that's not easily done or even impossible)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50101833

http://stackoverflow.com/q/50176037
tagged with: python
has answer: http://stackoverflow.com/a/50176274
type: Question
has title: OpenCV Python best thresholding for document photos with varying light
linked to: http://stackoverflow.com/q/42056592
has comment: http://stackoverflow.com/comment/87369780
has body: Thank you for your time dear reader, i´m trying to implement a document scanner in Python/OpenCV but im struggling with varying lights in the image. Im hoping that maybe some kind soul can at least point me in the right direction because I have no concrete clue how I could improve it - if that is possible or known at all. Im using otsus binarization for thresholding: https://docs.opencv.org/3.4.0/d7/d4d/tutorial_py_thresholding.html My results so far are pretty good: But for difficult lighting with either two bright/dark areas or one bright - one dark area for instance (this is a crass example) it fails: Playing around with Gimp curves sometimes gets me clear edges - maybe there is a best practice how to tackle this problem that I dont know of? I played around with the code a lot but got no real progress by combining hierarchy / chain approx / approxpolydp epsilon methods etc. My current code: #!/usr/bin/python # -*- coding: UTF-8 -*- import cv2 as cv import numpy as np import sys # zero at the end reads black white img = cv.imread(sys.argv[1],0) blur = cv.GaussianBlur(img,(5,5),0) # find normalized_histogram, and its cumulative distribution function hist = cv.calcHist([blur],[0],None,[256],[0,256]) hist_norm = hist.ravel()/hist.max() Q = hist_norm.cumsum() bins = np.arange(256) fn_min = np.inf thresh = -1 for i in range(1,256): p1,p2 = np.hsplit(hist_norm,[i]) # probabilities q1,q2 = Q[i],Q[255]-Q[i] # cum sum of classes b1,b2 = np.hsplit(bins,[i]) # weights # finding means and variances m1,m2 = np.sum(p1*b1)/q1, np.sum(p2*b2)/q2 v1,v2 = np.sum(((b1-m1)**2)*p1)/q1,np.sum(((b2-m2)**2)*p2)/q2 # calculates the minimization function fn = v1*q1 + v2*q2 if fn &lt; fn_min: fn_min = fn thresh = i # find otsu's threshold value with OpenCV function ret, otsu = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU) cv.imwrite('otsu.jpg',otsu) _, contours, hierarchy = cv.findContours(otsu, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) def biggestRectangle(contours): biggest = No…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87369494
tagged with: opencv
score: 0
answer count: 1

http://stackoverflow.com/q/50216747
accepted answer: http://stackoverflow.com/a/50218520
has answer: http://stackoverflow.com/a/50218520
has comment: http://stackoverflow.com/comment/87465315
has body: The input and labels of my dataset is stored in 10000 .npy files each. For example inputs/0000.npy,...inputs/9999.npy and labels/0000.npy,...labels/9999.npy. While each file independently can be stored in memory, the whole dataset of 20k arrays cannot be stored in memory. I would like to implement multi-threaded CPU pipeline to import the dataset as batches of say batch_size=8. I have tried to implement the functions mentioned in the new Tensorflow data API but haven't found any example for my requirements. All examples seem to be for cases where the whole dataset can be loaded into RAM. Any idea how to approach this?
type: AnsweredQuestion
answer count: 1
downvote count: 0
score: 1
upvote count: 1
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
has title: How to implement multi-threaded import of numpy arrays stored on disk as dataset in Tensorflow
type: Question
has comment: http://stackoverflow.com/comment/87465045
tagged with: python

http://stackoverflow.com/comment/87216254
type: QuestionComment
comment on: http://stackoverflow.com/q/50099378
score: 0
type: Comment
has text: @BurhanKhalid How goofy i am. Yes. i forget :) However after i have installed the `google-cloud-storage` i get the error: `ImportError: No module named 'google_auth_oauthlib'`

http://stackoverflow.com/q/50186427
score: 0
type: UnansweredQuestion
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50190739
tagged with: pytube
has title: Unresolved attributes reference 'get_videos' class for 'YouTube'
tagged with: python
has body: yt = pytube.YouTube(link) videos = yt.get_videos() I got a warning from the IDE: unresolved attributes reference 'get_videos' class for 'YouTube'. What should I do?

http://stackoverflow.com/comment/87222392
type: QuestionComment
score: 0
has text: are there any tutorials you would recommend that explain this without using the mnist dataset
comment on: http://stackoverflow.com/q/50101699
type: Comment

http://stackoverflow.com/a/50186837
has body: I think reduceByKey will help here. Remember that when using reduceByKey or any other "By Key" transformation or action you can define the key to be a tuple. rdd = sc.parallelize([(2,10482422,0.18), (2,10482422,0.4), (2,10482423,0.15), (2,10482423,0.43), (2,10482424,0.18), (2,10482424,0.49), (2,10482425,0.21), (2,10482425,0.52), (2,10482426,0.27), (2,10482426,0.64), (2,10482427,0.73)]) print rdd.map(lambda x: ((x[0], x[1]), x[2]))\ .reduceByKey(lambda x, y: x if x &gt;= y else y)\ .collect() result: [((2, 10482427), 0.73), ((2, 10482425), 0.52), ((2, 10482426), 0.64), ((2, 10482423), 0.43), ((2, 10482424), 0.49), ((2, 10482422), 0.4)]
score: 1
accepted answer of: http://stackoverflow.com/q/50184938
type: Answer
answers question: http://stackoverflow.com/q/50184938
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50204320
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50198393
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/50198393
has body: As already pointed out in the comments, you should not expect cython to speed-up your code because the most of the time the algorithm spends in itertools and creation of lists. Because I'm curios to see how itertools's generic implementation fares against old-school-tricks, let's take a look at this Cython implementation of "all subsets k out of n": %%cython ctypedef unsigned long long ull cdef ull next_subset(ull subset): cdef ull smallest, ripple, ones smallest = subset&amp; -subset ripple = subset + smallest ones = subset ^ ripple ones = (ones &gt;&gt; 2)//smallest subset= ripple | ones return subset cdef subset2list(ull subset, int offset, int cnt): cdef list lst=[0]*cnt #pre-allocate cdef int current=0; cdef int index=0 while subset&gt;0: if((subset&amp;1)!=0): lst[index]=offset+current index+=1 subset&gt;&gt;=1 current+=1 return lst def all_k_subsets(int start, int end, int k): cdef int n=end-start cdef ull MAX=1L&lt;&lt;n; cdef ull subset=(1L&lt;&lt;k)-1L; lst=[] while(MAX&gt;subset): lst.append(subset2list(subset, start, k)) subset=next_subset(subset) return lst This implementation uses some well-known bit-tricks and has the limitation, that it only works for at most 64 elements. If we compare both approaches: &gt;&gt;&gt; %timeit x(1,45,6) 2.52 s ± 108 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) &gt;&gt;&gt; %timeit all_k_subsets(1,45,6) 1.29 s ± 5.16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) The speed-up of factor 2 is quite disappointing. However, the bottle-neck is the creation of the lists and not the calculation itself - it is easy to check, that without list creation the calculation would take about 0.1 seconds. My take away from it: if you are serious about speed you should not create so many lists but proceed the subset on the fly (best in cython) - a speed-up of more than 10 is possible. If it is a must to have all subsets as lists, so you cannot expect a huge speed-up.
has comment: http://stackoverflow.com/comment/87425703
type: Answer
has comment: http://stackoverflow.com/comment/87434169
score: 7

http://stackoverflow.com/a/78737891
score: 0
answers question: http://stackoverflow.com/q/50225723
type: Answer
has body: You can apply Mini Batch Gradient Descent using SGDRegressor class of Sklearn, The code is : from sklearn.linear_model import SGDRegressor sgd=SGDRegressor(learning_rate='constant',eta0=0.01) batch_size=15 #specifying the batch size for i in range(100): indexes=random.sample(range(x_train.shape[0]),batch_size) sgd.partial_fit(x_train[indexes],y_train[indexes]) sgd.predict()

http://stackoverflow.com/comment/87506292
has text: what if i need power = 100 and also separate list of machines with power = 99 ? do i have to use two separate Counter() functions with the query ? If this is the case then, one counter is taking around .75 secs for avg case and when i use two then it takes 1.5 secs.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50227533

http://stackoverflow.com/q/50194532
score: 0
answer count: 0
duplicate of: http://stackoverflow.com/q/2239737
has body: The expected behaviour for this is to print 2949 is the magic number! when it hits 2949, yet the loop doesn't. The loop seems to start at 19, then jump to 513920 - why is this? magicNumber = 2949 for x in range(0, 100000000): if (x is magicNumber): print(x, "is the magic number!")
linked to: http://stackoverflow.com/q/306313
has comment: http://stackoverflow.com/comment/87406175
type: Question
duplicate of: http://stackoverflow.com/q/306313
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87406214
has comment: http://stackoverflow.com/comment/87406176
tagged with: python
has title: Python code doesn't work as expected?

http://stackoverflow.com/comment/87257313
type: Comment
type: QuestionComment
has text: Could I append "score" to a list and plot that instead?
comment on: http://stackoverflow.com/q/50119819
score: 0

http://stackoverflow.com/comment/87235313
score: 0
type: AnswerComment
has text: @DanielDaza You can not change the error every time, you should also read the documentation. you must iterate. I will update my answer.
type: Comment
comment on: http://stackoverflow.com/a/50108215

http://stackoverflow.com/a/50226910
accepted answer of: http://stackoverflow.com/q/50225801
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87490575
has comment: http://stackoverflow.com/comment/87472390
has comment: http://stackoverflow.com/comment/87494189
answers question: http://stackoverflow.com/q/50225801
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87495151
has comment: http://stackoverflow.com/comment/87472466
has body: A few notes on your script: (1) Since you are using rfft, the matching inverse would be irfft not ifft (2) As it stands the script accepts every frequency except 0 as valid (because 1 is included in valid_ratios (3) The complex number at a given frequency contains the amplitude and the phase (shift) of that "sine wave". I'm assuming you want to filter based on the amplitude. For that you have to take the absolute value of the complex number, i.e. np.abs(f) &gt; 1 etc. (4) Once you have a good set of valid frequencies you can proceed as follows. I'm going with @Mateen Ulhaq's suggestion of using geometric midpoints. boundaries = np.concatenate([[0], np.round(np.sqrt(0.25 + valid_frequencies[:-1] * valid_frequencies[1:])).astype(int)]) select = np.abs(data_fft) &gt; 1 filtered_data_fft = np.zeros_like(data_fft) filtered_data_fft[valid_frequencies] = np.add.reduceat(np.where(select, data_fft, 0), boundaries)
has comment: http://stackoverflow.com/comment/87495837
has comment: http://stackoverflow.com/comment/87495733
type: Answer

http://stackoverflow.com/q/50188207
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50188282
upvote count: 1
tagged with: scheduled-tasks
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: time
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has body: I'm using a = datetime.now() b = datetime(2018,4,26,00,7,00) time.sleep((b-a).total_seconds()) to start my script at a given time, but I want to change it. Instead of using datetime() I want to use the module time because the year, month and day is irrelevant for me. I also want to ask for the start time via input("Start time? "). I hope you can help me or maybe you have some alternatives.
has title: Python Start function at a given time: Using time.sleep()
score: 1

http://stackoverflow.com/a/50154711
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50154147
type: Answer
has body: If you apply qcut across the columns you will get a dataframe where each entry is the rank value. import numpy as np import pandas as pd data_a = np.random.random(100) data_b = 100*np.random.random(100) df = pd.DataFrame(columns=['A','B'], data=list(zip(data_a, data_b))) rank = df.apply(pd.qcut, axis=0, q=10, labels=False)
score: 1

http://stackoverflow.com/q/50107276
tagged with: string
has comment: http://stackoverflow.com/comment/87232099
has comment: http://stackoverflow.com/comment/87235617
has comment: http://stackoverflow.com/comment/87235510
favorite count: 0
type: Question
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50109189
accepted answer: http://stackoverflow.com/a/50109189
type: AnsweredQuestion
tagged with: split
has body: Please forgive my panda newbie question, but I have a column of U.S. towns and states, such as the truncated version shown below (For some strange reason, the name of the column is called 'Alabama[edit]' which is associated with the first 0-7 town values in the column): 0 Auburn (Auburn University)[1] 1 Florence (University of North Alabama) 2 Jacksonville (Jacksonville State University)[2] 3 Livingston (University of West Alabama)[2] 4 Montevallo (University of Montevallo)[2] 5 Troy (Troy University)[2] 6 Tuscaloosa (University of Alabama, Stillman Co... 7 Tuskegee (Tuskegee University)[5] 8 Alaska[edit] 9 Fairbanks (University of Alaska Fairbanks)[2] 10 Arizona[edit] 11 Flagstaff (Northern Arizona University)[6] 12 Tempe (Arizona State University) 13 Tucson (University of Arizona) 14 Arkansas[edit] 15 Arkadelphia (Henderson State University, Ouach... 16 Conway (Central Baptist College, Hendrix Colle... 17 Fayetteville (University of Arkansas)[7] 18 Jonesboro (Arkansas State University)[8] 19 Magnolia (Southern Arkansas University)[2] 20 Monticello (University of Arkansas at Monticel... 21 Russellville (Arkansas Tech University)[2] 22 Searcy (Harding University)[5] 23 California[edit] The towns that are in each state are below each state name, e.g. Fairbanks (column value 9) is a town in the state of Alaska. What I want to do is to split up the town names based on the state names so that I have two columns 'State' and 'RegionName' where each state name is associated with each town name, like so: RegionName State 0 Auburn (Auburn University)[1] Alabama 1 Florence (University of North Alabama) Alabama 2 Jacksonville (Jacksonville State University)[2] Alabama 3 Livingston (University of West Alabama)[2] Alabama 4 Montevallo (University of Montevallo)[2] Alabama 5 Troy (Troy University)[2] Alabama 6 Tuscaloosa (University of Alabama, Stillman Co... Alabama 7 Tuskegee (Tuskegee University)[5] Alabama 8 Fairbanks (University of Alaska Fairbanks)[2] Alaska 9 Flagstaff (No…
has title: Extract string from column following a specific pattern
has comment: http://stackoverflow.com/comment/87236633
answer count: 1
downvote count: 0
upvote count: 1

asterisk
tags question: http://stackoverflow.com/q/50136210
type: Tag
tag name: asterisk

http://stackoverflow.com/comment/87327583
type: QuestionComment
comment on: http://stackoverflow.com/q/50154976
score: 0
has text: Not within seaborn. Using matplotlib you have the option to create a gradient image and clip it by some path, which could in this case be the half-violin in question.
type: Comment

http://stackoverflow.com/a/52494501
answers question: http://stackoverflow.com/q/50146415
score: 0
type: Answer
has body: Here's the working solution: cars = input('Cars: ') if cars == "redish red'y maybe-red kindared": print('red: 0') print('blue: 0') kinda = False else: cars.strip(str(not('red' + 'blue'))) red = str(cars.count('red' or 'red ')) blue = str(cars.count('blue')) print('red: ' + red) print('blue: ' + blue) Edit: This code is the solution to ALL the 7 tests for this question - it may look different from what you want right now (with kinda and everything) but it works.

http://stackoverflow.com/a/50142662
type: Answer
has comment: http://stackoverflow.com/comment/87304192
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50142298
has body: The problem is that you try to apply method from the datetime class to str object. You need to convert the strings read from your Excel file to datetime object before applying the timezone conversion. import pandas as pd import pytz from datetime import datetime df = pd.read_excel('hello.xlsx', header=None) local_tz = pytz.timezone('US/Pacific') local_fmt = "%m/%d/%Y %H:%M:%S" df[0] = df[0].apply(lambda x: datetime.strptime(x, local_fmt)) df[0] = df[0].apply(lambda x: x.replace(tzinfo=pytz.utc).astimezone(local_tz).replace(tzinfo=None)) df.to_excel('out.xlsx', index=False, header=False)
answers question: http://stackoverflow.com/q/50142298

http://stackoverflow.com/comment/87299633
type: QuestionComment
comment on: http://stackoverflow.com/q/50140676
type: Comment
has text: What are you entering as `v` input ?
score: 0

http://stackoverflow.com/q/50154465
tagged with: keras
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50159650
type: UnansweredQuestion
tagged with: word-embedding
downvote count: 0
tagged with: word2vec
tagged with: python
has body: I am trying to build a relation extraction system for drug-drug interactions using a CNN and need to make embeddings for the words in my sentences. The plan is to represent each word in the sentences as a combination of 3 embeddings: (w2v,dist1,dist2) where w2v is a pretrained word2vec embedding and dist1 and dist2 are the relative distances between each word in the sentence and the two drugs that are possibly related. I am confused about how I should approach the issue of padding so that every sentence is of equal length. Should I pad the tokenised sentences with some series of strings(what string?) to equalise their lengths before any embedding?
tagged with: nlp
score: 1
has title: embedding word positions in keras
answer count: 1
upvote count: 1

http://stackoverflow.com/a/50174588
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87368476
has body: An inverse parabola (sampled at evenly spaced points) has the property that the differences between adjacent points always decreases. The maximum is just before the differences go negative. If the difference between the first two points is negative or zero, the maximum is the first point in the array. Otherwise, do a binary search to find the smallest positive difference between two adjacent points. The maximum will be the second of these two points.
type: Answer
accepted answer of: http://stackoverflow.com/q/50174228
has comment: http://stackoverflow.com/comment/87370030
has comment: http://stackoverflow.com/comment/87371457
answers question: http://stackoverflow.com/q/50174228
score: 0

http://stackoverflow.com/comment/87424419
has text: @randomir How exactly would you go about replacing `list`? Sure you can do `import builtins; builtins.list = MyCustomList`, but there are still list literals `[]` and builtin functions like `str.split` still return normal lists.
type: QuestionComment
comment on: http://stackoverflow.com/q/50203630
type: Comment
score: 1

http://stackoverflow.com/a/50101854
answers question: http://stackoverflow.com/q/50098338
has body: You can try rsplit: "centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg".rsplit("_", 1) ['centerOne_camera_2_2018-04-11_15:11:21', '2.0.jpg']
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/124418338
has text: I have `"subProcess": false`. But I am still able to debug into the supProcess module. Any idea?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/57557567
type: Comment

http://stackoverflow.com/a/50113945
upvote count: 1
has body: Try using following command instead driver = webdriver.chrome.webdriver.WebDriver(executable_path='E:\Selenium\chromedriver_win32\chromedriver.exe') Reference: Official document https://seleniumhq.github.io/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.webdriver.html#selenium.webdriver.chrome.webdriver.WebDriver
has comment: http://stackoverflow.com/comment/87249370
type: Answer
answers question: http://stackoverflow.com/q/50113232
score: 1
downvote count: 0

http://stackoverflow.com/a/79203500
upvote count: 0
type: Answer
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/50125472
has body: This error can occur due to an unstable or slow internet connection, even if ping or curl seem to work. High latency or packet loss can prevent Conda from downloading metadata. Steps that worked for me: Restart Your Computer: This can reconnect to a better signal or reset network settings. Switch Networks: Use a stronger Wi-Fi signal or a wired connection. Check Speed and Stability: Test your connection using Speedtest to ensure it's fast and reliable. Retry the Command: Once the connection is stable, re-run the Conda operation.

http://stackoverflow.com/comment/87382480
comment on: http://stackoverflow.com/q/50162738
type: QuestionComment
type: Comment
score: 0
has text: Try adding ``python-path=/home/xxx/is_websites/is_spa`` option to ``WSGIDaemonProcess``, I can't remember but don't think ``WSGIPythonPath`` is inherited by ``WSGIDaemonProcess`` process.

http://stackoverflow.com/q/50092710
favorite count: 0
type: Question
tagged with: python-3.x
has body: I still don't understand how URLs work in Django 1.x very well, and am having trouble doing so in Django 2.x. Could someone help with with how to translate this to Django 2.x? urlpatterns = [ url(r'^activate/(?P&lt;uidb64&gt;[0-9A-Za-z_\-]+)/(?P&lt;token&gt;[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), ]
accepted answer: http://stackoverflow.com/a/50093028
tagged with: django
upvote count: 1
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/47947673
type: AnsweredQuestion
score: 0
has title: Url in Django 2
answer count: 1
duplicate of: http://stackoverflow.com/q/47947673
has answer: http://stackoverflow.com/a/50093028

http://stackoverflow.com/q/50148570
type: Question
has title: Simple SQLAlchemy query in Flask performs very slowly
has body: I have a table like this: Table "public.transactions" Column | Type | Nullable | Default | Storage | ---------------------+--------------------------+----------+--------------------| id | integer | not null | nextval | plain | ticket | integer | | | plain | pay_station | character varying(50) | | extended| | stall | character varying(50) | | | extended | license_plate | character varying(8) | | | extended | purchased_date | timestamp with time zone | not null | | plain | expiry_date | timestamp with time zone | | | plain | payment_type | character varying(50) | | | extended | total_collections | numeric(10,2) | | | main | revenue | numeric(10,2) | | | main | rate_name | character varying(50) | | | extended | hours_paid | numeric(4,2) | | | main | validation_revenue | numeric(10,2) | | | main | transaction_fee | numeric(10,2) | | | main | method | character varying(50) | | | extended | Indexes: "transactions_pkey" PRIMARY KEY, btree (id) "transactions_expiry_date_idx" btree (expiry_date) "transactions_purchased_date_idx" btree (purchased_date) "transactions_stall_idx" btree (stall) And ~20 more columns I omitted for brevity. This table has ~2.5 million rows. Now my Python code in Flask which is serving an API looks like this for an example query: filters = [ datetime_range['start'] &lt; Transactions.expiry_date, datetime_range['end'] &gt; Transactions.purchased_date ] if 'parking_spaces' in params: spaces = params['parking_spaces'] # array filters.append(Transactions.stall.in_(spaces)) results = Transactions.query.with_entities( Transactions.stall, Transactions.purchased_date, Transactions.expiry_date ).filter(*filters).order_by(Transactions.purchased_date).all() Where the dates are datetime objects. Now, if I don't provide any input in the POST body, I default to a min/max time, no WHERE IN spaces, and the query looks like this: datetime_range: {'start': datetime.datetime(2016, 1, 1, 0, 0, tzinfo=datetime.timezone.utc), 'end': datetime.datetime(2019, 1, 1, 0, 0, tzi…
tagged with: postgresql
type: UnansweredQuestion
tagged with: database
has comment: http://stackoverflow.com/comment/87315396
tagged with: python
has comment: http://stackoverflow.com/comment/87338131
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/87471001
has comment: http://stackoverflow.com/comment/87315658
score: 1
tagged with: flask
tagged with: sqlalchemy
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87474113
has text: Ok, I would propose to also add the `ENTRYPOINT` and `CMD` of the failing container. It would also be useful to add more tags to your question, so that people who "follow" these tags can share their knowledge. For example `blender`, `celery`...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50227736

http://stackoverflow.com/a/50138933
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50138249
has body: Thanks to the suggestion from @NathanBlaine, the use of marking string literal with r is exceptionally suitable for my use case here. Always happy to learn a new thing every day. :) Though, I was not able to retrieve the string result with check_output. Instead, subprocess.call managed to return the expected strings. Here's the working code. import os import datetime import subprocess if __name__ == "__main__": fScript = r"""ffmpeg -i http://0.0.0.0:8080/stream/video.mjpeg -vcodec copy -map 0 -f segment -segment_time 2 -loglevel 40 -segment_format mp4 capture-%05d.mp4 2&gt;&amp;1 | grep --line-buffered -Eo "segment:.+ended" | gawk -F "'" '{print $2; system("")}'""" try: result = subprocess.call(fScript, stderr=subprocess.STDOUT, shell=True).decode('utf-8') print(result) except subprocess.CalledProcessError as e: print(e.output)
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50138249
score: 2
downvote count: 0

exchange-server
tags question: http://stackoverflow.com/q/50103169
type: Tag
tag name: exchange-server

http://stackoverflow.com/comment/87328882
type: QuestionComment
comment on: http://stackoverflow.com/q/50154693
score: 0
type: Comment
has text: Side-note: `range` is generally considered the idiomatic way to run a loop `n` times while ignoring the iteration value, but if you're trying to squeeze out every last drop of speed, you can do a little better by using `for _ in itertools.repeat(None, i + 1):`, which, like Py3 `range`, behaves as a virtual iterator in this context (values produced on demand, no large temporaries precomputed as in `[0]*(i+1)`), but in addition, doesn't produce any per iteration objects at all (`range` must make brand new `int`s beyond an implementation detail boundary).

http://stackoverflow.com/comment/87399640
score: 0
type: AnswerComment
has text: The text was created in a text editor, there is some possibility that it is giving error for this reason
comment on: http://stackoverflow.com/a/50190361
type: Comment

http://stackoverflow.com/comment/87411521
type: Comment
type: QuestionComment
score: 0
has text: Dates aren't put into "JSON format". It's just a string. Also, you're being downvoted here because date formatting and parsing is 1) answered before 2) documented enough in the python docs 3) you've not specified an exact format, so are we supposed to guess ISO8601?
comment on: http://stackoverflow.com/q/50197292

http://stackoverflow.com/a/50216729
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50216417
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50216417
type: Answer
has comment: http://stackoverflow.com/comment/87451315
has comment: http://stackoverflow.com/comment/87486755
upvote count: 4
score: 4
has body: following Features You will get if you are using Socket.io or socketcluster.io (which is developed on the top of Socket IO) scalability :- It will scale horizontally adding more nodes (scale-out) &amp; Linearly(scale-up) Reduces Payload size as message payload is compressed Authorisation via middle ware functions Reconnects Automatically if Connection drops If You want to use your own implementation then you have to take care of the above features/Solutions to problems which arises when User-base is increases.

http://stackoverflow.com/comment/87312858
type: QuestionComment
has text: Also, it would be much better as a [mcve] if you just took out the `requests` and `bs4` parts and just directly gave us `results = [<some Python list literal that reproduces the problem>]`.
type: Comment
comment on: http://stackoverflow.com/q/50147236
score: 0

http://stackoverflow.com/comment/87474340
comment on: http://stackoverflow.com/a/50228072
has text: I think I should read more about pandas it seems easier to use .. thank you for the help
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50282986
has body: Breakdown in the comments, enjoy! from lxml import etree import re #Convert html string to correct format for parsing with XPATHs root = etree.XML(html) tree = etree.ElementTree(root) #Your XPATH Selector xpathselector = 'body/ul' #List of lxml items that need to be decoded hold = tree.xpath(xpathselector) ''' 1. Get strings of each item in hold 2. Decode to string 3. Remove all tags and \n in each list 4. Split on spaces to create list of lists ''' df = pd.DataFrame([re.sub('(\\n)|(\&lt;.{0,3}\&gt;)','',etree.tostring(i).decode('utf-8')).split() for i in hold]) df 0 1 2 0 Name Many Stories 1 More None None 2 Stuff About None
accepted answer of: http://stackoverflow.com/q/50220333
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50220333

http://stackoverflow.com/q/50156391
possible better answer: http://stackoverflow.com/a/50156518
has answer: http://stackoverflow.com/a/50156609
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50211220
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/87330604
type: Question
has body: I have a list which may or may not have repeating elements, i wish to create ordered pairs such that in an element x is repeated the x,x is a valid pair other wise all x,y when x so far i have found a very non - pythonic way of doing this def foo(a): n = list() for x in range(len(a)): for y in range(x+1,len(a)): if a[x] &lt; a[y]: n.append([a[x],a[y]]) else: n.append([a[y],a[x]]) o = list() for p in n: if not (p in o): o.append(p) return o print(foo([1,3,5,-1])) # [[1, 3], [1, 5], [-1, 1], [3, 5], [-1, 3], [-1, 5]] print(foo([1,1,5,5])) # [[1, 1], [1, 5], [5, 5]] print(foo([1,1,1,1])) # [[1, 1]] i am aware i can use list comprehension but the solution i tried either skips the x,x type when repeats are present or and phantom x,x which should not be present a = [1,3,5,-1] o = [[x,y] for x in a for y in a if x&lt;=y] print(o) [[1, 1], [1, 3], [1, 5], [3, 3], [3, 5], [5, 5], [-1, 1], [-1, 3], [-1, 5], [-1, -1]] what will be the appropriate pythonic solution for readability. Additionally what will the be most efficient solution time wise (memory is not a constraint) in case the pythonic solution is not the most efficient
has title: Ordered Pair from repeating list
has answer: http://stackoverflow.com/a/50156518
accepted answer: http://stackoverflow.com/a/50156609
tagged with: python

http://stackoverflow.com/q/50124621
upvote count: 9
has comment: http://stackoverflow.com/comment/87267670
has comment: http://stackoverflow.com/comment/87268740
has comment: http://stackoverflow.com/comment/87267550
downvote count: 0
tagged with: python
type: AnsweredQuestion
has body: I'm trying to understand how python is using memory to estimate how many processes I can run at a time. Right now I process large files on a server with large amounts of ram (~90-150GB of free RAM). For a test, I would do things in python, then look at htop to see what the usage was. step 1: I open a file which is 2.55GB and save it to a string with open(file,'r') as f: data=f.read() Usage is 2686M step 2: I split the file on newlines data = data.split('\n') usage is 7476M step 3: I keep only every 4th line (two of the three lines I remove are of equal length to the line I keep) data=[data[x] for x in range(0,len(data)) if x%4==1] usage is 8543M step 4:I split this into 20 equal chunks to run through a multiprocessing pool. l=[] for b in range(0,len(data),len(data)/40): l.append(data[b:b+(len(data)/40)]) usage is 8621M step 5: I delete data, usage is 8496M. There are several things that are not making sense to me. In step two, why does the memory usage go up so much when I change the string into an array. I am assuming that the array containers are much larger than the string container? in step three why doesn't the data shrink significantly. I essentially got rid of 3/4 of my arrays and at least 2/3 of the data within the array. I would expect it to shrink accordingly. Calling the garbage collector did not make any difference. oddly enough when I assigned the smaller array to another variable it uses less memory. usage 6605M when I delete the old object data: usage 6059M This seems weird to me. Any help on shrinking my memory foot print would be appreciated. EDIT Okay, this is making my head hurt. Clearly python is doing some weird things behind the scenes here... and only python. I've made following script to demonstrate this using my original method and the method suggested in the answer below. Numbers are all in GB. TEST CODE import os,sys import psutil process = psutil.Process(os.getpid()) import time py_usage=process.memory_info().vms / 1000000000.0 in_file = …
has title: Understanding memory usage in python
accepted answer: http://stackoverflow.com/a/50125550
has comment: http://stackoverflow.com/comment/87267392
answer count: 1
has comment: http://stackoverflow.com/comment/87267584
has answer: http://stackoverflow.com/a/50125550
has comment: http://stackoverflow.com/comment/87267416
has comment: http://stackoverflow.com/comment/87268176
tagged with: memory
has comment: http://stackoverflow.com/comment/87268531
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87268314
has comment: http://stackoverflow.com/comment/87267705
has comment: http://stackoverflow.com/comment/87268758
score: 9
linked to: http://stackoverflow.com/q/14969739

partial-application
type: Tag
tag name: partial-application
tags question: http://stackoverflow.com/q/50143864

http://stackoverflow.com/comment/87179106
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50080353
score: 0
has text: I've added an example of my target dataframe in my question for you. I hope this provides clarity.

http://stackoverflow.com/q/50117960
has body: this is my python code, it list out three problem 'E1123:Unexpected keyword argument 'n_folds' in constructor call, E1123:Unexpected keyword argument 'n' in constructor call, E1133:Non-iterable value k_fold is used in an iterating context' import math import random import sys import warnings from math import sqrt import numpy as np import scipy.spatial import scipy.stats from sklearn.metrics import mean_squared_error from sklearn.model_selection import KFold warnings.simplefilter("error") users = 6040 items = 3952 def readingFile(filename): f = open(filename,"r") data = [] for row in f: r = row.split(',') e = [int(r[0]), int(r[1]), int(r[2])] data.append(e) return data def similarity_user(data): print "Hello User" user_similarity_cosine = np.zeros((users,users)) user_similarity_jaccard = np.zeros((users,users)) user_similarity_pearson = np.zeros((users,users)) for user1 in range(users): print user1 for user2 in range(users): if np.count_nonzero(data[user1]) and np.count_nonzero(data[user2]): user_similarity_cosine[user1][user2] = 1-scipy.spatial.distance.cosine(data[user1],data[user2]) user_similarity_jaccard[user1][user2] = 1-scipy.spatial.distance.jaccard(data[user1],data[user2]) try: if not math.isnan(scipy.stats.pearsonr(data[user1],data[user2])[0]): user_similarity_pearson[user1][user2] = scipy.stats.pearsonr(data[user1],data[user2])[0] else: user_similarity_pearson[user1][user2] = 0 except: user_similarity_pearson[user1][user2] = 0 return user_similarity_cosine, user_similarity_jaccard, user_similarity_pearson def modelSelection(data): k_fold = KFold(n=len(data), n_folds=10) Mat = np.zeros((users,items)) for e in data: Mat[e[0]-1][e[1]-1] = e[2] sim_user_cosine, sim_user_jaccard, sim_user_pearson = similarity_user(Mat) '''sim_user_cosine = np.zeros((users,users)) sim_user_jaccard = np.zeros((users,users)) sim_user_pearson = np.zeros((users,users)) f_sim = open("sim_user_based.txt", "r") for row in f_sim: r = row.strip().split(',') sim_user_cosine[int(r[0])][in…
has comment: http://stackoverflow.com/comment/87253380
score: 0
has comment: http://stackoverflow.com/comment/87253427
answer count: 0
has comment: http://stackoverflow.com/comment/87281305
has title: python list three problems out and gives an error message
upvote count: 1
has comment: http://stackoverflow.com/comment/87281185
has comment: http://stackoverflow.com/comment/87292623
downvote count: 1
has comment: http://stackoverflow.com/comment/87254412
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/4117530
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50190974
score: 1
upvote count: 1
has body: I have next code: import networkx grafoPetersen = { 1: [2,5,6], 2: [3,1,7], 3: [4,2,8], 4: [5,3,9], 5: [1,4,10], 6: [1,8,9], 7:[2,9,10], 8: [3,10,6], 9: [4,6,7], 10: [5,7,8] } for k in grafoPetersen: grafoPetersen[k].append(-1) grafoPetersen[k].append(-2) grafoPetersen[-1] = list(range(1,11)) grafoPetersen[-2] = list(range(1,11)) rutaHamiltoniana = [8, 3, 4, 5, 10, 7, 2, 1, 6, 9]; g = networkx.Graph() for k, vs in grafoPetersen.items(): for v in vs: if v in [-1, -2] or k in [-1, -2]: continue if abs(rutaHamiltoniana.index(k) - rutaHamiltoniana.index(v)) == 1: g.add_edge(k,v, color='red', width=1.5) else: g.add_edge(k,v, color='black', width=0.5) posicion = networkx.circular_layout(g) edges = g.edges() colores = [g[u][v]['color'] for u,v in edges] anchuras = [g[u][v]['width'] for u,v in edges] networkx.draw(g, posicion, edges=edges, edge_color=colores, width=anchuras, with_labels = True) And I get an output like: My graph is a Petersen's graph, and I want show it like: But with same style of I have set in the first pict. I have tryed it like: options = { 'with_labels': True, 'node_color': 'black', 'node_size': 200, 'width': 3, } networkx.draw_shell(g, nlist=[range(5,10), range(5)], **options) as here suggest: How to show a graph like a Petersen's graph but I get several errors. Any idea how can I parse first pict into second pict maintaning first pict styles? EDIT 1: Here is full code how I get a path of Petersen's graph and draw it like first pict: Hamiltonian path inside Petersen's graph algorithm
has answer: http://stackoverflow.com/a/50191920
accepted answer: http://stackoverflow.com/a/50191920
favorite count: 0
tagged with: networkx
type: Question
tagged with: graph
tagged with: python-3.x
has answer: http://stackoverflow.com/a/75009808
possible better answer: http://stackoverflow.com/a/75009808
linked to: http://stackoverflow.com/q/50178527
tagged with: python
type: AnsweredQuestion
answer count: 2
has title: Reorder vertex of a graph. It should be ordered like Petersen graph
downvote count: 0

facebook-graph-api
tags question: http://stackoverflow.com/q/50162757
tag name: facebook-graph-api
tags question: http://stackoverflow.com/q/50159067
tags question: http://stackoverflow.com/q/50200669
tags question: http://stackoverflow.com/q/50175143
tags question: http://stackoverflow.com/q/50101298
tags question: http://stackoverflow.com/q/50108314
type: Tag

http://stackoverflow.com/q/50078977
has title: create new column in data frame based on another data frame
type: Question
duplicate of: http://stackoverflow.com/q/18792918
has comment: http://stackoverflow.com/comment/87174082
has body: I have two dataframes df1: ID col2 col3 type 123 1. 2. T 132 3. 1. N 111 2. 1. U df2 ID A B 123 0. 3. 111 2. 3. 132 1. 2. df2 contains different information about the same ID but in different order I wanted to create a new column in df2 named (type) and match the type column in df1. If it's the same ID to the one in df1, it should copy the same type (T, N or U) from df1. In another word, I need it to look like ID A B type 123 0. 3. T 111 2. 3. U 132 1. 2. N I tried df2['Type'] = df2[df2.ID.isin(df1.ID)]
has comment: http://stackoverflow.com/comment/87174667
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87174531
tagged with: pandas
linked to: http://stackoverflow.com/q/18792918

http://stackoverflow.com/q/50084233
answer count: 0
has body: I am confuse with when building a machine learning chatbot for a close domain topic about car. I have lot of text format information about different car models and do a Word2Vec process with these data and saved a Word2Vec.model. Then question sets and answer set will be converted to vectors by looking up in the word2vec.model. And finally, put them to a seq2seq model for network training. ——- My questions: Should I build two word2vec.model instead of one?, e.g. word2vec_question.model and word2vec_answer.model? and feed to question-set and converts to vector based on word2vec_question.model while answer set according to word2vec_answer.model ? Why there are chatbot examples do not use Word embeddings but just tokenised those question-set and answer-sets and go straight to seq2seq training? Is this because the conversation sets are huge enough to train the S2S network without vectorise? Should we say that if data is hugh enough, just tokenise is enough and no need to do word2vec modelling? Back to my car expert system, please give me some advise what the right way to prepare the data and feed to the Q&amp;A examples. My ultimate wish is that, every week, I feed the word2vec model(s?) with information from car magazines (not in conversation format but just passages about new cars) then, the chatbot can answer questions also about that new model. Thanks in advance.
type: UnansweredQuestion
downvote count: 0
tagged with: training-data
tagged with: word2vec
upvote count: 1
favorite count: 0
type: Question
has title: Should I have two set of word vectors(word2vec), one for questionSet and one for answerSet before neural network training?
score: 1
tagged with: seq2seq
tagged with: python
tagged with: chatbot

http://stackoverflow.com/q/50164737
downvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
tagged with: text-classification
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87366163
has comment: http://stackoverflow.com/comment/87365655
has title: How to add another text feature to current bag of words classification? In Scikit-learn
has answer: http://stackoverflow.com/a/50171034
accepted answer: http://stackoverflow.com/a/50171034
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/87351688
favorite count: 0
type: Question
score: 2
upvote count: 2
has body: this is my input matrix enter image description here my sample Code: from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score X_train, X_test, y_train, y_test = train_test_split(data['Extract'], data['Expense Account code Description'], random_state = 0) from sklearn.pipeline import Pipeline , FeatureUnion text_clf = Pipeline([('vect', CountVectorizer(ngram_range=(1,1))), ('tfidf', TfidfTransformer(use_idf = False)), ('clf', RandomForestClassifier(n_estimators =100, max_features='log2',criterion = 'entropy')), ]) text_clf = text_clf.fit(X_train, y_train) here I am applying Bag of word model for 'Extract' column classifying 'Expense Account code Description' , Here i am getting an accuracy of around 92% , but if i want to include 'Vendor name' as the set of another input feature how can i do that. Is there any way of doing it along with the bag of words ? ,

http://stackoverflow.com/comment/87387124
score: 5
comment on: http://stackoverflow.com/q/50184845
type: Comment
type: QuestionComment
has text: The correct way to solve this problem is to stop trying to read the entire file into memory all at once.

http://stackoverflow.com/comment/87197965
type: QuestionComment
has text: Oh, sorry, I misread your question. You can create a new terminal programmatically with a POST request to `/api/terminals`, or by sending a browser window to `/terminals/{name}` with any unused name. Sending commands to it programmatically might be trickier, and might depend on what it is you want to do.
comment on: http://stackoverflow.com/q/50088835
score: 1
type: Comment

http://stackoverflow.com/q/50178477
has body: I am trying to resize all images in my samples folder and then save all the images back in the test folder. The code below resize the images but it doesn't save them into the destination folder "test". I fail to understand what is the problem and I have referred to all documentation and nothing can help me understand what goes wrong here. import cv2 import glob import os from tqdm import tqdm imgs = glob.glob('samples/*.jpg') print('Images files:', imgs) width = 100 height = 100 folder = 'test' if not os.path.exists(folder): os.makedirs(folder) #Resizing &amp; Saving for img in tqdm(imgs): pic = cv2.imread(img, cv2.IMREAD_UNCHANGED) pic = cv2.resize(pic, (width, height)) cv2.imwrite(os.path.join(folder,img), pic) print(img) The script can read the images and resize them successfully, the only part is imwrite doesn't function as expected.
has comment: http://stackoverflow.com/comment/87378266
has answer: http://stackoverflow.com/a/50178764
answer count: 1
downvote count: 0
upvote count: 1
has title: Python opencv imwrite doesn't save images into destination
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/87398198
has comment: http://stackoverflow.com/comment/87387147
type: UnansweredQuestion
score: 1
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/comment/87356969
comment on: http://stackoverflow.com/a/50169626
score: 0
type: Comment
type: AnswerComment
has text: Sorry Axel ... can you clarify what `data` is? Is this the actual data I want to plot i.e., the mean of Z in my example

http://stackoverflow.com/a/63988765
downvote count: 0
score: 3
upvote count: 3
has body: Is your SPI enabled via sudo raspi-config? I think that is what you are missing. Enable it and reboot your pi, it should get fixed.
type: Answer
has comment: http://stackoverflow.com/comment/119627196
has comment: http://stackoverflow.com/comment/115790996
answers question: http://stackoverflow.com/q/50183951

http://stackoverflow.com/a/50614769
upvote count: 1
score: 1
type: Answer
downvote count: 0
has body: Fer Nando's answer is correct. I made a video about the whole process after getting it figured out on make Mac and Windows 10 if you're interested. Not intended to be a promotional thing, just happen to know of a few people who were trying to pull that together. https://youtu.be/g-aS9oVY-DA
answers question: http://stackoverflow.com/q/50190482

http://stackoverflow.com/q/50125058
tagged with: python
has answer: http://stackoverflow.com/a/50131515
has title: Tensorflow: estimator n_classes issue
score: 0
linked to: http://stackoverflow.com/q/48114258
has body: Getting the error: ValueError: Mismatched label shape. Classifier configured with n_classes=1. Received 4. Suggested Fix: check your n_classes argument to the estimator and/or the shape of your label. import pandas as pd import tensorflow as tf import numpy as np import os dir_path = os.path.dirname(os.path.realpath(__file__)) csv_path = dir_path + "/good.csv" CSV_COLUMN_NAMES = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', 'Quartile'] def load_data(y_name='Quartile'): all = pd.read_csv(csv_path, names=CSV_COLUMN_NAMES, header=0) one_hot = pd.get_dummies(all['Quartile']) all = all.drop('Quartile', axis=1) all = all.join(one_hot) x = all.drop([0, 1, 2, 3], axis=1) y = all[[0, 1, 2, 3]].copy() size = x.shape[0] cutoff = int(0.75*size) train_x = x.head(cutoff) train_y = y.head(cutoff) test_x = x.tail(size-cutoff) test_y = y.tail(size-cutoff) return (train_x, train_y), (test_x, test_y) def train_input_fn(features, labels, batch_size): """An input function for training""" # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) # Return the dataset. return dataset def eval_input_fn(features, labels, batch_size): """An input function for evaluation or prediction""" features=dict(features) if labels is None: # No labels, use only features. inputs = features else: inputs = (features, labels) # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices(inputs) # Batch the examples assert batch_size is not None, "batch_size must not be None" dataset = dataset.batch(batch_size) # Return the dataset. return dataset def main(argv): batch_size = 50; # Fetch the data (train_x, train_y), (test_x, test_y) = load_data() # Feature columns describe how to use the input. my_feature_columns = [] for key in train_x.keys(): my_feature_columns.append(tf.feature_column.numeric_col…
answer count: 1
tagged with: machine-learning
tagged with: tensorflow
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/50204240
tagged with: python
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50204510
type: Question
has answer: http://stackoverflow.com/a/50204510
has title: Django - A link that will update database row before leaving site
has body: I'm quite new to Python development and working on a specific project. I have a list of 'action items' that people can 'claim'. So I created a Model that has all of the information about the action item, including a BooleanField called is_claimed which is defaulted to False. I'm printing out all of the action items in a table, of which the last column is a link to an external site (which is also a URLField in my model). I want to have that last table cell be something like this: Claim and Complete Action Item When someone clicks that URL, I need to update the database to show is_claimed=True. Any ideas or help? Sorry if this question is too simplistic. Learning a lot but need some expert help! Thanks
tagged with: django

http://stackoverflow.com/a/50219173
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50219144
answers question: http://stackoverflow.com/q/50219144
type: Answer
score: 2
has body: By definition, nan compared to anything (using built-in operands) returns False. In particular, np.nan == np.nan returns False. Note, however, that != is defined as the negation of ==, so we get: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.nan == np.nan False &gt;&gt;&gt; np.nan != np.nan True You can check directly using &gt;&gt;&gt; np.isnan(np.nan) True
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/114877834
type: Comment
score: 0
type: AnswerComment
has text: That did it. Why is this still an issue with Flask-Security
comment on: http://stackoverflow.com/a/50112723

http://stackoverflow.com/a/50115629
has body: thank you... this is it need to add the tomcat8 user to sudoers file with no password and execute python script with sudo...
score: 0
answers question: http://stackoverflow.com/q/50113511
type: Answer

http://stackoverflow.com/comment/87389189
comment on: http://stackoverflow.com/q/50186129
type: Comment
score: 0
has text: @UTK007 if one of the answers solves the problem for you, please click the green check-mark to mark it as correct.
type: QuestionComment

http://stackoverflow.com/q/50139016
has answer: http://stackoverflow.com/a/50141805
type: AnsweredQuestion
score: 0
has title: Moving node_modules location under a Python venv
answer count: 1
linked to: http://stackoverflow.com/q/18974436
tagged with: virtual-environment
has body: I have a Python venv to develop a Django application and I use babel to transpile my javascript. Currently, I install node.js with nodeenv -p whilst working under my Python venv. Everything works fine if I have the node_modules and package.json folder at the root of my project, but it is messing up the project folder structure. I would rather have node_modules under venv: project_folder | |- venv |- node_modules package.json or even: project_folder | |- venv |- node |- node_modules package.json If I put my package.json in venv and execute npm install from there, npx babel only works if I am in venv, not a the root of the project. Running npx babel from the project's root directory gives me: npx: installed 1 in 0.655s You have mistakenly installed the `babel` package, which is a no-op in Babel 6. Babel's CLI commands have been moved from the `babel` package to the `babel-cli` package. npm uninstall -g babel npm install --save-dev babel-cli See http://babeljs.io/docs/usage/cli/ for setup instructions. How can I have node_modules under the venv folder and be able to use npx babel from anywhere in the project folder? This question is related but I can't see how to adapt the answer to nodeenv.
type: Question
tagged with: python
tagged with: node.js
accepted answer: http://stackoverflow.com/a/50141805

http://stackoverflow.com/a/50109314
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50109289
has comment: http://stackoverflow.com/comment/87236135
score: 2
answers question: http://stackoverflow.com/q/50109289
has comment: http://stackoverflow.com/comment/87236038
has body: You can ignore the keys of the dictionary and instead, use a double max: x = {'a': [[1], [1, 2, 3], [1], [1]], 'c': [[1], [1, 2], [1], [1]], 'b': [[1], [1, 2], [1], [1]]} result = max(max(map(len, i)) for i in x.values()) Output: 3
upvote count: 2

http://stackoverflow.com/comment/87260041
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50120955
score: 0
has text: It is possible that you need to remove the space where I've added a hash symbol. Depending on the editor, I've seen the placing of a space between the method name and the bracket "break" it. ***line.startswith#(v)*** I note that you have no space when using the enumerate(data) call or the find_ends(data, v) calls... this might just be the cause

http://stackoverflow.com/comment/87346086
comment on: http://stackoverflow.com/q/50163992
type: QuestionComment
score: 0
has text: "I suppose I could always check the value after the return" Check the value of what? You don't seem to be assigning any globals, mutating any values, or returning anything from any part of this.
type: Comment

http://stackoverflow.com/comment/94342870
comment on: http://stackoverflow.com/a/50104017
type: Comment
has text: Eventually you can fire directly `to_parquet()`/`to_csv()` instead of `.compute()`
score: 0
type: AnswerComment

http://stackoverflow.com/q/50170171
type: UnansweredQuestion
has title: can I stop tensorflow training and still safely close tfrecords file from summary writer?
tagged with: tensorflow
score: 2
downvote count: 0
tagged with: python
favorite count: 0
type: Question
upvote count: 2
has body: I set a large epoch number and I want to stop it early. Simply killing the python process seems not to work (I tried on one training process). This is what I get when I try to read the summary file using tools like summary_iterator during training or after killed: Traceback (most recent call last): File "tensorboard_reader.py", line 47, in &lt;module&gt; train_loss = reader(train_file[0], ['cost', 'likelihood_loss', 'focal_loss']) File "tensorboard_reader.py", line 13, in reader for e in tf.train.summary_iterator(filename): File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/summary/summary_iterator.py", line 353, in summary_iterator for r in tf_record.tf_record_iterator(path): File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/lib/io/tf_record.py", line 77, in tf_record_iterator reader.GetNext(status) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.DataLossError: truncated record at 27159094
answer count: 0

http://stackoverflow.com/comment/87454997
score: 0
has text: @dawg Sorry, I don't know what you mean with input tuple or desired output.
type: QuestionComment
comment on: http://stackoverflow.com/q/50218054
type: Comment

http://stackoverflow.com/q/50100996
type: Question
upvote count: 2
tagged with: python
type: UnansweredQuestion
tagged with: timestamp
tagged with: recursion
tagged with: pandas
score: 2
answer count: 0
downvote count: 0
has body: I am playing with an algorithm to optimally insert three vacation periods of a total of 30 days into a year calendar. Sometimes it Works (I have not iterated for optimal yet) and sometimes I get an error: ValueError: cannot set a Timestamp with a non-timestamp I cannot understand why it Works occasionally, but at other times it doesn't. Full code is below. Just copy and run. ''' Program to find three periods of vacation of varying length that does not start in a weekend or holiday''' from datetime import date from random import randint, choice import pandas as pd from pandas.tseries.holiday import Holiday, AbstractHolidayCalendar class Brazil(AbstractHolidayCalendar): # Brazilian official holidays for 2018 rules = [Holiday('Universal', year=2018, month=1, day=1), Holiday('Carnaval', year=2018, month=2, day=12), Holiday('Carnaval', year=2018, month=2, day=13), Holiday('Carnaval', year=2018, month=2, day=14), Holiday('Paixão', year=2018, month=3, day=30), Holiday('Tiradentes', year=2018, month=4, day=21), Holiday('Trabalho', year=2018, month=5, day=1), Holiday('Christi', year=2018, month=5, day=31), Holiday('Independência', year=2018, month=9, day=7), Holiday('Aparecida', year=2018, month=10, day=12), Holiday('Servidor', year=2018, month=10, day=28), Holiday('Finados', year=2018, month=11, day=2), Holiday('República', year=2018, month=11, day=15), Holiday('Natal', year=2018, month=12, day=25)] class Working: # Initiates a calendar for 2018 as a pandas DataFrame. Includes holidays and weekends as 'not_working' = True def __init__(self, start, end): self.cal = Brazil() self.df = pd.DataFrame() self.df['date'] = pd.date_range(start=start, end=end) self.holidays = self.cal.holidays(start=start, end=end) self.df['not_working'] = self.df.date.apply(lambda x: x.dayofweek == 5 or x.dayofweek == 6 or x in self.holidays) def total_working_days(self): # Calculates total working days print('Total working days this configuration is {} days'.format(sum(self.df['not_working'] == Fal…
tagged with: calendar
has comment: http://stackoverflow.com/comment/87220673
favorite count: 0
has title: Optimal vacation searching with recursion or Timestamp error

http://stackoverflow.com/comment/87457845
type: Comment
type: QuestionComment
score: 0
has text: maybe you can solve this by concatenating all the letters, separating them when a space or special chars appear
comment on: http://stackoverflow.com/q/50219672

http://stackoverflow.com/a/50165455
upvote count: 2
has body: You can delete those files by using glob like (untested): for dir_name, numbers in (('primary', pri), ('secondary', snd)): for number in numbers: for filename in glob.glob('/{}/proc_{}_for_*.log'.format(dir_name, number)): os.unlink(filename)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87348949
has comment: http://stackoverflow.com/comment/87349012
has comment: http://stackoverflow.com/comment/87349111
answers question: http://stackoverflow.com/q/50165162
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/87349086
accepted answer of: http://stackoverflow.com/q/50165162
has comment: http://stackoverflow.com/comment/87349121

http://stackoverflow.com/comment/87252877
has text: Save `(int(raw_input('Choose an item to mark pending and hit enter. ')))` by making it something like `my_index = (int(raw_input('Choose an item to mark pending and hit enter. ')))` then instead of `mylist[0]` use `mylist[my_index]`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50117765
score: 0

http://stackoverflow.com/a/56821380
accepted answer of: http://stackoverflow.com/q/50091004
score: 1
type: AcceptedAnswer
downvote count: 0
has body: I was able to do this by subclassing SelectDateWidget and overriding get_context. class MySelectDateWidget(SelectDateWidget): def get_context(self, name, value, attrs): old_state = self.is_required self.is_required = False context = super(MySelectDateWidget, self).get_context(name, value, attrs) self.is_required = old_state return context This answer is similar to GwynBleidD's from the thread here: Display empty_label on required selectDateWidget on Django, but updated to work with more recent versions of Django.
upvote count: 1
answers question: http://stackoverflow.com/q/50091004
type: Answer

http://stackoverflow.com/comment/87236642
score: 0
type: Comment
type: QuestionComment
has text: Have you checked that the `dtypes` match?
comment on: http://stackoverflow.com/q/50108650

http://stackoverflow.com/comment/87258509
comment on: http://stackoverflow.com/a/50117390
has text: Let me try and make sure I’m accessing the console the same way you are...
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87336313
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50158046
has text: Thank you for your response! The solution you proposed is the one i am currently using. However, it requires me to copy all variables names i used by hand which i would like to avoid.
type: Comment

pivot
tags question: http://stackoverflow.com/q/50194488
tags question: http://stackoverflow.com/q/50136563
tags question: http://stackoverflow.com/q/50138622
tag name: pivot
type: Tag

hidden-markov-models
tags question: http://stackoverflow.com/q/50150694
tag name: hidden-markov-models
type: Tag

http://stackoverflow.com/q/50185446
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87388766
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87388120
tagged with: convex-hull
has comment: http://stackoverflow.com/comment/87388446
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50810223
tagged with: qhull
tagged with: python
has body: Update: I've decided to try to use a linear programming package in order to determine if the vertices of the two polytopes are linearly separable. (The vertices are really my data, not the polytopes.) I think this will work better, so I no longer need an answer to this question. I'm writing some code that involves checking if certain polytopes are disjoint. These polytopes are defined by the convex hulls of their vertices, and I'm creating the convex hulls using Qhull. In particular, I'm using the method: from scipy.spatial import ConvexHull This works fine, except that sometimes my sets have only 2 or 1 points in them. Qhull doesn't like this, and it spits out this error: QhullError: QH6214 qhull input error: not enough points(1) to construct initial simplex (need 3) While executing: | qhull i Qt Options selected for Qhull 2015.2.r 2016/01/18: run-id 109084531 incidence Qtriangulate _pre-merge _zero-centrum While I can deal with this by writing some subroutines that catch the situation that there are less than 3 points, it's frustrating that Qhull doesn't deal with this case. So I'm looking for: 1) A simple way to make Qhull deal with this correctly or 2) An alternative package to use Thank you!
has title: Qhull Convex hull wants me to input at least 3 points
has comment: http://stackoverflow.com/comment/87388468
type: Question

http://stackoverflow.com/q/50138291
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50138392
favorite count: 0
type: Question
upvote count: 2
has body: Is it possible to save a matplotlib figure after it has been created? For instance: import matplotlib.pyplot as plt import numpy normal = numpy.random.normal(0, 1, 100) df = pandas.DataFrame(normal.reshape((10, 10))) figs = [] for i in df.keys(): fig = plt.figure() plt.plot(df.index, df[i]) figs.append(fig) print(figs) produces the figures in a list: [&lt;matplotlib.figure.Figure object at 0x7f8f158f1b00&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f100d6128&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f10081da0&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f0a0354a8&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f09fbd470&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f09f18b00&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f09f12d68&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f09e88860&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f09ebbc18&gt;, &lt;matplotlib.figure.Figure object at 0x7f8f09d6e198&gt;] I would like to not have to explicitly save the plot directly after creation but have the option to do it later (maybe from within another class). The ideal would be to pass the fig to plt.savefig, but there doesn't seem to be a slot available for this type of usage. To clarify. I would like to do: fname = r'/path/to/file.jpg' plt.savefig(fname, fig=figs[2]) Is this possible in another way?
tagged with: python
accepted answer: http://stackoverflow.com/a/50138392
score: 2
type: AnsweredQuestion
tagged with: matplotlib
has title: How to save a matplotlib figure from a list of matplotlib.figure.Figure's?

http://stackoverflow.com/a/50147963
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/50147760
has comment: http://stackoverflow.com/comment/87314307
has comment: http://stackoverflow.com/comment/87314630
has comment: http://stackoverflow.com/comment/87315201
type: Answer
has comment: http://stackoverflow.com/comment/87314228
upvote count: 6
has comment: http://stackoverflow.com/comment/87314387
has body: return is a statement. List comprehensions cannot contain statements, only expressions. In fact, that's true for all expressions in Python: they can only contain other expressions. So, no, you can't put a return inside a list comprehension. If you really need to mutate foo in-place, what you're trying to do is much better written as a for statement (which, being a compound statement, can of course contain other statements): for i in bar: foo.remove(i) return ''.join(foo) While comprehensions are faster than for statements for building a list, that's mainly because they can use a specially-optimized version of list.append. If you don't actually want the resulting list, they're slower, because even a really fast list.append is still a lot slower than not building a list at all. And, more importantly, using comprehensions just for side effects isn't just inefficient, it makes your code less idiomatic, and harder to understand. Anyway, if you really need to optimize this code, you probably shouldn't be mutating foo in-place. Every time you call foo.remove(i), that takes linear work to find the first occurrence of i and then shift the whole rest of the list up. So, if bar is roughly the same size as foo, this takes quadratic work. But you can just copy the list, filtering as you go, in linear time: barset = set(bar) return ''.join([x for x in foo if x not in barset]) (I'm assuming here you don't have any duplicate values in foo and bar—if you do, I'd be willing to bet remove wasn't actually doing what you want. But, if so, you do need something a bit more complicated here.)
has comment: http://stackoverflow.com/comment/87314341

http://stackoverflow.com/q/50224489
tagged with: multiprocess
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/50384179
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87466560
tagged with: chainer
answer count: 1
has comment: http://stackoverflow.com/comment/87466677
downvote count: 1
has title: MultiprocessIterator doesn't work
favorite count: 0
tagged with: parallel-processing
has body: I am using MultiprocessIterator from chainer to train an NN. The code is here. The results are: nproc = 1, 307.65s nproc = 4, 318.85s nproc = 8, 302.91s nproc = 16, 318.18s System info: Ubuntu 14.04.5 LTS (GNU/Linux 4.4.0-104-generic x86_64) CPU(s): 16 Model name: Intel(R) Xeon(R) CPU E5-2695 v4 @ 2.10GHz VGA compatible controller: Cirrus Logic GD 5446 It seems MultiprocessIterator doesn't work. Anyone has a clue? Thank you in advance.
score: -1

http://stackoverflow.com/q/50087845
linked to: http://stackoverflow.com/q/1373164
has title: Python classes: how to handle "future" instances
tagged with: python
has comment: http://stackoverflow.com/comment/87193490
accepted answer: http://stackoverflow.com/a/50088093
has comment: http://stackoverflow.com/comment/87191608
has comment: http://stackoverflow.com/comment/87193457
has comment: http://stackoverflow.com/comment/87191673
tagged with: class
has answer: http://stackoverflow.com/a/50088093
type: AnsweredQuestion
tagged with: oop
tagged with: instance
answer count: 2
upvote count: 3
score: 3
downvote count: 0
has body: I'm teaching myself Python (2.7, no previous coding experience) and I've just started dealing with classes and OOP concepts. As an exercise, I'm trying to code a very simple address book. I think I managed to understand the basics of classes and instances, but what I'm finding hard to grasp is how to further develop the level of abstraction at this point. Trying to explain better, say I have this, which is often the base example many tutorials use to introduce classes: class Contact(object): def __init__(self, name, surname, phone): self.name = name self.surname = surname self.phone = phone contact1 = Contact('Mark', 'Doe', '123456789') contact2 = Contact('Sally', 'Preston', '456789123') So far so good, I can do many other interesting things using contact1.attribute or other methods. No problem here. What I'm having trouble understanding is the following: Question 1: I don't know how many contacts I will have. How do I make a method, say, create_contact(), that makes me create a new contact and store it in a list/dict, if I don't know how many I will have? How do I call it? I can't understand how to make it so that I can create a new instance without hardcoding its name, like "contact1" etc. How do I make the line with "contact1" and "contact2" a dynamic thing? I tried solving the problem using a list as a class variable. Something like (assuming "contact_list" already exists as a class variable): Contact.contact_list.append(Contact('Mark', 'Doe','123456789')) # obviously I'd use raw_input instead of 'Mark' etc, but I avoided it here for readability But I end up with a list of nameless objects, and my brain has a hard time dealing with it. I can access them with list indexes, but I'm not sure I'm on the right track here... any help would be most appreciated. Question 2: (somewhat related, to better understand the issue) if in the python CLI I put something like (assuming the previous block defining the class has already been run): &gt;&gt;&gt; Contact('Bob', 'Steven…
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50088051
has comment: http://stackoverflow.com/comment/87193135
has answer: http://stackoverflow.com/a/50088051

http://stackoverflow.com/q/50106975
has comment: http://stackoverflow.com/comment/87232940
has body: I need a help in my code, I am not able to do the binary file manipulation. code for creating the binary file: import struct numeros = [-9 ,20.5, 6, 10.8, 10, 8.0, 45, -99.6 ,12, -54.7]; try: with open('value.bin', "wb") as arq: arq.write(struct.pack("i", 5)) for num in numeros: if isinstance(num, int): arq.write(struct.pack("i", num)) elif isinstance(num, float): arq.write(struct.pack("f", num)) except IOError: print("Error opening or handling file.") code for file manipulation: try: with open('value.bin', 'r+b') as arq: n = struct.unpack('=i', arq.read(4))[0] for i in range(n): j = i numInt= struct.unpack('=i', arq.read(4)) numFloat = struct.unpack('=f', arq.read(4)) arq.seek(4) if numInt[0] &lt;10: arq.write(struct.pack("i", -1)) elif numFloat[0] &gt;9.0: arq.write(struct.pack("f", 9999.0)) except IOError: print('Error opening or handling file.') correct output: 5 -1 9999.0 -1 9999.0 10 8.0 45 -99.6 12 -54.7 Exit from my code: 5 -9 20.5 6 10.80000019073486310 8.0 45 -99.599998474121112 -54.70000076293945 the numbers -9, 20.5, 6, 10.8 are not being changed. I need this help.
has answer: http://stackoverflow.com/a/50108545
answer count: 1
has title: binary file manipulation in python
has comment: http://stackoverflow.com/comment/87231834
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87231785
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50108545
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87232874
has comment: http://stackoverflow.com/comment/87231526
has comment: http://stackoverflow.com/comment/87232652
has comment: http://stackoverflow.com/comment/87231758
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50160098
tagged with: pyside2
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
has title: PySide2 with qml as ui
type: Question
tagged with: qt
has body: I am using pyqt5 and pyside2 to play around with qtquick2 controls, even though pySide2 claims they pyQt syntax and logic, its not always true, and pySide2 documentation is either seriously outdated or its simply inaccurate. (i do realise pySide2 is not ready for proper use, but i would still try to get hang of it) For example slot usage i do get pyQt5 @pyqtSlot() def sayHi(self): print("Hi") pySide2 @Slot() def sayHi(self): print("Hi") Then just from myQml i call that function and it works. However i need alternatives for : @pyqtProperty(float, notify=currentValueChanged) @currentValue.setter variableX =pyqtSignal() And last an actual code : import sys import os from PyQt5.QtCore import QObject, QUrl, Qt, pyqtSlot, pyqtSignal, pyqtProperty from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import QQmlApplicationEngine class Manager(QObject): #slider Value currentValueChanged = pyqtSignal() def __init__(self): QObject.__init__(self) self.m_currentValue =0 #slider self.currentValueChanged.connect(self.on_currentValueChanged) #slide stuff @pyqtProperty(float, notify=currentValueChanged) def currentValue(self): return self.m_currentValue #slider @currentValue.setter def currentValue(self, val): if self.m_currentValue == val: return self.m_currentValue = val self.currentValueChanged.emit() #slider VOlUME CHANGED &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; WORKS&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; @pyqtSlot() def on_currentValueChanged(self): print(self.m_currentValue) if __name__ == "__main__": os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material" app = QApplication(sys.argv) engine = QQmlApplicationEngine() manager = Manager() ctx = engine.rootContext() ctx.setContextProperty("Manager", manager) engine.load('main.qml') if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_()) QML import QtQuick 2.10 import QtQuick.Controls 2.1 import QtQuick.Window 2.2…
tagged with: qml
tagged with: python
tagged with: qtquick2
has comment: http://stackoverflow.com/comment/97417392
accepted answer: http://stackoverflow.com/a/50160899
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50160899
score: 1

http://stackoverflow.com/comment/87375469
has text: @Pad You are right. Although, there is a work around of it. I tried your problem with more than 420 rows. This gives me a repeating index. try this. Let me know if it works. Get a list of objects that you would like to repeat. `daterange = pd.date_range('1981/1/1', periods=420, freq='MS')` Then expand it to fit your dataframe by repeating it. `df2.index = list(daterange) * math.floor(len(df2)/len(list(daterange))) + list(daterange)[0:math.floor(len(df2)%len(list(daterange)))] `
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50177286
type: AnswerComment

http://stackoverflow.com/q/50167582
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: threadpool
has title: How can I schedule a task with asyncio to run in executor?
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/50169023
downvote count: 0
favorite count: 0
has body: I have been using asyncio for concurrency, however I have run into a problem. I have the need to schedule a task with asyncio but it is blocking and so I would like to execute it in an executor using threadpool from concurrent.futures. I have seen example like this, that schedule tasks: now = loop.time() loop.call_at(now + 60, callback, arg, loop) and like this that run tasks in executors: blocking_tasks = [ loop.run_in_executor(executor, blocks) for i in range(6) ] completed, pending = await asyncio.wait(blocking_tasks) But how can I schedule a blocking task to run in executor?
has answer: http://stackoverflow.com/a/59508902
type: Question
upvote count: 5
score: 5

http://stackoverflow.com/a/50122411
accepted answer of: http://stackoverflow.com/q/50122358
type: Answer
has body: def evenly(walk,steps): Here parameter walk (instead of walks) masks outer variable with the same name, and is defined for subsequent statement walk[s+1] = walk[s] + stepn(). I guess it should be walks
answers question: http://stackoverflow.com/q/50122358
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/50189331
tagged with: python
tagged with: image-processing
type: UnansweredQuestion
has title: Line removal in image captcha using Python
upvote count: 6
tagged with: numpy
linked to: http://stackoverflow.com/q/42736616
downvote count: 0
answer count: 1
score: 6
favorite count: 0
tagged with: opencv
has answer: http://stackoverflow.com/a/50189786
has body: I had used this link - How to remove line from captcha completely and edited the code provided to remove lines from a dummy captcha that I have given below lineRemoval.py from PIL import Image,ImageFilter from scipy.misc import toimage from operator import itemgetter from skimage import measure import numpy as np import heapq import cv2 import matplotlib.pyplot as plt from scipy.ndimage.filters import median_filter #---------------------------------------------------------------- class preprocessing: def pre_proc_image(self,img): img_removed_noise=self.apply_median_filter(img) #img_removed_noise=self.remove_noise(img) p1,p2,LL=self.get_line_position(img_removed_noise) img=self.remove_line(p1,p2,LL,img_removed_noise) img=median_filter(np.asarray(img),1) return img def remove_noise(self,img): img_gray=img.convert('L') w,h=img_gray.size max_color=np.asarray(img_gray).max() pix_access_img=img_gray.load() row_img=list(map(lambda x:255 if x in range(max_color-15,max_color+1) else 0,np.asarray(img_gray.getdata()))) img=np.reshape(row_img,[h,w]) return img def apply_median_filter(self,img): img_gray=img.convert('L') img_gray=cv2.medianBlur(np.asarray(img_gray),3) img_bw=(img_gray&gt;np.mean(img_gray))*255 return img_bw def eliminate_zeros(self,vector): return [(dex,v) for (dex,v) in enumerate(vector) if v!=0 ] def get_line_position(self,img): sumx=img.sum(axis=0) list_without_zeros=self.eliminate_zeros(sumx) min1,min2=heapq.nsmallest(2,list_without_zeros,key=itemgetter(1)) l=[dex for [dex,val] in enumerate(sumx) if val==min1[1] or val==min2[1]] mindex=[l[0],l[len(l)-1]] cols=img[:,mindex[:]] col1=cols[:,0] col2=cols[:,1] col1_without_0=self.eliminate_zeros(col1) col2_without_0=self.eliminate_zeros(col2) line_length=len(col1_without_0) dex1=col1_without_0[round(len(col1_without_0)/2)][0] dex2=col2_without_0[round(len(col2_without_0)/2)][0] p1=[dex1,mindex[0]] p2=[dex2,mindex[1]] return p1,p2,line_length def remove_line(self,p1,p2,LL,img): m=(p2[0]-p1[0])/(p2[1]-p1[1]) if p2[…
type: Question

http://stackoverflow.com/comment/87399599
comment on: http://stackoverflow.com/a/50190837
type: Comment
type: AnswerComment
score: 0
has text: Yes just tested it and can see that players isnt updated when adding new players to 'd' - but what if just skip using "players" and instead build it all up in 'd' ? am not pro enough yet to quite spot what kinda of difference there is between players and 'd' - im loading players from the fly so will try here to see if i can make it work buidling it all up with 'd' - aka initializing 'players' with nothing ( if its possible ).

http://stackoverflow.com/comment/87433581
score: 0
type: Comment
type: AnswerComment
has text: This is much more easier to understand ! Thanks @wwii
comment on: http://stackoverflow.com/a/50206846

http://stackoverflow.com/a/50086706
score: 4
has comment: http://stackoverflow.com/comment/87194517
answers question: http://stackoverflow.com/q/50086656
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50086656
upvote count: 4
has comment: http://stackoverflow.com/comment/87189270
downvote count: 0
type: Answer
has body: What you see is the raw representation of the object which is returned by __repr__ method of the respective object. It's what is called when you type an object in Python's interactive shell. When you're in a file you need to print the result using print function that triggers the __str__ method. state=True print(type(state))

http://stackoverflow.com/a/50149772
answers question: http://stackoverflow.com/q/50145101
has comment: http://stackoverflow.com/comment/87342729
has body: You can use the method that gives you the direct URL: download_url = client.file(file_id='SOME_FILE_ID').get_shared_link_download_url() And then you can use urlib to download it to your local computer: import urllib urllib.urlretrieve (download_url , your_local_file_name) Could it solve your problem?
downvote count: 0
has comment: http://stackoverflow.com/comment/90655439
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/87339931
type: QuestionComment
comment on: http://stackoverflow.com/q/50160981
has text: What version of OpenCV on which platform? Can you create a [mcve] that reproduces it?
score: 2
type: Comment

http://stackoverflow.com/q/50184243
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/50184284
score: 4
accepted answer: http://stackoverflow.com/a/50184284
possible better answer: http://stackoverflow.com/a/50184260
has comment: http://stackoverflow.com/comment/87400703
type: Question
tagged with: int
tagged with: char
answer count: 3
downvote count: 0
tagged with: join
has answer: http://stackoverflow.com/a/50184388
favorite count: 0
has answer: http://stackoverflow.com/a/50184260
type: AnsweredQuestion
has body: Is there a better way of the following for concatenating items in a list that are "integers" into a string: import numpy as np my_list = [1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] changed_list = np.char.mod('%d', my_list) final_ans = ''.join(changed_list )
has title: python: concatenate integer items in a list to a single string

http://stackoverflow.com/comment/87462251
comment on: http://stackoverflow.com/q/50222286
has text: I edited my post, maybe you can help with that? thanks
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87298198
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50139363
type: Comment
has text: Thank you. I couldnt quite catch this sentence `If your task is really massive, use a compiled programming language for fast mass number crunching.`

http://stackoverflow.com/q/50204473
has answer: http://stackoverflow.com/a/50224280
upvote count: 2
has body: I'm running tests on a django App called stats which uses a Postgre database. The project keeps all tests in a folder ./stats/tests/. When I run a test i.e. python manage.py test stats.tests.test_dataGeneration, several minutes of nothing pass where the text cursor in my command line just blinks. At this early stage I cannot even use a keyboard interrupt to instantly stop the test (keyboard interrupt takes at least 30 seconds to register). Eventually, after several minutes I see the Creating test database for alias 'default' ('test_statsdb')... message which creates the database for testing. From this point the tests always complete in less than 10 seconds (as in django outputs Ran XX tests in 5.00s). I don't know or understand why the tests take so long to start, or what is exactly being executed in the first few minutes. A few days ago I had no issues testing the app. Using --keepdb to recycle the test database between test runs does not noticeably improve the time that running tests takes. I was hoping someone could shed some light on what is happeneing. Example output of test results when i run them with verbosity=2 for extra details: &gt;python manage.py test stats.tests.test_dataGeneration --verbosity=2 Creating test database for alias 'default' ('test_statsdb')... Operations to perform: Synchronize unmigrated apps: messages, portfolio_web, staticfiles, updateDatabase Apply all migrations: auth, contenttypes, sessions, stats Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_m…
tagged with: django
tagged with: python
tagged with: django-testing
accepted answer: http://stackoverflow.com/a/50224280
type: AnsweredQuestion
score: 2
tagged with: postgresql
has title: Django tests taking a long time to start
answer count: 1
downvote count: 0
favorite count: 0
type: Question

algorithm
tags question: http://stackoverflow.com/q/50082861
tags question: http://stackoverflow.com/q/50189804
tags question: http://stackoverflow.com/q/50162964
tags question: http://stackoverflow.com/q/50086395
type: Tag
tag name: algorithm
tags question: http://stackoverflow.com/q/50077308
tags question: http://stackoverflow.com/q/50174228
tags question: http://stackoverflow.com/q/50083839
tags question: http://stackoverflow.com/q/50090099
tags question: http://stackoverflow.com/q/50207041
tags question: http://stackoverflow.com/q/50150148
tags question: http://stackoverflow.com/q/50202870
tags question: http://stackoverflow.com/q/50192878
tags question: http://stackoverflow.com/q/50080414
tags question: http://stackoverflow.com/q/50180035
tags question: http://stackoverflow.com/q/50204252
tags question: http://stackoverflow.com/q/50139050
tags question: http://stackoverflow.com/q/50126232
tags question: http://stackoverflow.com/q/50122983
tags question: http://stackoverflow.com/q/50091594
tags question: http://stackoverflow.com/q/50087301
tags question: http://stackoverflow.com/q/50164917
tags question: http://stackoverflow.com/q/50109370
tags question: http://stackoverflow.com/q/50175706
tags question: http://stackoverflow.com/q/50169854
tags question: http://stackoverflow.com/q/50119976
tags question: http://stackoverflow.com/q/50136954
tags question: http://stackoverflow.com/q/50167737
tags question: http://stackoverflow.com/q/50148107
tags question: http://stackoverflow.com/q/50190508
tags question: http://stackoverflow.com/q/50125658
tags question: http://stackoverflow.com/q/50088789
tags question: http://stackoverflow.com/q/50224772

http://stackoverflow.com/q/50144817
score: 0
type: UnansweredQuestion
tagged with: error-handling
has body: I'm new to python and I was trying to create an error handling for multiple users input. I made the code as the following. ` #load and filter dataset import pandas as pd CITY_DATA = {'Chicago' : 'chicago.csv', 'New York City':'new_york_city.csv', 'Washington':'washington.csv'} #filtering dataset def get_filters (): city_options = ['Chicago','New York City','Washington'.title()] month_options = ['January','February','March','April','May','June','July','August','September','November','December','all'.title()] day_options = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','all'] while True: city = input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'.title()) if city in city_options : break else: print('Your choice is not available. Please try again') while True: month = input('\nInsert month to filter by or "all" to apply no month filter! (January, February, etc.)\n'.title()) if month in month_options : break else: print('Your choice is not available. Please try again') while True: day = input('\nInsert day of the week to filter by or "all" to apply no day filter! (Monday, Tuesday, etc.)\n'.title()) if day in day_options : break else: print('Your choice is not available. Please try again') return city, month, day But I believe there is a simpler way for this or maybe create a function? Any help would be greatly appreciated!
type: Question
has comment: http://stackoverflow.com/comment/87307968
tagged with: python
has title: Python - How to create for multiple user input error handling?
has answer: http://stackoverflow.com/a/50144973
tagged with: user-input
has answer: http://stackoverflow.com/a/50145894
answer count: 2

http://stackoverflow.com/comment/87427356
type: Comment
score: 0
has text: See also this related question about the strange down-versioning of pip inside the environment (https://stackoverflow.com/questions/50194070/a-python-virtual-environment-ends-up-with-an-older-version-of-pip-than-the-one-t/50201418#50201418)
type: AnswerComment
comment on: http://stackoverflow.com/a/50183534

http://stackoverflow.com/a/50134201
has body: bad indent for t[i][j].append(p)? Althought it's hard to understand what you want to achieve, but below results looks very similar to your expect. for i in range(3): for j in range(len(a[i])): for k in range(len(a[i][j])-1): p = k*(a[i][j][k+1]-a[i][j][k]) #print(p) t[i][j].append(p) print(t) prints: [[[0, 1, 2, 3]], [[0, 1], [0]], [[0], [0], []]]
answers question: http://stackoverflow.com/q/50133982
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50133982
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87286602
type: Answer
has comment: http://stackoverflow.com/comment/87286834

http://stackoverflow.com/q/50125386
has comment: http://stackoverflow.com/comment/87268853
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50125594
score: 3
has comment: http://stackoverflow.com/comment/87268875
tagged with: pandas
has title: Python: how can I get the smoother-starting-point in graph?
linked to: http://stackoverflow.com/q/47068504
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87269031
has body: What I want to get is the point, (x, y), where the y value getting smoother for given x and y values. For example, x = range(10) y = [0.3, 0.37, 0.41, 0.52, 0.64, 0.68, 0.71, 0.72, 0.73, 0.74] plt.plot(x, y) I want to get the red-circle point (or near point) where the graph starts getting stable. How can I do this?
upvote count: 4
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50125594
answer count: 1

scintilla
type: Tag
tags question: http://stackoverflow.com/q/50177976
tag name: scintilla

http://stackoverflow.com/a/50307672
answers question: http://stackoverflow.com/q/50200917
accepted answer of: http://stackoverflow.com/q/50200917
type: Answer
score: 0
has body: This Python implementation works well for both 'small' and 'large' input files: def free_by_shuffling(self, die): assert die.current_value is not None stack = [die] found = False while stack: this_die = stack.pop() if found: if stack: this_die.current_value = stack[-1].current_value stack[-1].current_value = None continue for other_die in this_die.current_value.dice: if other_die.current_value is None: stack.extend((this_die, other_die)) found = True break else: self.visited.add(this_die) for other_die in this_die.current_value.dice: if other_die not in self.visited: stack.extend((this_die, other_die)) break else: if stack: for other_die in stack[-1].current_value.dice: if other_die not in self.visited: stack.append(other_die) break return found Any comments and suggestions are welcome.
type: AcceptedAnswer

http://stackoverflow.com/q/50202741
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87422825
upvote count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/50216546
favorite count: 0
has body: What i am trying to achieve: Parallelize a function that spawn a number of threads per call, like this: - PROCESS01 -&gt; 16 Threads - PROCESS02 -&gt; 16 Threads - ... - PROCESSn -&gt; 16 Threads The code: with multiprocessing.Pool(4) as process_pool: results = process_pool.map(do_stuff, [drain_queue()]) Where drain_queue() return a list of items and do_stuff(item_list): print('&gt; PID: ' + str(os.getpid())) with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: result_dict = {executor.submit(thread_function, item): item for item in item_list} for future in concurrent.futures.as_completed(result_dict): pass And thread_function() process every item passed to it. However, when executed the code outputs like this: &gt; PID: 1000 (WAITS UNTIL THE PROCESS FINISHES, THEN START NEXT) &gt; PID: 2000 (WAITS UNTIL THE PROCESS FINISHES, THEN START NEXT) &gt; PID: 3000 (WAITS UNTIL THE PROCESS FINISHES, THEN START NEXT) &gt; PID: 3000 (WAITS UNTIL THE PROCESS FINISHES, THEN START NEXT) Here is a screenshot of Task Manager What am i missing here? I can't figure it out why does not work as expected. Thanks!
type: Question
tagged with: python-multiprocessing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87423884
answer count: 1
downvote count: 0
has title: multiprocessing.Pool.map does not work in parallel
has comment: http://stackoverflow.com/comment/87423743
has answer: http://stackoverflow.com/a/50216546

http://stackoverflow.com/q/50141770
has body: def individualstudent(): count=1 for i in range (1,3): sname=input('Enter name for student '+str(count) +' : ') sID=int(input('Enter ID for student '+str(count)+' : ')) smark=int(input('Enter mark for student '+str(count)+' : ')) studno=('student'+str(count)) studno={'name':sname,'ID':sID,'mark':smark} totaldict[count]=studno count+=1 print(totaldict) individualstudent() I'm trying to create a dictionary containing 200 dictionaries. However, when I try to print the momma dictionary only the most recent one will print.
downvote count: 0
tagged with: nested
has comment: http://stackoverflow.com/comment/87301976
upvote count: 1
score: 1
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87301971
has title: Nesting multiple dictionaries made from user input
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87301883
has comment: http://stackoverflow.com/comment/87302172
accepted answer: http://stackoverflow.com/a/50141800
has answer: http://stackoverflow.com/a/50141800
type: AnsweredQuestion

nullable
tag name: nullable
tags question: http://stackoverflow.com/q/50145194
type: Tag

http://stackoverflow.com/q/50093582
tagged with: python
has answer: http://stackoverflow.com/a/50094027
tagged with: conda
answer count: 3
has answer: http://stackoverflow.com/a/65055430
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/87224674
downvote count: 0
favorite count: 0
type: Question
has title: Powershell not recognizing conda as cmdlet, function, or operable program
has comment: http://stackoverflow.com/comment/87203964
type: UnansweredQuestion
has body: I've been having this issue on my new laptop for a couple of hours and cannot figure out what's causing it. I'm trying to install scikit-learn with conda and get the following error conda : The term 'conda' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + conda install -c anaconda scikit-learn + ~~~~~ + CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Has anybody else had a similar issue on Windows 10?
tagged with: powershell
has answer: http://stackoverflow.com/a/65834602

http://stackoverflow.com/q/50150951
tagged with: module
has comment: http://stackoverflow.com/comment/87324471
score: 0
linked to: http://stackoverflow.com/q/13181559
has body: I have the following directory dir1\ ..\main.py ..\file2.py in main.py i have the following code import myObj obj1 = None def func1(): global obj1 obj1 = myObj.myObj() if __name__ == "__main__": func1() import file2.py in file2.py: from main.py import obj1 but obj1 is None , any idea why ? Update: Changing the question to this : I have the following directory dir1\ ..\main.py ..\file2.py ..\file3.py in main.py i have the following code import file2 def func1(): file2.init_func() if __name__ == "__main__": func1() in file2.py : import myObj obj1=None def init_func(): global myobj obj1= myObj.myObj() in file3.py: from file2 import obj1 But obj1 is None in file3,Why it is not initialized?
answer count: 0
has title: Importing initialized object from the same directory stay None - Python
duplicate of: http://stackoverflow.com/q/13181559
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/87319910
type: UnansweredQuestion
tagged with: package
has comment: http://stackoverflow.com/comment/87319735
tagged with: python

http://stackoverflow.com/a/50196300
has comment: http://stackoverflow.com/comment/87409624
has comment: http://stackoverflow.com/comment/87409607
has comment: http://stackoverflow.com/comment/87409795
type: Answer
answers question: http://stackoverflow.com/q/50196272
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87409896
downvote count: 0
has body: I am assuming you are not running your program with Python 3.5+. Since your code imports from a module that seems to be Python 3 compatible only, a SyntaxError is raised. Type hints (the config_path: str) are new in Python 3.5 - make sure you're running that python version by typing: $ python3 --version Python 3.6.2 In your terminal. Make sure you're also executing your program like so: $ python3 launcher.py

http://stackoverflow.com/comment/87646158
has text: Please, refrain from sharing Project IDs, keys and other sensitive information in your answers (including screenshots), as this can lead to security issues.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50300082
type: Comment

http://stackoverflow.com/comment/87481523
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50173178
type: AnswerComment
has text: @C.Yduqoli I'm not sure, but I *think* the class is referencing itself in its [MRO](https://docs.python.org/3/glossary.html#term-method-resolution-order): Printing `Inner.__mro__` gives you `(<class '__main__.leak2.<locals>.Inner'>, <class 'object'>)`. If that's not a weak reference (or dynamically generated), then you won't be able to write a class that _doesn't_ have a reference cycle.

http://stackoverflow.com/q/50196186
type: Question
accepted answer: http://stackoverflow.com/a/50201695
downvote count: 5
has comment: http://stackoverflow.com/comment/87409383
tagged with: python
has comment: http://stackoverflow.com/comment/87409457
has title: tkinter get int value instead of nonetype
type: AnsweredQuestion
upvote count: 0
score: -5
tagged with: tkinter
has answer: http://stackoverflow.com/a/50201695
has body: Does anyone know why var2.set(E2.get()) function gets none type not int? var1 = Tkinter.IntVar() E1 = Tkinter.Entry(root, textvariable = var1 ,bd =5) E1.pack(side = Tkinter.LEFT) n = var1.set(E1.get()) and I got this error: File "/home/rostom/Desktop/statistic.py", line 36, in estimate_prob for m in range(0,m): TypeError: range() integer end argument expected, got NoneType. the whole code import numpy as np import Tkinter import tkMessageBox root = Tkinter.Tk() var1 = Tkinter.IntVar() var2 = Tkinter.IntVar() var3 = Tkinter.IntVar() var4 = Tkinter.IntVar() text1= Tkinter.StringVar() text2= Tkinter.StringVar() text3= Tkinter.StringVar() text4= Tkinter.StringVar() def seq_sum(n): x1 = 0 x2 = 0 for i in range(0,n): r = np.random.rand() if r &gt; 0.5: x1=x1+1 else: x2=x2+1 return x1 def estimate_prob(n,k1,k2,m): ran=0 for m in range(0,m): head = seq_sum(n) if k1&lt;=head &lt; k2: ran =ran + 1 p = ran/float(m) print ran return tkMessageBox.showinfo("results ", p) L1 = Tkinter.Label(root, textvariable = text1) L1.grid(row=0,column=0) E1 = Tkinter.Entry(root, textvariable = var1 ,bd =5) E1.grid(row=0,column=1) text1.set("number of flips ") n = var1.set(E1.get()) L2 = Tkinter.Label(root, textvariable = text2) L2.grid(row=1,column=0) E2 = Tkinter.Entry(root, textvariable = var2 ,bd =5) E2.grid(row=1,column=1) text2.set("lower limit ") k1 = var2.set(E2.get()) L3 = Tkinter.Label(root, textvariable = text3) L3.grid(row=2,column=0) E3 = Tkinter.Entry(root, textvariable = var3 ,bd =5) E3.grid(row=2,column=2) text3.set("upper limit ") k2= var3.set(E3.get()) L4 = Tkinter.Label(root, textvariable = text4) L4.grid(row=3,column=0) E4 = Tkinter.Entry(root, textvariable = var4 ,bd =5) E4.grid(row=3,column=1) text4.set("number of trials ") m = var4.set(E4.get()) B1 = Tkinter.Button(root,text = "calculate the probability", command = lambda: estimate_prob(n,k1,k2,m) ) B1.grid(row=4,column=1) root.mainloop()
has comment: http://stackoverflow.com/comment/87409479
answer count: 1
has comment: http://stackoverflow.com/comment/87409485
favorite count: 0

http://stackoverflow.com/q/50091784
has answer: http://stackoverflow.com/a/50091816
has comment: http://stackoverflow.com/comment/87199835
tagged with: unit-testing
favorite count: 0
score: 13
possible better answer: http://stackoverflow.com/a/74156041
has answer: http://stackoverflow.com/a/74156041
type: Question
has comment: http://stackoverflow.com/comment/87199792
tagged with: python
upvote count: 13
has body: I am doing a unit test on two list of list values: self.assertEqual(sale, [['1',14], ['2',5], ['3',7], ['4',1]]) But it gives the below error: AssertionError: Lists differ: [['1', 14], ['4', 1], ['2', 5], ['3', 7]] != [['1' , 14], ['2', 5], ['3', 7], ['4', 1]] First differing element 1: ['4', 1] ['2', 5] - [['1', 14], ['4', 1], ['2', 5], ['3', 7]] + [['1', 14], ['2', 5], ['3', 7], ['4', 1]] How can I make this scenario pass, Prevent the assertEqual function to avoid checking the order of the elements in the list.
type: AnsweredQuestion
has title: unittest - compare list irrespective of order
accepted answer: http://stackoverflow.com/a/50091816
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/87331509
has text: @cᴏʟᴅsᴘᴇᴇᴅ the data is defined in the x and y variables
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50156643
score: 0

http://stackoverflow.com/comment/87219448
type: Comment
type: QuestionComment
score: 0
has text: I don't think so, although one cannot test without [mcve].
comment on: http://stackoverflow.com/q/50097765

http://stackoverflow.com/comment/87242533
type: Comment
comment on: http://stackoverflow.com/q/50112684
type: QuestionComment
has text: Why is this a requirement? This is simply how the `dict` string is defined, it uses the `__repr__` of the objects it contains
score: 0

http://stackoverflow.com/comment/117673301
type: Comment
has text: I am still getting this in 2021 with Django 3.1, and not in tests
type: QuestionComment
comment on: http://stackoverflow.com/q/50116971
score: 0

http://stackoverflow.com/comment/87299184
score: 0
type: AnswerComment
has text: That's strange, The output I posted is literally the exact output of the functions I posted, when I use your exact dataframe (as read by `pd.read_clipboard()`). Note that you should post your output as an edit to your question, not to the answer
type: Comment
comment on: http://stackoverflow.com/a/50139372

http://stackoverflow.com/q/50200678
type: Question
has comment: http://stackoverflow.com/comment/87417910
has answer: http://stackoverflow.com/a/56265523
tagged with: pascal
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
answer count: 2
has comment: http://stackoverflow.com/comment/87420445
has comment: http://stackoverflow.com/comment/88005662
tagged with: plc
tagged with: structured-text
has answer: http://stackoverflow.com/a/50269490
has comment: http://stackoverflow.com/comment/87432365
has body: I have a situation where I have a rectangle that moves in 25 px increments. I need to stop the rectangle when it’s x position is equal to 740. 740 is not dividable by 25 so the x pos will never fall on 740. This increment of 25 is also dynamic and can be from 25-100. Question is language independent.
downvote count: 3
has comment: http://stackoverflow.com/comment/87419078
has title: How to stop a incrementally moving rectangle at a point not divides Le with the increment?
favorite count: 0

http://stackoverflow.com/q/50080414
has answer: http://stackoverflow.com/a/50080450
accepted answer: http://stackoverflow.com/a/50080450
has comment: http://stackoverflow.com/comment/87176902
has body: I want to search for words that match a given word in a list (example below). However, say there is a list that contain millions of words. What is the most efficient way to perform this search?. I was thinking of tokenizing each list and putting the words in hashtable. Then perform the word search / match and retrieve the list of words that contain this word. From what I can see is this operation will take O(n) operations. Is there any other way? may be without using hash-tables?. words_list = ['yek', 'lion', 'opt']; # e.g. if we were to search or match the word "key" with the words in the list we should get the word "yek" or a list of words if there many that match Also, is there a python library or third party package that can perform efficient searches?
tagged with: complexity-theory
downvote count: 0
tagged with: algorithm
answer count: 1
has comment: http://stackoverflow.com/comment/87177051
tagged with: python
has comment: http://stackoverflow.com/comment/87176795
has title: Fastest way to extract matching strings
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87183471
has comment: http://stackoverflow.com/comment/87176812
has comment: http://stackoverflow.com/comment/87176871
favorite count: 0
tagged with: search
type: Question

http://stackoverflow.com/comment/87302513
type: AnswerComment
has text: Lifesaver, I could have continued staring at it for the next couple of hours and not seen it. Thank you very much.
comment on: http://stackoverflow.com/a/50142126
type: Comment
score: 0

http://stackoverflow.com/comment/87354660
has text: What do you mean by "image itself"?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50168117

http://stackoverflow.com/comment/87335612
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50158863
has text: @sayaton Your code leaves at least 4 values undefined; it's impossible for us to say what this code is doing without a complete example.

http://stackoverflow.com/comment/133139103
type: AnswerComment
has text: I have mine working with jupyterlab 3.2.1 and ipympl 0.8.2. Do you have your `%matplotlib widget` decoration placed before you `import matplotlib.pyplot as plt`?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/66246240

http://stackoverflow.com/q/50180999
has answer: http://stackoverflow.com/a/50181045
upvote count: 0
downvote count: 3
answer count: 1
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87379146
has title: AttributeError: 'tuple' object has no attribute 'emp_info'
type: UnansweredQuestion
score: -3
has body: Trying to learn an Inheritance concept for the class. I am getting an error for a class attribute. An Error is coming on this line --> print(parent.emp_info()) My Python script is: class Person: def __init__(self, fname, lname): self.fname = fname self.lname = lname self.email = fname+lname+'@company.com' def emp_info(self): return self.email class Employee(Person): def __init__(self, fname, lname, ID, Cell_No): Person.__init__(self, fname, lname) self.ID = ID self.Cell_No = Cell_No def get_emp_details(self): return self.emp_info() + ' ' + self.ID + ' ' + self.Cell_No parent = ('Sam', 'Robinson') child = ('Ronny', 'Joice', '123', '27389476231') print(parent.emp_info()) parent(child.get_emp_details()) Thank you for suggestions.

http://stackoverflow.com/q/50154940
tagged with: dom
has answer: http://stackoverflow.com/a/50162750
favorite count: 0
linked to: http://stackoverflow.com/q/3423864
upvote count: 4
type: Question
answer count: 2
has title: How can I make sure if some HTML elements are loaded for Selenium + Python?
has answer: http://stackoverflow.com/a/50159359
possible better answer: http://stackoverflow.com/a/50162750
tagged with: python
has body: From this link, I assume the DOM should be loaded as a whole at first in RAM. How DOM works/is loaded? (in HTML) But then I test in Selenium with a timeout exception. It seems even the timeout exception is raised, some elements can already be found, so it is not an empty object. But I am wondering, how can I make sure some elements are already loaded? E.g. the HTML example, how can I make sure all elements are loaded? Given the fact that I actually do not know the number of the elements. Code trial : driver = webdriver.Chrome() driver.set_page_load_timeout(10) try: driver.get(url) print('load success!') except TimeoutException: print(self.page_source) Sample HTML: Symbol Name
tagged with: selenium-webdriver
score: 4
accepted answer: http://stackoverflow.com/a/50159359
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
tagged with: selenium

http://stackoverflow.com/comment/87337375
has text: Show how your program is invoked from the operating system.
type: Comment
comment on: http://stackoverflow.com/q/50159567
score: 0
type: QuestionComment

http://stackoverflow.com/a/50177602
has comment: http://stackoverflow.com/comment/87380605
score: 0
has body: Your mistake lies in returning immediately inside the for loop, and in not assigning the capitalization: first_name = input("enter your first name\n") last_name = input("enter your last name\n") first_name = first_name.lower() last_name = last_name.lower() def rev(s): str = "" for i in s: str = i + str return str first_name = rev(first_name) last_name = rev(last_name) first_name = first_name[0].upper() + first_name[1:] last_name = last_name[0].upper() + last_name[1:] print(first_name + " " + last_name) Note that there are of course nicer, quicker, and easier ways of doing this, as shown in the other answer.
type: Answer
has comment: http://stackoverflow.com/comment/87385104
answers question: http://stackoverflow.com/q/50177527

http://stackoverflow.com/comment/87318294
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50150055
has text: I guess I begin to see what's happening/why. Rather confusing that `=` has different meanings, depending on what I apply it to.

http://stackoverflow.com/q/50163237
has title: Sort numpy array using two arguments
tagged with: python
tagged with: sorting
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50163468
has answer: http://stackoverflow.com/a/50163535
has body: A small snippet of a data set I have is the following: import numpy fns = numpy.array(["filename_0004_0003_info.hdf5", "filename_0003_0003_info.hdf5", "filename_0001_0001_info.hdf5", "filename_0002_0001_info.hdf5", "filename_0006_0002_info.hdf5", "filename_0005_0002_info.hdf5"]) The first integer I call run, whereas the second integer I denote as order. I want to sort this data set. First based on the order number, and second based on the run number. Every order number exists twice while the run number is unique. When I only sort based on the order number using numpy.argsort(): order_nrs = numpy.array([int(fn.split("_")[2]) for fn in fns]) fns = numpy.copy(fns)[numpy.argsort(order_nrs)] I obtain ['filename_0001_0001_info.hdf5' 'filename_0002_0001_info.hdf5' 'filename_0006_0002_info.hdf5' 'filename_0005_0002_info.hdf5' 'filename_0004_0003_info.hdf5' 'filename_0003_0003_info.hdf5'] Although fns is sorted based on order it should afterwards also be sorted by run. The results should be: filename_0001_0001_info.hdf5 filename_0002_0001_info.hdf5 filename_0005_0002_info.hdf5 filename_0006_0002_info.hdf5 filename_0003_0003_info.hdf5 filename_0004_0003_info.hdf5 How do I achieve this?
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87356663
has answer: http://stackoverflow.com/a/50185910
has answer: http://stackoverflow.com/a/50165117
favorite count: 0
has comment: http://stackoverflow.com/comment/87376273
tagged with: numpy
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/87344467
has comment: http://stackoverflow.com/comment/87344940

http://stackoverflow.com/a/50223414
score: -2
upvote count: 0
has body: You just don't have UserProfile for that User in database. RelatedObjectDoesNotExist says by itself)
downvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50215761

http://stackoverflow.com/q/50163877
has title: Combine multiple lists of items in python
has answer: http://stackoverflow.com/a/50163907
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87345824
tagged with: python
score: 4
has body: Coding in Python and I need to get every possible combination of items such that: [a, [a, b], [c, d, e]] gets transformed into: [a, a, c] [a, a, d] [a, a, e] [a, b, c] [a, b, d] [a, b, e] The number of total positions, and number of items at each position are variable. I've already looked at itertools and I haven't found anything that does this. Any ideas?
has answer: http://stackoverflow.com/a/50163903

http://stackoverflow.com/comment/87300500
type: Comment
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/50141123
has text: You have no base case; what should `Fibonacii` return when `n < 1`?

http://stackoverflow.com/q/50144762
score: 0
has body: I am trying to build an activity monitor that tracks what program I have used. Is there a command that retrieves the name of an active process? I am using Ubuntu, and unlike top which tells me all the process, I want the name of the process being really used, as in not in the background but I am clicking on them. Once I know which program it is, is there also a command that gives specifics such as meta-data to it?
type: Question
has comment: http://stackoverflow.com/comment/87307851
answer count: 0
type: UnansweredQuestion
has title: Retrieving actively used process with Python
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/87307813
has comment: http://stackoverflow.com/comment/87307755

http://stackoverflow.com/comment/87401043
comment on: http://stackoverflow.com/q/50191782
has text: I want the modification to take place immediately, because the modification of my graph depends on whether or not an edge is there. And, if I remove or add an edge, the next modification may depend upon the last addition or removal.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87289011
type: Comment
type: QuestionComment
score: 0
has text: These views and urls were working before in the CRUD app that I made before and they were working. I just copied the code and made some changes. Now I don't know why it's not working. I've cross checked it many times still no luck.
comment on: http://stackoverflow.com/q/50135211

http://stackoverflow.com/a/50212433
accepted answer of: http://stackoverflow.com/q/50211619
answers question: http://stackoverflow.com/q/50211619
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Do you need to have multiple separate instances of the factory class? If not, just create a global singleton and use that everywhere: factory = Factory() Otherwise, all of the options below allow you to write code like: ui = UI() ui.factory.make_stuff() so you can easily switch between these method if desired. OK, you need separate factory instances. But do you need a separate instance for each instance of the UI class? If not: class UI(object): factory = Factory() OK, you need one factory per UI instance. Is it expensive to make a factory? Do you often have UI instances that never use a factory? Have you measured a performance problem? If the answer to any of these is no, you can probably just create a factory when you create a UI: class UI(object): def __init__(self): self.factory = Factory() Finally, the answer to your question, if you really want to lazily instantiate a factory: class UI(object): def __init__(self): self._factory = None @property def factory(self): if self._factory is None: self._factory = Factory() return self._factory The @property decorator will allow you to write ui.factory. If you find yourself often writing this kind of pattern in your classes and are tired of it, consider the third party cached_property package: from cached_property import cached_property class UI(object): @cached_property def factory(self): return Factory()

deserialization
type: Tag
tags question: http://stackoverflow.com/q/50077971
tag name: deserialization

http://stackoverflow.com/comment/87236031
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50108650
has text: You mean the output file? Sure, added! The whole thing is over 2000 columns, so I pasted in the first dozen to give an idea.
score: 0

http://stackoverflow.com/comment/87250344
type: AnswerComment
comment on: http://stackoverflow.com/a/50109762
score: 0
type: Comment
has text: @plutonium244 Dont forget to +1 ...and mark as the answer if it solves your problem

http://stackoverflow.com/q/50226395
has title: tensorflow training endless when num epoch is set to None
score: 0
has answer: http://stackoverflow.com/a/50269545
answer count: 1
tagged with: training-data
tagged with: machine-learning
tagged with: tensorflow
type: Question
type: UnansweredQuestion
tagged with: python
has body: I use the tf.estimator.inputs.numpy_input_fnto generate input function, and it is something like this: train_input = tf.estimator.inputs.numpy_input_fn(x={'x': sst_train}, y=precip_train, shuffle=True, batch_size=100, num_epochs=None) And the training process, I set up a for loop to control it. Here is the code: for i in range(15): est.train(input_fn=train_input, steps=20) I think it should train 20*15 times in total, but it ends up with the endless loop. What's the problem here?

http://stackoverflow.com/a/50118979
answers question: http://stackoverflow.com/q/50118843
upvote count: 4
has body: You almost never want to do this, but if you really do - all variables in python are stored in dictionaries. You can directly access these dictionaries, for example the dictionary for local variables. for case in cases: locals()[case+'biofile'] = pandas.read_csv(case+'/InputFiles/BioSave.csv') But unfortunately this turns out to be useless! Not because of how we assigned it, but because the name starts with a number, which means we can't access it (except through the dictionary), because the python parser will try and split off the number as something separate. We could instead go with for case in cases: locals()['biofile'+case] = pandas.read_csv(case+'/InputFiles/BioSave.csv') Which would give you a valid python name (e.g biofile087360). But it's much more natural (and probably what you want to do) to just put them in a dictionary biofiles = {} for case in cases: biofiles[case] = pandas.read_csv(case+'/InputFiles/BioSave.csv')
downvote count: 0
has comment: http://stackoverflow.com/comment/87255366
type: Answer
score: 4

http://stackoverflow.com/comment/87460060
type: Comment
has text: Please read the guidance on how to provide a [mcve].
type: QuestionComment
comment on: http://stackoverflow.com/q/50221046
score: 0

http://stackoverflow.com/comment/87519604
score: 0
has text: @rzr I recommend you to take a look at some tutorials which might help you - to understand splitting into train/[validation or test] set (and explaining what they are) because I think that you train your model on whole training set and if you want to build confusion matrix on data which was used in training it might give you some misleading results. Here you have nice tutorials about Keras - https://www.youtube.com/watch?v=dzoh8cfnvnI&list=PLZbbT5o_s2xrwRnXk_yCPtnqqo4_u2YGL&index=5 or if you want to understand a bit more what happen behind the hood you may take a look at Andrew Ng ML course.
type: Comment
comment on: http://stackoverflow.com/a/50216673
type: AnswerComment

http://stackoverflow.com/a/50109879
has comment: http://stackoverflow.com/comment/87237284
upvote count: 2
score: 2
downvote count: 0
has body: There are a couple of things going on here. First, When python compiles command=counter(var), it calls the function and assigns its result to command. You called counter and your callback is now None and that's obviously not what you want. You can't just do command=counter which would simply make counter the function to use in the callback because the API doesn't have a way to include arguments for the callback. So you do command=lambda:counter(var) This assigns an anonymous function that takes no parameters to command just like the API wants. The lambda contains a reference to var in the containing scope which it then uses to call counter. And that's how you created a parameter for the target callback you really wanted. This reference is a bit strange. Its a reference to the var slot in the containing scope, not the object that happens to be in var at the time of assignment. If you change var before the callback is made (or the containing scope disappears as in locals disappearing on return from a function), that new object is used. So, put your code in a function so you don't drive yourself crazy!
answers question: http://stackoverflow.com/q/50109515
type: Answer

http://stackoverflow.com/a/50181564
has comment: http://stackoverflow.com/comment/87447709
has comment: http://stackoverflow.com/comment/87422792
has comment: http://stackoverflow.com/comment/87409775
accepted answer of: http://stackoverflow.com/q/50181359
has comment: http://stackoverflow.com/comment/87433346
type: Answer
has body: Here's a version that accomplishes the task using cycle and islice. To make the code cleaner I've created a generator function aligned_cycle which cycles through the items yielded by cycle until we get the one we want to start the current cycle with. This updated version can cope with Numberset1 having greater length than Numberset2. from itertools import cycle, islice def aligned_cycle(seq, start_item): ''' Make a generator that cycles over the items in `seq`. The first item yielded equals `start_item`. ''' if start_item not in seq: raise ValueError("{} not in {}".format(start_item, seq)) it = cycle(seq) for u in it: if u == start_item: break yield u yield from it Numberset1 = [10, 11, 12] Numberset2 = [1, 2, 3, 4, 5] cycle_length = len(Numberset2) for i, u in zip(Numberset1, cycle(Numberset2)): for j in islice(aligned_cycle(Numberset2, u), cycle_length): for k in islice(aligned_cycle(Numberset2, j), cycle_length): print(i, j, k) output 10 1 1 10 1 2 10 1 3 10 1 4 10 1 5 10 2 2 10 2 3 10 2 4 10 2 5 10 2 1 10 3 3 10 3 4 10 3 5 10 3 1 10 3 2 10 4 4 10 4 5 10 4 1 10 4 2 10 4 3 10 5 5 10 5 1 10 5 2 10 5 3 10 5 4 11 2 2 11 2 3 11 2 4 11 2 5 11 2 1 11 3 3 11 3 4 11 3 5 11 3 1 11 3 2 11 4 4 11 4 5 11 4 1 11 4 2 11 4 3 11 5 5 11 5 1 11 5 2 11 5 3 11 5 4 11 1 1 11 1 2 11 1 3 11 1 4 11 1 5 12 3 3 12 3 4 12 3 5 12 3 1 12 3 2 12 4 4 12 4 5 12 4 1 12 4 2 12 4 3 12 5 5 12 5 1 12 5 2 12 5 3 12 5 4 12 1 1 12 1 2 12 1 3 12 1 4 12 1 5 12 2 2 12 2 3 12 2 4 12 2 5 12 2 1 Jon Clements has written a more robust and more efficient version of aligned_cycle: def aligned_cycle(iterable, start_item): a, b = tee(iterable) b = cycle(b) for u, v in zip(a, b): if u == start_item: break else: return yield u yield from b Thanks, Jon!
has comment: http://stackoverflow.com/comment/87429691
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87421878
has comment: http://stackoverflow.com/comment/87422747
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50181359

http://stackoverflow.com/q/50229710
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50231770
has comment: http://stackoverflow.com/comment/87491874
has title: same locations memory but the result false (python)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87476592
score: 0
has body: i just get confuse about the identity operator in python , how to use it and how the identity operator works , i'll give you the example : var_1 = 10 print (id(var_1) is id(var_1)) the result is "False" , i don't know why be like that , some one can explain in simple way ? and explain the id() function works . thank's
has comment: http://stackoverflow.com/comment/87492069
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50107437
tagged with: python
has title: How to successfully save a high resolution image from Python
tagged with: fractals
has comment: http://stackoverflow.com/comment/87236360
answer count: 0
tagged with: http://stackoverflow.com/tag/pdf
score: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87249089
has body: I've been experimenting with drawing fractals on Python, and I'm finding the PDF file format to be insufficient for what I want to do. I am using matplotlib pyplot to generate and save these images. Originally, I thought that a PDF would have been sufficient to see all the detail that my program had actually calculated. Instead, however, at a certain scale, the result from my output PDF becomes jagged and looks like this: When I use a PDF, there doesn't seem to be anything I can do in my program to avoid it becoming jagged. No matter how finely or otherwise I actually compute the fractal, it becomes jagged always at the same scale. When I use a JPEG at, say, 1500dpi, I do not get this problem. Instead, I get a result like this: However, the issue is that I can't really produce a JPEG at a resolution greater than around 4000dpi or my program just stops, and my computer struggled to open the images if they are successfully saved. Is there a way to improve the quality of the PDFs I am generating, or perhaps some other file format I can try? Thanks
upvote count: 2
type: UnansweredQuestion
tagged with: matplotlib

http://stackoverflow.com/q/50140597
has answer: http://stackoverflow.com/a/50140614
duplicate of: http://stackoverflow.com/q/38460486
type: UnansweredQuestion
score: -2
has body: I'm nearly finished with a project I've been working on, it is a hangman game. I've been trying to add a feature where you can restart the game after you finish and pick a new difficulty. It works, sorta, but whenever you select a difficulty that has already been selected, it kills the program. I was wondering if there was a command that will allow me to reset the program to a certain line somewhere in the beginning of the code. Full Code Here Problem areab(for reference purposes): if lives == 0: print(" ") print("-Im sorry, " + playername + ", it seems that you cannot make any more mistakes.") print("-The answer was '" + letter1 + letter2 + letter3 + letter4 + "'.") print("-Better luck next time.") print(" ") playagain = str(input("Would you like to play again, " + playername + "? ")) while True: if playagain in (accept, reject): break print(" ") print("-I'm sorry, " + playername + ", I do not understand your answer . . .") print(" ") playagain = str(input("Would you like to play again, " + playername + "? ")) print(" ") if playagain == accept: lives = 6 from random import randint num = randint(1,10) true1 = False true2 = False true3 = False true4 = False difficulty = str(input("Choose a difficulty, easy, medium or hard. ")) break if playagain == reject: print("⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀") print("Thank you for playing!") print("This game was coded by *developer name*") break
tagged with: python
upvote count: 0
downvote count: 2
has title: Is there a command to make the code reset to a certain line? (Python)
linked to: http://stackoverflow.com/q/38460486
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/50106628
has body: If you want to communicate with a server using a "line-oriented" protocol (ie, each line sent terminated by \n, reading lines using readline type functions, you should create file objects for the socket in python, and simply use these sock_in and sock_out objects instead of the standard IO channels sys.stdin and sys.stdout in your input/output statements. socket.makefile() is used to create the sock_in and sock_out file objects. Using encoding='utf-8' specifies the conversion between Python characters and the socket's byte stream. c.sendall is not used at all. Instead we use print(..., file=sock_out) to transmit the text. flush=True should only be used only on the last output from the server in response to any single command; it may be used on every output statement, but will result in more overhead and lower performance. Here is a Minimal, Complete, Verifiable example of such as server, in Python3.6. It simply echo's back whatever is sent to it, except for the exit and kill commands. You can test it without involving a Java client using a command like telnet localhost 8889. server.py: import socket class ClientKill(Exception): pass def _serviceClient(sock_in, sock_out): for line in sock_in: line = line.rstrip('\n') if line == 'exit': break if line == 'kill': raise ClientKill() print(line, file=sock_out, flush=True) # Echo back def serviceClient(client, addr): with client, client.makefile('r', encoding='utf-8', newline='\n') as sock_in, \ client.makefile('w', encoding='utf-8', newline='\n') as sock_out: _serviceClient(sock_in, sock_out) port = 8889 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: listener.bind(('localhost', port)) listener.listen(0) try: while True: client, addr = listener.accept() serviceClient(client, addr) except ClientKill: print("Server killed by remote client") On the Java side, change ... out.print("Try"); out.flush(); ... to ... out.println("Try"); out.flush(); ... or the server will keep waiting for the \n character which…
score: 0
answers question: http://stackoverflow.com/q/50089210
type: Answer

http://stackoverflow.com/comment/132120777
type: Comment
type: QuestionComment
score: 0
has text: Did you find out the reason? I've the problem even if the firewall is off.
comment on: http://stackoverflow.com/q/50190990

http://stackoverflow.com/q/50182411
score: 1
tagged with: ibm-cloud-storage
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50215231
tagged with: python
tagged with: object-storage
has answer: http://stackoverflow.com/a/50215231
has body: I have a Python 3.6 application that uses scikit-learn, deployed to IBM Cloud (Cloud Foundry). It works fine. My local development environment is Mac OS High Sierra. Recently, I added IBM Cloud Object Storage functionality (ibm_boto3) to the app. The COS functionality itself works fine. I'm able to upload, download, list, and delete objects just fine using the ibm_boto3 library. Strangely, the part of the app that uses scikit-learn now freezes up. If I comment out the ibm_boto3 import statements (and corresponding code), the scikit-learn code works fine. More perplexingly, the issue only happens on the local development machine running OS X. When the app is deployed to IBM Cloud, it works fine -- both scikit-learn and ibm_boto3 work well side-by-side. Our only hypothesis at this point is that somehow the ibm_boto3 library surfaces a known issue in scikit-learn (see this -- parallel version of the K-means algorithm is broken when numpy uses Accelerator on OS X). Note that we only face this issue once we add ibm_boto3 to the project. However, we need to be able to test on localhost before deploying to IBM Cloud. Are there any known compatibility issues between ibm_boto3 and scikit-learn on Mac OS? Any suggestions on how we can avoid this on the dev machine? Cheers.
type: AnsweredQuestion
has title: ibm_boto3 compatibility issue with scikit-learn on Mac OS

http://stackoverflow.com/comment/87412767
type: Comment
type: QuestionComment
has text: `/LD`? Are you sure?
comment on: http://stackoverflow.com/q/50197984
score: 0

http://stackoverflow.com/q/50217834
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87453247
has comment: http://stackoverflow.com/comment/87452694
has answer: http://stackoverflow.com/a/50217944
tagged with: random
has comment: http://stackoverflow.com/comment/87452663
linked to: http://stackoverflow.com/q/45437988
has comment: http://stackoverflow.com/comment/87452775
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50217944
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/45437988
has comment: http://stackoverflow.com/comment/87452746
has title: Efficient Way to create a 2d array of random shuffling of a range of numbers
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/87456818
has body: I need to create a N x M numpy array of randomly shuffled numbers 0 to N. That is to say that each row of the matrix has exactly one of each numbers 0 to N in a random order with no repeating elements and every number is represented. The best I've been able to come up with so far is (for N = 10 and M = 5) import random import numpy as np a = np.array([random.sample(range(10), 10) for x in range(5)]) which gives me [[5 9 1 3 8 2 6 4 0 7] [4 8 5 2 9 3 7 6 0 1] [8 4 6 7 9 2 0 5 1 3] [3 5 4 9 2 0 6 7 1 8] [6 0 4 7 3 2 1 8 5 9]] My current solution does work, but I'd like to only have one random library if possible (I'm using numpy elsewhere so a numpy only solution would be ideal). I'm assuming numpy has an easier way to do this, but I'm currently missing it.
has comment: http://stackoverflow.com/comment/87452672
has comment: http://stackoverflow.com/comment/87452730

http://stackoverflow.com/comment/87455541
type: AnswerComment
has text: Or use `apply(validate_email.validate_email)`, if I understand the answer correctly.
comment on: http://stackoverflow.com/a/50217952
score: 0
type: Comment

http://stackoverflow.com/q/50191969
tagged with: python
type: Question
tagged with: sumo
type: UnansweredQuestion
answer count: 1
has body: Is there any way to save changes to the loaded net automatically? Like there is an option for: net = sumolib.net.readNet("net.net.xml") Is there an option to save it like net.saveNet("net.net.xml") To save the whole net loaded, including existing properties and including changes?
has title: Sumolib: saving the net
score: 0
has answer: http://stackoverflow.com/a/50204393

http://stackoverflow.com/q/50082878
has title: Need help taking API response, converting to Pandas Dataframe, and load into an existing SQLite table
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
tagged with: sqlite
answer count: 1
type: Question
tagged with: scraper
type: UnansweredQuestion
has body: I have been teaching myself Python for the last few weeks, and am trying to figure out how to achieve the following: Run an API call Take the API call response and transform into a DataFrame. Take the DataFrame and load into a SQLite table I have the first two parts down, but am stumped on the third part. Here is what I have for parts 1 and 2: import csv import pandas as pd import requests data_request=requests.get('https://api.blockcypher.com/v1/eth/main/txs') json=data_request.json() df=pd.DataFrame(json) This is what I have so far for part 3: import sqlite3 conn = sqlite3.connect('transactions.db') c = conn.cursor() c.execute("INSERT INTO transactions VALUES ('')") conn.commit() conn.close() I know that what I have for part 3 works, because I put sample data into the Insert clause and it works just fine. The question is, how do I get that snippet of code to take the contents of my dataframe and load it into my SQLite table instead?
tagged with: python
has answer: http://stackoverflow.com/a/50083603

http://stackoverflow.com/q/50077353
favorite count: 0
type: Question
has body: I want to get labels from Tensorflow object detection api and put them into array instead of showing them on the video this is detect_object function def detect_objects(image_np, sess, detection_graph): # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8) return image_np
has answer: http://stackoverflow.com/a/66885097
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51023001
has title: Tensorflow object detection api get labels in array
tagged with: python
score: 3
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/55364571
downvote count: 0
tagged with: tensorflow

http://stackoverflow.com/comment/87235617
type: Comment
type: QuestionComment
has text: Okay, and are the universities the only thing listed in your text file?
comment on: http://stackoverflow.com/q/50107276
score: 0

http://stackoverflow.com/comment/87267011
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50124405
type: Comment
has text: This would assign `None` to `obj.attribute`, which is not quite the same as not assigning

http://stackoverflow.com/q/50182546
has comment: http://stackoverflow.com/comment/87383118
favorite count: 0
type: Question
tagged with: python-2.7
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87384373
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87384050
has comment: http://stackoverflow.com/comment/87385466
has comment: http://stackoverflow.com/comment/87384094
has comment: http://stackoverflow.com/comment/87383289
has body: import ssl import socket port = 3001 while True: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ssl_socket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='scert.pem') ssl_socket.connect(('127.0.0.1', 3001)) ssl_socket.write(str(input("Enter two numbers to add:")).encode()) z = ssl_socket.recv(1024) print(z.decode()) ssl_socket.close() The error I'm getting is: Traceback (most recent call last): ssl_socket.connect(('127.0.0.1', 3001)) self._real_connect(addr, False) socket.connect(self, addr) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) error: [Errno 111] Connection refused I am confused as to what to do. Already tried the methods on the other thread on socket.
score: 0
has title: Why am I getting a "Connection refused" in python? Can't resolve using existing solutions
tagged with: sockets
tagged with: ssl
tagged with: python

http://stackoverflow.com/q/50137473
type: UnansweredQuestion
has title: How to change properties of objects in blender with python
score: 0
has body: I am currently using the game engine in Blender. I was wondering how can I change the properties of an object via script, like position, rotation, color, and change the related variables in the objects. scene = bpy.data.scenes["Scene"] scene.Cube.diffuse_color = [0]=red [1]=green [2]=blue In the example above I tried to change the color of a Cube, but it fails with the error "Cannot assign to literal". How can I solve it?
tagged with: blender
has answer: http://stackoverflow.com/a/50148968
type: Question
has answer: http://stackoverflow.com/a/50204920
answer count: 2
tagged with: python

http://stackoverflow.com/a/50204713
type: AcceptedAnswer
downvote count: 0
has body: You can take the transpose, groupby the second part of each string, then transpose back: &gt;&gt;&gt; df.T.groupby(df.T.index.str.split('_').str[1]).sum() &gt; 0).T.astype(int) AA7542 RG7509 WE4818 YY6124 0 0 1 1 1
has comment: http://stackoverflow.com/comment/87426796
score: 3
has comment: http://stackoverflow.com/comment/87426763
type: Answer
answers question: http://stackoverflow.com/q/50204623
accepted answer of: http://stackoverflow.com/q/50204623
upvote count: 3

http://stackoverflow.com/q/50108048
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50108201
accepted answer: http://stackoverflow.com/a/50108111
tagged with: nested
has answer: http://stackoverflow.com/a/50108111
has body: I have 3 variables, a,b and c, and 3 coefficients a_b, a_c and b_c. I want to use these to build a nested dictionary rels that would be the following: a b c a 1 a_b a_c b a_b 1 b_c c a_c b_c 1 So for example: rels['a']['b']=a_b rels['b']['c']=b_c rels['a']['a']=1 and so on Clearly, I can make this by hardcoding: rels = {} rels['a']={{'a':1,'b':a_b,'c':a_c}} and so on. I was wondering if there was a more elegant/efficient way of doing this?
type: Question
has answer: http://stackoverflow.com/a/50108201
tagged with: python
tagged with: dictionary
has title: Build nested dictionary based on relationship coefficients
has comment: http://stackoverflow.com/comment/87234246
has comment: http://stackoverflow.com/comment/87234572
has comment: http://stackoverflow.com/comment/87233806
has comment: http://stackoverflow.com/comment/87234424
has comment: http://stackoverflow.com/comment/87234483

http://stackoverflow.com/q/50218044
score: 0
has answer: http://stackoverflow.com/a/50218620
downvote count: 2
possible better answer: http://stackoverflow.com/a/50218620
has answer: http://stackoverflow.com/a/50218152
has title: Python 3 using an if statement to read the values in 1 array and append another value to another array
accepted answer: http://stackoverflow.com/a/50218152
has comment: http://stackoverflow.com/comment/87453158
has answer: http://stackoverflow.com/a/50218102
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50218111
has answer: http://stackoverflow.com/a/50218215
tagged with: if-statement
has answer: http://stackoverflow.com/a/50218160
tagged with: arrays
has comment: http://stackoverflow.com/comment/87453083
tagged with: python
answer count: 6
has body: I am new to Python and trying to write a program that reads the integer values stored in the array (percent) then based on there value using an if statement append a string to the array (grade). The code seems to be reading the array (percent) but not storing the correct value in the (grade) array. I can't seem to find an answer that solves the problem. Here is my code percent = [33, 44, 55, 66, 77, 88, 99] grade = [] for i in range(0, len(percent)): if i &gt;= 70 and i &lt;= 100: grade.append("Grade A") elif i &gt;= 60 and i &lt;= 69: grade.append("Grade B") elif i &gt;= 50 and i &lt;= 59: grade.append("Grade C") elif i &gt;= 45 and i &lt;= 49: grade.append("Grade D") else: grade.append("No grade achieved") print(grade) All that is prints out is "No grade achieved" even though the values do not match that. What am I doing wrong here?
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/a/50248257
has comment: http://stackoverflow.com/comment/87535015
has comment: http://stackoverflow.com/comment/87531254
has comment: http://stackoverflow.com/comment/87531428
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 7
answers question: http://stackoverflow.com/q/50207218
has comment: http://stackoverflow.com/comment/87588015
has comment: http://stackoverflow.com/comment/87537496
has comment: http://stackoverflow.com/comment/87533641
accepted answer of: http://stackoverflow.com/q/50207218
score: 7
has comment: http://stackoverflow.com/comment/87537571
has body: EDIT: I managed to reform the solution using Django subqueries. We can translate the query to Django ORM using Django's aggregates with SubQuery expressions: Create a subquery to retrieve the lowest close for every symbol: from django.db.models import OuterRef, Subquery, Min lows = StockHistory.objects.filter( stock=OuterRef('stock'), trading_date__gte='2017-05-04' ).values('stock__symbol') .annotate(low=Min('close')) .filter(trading_date__gte='2018-04-30') Breakdown: filter the queryset to get only the stocks with trading_date &gt;= '2017-05-04'. "GROUP BY" stock__symbol (examples of group by in Djnago: GROUP BY ... MIN/MAX, GROUP BY ... COUNT/SUM). annotate the lowest (low) price to every element. filter the queryset again to get only the objects with a low field occurring on trading_date &gt;= '2018-04-30'. Intermediate Result: Although we cannot get a result at this stage, the subquery will look like this: [ {'stock__symbol': 'A', 'low': Decimal('105.00000')}, {'stock__symbol': 'C', 'low': Decimal('90.00000')} ] We are missing the trading_date. Utilize the subquery to retrieve the specific StockHistory objects: StockHistory.objects.filter( stock__symbol=Subquery(lows.values('stock__symbol')), close=Subquery(lows.values('low')), trading_date__gte='2018-04-30' ).values('stock__symbol', 'trading_date', 'close') .order_by('stock__symbol') Breakdown: lows.values('stock__symbol') and lows.values('low') retrieve the respective values from the subquery. filter the queryset against the lows subquery values. Also filter against the specified date in order to eliminate low close prices occurring before that date. Get the specified values. Order the result by stock__symbol (by default ascending). Result: [ { 'close': Decimal('105.00000'), 'trading_date': datetime.date(2018, 5, 3), 'stock__symbol': 'A' }, { 'close': Decimal('90.00000'), 'trading_date': datetime.date(2018, 5, 4), 'stock__symbol': 'C' } ]

http://stackoverflow.com/q/50082638
has comment: http://stackoverflow.com/comment/87286375
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87249260
has comment: http://stackoverflow.com/comment/87238583
has comment: http://stackoverflow.com/comment/87249207
has comment: http://stackoverflow.com/comment/87194267
tagged with: fits
tagged with: multidimensional-array
has body: I have a list of two arrays which returns two arrays like the following: mainarray = array1, array2 The size of array1 is let's say 50. However, array2 is multidimensional of the shape [100, 100, 50], where say [100, 100] is the sky coordinates, and for each sky coordinate we have 50 values corresponding to array1. Now I want to write this data into a fits file, with a proper formatting of first two axes corresponding to [100, 100] data points, second axes corresponding to [50, 50] values of array1 and array2[axis=2]. What is the proper way of doing this? Will just hdu = fits.PrimaryHDU(mainarray) hdu.writeto('skymap.fits', clobber = True) work?
score: 1
type: Question
has comment: http://stackoverflow.com/comment/87261646
answer count: 0
type: UnansweredQuestion
has title: How to write a multidimensional array into a fits with proper axes formatting?
downvote count: 0

http://stackoverflow.com/q/50168663
has comment: http://stackoverflow.com/comment/87354699
answer count: 1
has answer: http://stackoverflow.com/a/50168869
tagged with: selenium
has title: Skip waiting for a website timer selenium Python
accepted answer: http://stackoverflow.com/a/50168869
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: webdriverwait
upvote count: 2
has body: I'm running Selenium in Python ide with geckodriver. The site I'm trying to open has a timer of 30 seconds that after this 30 seconds a button appears and I send a click on it. What I'm asking is the following: Can I somehow ignore/skip/speed up the waiting time? Right now what I'm doing is the following: driver = webdriver.Firefox() driver.get("SITE_URL") sleep(30) driver.find_element_by_id("proceed").click() Which is very inefficient because every time I run the code to do some tests I need to wait. Thanks in advance, Avi. UPDATE: I haven't found a way to get over the obstacle but until I do I'm trying to focus the next achievable progress: &lt;video class="jw-video jw-reset" disableremoteplayback="" webkit-playsinline="" playsinline="" preload="metadata" src="//SITE.SITE.SITE/SITE/480/213925.mp4?token=jbavPPLqNqkQT1SEUt4crg&amp;amp;time=1525458550" style="object-fit: fill;"&gt;&lt;/video&gt; (censored site's name) In each page there is a video, all the videos are under the class "jw-video jw-reset" I had trouble using find element by class so I used: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "video[class='jw-video jw-reset']"))) It works but I can't figure how to select the element's src...
downvote count: 0
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/87452402
has text: @CristianCiupitu I have been practising importing and other random pages did import, but this one seems interesting ! So I am trying to understand how to import from this page
comment on: http://stackoverflow.com/q/50216844
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87172728
comment on: http://stackoverflow.com/q/50078269
score: 0
has text: So you've posted your dataArray, now please show us an example of what it should look like after the transformation.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87383898
comment on: http://stackoverflow.com/a/50149193
type: Comment
has text: @jezrael - I keep getting this error when using: `df1 = df[df['email'].apply(validate_email)]` - TypeError: 'module' object is not callable - Any idea where this could come from. "email" is of dtype object
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87339811
score: 0
comment on: http://stackoverflow.com/a/50160489
type: Comment
has text: when i tried your code, it gives me an error: data = np.array(itertools.islice(fp, num)) ValueError: Stop argument for `islice()` must be None or an integer: 0 <= x <= sys.maxsize. (i've used `islice()` like this: `for line in islice(f1, sizeOfWindowInactive, None): pass`to skip unnecessary lines. As i said, i took more memory, i don't know why
type: AnswerComment

http://stackoverflow.com/comment/87308069
score: 0
type: QuestionComment
has text: @anishtain4 True, but how I may find the similar arrays, and how I may replace them with some new arrays that are not already in my list is my question indeed!!
type: Comment
comment on: http://stackoverflow.com/q/50144888

http://stackoverflow.com/a/50163755
answers question: http://stackoverflow.com/q/50163636
has body: Is there a way to do this using dict.setdefault() ? Of course! There's nothing magic about setdefault; it just returns my_dict[name] if it exists, or sets my_dict[name] = default and returns default if not. Either way, what it returns is the (potentially new) dict in my_dict[name], so all you have to do is update it: my_dict.setdefault(name, {})[id] = pin Or, if you really like using update instead of just [] =: my_dict.setdefault(name, {}).update({id: pin}) For example: &gt;&gt;&gt; my_dict.setdefault('name1', {})['id10']= 'pin10' &gt;&gt;&gt; my_dict.setdefault('name3', {})['id20']= 'pin20' {'name1': {'id1': 'pin1', 'id10': 'pin10', 'id2': 'pin2'}, 'name2': {'id3': 'pin3', 'id4': 'pin4'}, 'name3': {'id20': 'pin20'}} More generally, you could obviously rewrite your existing code to this: if name not in my_dict: my_dict[name] = {} my_dict[name].update({ id : pin } Whenever you can do that, you can use setdefault. (But notice that we're calling a mutating method or assigning to a key/index/member of my_dict[name] here, not just assigning a new value to my_dict[name]. That's the key to it being useful.) Of course almost any time you can use setdefault, you can also use defaultdict (as demonstrated in CoryKramer's answer) (and vice-versa). If you want defaulting behavior all the time, use defaultdict. Only use setdefault if you want defaulting behavior just this once (e.g., you want defaulting while building the dict up, but you want KeyErrors later when using it).
has comment: http://stackoverflow.com/comment/87737589
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87738623
upvote count: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/50163636
score: 9

http://stackoverflow.com/comment/87238457
has text: Are you talking about the CLI anaconda 'something' or conda 'something'?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50110474

http://stackoverflow.com/q/50196451
has body: Is there something faster I can use to fill forms since finding id's and sending info via .send_keys takes like 10 seconds for 7 fields. I'm using this currently but its way to slow for what I need it to do, thanks for any help. driver.find_element_by_xpath("//*[@id='order_billing_name']").send_keys("John Doe") driver.find_element_by_xpath("//*[@id='order_email']").send_keys("supreme@gmail.com") driver.find_element_by_xpath("//*[@id='order_tel']").send_keys("012-345-6789") driver.find_element_by_xpath("//*[@id='bo']").send_keys("439 N Fairfax Ave") driver.find_element_by_xpath("//*[@id='order_billing_city']").send_keys("Los Angeles") driver.find_element_by_xpath("//*[@id='order_billing_zip']").send_keys("90036") driver.find_element_by_xpath("//*[@id='nnaerb']").send_keys("1111222233334444")
favorite count: 0
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/87410003
answer count: 2
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/59130200
linked to: http://stackoverflow.com/q/69982660
downvote count: 0
linked to: http://stackoverflow.com/q/57747480
has comment: http://stackoverflow.com/comment/87410548
type: Question
possible better answer: http://stackoverflow.com/a/70037574
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70037574
accepted answer: http://stackoverflow.com/a/50196546
has answer: http://stackoverflow.com/a/50196546
linked to: http://stackoverflow.com/q/47453087
tagged with: python
has title: Send keys fills form to slow (Python + Selenium)

http://stackoverflow.com/comment/87416916
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50200085
has text: urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), path('contact/', views.contact, name='contact'), path('admin/', admin.site.urls), path('accounts/', allauth.urls), ]
type: Comment

http://stackoverflow.com/q/50179311
score: 2
has comment: http://stackoverflow.com/comment/87375850
has answer: http://stackoverflow.com/a/50179426
favorite count: 0
has comment: http://stackoverflow.com/comment/87375928
has comment: http://stackoverflow.com/comment/87375954
type: Question
has comment: http://stackoverflow.com/comment/87375800
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87375919
has comment: http://stackoverflow.com/comment/87376057
answer count: 2
has comment: http://stackoverflow.com/comment/87375975
upvote count: 2
has comment: http://stackoverflow.com/comment/87375843
type: UnansweredQuestion
has title: ValueError: I/O operation on closed (csv) file
has answer: http://stackoverflow.com/a/50179412
downvote count: 0
tagged with: python
has body: I get this error: Traceback (most recent call last): File "so.py", line 7, in &lt;module&gt; for review in x: ValueError: I/O operation on closed file. Code: def get_reviews(path): with open(path, 'r', encoding = "utf-8") as file1: reviews = map(lambda x: x.strip().split(','), file1) return reviews x = get_reviews("reviews.csv") for review in x: print(review)
has comment: http://stackoverflow.com/comment/87375961

http://stackoverflow.com/a/72809583
score: 0
answers question: http://stackoverflow.com/q/50121477
has body: jupyter. Clone from official git and manually appended the path to sys. !git clone https://github.com/tensorflow/models.git import sys sys.path.append("C:/Windows/System32/models") sys.path
type: Answer

http://stackoverflow.com/q/50187746
has body: I'm not quite sure what is the best approach in recreating an UDP frame in python...one thing that came up to my mind is creating classes with __init__ methods and the other way is just literally create a dictionary. Basicly the frame is split in 5 pieces: First 4 bytes (0-3) are used for header description. Next 32 bytes (4-35) are used for common data. Next 16 bytes (36-51) are all empty. Next 4 bytes (52-55) are used for description of payload. Last 200 bytes are used for payload. First 4 pieces (header, common, 16-byte empty, payload description) are all parsed from bunch of other files while the payload is given in plain list of int. What would be the best approach in recreating the frame piece by piece? This following snippet is the first idea: class common: def __init__(self, par1, par2): self.par1 = par1 self.par2 = par2 class header: def __init__(self, par1, par2): self.par1 = par1 self.par2 = par2 class empty: def __init__(self): self.par1 = 16*[[0]] class description: def __init__(self, par1, par2): self.par1 = par1 self.par2 = par2 class udp_frame: def __init__(self, payload, h_par_1, h_par_2, c_par_1, c_par_2, d_par_1, d_par_2,): self.payload = payload self.header = header(h_par_1, h_par_2) self.common = common(c_par_1, c_par_2) self.empty = empty() self.description = description(d_par_1, d_par_2) def create_frame(self): temp = [self.header.par1, self.header.par2, self.common.par1, self.common.par2, self.empty.par1, self.description.par1, self.description.par2, self.payload ] while len(temp) &lt; 256: temp.extend(0) return bytearray(temp) Is there any other more eye-appealing / efficient / standardized way of doing this kind of stuff?
has comment: http://stackoverflow.com/comment/87392552
upvote count: 3
downvote count: 0
answer count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
score: 3
has title: Best way to "re-create" raw 256-byte UDP frame in python?
has comment: http://stackoverflow.com/comment/87392189
tagged with: python

http://stackoverflow.com/comment/87460032
has text: it works perfecly for the 3 first lines but when I try for the whole dataset it doenst work
comment on: http://stackoverflow.com/a/50183282
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50082493
type: Answer
has comment: http://stackoverflow.com/comment/87194063
accepted answer of: http://stackoverflow.com/q/50078229
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50078229
has body: It is easier just to iterate through the dates in daterange: daterange = pd.date_range(start_date, end_date) url_template = base_url + 'KOWD/{d.year}/{d.month}/{d.day}' + end_url for date in daterange: url = url_template.format(d=date) weather_list = pd.read_html(url) # etc. If this works for you then you can drop all the subsequent code that stores the dates in a dataframe, changes them into strings, and creates separate columns for year, month and date. If you do need to create a dataframe of the dates you could do this: date_list = pd.DataFrame(daterange, columns=['date']) for k in ['year', 'month', 'day']: date_list[k] = date_list.apply(lambda r: getattr(r.date, k), axis=1) You can then iterate throw the rows. for index, row in date_list.iterrows(): url = url_template.format(d=row) weather_list = pd.read_html(url) # etc. Then consider what format you want the weather_list output to be in. If the information scraped is not suitable to be included in the data frame then it might make more sense as a dictionary of {date: table} pairs. Edit: For example if you want to pick the 3rd table from each page and concatenate it together with the date into a single dataframe, you could do this: weather_dict = {} for date in daterange: table = pd.read_html(url, header=0)[2] table.set_index(table.columns.values[0], inplace=True) table.index.set_names(None, inplace=True) weather_dict[date] = table weather_df = pd.concat(weather_dict)
has comment: http://stackoverflow.com/comment/87197232
downvote count: 0
score: 1

http://stackoverflow.com/comment/87191956
has text: `sorted(matrix, key=lambda row: row[1], reverse=True)`
score: 2
comment on: http://stackoverflow.com/q/50088038
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50170781
answers question: http://stackoverflow.com/q/50170700
has comment: http://stackoverflow.com/comment/87358964
has body: Use models.DateTimeField(auto_now_add=True) See https://docs.djangoproject.com/en/2.0/ref/models/fields/#datefield
type: Answer
score: 0

http://stackoverflow.com/q/50114132
has title: Python Pandas - Creating a new column using currency_converter
tagged with: pandas
type: AnsweredQuestion
score: 0
has body: I have a dataframe (dfFF) like this: Sector Country Currency Amount Fund Start Year 0 Public USA USD 22000 2016 0 Private Hong Kong HKD 42000 2015 ... I want to create a new column that converts the currency/amount/fund start year into Euros and then to GBP (currency_converter only converts to everything to Euros or back hence why I am not converting straight to GBP). I want the currency rate for the year that the funding took place. I am using the template code given by the website: https://pypi.org/project/CurrencyConverter/ from currency_converter import CurrencyConverter from datetime import date c = CurrencyConverter() c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) I want to use the 1st of January for every year to make it consistent, so I have tried doing the following: c = CurrencyConverter() dfFF['Value'] = (c.convert(dfFF['Amount'],dfFF['Currency'], 'EUR',date=date(dfFF['Fund Start Year'],1,1))) I am getting the error: TypeError: 'Series' objects are mutable, thus they cannot be hashed Although I feel that my solution isnt the best way of doing this. Any suggestions? Even if I just get it into EUROS, and then I can do the same to convert it to GBP would be great. Thank you
accepted answer: http://stackoverflow.com/a/50114235
has answer: http://stackoverflow.com/a/50114235
type: Question
tagged with: python
answer count: 1

http://stackoverflow.com/comment/87332238
type: Comment
type: QuestionComment
has text: Though it accomplishes the same thing, it is more natural to use `struct.pack("b", 100)` if you have a number to start with. (Likewise, for the length, you will want `struct.pack("I", len(data))` [capital i] for an unsigned 4-byte integer.)
score: 1
comment on: http://stackoverflow.com/q/50148738

http://stackoverflow.com/comment/87219160
comment on: http://stackoverflow.com/a/50101234
type: AnswerComment
score: 0
has text: I modified the answer
type: Comment

http://stackoverflow.com/a/50106318
type: Answer
has body: Actually, you don't need to check the upper range at all since it is always covered by previous checks and you're using elif. examscore = int(input(("Enter exam score: "))) attendance = int(input(("Enter attendance: "))) if examscore &gt;90 and attendance &gt;90: print("Grade A") elif examscore &gt;80 and attendance &gt;90: print("Grade B") elif examscore &gt;70 and attendance &gt;90: print("Grade C")
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50106148
score: 0
accepted answer of: http://stackoverflow.com/q/50106148

http://stackoverflow.com/a/50282803
has body: I did something similar a while back and ended up defining my own basic colors in HSV space, including monochrome definitions (which I admit are a little arbitrary). Anyway, as those in the comments stated, in HSV, the red hue is split, so I made a simple function to combine any colors I defined to easily create masks for them: import cv2 import numpy as np HSV_RANGES = { # red is a major color 'red': [ { 'lower': np.array([0, 39, 64]), 'upper': np.array([20, 255, 255]) }, { 'lower': np.array([161, 39, 64]), 'upper': np.array([180, 255, 255]) } ], # yellow is a minor color 'yellow': [ { 'lower': np.array([21, 39, 64]), 'upper': np.array([40, 255, 255]) } ], # green is a major color 'green': [ { 'lower': np.array([41, 39, 64]), 'upper': np.array([80, 255, 255]) } ], # cyan is a minor color 'cyan': [ { 'lower': np.array([81, 39, 64]), 'upper': np.array([100, 255, 255]) } ], # blue is a major color 'blue': [ { 'lower': np.array([101, 39, 64]), 'upper': np.array([140, 255, 255]) } ], # violet is a minor color 'violet': [ { 'lower': np.array([141, 39, 64]), 'upper': np.array([160, 255, 255]) } ], # next are the monochrome ranges # black is all H &amp; S values, but only the lower 25% of V 'black': [ { 'lower': np.array([0, 0, 0]), 'upper': np.array([180, 255, 63]) } ], # gray is all H values, lower 15% of S, &amp; between 26-89% of V 'gray': [ { 'lower': np.array([0, 0, 64]), 'upper': np.array([180, 38, 228]) } ], # white is all H values, lower 15% of S, &amp; upper 10% of V 'white': [ { 'lower': np.array([0, 0, 229]), 'upper': np.array([180, 38, 255]) } ] } def create_mask(hsv_img, colors): """ Creates a binary mask from HSV image using given colors. """ # noinspection PyUnresolvedReferences mask = np.zeros((hsv_img.shape[0], hsv_img.shape[1]), dtype=np.uint8) for color in colors: for color_range in HSV_RANGES[color]: # noinspection PyUnresolvedReferences mask += cv2.inRange( hsv_img, color_range['lower'], color_range['upper'] ) return mask Applying it to your example (…
has comment: http://stackoverflow.com/comment/87637789
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/87637710
answers question: http://stackoverflow.com/q/50221851
accepted answer of: http://stackoverflow.com/q/50221851
has comment: http://stackoverflow.com/comment/87589851
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87211511
score: 0
comment on: http://stackoverflow.com/a/50097050
has text: @ ags29, that another to do it, yes, 'date' is not a datetime, maybe can change to 'a_date' then it will not be confusing, sorry for that. So was wonder, since the dt.month==5, so the option prompt to user need to be change? and for your information, the initial function import as below: import numpy as np import pandas as pd from datetime import datetime import time import os import matplotlib.dates as mdates import matplotlib.pyplot as plt import seaborn as sns Thank you.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50198160
tagged with: random
has comment: http://stackoverflow.com/comment/87413141
has title: How to change the characters order in a string in python 3.X?
answer count: 1
has comment: http://stackoverflow.com/comment/87414277
tagged with: string
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87413923
duplicate of: http://stackoverflow.com/q/1022141
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/8306654
has answer: http://stackoverflow.com/a/50198656
tagged with: python
tagged with: replace
score: 0
duplicate of: http://stackoverflow.com/q/8306654
has body: let's say for example that I got 100 random words (not even real words just words)... like "ABCD" and I want to make a program that takes a word like the one I mentioned and prints you all the options of this word in random order. for example the word "ABC" will print: "ABC", "BAC", CAB", "BCA", "CBA". I could do it manually but if I have 100 words I can't... so how do I write a code that does it in python?

http://stackoverflow.com/a/50220905
has body: I have tried this in my machine also and it worked fine. The problem is that you are seeing different random_bite than the actual random_bite that is removed. When you call a.new_bite(), it calls the first _pick_random_bite() and when you call print(a._pick_random_bite()), chances are it is different from the the result of random bite in new_bite call. To simply check the result, you can move the print for random bite inside new_bite method. Something like below: class Promo: def __init__(self, bites=BITES, bites_done=BITES_DONE): self.bites = bites self.bites_done = bites_done def _pick_random_bite(self): return random.choice(self.bites.keys()) def new_bite(self): this_bite = self._pick_random_bite() print(this_bite) # Print the actual random_bite if this_bite not in self.bites_done: self.bites_done.add(this_bite) self.bites.pop(this_bite, None) a = Promo() a.new_bite() print(a.bites_done) print(a.bites)
answers question: http://stackoverflow.com/q/50220617
type: Answer
accepted answer of: http://stackoverflow.com/q/50220617
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87459502
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50202283
answers question: http://stackoverflow.com/q/50202170
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50202170
has body: print_number() is running an infinite loop - it never exits, so the thread never ends. It sits in number_queue_display.get() forever, waiting for another queue item that never appears. Then, since the thread never ends, printing_numbers.join() also waits forever. So you need some way to tell the thread to quit. One common way is to put a special "sentinel" value on the queue, and have the thread exit when it sees that. For concreteness, here's a complete program, which is very much the same as what you started with. None is used as the sentinel (and is commonly used for this purpose), but any unique object would work. Note that the .task_done() parts were removed, because they no longer serve a purpose. from threading import Thread import queue def print_number(number_queue_display): while True: number = number_queue_display.get() if number is None: break print(number) number_queue = queue.Queue() printing_numbers = Thread(target=print_number, args=(number_queue,),) printing_numbers.start() number_queue.put(5) number_queue.put(10) number_queue.put(15) number_queue.put(20) number_queue.put(None) # tell the thread it's done printing_numbers.join() # wait for the thread to exit
type: Answer
score: 2

http://stackoverflow.com/q/50192120
has body: This is my second week learning Python. The code I wrote below works up to 1968. Anything beyond 1968 for instance 1971 gives the same result between 1965 and 1968 of 6000. Can anyone help to explain the cause for this. year = int(input('Enter year: ')) while year: if year &lt; 1962: print('Car did not exist yet!') print('Please enter a valid year after 1962') elif year &lt;= 1964: print('$18500') elif year &gt;= 1965 &lt;= 1968: print('$6000') elif year &gt;= 1969 &lt;= 1971: print('$12000') elif year &gt;= 1972 &lt;= 1975: print('$48000') elif year &gt;= 1976 &lt;= 1980: print('$200000') elif year &gt;= 1981 &lt;=1985: print('$650000') elif year &gt;= 1986 &lt;=2012: print('$35000000') elif year &gt;=2013 &lt;=2014: print('$52000000') else: print('Error Message') int(input('Enter year: '))
type: Question
has title: Why does elif execute one statement among many without syntax error
upvote count: 0
has comment: http://stackoverflow.com/comment/87401540
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87401147
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87401176
answer count: 2
has comment: http://stackoverflow.com/comment/87401514
has answer: http://stackoverflow.com/a/50192172
has answer: http://stackoverflow.com/a/50192299
has comment: http://stackoverflow.com/comment/87401792
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/123876061
type: AnswerComment
has text: Please delete your answer. It does not at all address the question. It is arguing to the OP to be inspired to use Google Cloud. In fact the OP is asking how to NOT use Collaboratory on Google Cloud.
type: Comment
comment on: http://stackoverflow.com/a/50194820
score: 0

http://stackoverflow.com/q/50135592
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/50148546
has body: lxml.etree.XMLSyntaxError, Document labelled UTF-16 but has UTF-8 content I am getting the error using lxml lib in python. Other solutions/hacks are replacing utf-16 to utf-8 in file php. What is the pythonic way to solve this? python code: import lxml.etree as etree tree = etree.parse("req.xml") req.xml: <?xml version="1.0" encoding="utf-16"?>
favorite count: 0
tagged with: utf-16
type: AnsweredQuestion
score: 3
tagged with: lxml
tagged with: python
tagged with: utf-8
accepted answer: http://stackoverflow.com/a/50150465
has comment: http://stackoverflow.com/comment/87289403
has answer: http://stackoverflow.com/a/50148546
has title: lxml.etree.XMLSyntaxError, Document labelled UTF-16 but has UTF-8 content
tagged with: http://stackoverflow.com/tag/xml
type: Question
has answer: http://stackoverflow.com/a/50150465
answer count: 2
has comment: http://stackoverflow.com/comment/87291351

http://stackoverflow.com/a/50163907
downvote count: 0
upvote count: 1
has body: You can use product method by importing it from itertools. my_list = ['a', ['a', 'b'], ['c', 'd', 'e']] list = list(itertools.product(*my_list)) print(list) Output [('a', 'a', 'c') ('a', 'a', 'd') ('a', 'a', 'e') ('a', 'b', 'c') ('a', 'b', 'd') ('a', 'b', 'e')]
score: 1
has comment: http://stackoverflow.com/comment/87346813
type: Answer
answers question: http://stackoverflow.com/q/50163877

http://stackoverflow.com/comment/94520018
type: AnswerComment
has text: Does it print properly? Because I've read that the website has anti-scraping restrictions. Here's a link for reference: https://stackoverflow.com/questions/52570401/https-preventing-website-scraping-in-python3
comment on: http://stackoverflow.com/a/50185020
type: Comment
score: 0

http://stackoverflow.com/q/50129208
answer count: 1
tagged with: tensorflow
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50129383
has body: I am going CRAZY trying to download tensorflow at the moment. I have tried many different things but I just either don't understand the instructions or it doesn't work for me. At the moment I am trying this: Download python 3.6 from https://www.anaconda.com/download/ Open Command Window as Administrator Type: conda create -n tensorflow pip python=3.6 activate tensorflow Type: pip install --upgrade tensorflow As per the tensorflow website I can execute this command: &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; hello = tf.constant('Hello, TensorFlow!') &gt;&gt;&gt; sess = tf.Session() &gt;&gt;&gt; print(sess.run(hello)) And it outputs Hello, TensorFlow! BUT I cannot create a new file through IDLE and execute that code - only in the command window Please help... of if you have a better solution for me I am all ears but very new to this so in need of simple instructions :) Thanks!
score: 0
has title: Downloading Tensorflow for Python - how do I get rid of this error?
tagged with: installation
has comment: http://stackoverflow.com/comment/87278688
type: UnansweredQuestion

http://stackoverflow.com/comment/87404206
type: AnswerComment
comment on: http://stackoverflow.com/a/50193364
has text: I don't get it. For some reason your solution runs 10 times slower than mine when timing.
score: 0
type: Comment

windows
tags question: http://stackoverflow.com/q/50182427
tags question: http://stackoverflow.com/q/50118919
tags question: http://stackoverflow.com/q/50143215
tags question: http://stackoverflow.com/q/50137512
tags question: http://stackoverflow.com/q/50209920
tags question: http://stackoverflow.com/q/50074881
type: Tag
tags question: http://stackoverflow.com/q/50219985
tags question: http://stackoverflow.com/q/50212416
tags question: http://stackoverflow.com/q/50213156
tags question: http://stackoverflow.com/q/50126109
tags question: http://stackoverflow.com/q/50221512
tags question: http://stackoverflow.com/q/50195080
tags question: http://stackoverflow.com/q/50152856
tags question: http://stackoverflow.com/q/50214775
tags question: http://stackoverflow.com/q/50086178
tags question: http://stackoverflow.com/q/50082649
tags question: http://stackoverflow.com/q/50175733
tags question: http://stackoverflow.com/q/50125864
tags question: http://stackoverflow.com/q/50210081
tags question: http://stackoverflow.com/q/50110474
tags question: http://stackoverflow.com/q/50229600
tags question: http://stackoverflow.com/q/50159567
tags question: http://stackoverflow.com/q/50084487
tags question: http://stackoverflow.com/q/50098379
tag name: windows
tags question: http://stackoverflow.com/q/50130997
tags question: http://stackoverflow.com/q/50119565
tags question: http://stackoverflow.com/q/50143360
tags question: http://stackoverflow.com/q/50176925
tags question: http://stackoverflow.com/q/50121192
tags question: http://stackoverflow.com/q/50122873
tags question: http://stackoverflow.com/q/50171922
tags question: http://stackoverflow.com/q/50160196

http://stackoverflow.com/comment/87425014
comment on: http://stackoverflow.com/q/50203984
type: Comment
has text: Like skiprows, there's another parameter called `usecols`. Use it to choose the columns you're interested in. And perhaps you have to set `delimiter` to '\s' for spaces explicitly.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87441881
type: QuestionComment
has text: Possible duplicate of [Printing Lists as Tabular Data](https://stackoverflow.com/questions/9535954/printing-lists-as-tabular-data)
type: Comment
comment on: http://stackoverflow.com/q/50212460
score: 2

http://stackoverflow.com/q/50119668
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87256840
tagged with: generator
has answer: http://stackoverflow.com/a/50119842
possible better answer: http://stackoverflow.com/a/50119842
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 3
answer count: 3
linked to: http://stackoverflow.com/q/25962114
has body: I am trying to create a datafrmae from fixedwidth file and load into postgresql database. My input file is very huge (~16GB) and 20Million records. So if i create dataframe it is consuming most of the available RAM. It is taking long time to complete. So i thought of using chunksize(using python generator) option and commit records to table. But it is failing with 'AttributeError: 'generator' object has no attribute 'to_sql' error. Inspired by this answer here https://stackoverflow.com/a/47257676/2799214 input file: test_file.txt XOXOXOXOXOXO9 AOAOAOAOAOAO8 BOBOBOBOBOBO7 COCOCOCOCOCO6 DODODODODODO5 EOEOEOEOEOEO4 FOFOFOFOFOFO3 GOGOGOGOGOGO2 HOHOHOHOHOHO1 sample.py import pandas.io.sql as psql import pandas as pd from sqlalchemy import create_engine def chunck_generator(filename, header=False,chunk_size = 10 ** 5): for chunk in pd.read_fwf(filename, colspecs=[[0,12],[12,13]],index_col=False,header=None, iterator=True, chunksize=chunk_size): yield (chunk) def _generator( engine, filename, header=False,chunk_size = 10 ** 5): chunk = chunck_generator(filename, header=False,chunk_size = 10 ** 5) chunk.to_sql('sample_table', engine, if_exists='replace', schema='sample_schema', index=False) yield row if __name__ == "__main__": filename = r'test_file.txt' engine = create_engine('postgresql://ABCD:ABCD@ip:port/database') c = engine.connect() conn = c.connection generator = _generator(engine=engine, filename=filename) while True: print(next(generator)) conn.close() Error: chunk.to_sql('sample_table', engine, if_exists='replace', schema='sample_schema', index=False) AttributeError: 'generator' object has no attribute 'to_sql' My Primary goal is to improve performance. Please help me in resolving the issue or please suggest better approach. Thanks in advance.
downvote count: 0
has comment: http://stackoverflow.com/comment/87256892
favorite count: 0
has title: AttributeError: 'generator' object has no attribute 'to_sql' While creating datframe using generator
type: Question
has answer: http://stackoverflow.com/a/50119776
score: 3
has comment: http://stackoverflow.com/comment/87256787
has answer: http://stackoverflow.com/a/50179495
accepted answer: http://stackoverflow.com/a/50179495
tagged with: pandas

http://stackoverflow.com/comment/87367377
score: 0
type: QuestionComment
has text: I would do: oldstr = '2018-03-16T18:00:00+01:00', newstr = oldstr.replace(":", ""), d = datetime.datetime.strptime(newstr, "%Y-%m-%dT%H%M%S%z).
type: Comment
comment on: http://stackoverflow.com/q/50175035

http://stackoverflow.com/comment/87377703
comment on: http://stackoverflow.com/a/50180068
type: Comment
score: 0
type: AnswerComment
has text: @SandeepDcunha But we aren't looking at the ticket number (which could very well be an alphanumeric "number"), we're looking at the tuple of `(line[36], line[37])` from the CSV file. However, I will agree that in many cases it _is_ better to use `if x is not None:` rather than simply `if x:`

http://stackoverflow.com/a/50078002
score: -2
type: Answer
answers question: http://stackoverflow.com/q/50077712
upvote count: 0
downvote count: 2
has body: for i, block in enumerate(a): if (block &lt; 0.2).flatten().any(): a[i] = np.ones(np.shape(block)) * 0.2 print(a) array([[[ 0.2 , 0.2 , 0.2 ], [ 0.2 , 0.2 , 0.2 ], [ 0.2 , 0.2 , 0.2 ]], [[ 0.28983508, 0.31122743, 0.67818926], [ 0.42720309, 0.24416101, 0.5469823 ], [ 0.22894097, 0.76159389, 0.80416832]], [[ 0.25661154, 0.64389696, 0.37555374], [ 0.87871659, 0.27806621, 0.3486518 ], [ 0.26388296, 0.8993144 , 0.7857116 ]]])

http://stackoverflow.com/comment/87293615
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50137159
has text: @Jean-FrançoisFabre Yep, done.

http://stackoverflow.com/comment/102007881
score: 2
type: AnswerComment
has text: When I use this method, the type of `dct` is still string
comment on: http://stackoverflow.com/a/50186126
type: Comment

http://stackoverflow.com/comment/87396214
comment on: http://stackoverflow.com/q/50189659
score: 0
type: Comment
has text: So show us your code (with relevant sample input) and we can help you fix it. Otherwise your question may be closed as unclear until you more clearly explain the actual problem you're having.
type: QuestionComment

http://stackoverflow.com/a/74078513
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50221980
type: Answer
answers question: http://stackoverflow.com/q/50221980
has body: You can set currentmodule to None before those objects: .. currentmodule:: None And, if later you have other objects for which you do want the current module to be prefixed, you can re-set the module as well: .. currentmodule:: your.module
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/50198057
possible better answer: http://stackoverflow.com/a/50198257
has comment: http://stackoverflow.com/comment/87413079
accepted answer: http://stackoverflow.com/a/50198778
has answer: http://stackoverflow.com/a/50198778
has comment: http://stackoverflow.com/comment/87412921
has answer: http://stackoverflow.com/a/50198257
has title: Python C API free() errors after using Py_SetPath() and Py_GetPath()
tagged with: python
has comment: http://stackoverflow.com/comment/87413074
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/87413385
has comment: http://stackoverflow.com/comment/87413510
tagged with: python-c-api
has comment: http://stackoverflow.com/comment/87413982
type: Question
has body: I'm trying to figure out why I can't simply get and set the python path through its C API. I am using Python3.6, on Ubuntu 17.10 with gcc version 7.2.0. Compiling with: gcc pytest.c `python3-config --libs` `python3-config --includes` #include &lt;Python.h&gt; int main() { Py_Initialize(); // removes error if put after Py_SetPath printf("setting path\n"); // prints Py_SetPath(L"/usr/lib/python3.6"); // Error in `./a.out': free(): invalid size: 0x00007fd5a8365030 *** printf("success\n"); // doesn't print return 0; } Setting the path works fine, unless I also try to get the path prior to doing so. If I get the path at all, even just to print without modifying the returned value or anything, I get a "double free or corruption" error. Very confused. Am I doing something wrong or is this a bug? Anyone know a workaround if so? Edit: Also errors after calling Py_Initialize();. Updated code. Now errors even if I don't call Py_GetPath() first.
score: 2
has comment: http://stackoverflow.com/comment/87412965
answer count: 2
has comment: http://stackoverflow.com/comment/87413621
has comment: http://stackoverflow.com/comment/87413198
upvote count: 3
has comment: http://stackoverflow.com/comment/87413030
has comment: http://stackoverflow.com/comment/87413401
has comment: http://stackoverflow.com/comment/87413162
downvote count: 1
has comment: http://stackoverflow.com/comment/87413392
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/87540632
has text: (*Spyder maintainer here*) What's your Spyder version?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50162165

http://stackoverflow.com/q/50145876
has title: Matching values from multiple txt files in Python
tagged with: python
has answer: http://stackoverflow.com/a/50146257
score: -3
tagged with: text
type: UnansweredQuestion
upvote count: 0
answer count: 1
downvote count: 3
tagged with: match
favorite count: 0
type: Question
tagged with: extract
has body: I have 2 txt files and I need to grab a value from fileA, match it with fileB and print the result. fileA contains userID, artistID and how many times artistID has been played. fileB contains artistID and the name of the artist. I need to write a function that will tell me how many times a certain user has played an artist. I need to print the name of the artist and the number of times. I got the pseudocode done but having trouble moving forward. def printListenersTimesPlayed(userID) find all artists and number of time they've been played from fileA find the name of the artist from fileB print list of artists and times that the user (userID) has played any help is appreciated!

http://stackoverflow.com/comment/87245458
type: QuestionComment
score: 0
has text: [Related.](https://stackoverflow.com/questions/31095461/how-to-replace-many-if-elif-statements-in-python)
comment on: http://stackoverflow.com/q/50114208
type: Comment

http://stackoverflow.com/comment/87259411
comment on: http://stackoverflow.com/q/50120823
score: 4
type: Comment
type: QuestionComment
has text: I can neither confirm nor deny that without your data (and I certainly need more than 1 row). You have only posted your code and output, both of which seem right to me. What would you have me do now?

http://stackoverflow.com/q/50200617
tagged with: gmail
has body: I try to open mails on gmail. I have the following code but it actually reads the mail on the console. I would like gmail detects the mail has been opened, because when I run the script on the console, the mail is not really opened. It is still in bold in my gmail. import imaplib, email user = 'xxx@gmail.com' password = 'xxx' imap_url = 'imap.gmail.com' def get_body(msg): if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None,True) con = imaplib.IMAP4_SSL(imap_url) con.login(user,password) con.select('INBOX') result, data = con.fetch(b'3','(RFC822)') raw = email.message_from_bytes(data[0][1]) print(get_body(raw)) if I mark message as seen, the message will look like I have read it but gmail or the sender of the message know I won't have read it
score: 1
has answer: http://stackoverflow.com/a/50200830
tagged with: email
linked to: http://stackoverflow.com/q/2251977
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87418204
has answer: http://stackoverflow.com/a/50202254
has title: python open mail vs read mail

http://stackoverflow.com/q/50108109
tagged with: coordinates
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50108303
has comment: http://stackoverflow.com/comment/87233888
tagged with: python
has title: Find the nearest set of coordinates in commandline
linked to: http://stackoverflow.com/q/28384055
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50108303
score: 1
has body: I'm looking for a commandline solution to find the nearest sets of points from a list of CSV coordinates. Here this was answered for Excel, but I need a somewhat different solution. I'm NOT looking for the nearest point for every point, but for the point pairs with least distance from each other. I would like to match many power plants from GEO, so a (python?) commandline tool would be great. Here is an example dataset: Chicoasén Dam,16.941064,-93.100828 Tuxpan Oil Power Plant,21.014891,-97.334492 Petacalco Coal Power Plant,17.983575,-102.115252 Angostura Dam,16.401226,-92.778926 Tula Oil Power Plant,20.055825,-99.276857 Carbon II Coal Power Plant,28.467176,-100.698559 Laguna Verde Nuclear Power Plant,19.719095,-96.406347 Carbón I Coal Power Plant,28.485238,-100.69096 Manzanillo I Oil Power Plant,19.027372,-104.319274 Tamazunchale Gas Power Plant,21.311282,-98.756266 The tool should print "Carbon II" and "Carbon I", because this pair has the minimal distance. A code fragment could be: from math import radians, cos, sin, asin, sqrt import csv def haversine(lon1, lat1, lon2, lat2): # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) km = 6371 * c return km with open('mexico-test.csv', newline='') as csvfile: so = csv.reader(csvfile, delimiter=',', quotechar='|') data = [] for row in so: data.append(row) print(haversine(28.467176,-100.698559,28.485238,-100.69096))
tagged with: geospatial
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50144045
has comment: http://stackoverflow.com/comment/87306477
has body: You are taking the mean of entire matrix X_train when you do np.mean(X_train). What you should do is take mean across the sample axis i.e. if your features are across columns and different samples are across rows, then replace np.mean(X_train) by np.mean(X_train, axis=0). This should solve the error. Including this line in the above code makes it work. Basically, np.mean(c4[test_index], axis=0) will given you a 1 x 30 mean vector instead of a scalar mean. from scipy.stats import multivariate_normal as mvn v = mvn(np.mean(c4[test_index], axis=0), X_train_cov + np.eye(30)) I had to add an identity matrix because I was getting a singular matrix error. However, that has to do with how c4 is defined and nothing to do with this code. Note that to avoid the singularity, you typically add a very small value on the diagonal and not an identity matrix. This is just for illustration.
has comment: http://stackoverflow.com/comment/87306507
accepted answer of: http://stackoverflow.com/q/50143825
has comment: http://stackoverflow.com/comment/87306377
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50143825
has comment: http://stackoverflow.com/comment/87306416
upvote count: 1
has comment: http://stackoverflow.com/comment/87306657
has comment: http://stackoverflow.com/comment/87306685
type: Answer

http://stackoverflow.com/comment/87383082
score: 0
type: Comment
type: QuestionComment
has text: Perhaps you don't need any class specific code: Just use `copy.copy` (or maybe `copy.deepcopy` if you need it) wherever you want to make the copy of an object.
comment on: http://stackoverflow.com/q/50182648

waveform
tag name: waveform
type: Tag
tags question: http://stackoverflow.com/q/50085735

http://stackoverflow.com/comment/87229567
has text: are you use a framework css?? or custom style css ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50106138
score: 0

http://stackoverflow.com/q/50164024
has comment: http://stackoverflow.com/comment/87346171
tagged with: counter
linked to: http://stackoverflow.com/q/10415028
tagged with: python
has body: I have a list of CSV files. I want to do a set of operations on each of them and then produce a counter dict and i want to cerate a master list containing individual counter dict from all CSV files. I want to parallelize processing each of the csv file and then return the counter dict from each file. I found a similar solution here : How can I recover the return value of a function passed to multiprocessing.Process? I used the solution suggested by David Cullen. This solution works perfectly for strings, but when I tried to return a counter dict or a normal dict. All the CSV files are processed until the send_end.send(result) and it hangs on there forever when executed and then throws a memory error. I am running this in a Linux server with more than sufficient memory for creating the list of counter dicts. I used the following code: import multiprocessing #get current working directory cwd = os.getcwd() #take a list of all files in cwd files = os.listdir(cwd) #defining the function that needs to be done on all csv files def worker(f,send_end): infile= open(f) #read liens in csv file lines = infile.readlines() #split the lines by "," and store it in a list of lists master_lst = [line.strip().split(“,”) for line in lines] #extract the second field in each sublist counter_lst = [ element[1] for element in master_lst] print “Total elements in the list” + str(len(counter_lst)) #create a dictionary of count elements a = Counter(counter_lst) # return the counter dict send_end.send(a) def main(): jobs = [] pipe_list = [] for f in files: if f.endswith('.csv'): recv_end, send_end = multiprocessing.Pipe(duplex=False) p = multiprocessing.Process(target=worker, args=(f, send_end)) jobs.append(p) pipe_list.append(recv_end) p.start() for proc in jobs: proc.join() result_list = [x.recv() for x in pipe_list] print len(result_list) if __name__ == '__main__': main() The error that i get is the following: Process Process-42: Traceback (most recent call last): File "/usr/lib64/python2.…
type: AnsweredQuestion
has title: How to return a counter dictionary from a function passed to multiprocessing?
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87346789
accepted answer: http://stackoverflow.com/a/50164605
answer count: 1
type: Question
tagged with: python-multiprocessing
tagged with: return
has answer: http://stackoverflow.com/a/50164605

http://stackoverflow.com/comment/87356914
comment on: http://stackoverflow.com/a/50169626
score: 0
has text: Sorry - one clarifying question. Can you explain the `func(...)` line. I assume this is my own bespoke function to do the interpolation across the z-grid rather than a standard python function
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87623073
type: QuestionComment
comment on: http://stackoverflow.com/q/50191723
score: 0
has text: Thank you Salix, this was what I was looking for.
type: Comment

http://stackoverflow.com/comment/87254987
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50112775
type: AnswerComment
has text: On which line? Did you use `time.sleep()` before that line?

http://stackoverflow.com/q/50228008
possible better answer: http://stackoverflow.com/a/57382223
has answer: http://stackoverflow.com/a/50228051
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/34399172
upvote count: 8
tagged with: encoding
accepted answer: http://stackoverflow.com/a/50228072
downvote count: 2
score: 6
has comment: http://stackoverflow.com/comment/87473261
tagged with: python
has answer: http://stackoverflow.com/a/50228072
has body: I try to read a CSV file in Python, but the first element in the first row is read like that ï»¿0, while the strange character isn't in the file, its just a simple 0. Here is the code I used: matriceDist=[] file=csv.reader(open("distanceComm.csv","r"),delimiter=";") for row in file: matriceDist.append(row) print (matriceDist)
answer count: 4
has answer: http://stackoverflow.com/a/57382223
type: AnsweredQuestion
has title: Strange character while reading a CSV file
has answer: http://stackoverflow.com/a/68202524
linked to: http://stackoverflow.com/q/34399172

http://stackoverflow.com/a/50185326
score: 1
has body: Do a curl or http request on subdomain which you want to verify, if you get 404 that means it doesn't exists, if you get 200 it definitely exists
type: Answer
answers question: http://stackoverflow.com/q/50185118
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87427145
type: Comment
comment on: http://stackoverflow.com/q/50205003
type: QuestionComment
score: 2
has text: Can you give a small example of purchase_data_df that could be run? I don't think your code is correct, it has syntax errors...

http://stackoverflow.com/comment/87378118
has text: @romainl i agree. I searched around and read that nerdtree may be causing the issue so I just decided to uninstalled it but nothing changed. Also, i can run python script in terminal and it creates the files but just isn't working in VIM for some reason.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50165273

http://stackoverflow.com/q/50195080
type: Question
has body: I've tried the installing Pytorch with Anaconda on a Windows 10 system but have gotten a variety of errors back with each attempt. I downloaded a windows compatible tar file of the package from https://anaconda.org/peterjc123/pytorch/files and was apparently able to get the the package installed using conda install filename.tar.bz2. By apparently, I mean that the Pytorch shows up in the list of packages available in the environment I set up for using Pytorch. But when I go to load the package I get this error: >>> import torch Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\conner\Anaconda3\envs\pytorch\lib\site-packages\torch\__init__.py", line 76, in <module> from torch._C import * ImportError: DLL load failed: The specified module could not be found. I also tried updating Anaconda with conda update --all which raised a relevant warning: (pytorch) C:\Users\User 1\Downloads>conda update --all Fetching package metadata ............. Solving package specifications: Warning: ['Dependency missing in current win-64 channels: \n - pytorch -> mkl >=2018'], skipping Fetching package metadata ............. Solving package specifications: Warning: ['Dependency missing in current win-64 channels: \n - pytorch -> mkl >=2018'], skipping NoPackagesFoundError: Dependency missing in current win-64 channels: - pytorch -> mkl >=2018 The mkl package also shows up in the list of packages connected to the pytorch environment. I interpret the error to mean that there isn't a recent enough version of mkl. Would that be correct? Any other insights or advice?
tagged with: installation
downvote count: 0
tagged with: pytorch
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50574928
favorite count: 0
has answer: http://stackoverflow.com/a/63249368
has answer: http://stackoverflow.com/a/54390600
tagged with: anaconda
answer count: 3
score: 1
tagged with: windows
tagged with: python
has title: Getting error when trying to get Pytorch working

http://stackoverflow.com/q/50101148
has comment: http://stackoverflow.com/comment/87219880
tagged with: django
tagged with: python
score: 4
tagged with: django-serializer
upvote count: 4
accepted answer: http://stackoverflow.com/a/50130691
type: AnsweredQuestion
has title: Django DRF - Different Request and Response Serialization
has comment: http://stackoverflow.com/comment/87219817
answer count: 1
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50130691
has body: I;ve an API endpoint that requests data in the below format:- { "platform": "value", "username": "value", "login_type": "value" } Now, I've a model :- class ModelA(models.Model): field1 = models.IntegerField() The request variables are not the part of the model, hence I create the following serializer:- class ModelASerializer(serializers.ModelSerializer): username = serializers.CharField() login_type = serializers.IntegerField() platform = serializers.ChoiceField(choices=User.PLATFORM_CHOICES) def create(self, data): platform, username = data.get('platform'), data.get('username') login_type = data.get('login_type') ###### some processing based on above input instance = ModelA.objects.create(field1=11111) return instance class Meta: model = ModelA fields = ('username', 'login_type', 'platform') read_only_fields = ('field1', ) When I POST the data, the error returned back is The serializer field might be named incorrectly and not match any attribute or key on the `ModelA` instance. Original exception text was: 'ModelA' object has no attribute 'username'. I understand that it tries to get_attr the fields from the instance object. How do I send back the response where INPUT request is different(ie unrelated to the model fields) and response is different(ie related to the model fields)?

http://stackoverflow.com/q/50082388
has comment: http://stackoverflow.com/comment/87180829
has title: Keras installation error
has comment: http://stackoverflow.com/comment/87180748
has comment: http://stackoverflow.com/comment/87180809
has comment: http://stackoverflow.com/comment/87180734
tagged with: python
has answer: http://stackoverflow.com/a/50082498
has comment: http://stackoverflow.com/comment/87180736
type: AnsweredQuestion
upvote count: 3
downvote count: 2
accepted answer: http://stackoverflow.com/a/50082498
answer count: 1
has comment: http://stackoverflow.com/comment/87180749
score: 1
has body: I'm using Anaconda, and I have already installed TensorFlow which works fine. Now I want to install keras. Here what i did: activate tensorflow pip install keras installation seems to be successful. after that i run idle and then to test correctness, i run this: from keras.models import Sequential and receive following error: Warning (from warnings module): File "C:\Users\ccc\AppData\Local\Continuum\anaconda3\envs\tensorflow\lib\site-packages\h5py__init__.py", line 36 from ._conv import register_converters as _register_converters FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type. Using TensorFlow backend. I thought maybe this is just a warning, and then I run jupyter notebook and then try to import stuff. Error is this: import seaborn as sns import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegressionCV from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.utils import np_utils ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-2-4f6dad112f73&gt; in &lt;module&gt;() 5 from sklearn.linear_model import LogisticRegressionCV 6 ----&gt; 7 from keras.models import Sequential 8 from keras.layers.core import Dense, Activation 9 from keras.utils import np_utils &gt; &gt; ModuleNotFoundError: No module named 'keras' EDIT i've done cd to folder where I want to do my project. print(sys.path) in idle returns this: ['', 'C:\\Users\\smuminov\\Desktop\\UC\\Spring-2018\\CS504\\Project\\Prediction', 'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\Scripts', 'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\python35.zip', 'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\DLLs', 'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\lib', 'C:\Users\smuminov\AppData\Local\C…
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87180742

http://stackoverflow.com/q/50175711
tagged with: autograd
type: Question
tagged with: gradient-descent
has comment: http://stackoverflow.com/comment/87369259
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/87368709
upvote count: 4
has body: I'm interested in Finding the Gradient of Neural Network output with respect to the parameters (weights and biases). More specifically, assume I have the following Neural Network Structure [6,4,3,1]. The input samples size is 20. What I'm interested in, is finding the gradient of Neural Network output w.r.t the weights (and biases), which if I'm not mistaken, in this case would be 47. In Literature , this gradient is sometimes known as Weight_Jacobian. I'm using Pytorch version 0.4.0 on Python 3.6 on Jupyter Notebook. The Code that I have produced is this: def init_params(layer_sizes, scale=0.1, rs=npr.RandomState(0)): return [(rs.randn(insize, outsize) * scale, # weight matrix rs.randn(outsize) * scale) # bias vector for insize, outsize in zip(layer_sizes[:-1],layer_sizes[1:])] layers = [6, 4, 3, 1] w = init_params(layers) first_layer_w = Variable(torch.tensor(w[0][0],requires_grad=True)) first_layer_bias = Variable(torch.tensor(w[0][1],requires_grad=True)) second_layer_w = Variable(torch.tensor(w[1][0],requires_grad=True)) second_layer_bias = Variable(torch.tensor(w[1][1],requires_grad=True)) third_layer_w = Variable(torch.tensor(w[2][0],requires_grad=True)) third_layer_bias = Variable(torch.tensor(w[2][1],requires_grad=True)) X = Variable(torch.tensor(X_batch),requires_grad=True) output=torch.tanh(torch.mm(torch.tanh(torch.mm(torch.tanh(torch.mm(X,first_layer_w)+first_layer_bias),second_layer_w)+second_layer_bias),third_layer_w)+third_layer_bias) output.backward() As it is obvious from the code, I'm using hyperbolic tangent as the Non Linearity. The code produces the output vector with length 20. Now, I'm interested in finding the Gradient of this Output vector w.r.t all the weights (all 47 of them). I have read the documentation of Pytorch at here. I have also seen similar questions for example, here. However, I have failed to find the gradient of output vector w.r.t parameters. If I use the Pytorch function backward(), it generates an error as RuntimeError: gra…
has answer: http://stackoverflow.com/a/76266263
answer count: 3
tagged with: pytorch
has answer: http://stackoverflow.com/a/59892526
downvote count: 0
has comment: http://stackoverflow.com/comment/87368586
has title: Pytorch: Gradient of output w.r.t parameters
has answer: http://stackoverflow.com/a/66885946
favorite count: 0

http://stackoverflow.com/comment/87196862
type: AnswerComment
has text: Omg, I didn't notice that my array was made of strings! When I read the file I create a list of lists and I read each entry as integer, float, or string. I don't get why numpy changes them all to strings...
comment on: http://stackoverflow.com/a/50090215
type: Comment
score: 0

http://stackoverflow.com/q/50099003
type: AnsweredQuestion
score: 0
answer count: 1
has body: I have the following code which works as expected: clf = Pipeline([ ('vectorizer', DictVectorizer(sparse=False)), ('classifier', DecisionTreeClassifier(criterion='entropy')) ]) clf.fit(X[:size], y[:size]) score = clf.score(X_test, y_test) I wanted to do the same logic without using Pipeline: v = DictVectorizer(sparse=False) Xdv = v.fit_transform(X[:size]) Xdv_test = v.fit_transform(X_test) clf = DecisionTreeClassifier(criterion='entropy') clf.fit(Xdv[:size], y[:size]) clf.score(Xdv_test, y_test) But I receive the following error: ValueError: Number of features of the model must match the input. Model n_features is 8251 and input n_features is 14303 It seems that DictVectorizer learns more features for the test set than for the training set. I want to know how does Pipeline handle this issue and how can I accomplish the same.
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50099038
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/87214511
tagged with: python
has answer: http://stackoverflow.com/a/50099038
has title: DictVectorizer learns more features for the training set
tagged with: numpy

http://stackoverflow.com/q/50198116
has title: Django Channels - Client receives only one message when Group.send() is called in a loop in consumers.py
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50202700
type: Question
has answer: http://stackoverflow.com/a/50202700
has body: I have built a Django app which runs automated testing. I collect the inputs from the user, as to what all tests need to be run and when the user clicks on submit button, the tests run for a few hours to a couple of days (depending on the number of tests selected) and once all the tests are completed, the results are showed on a template. Now the problem is, till all the tests are completed, the user is not updated with the progress. So I decided to use Django Channles to provide live update to the client as and when I have results for individual tests. With my implementation, I call the Group('user-1').send({'text': i}) method in a for loop. But all I see in the template is only the output of the last Group('user-1').send({'text': i}) operation. As per my requirement, once Group('user-1').send({'text': i}) is called, the socket.onmessage() function in the section of my template should receive the message and should again wait for messages sent by subsequent Group('user-1').send({'text': i}) calls. I saw a very similar question here which is already answered, but the solution is not working for me. Please help me identify what needs to corrected in my code, shown below. consumers.py ------------ @channel_session_user_from_http def ws_connect(message, **kwargs): http_user = message.user if not http_user.is_anonymous: message.reply_channel.send({'accept': True}) Group('user-'+str(http_user.id)).add(message.reply_channel) def ws_message(message): for i in my_results_list: Group('user-1').send({'text': i}) sleep(1) results.html ------------ &lt;script&gt; // Note that the path doesn't matter for routing; any WebSocket // connection gets bumped over to WebSocket consumers socket = new WebSocket("ws://" + window.location.host + "/task/summary/"); socket.onopen = function() { socket.send("Hello"); } socket.onmessage = function(message) { document.getElementById("demo").innerHTML = message.data; } socket.onmessage() // Call onopen directly if socket is already open // if (s…
tagged with: django-channels
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/46287849
answer count: 1

http://stackoverflow.com/q/50090052
has body: I am working on a project involving object detection through deep learning, with the underlying detection code written in C. Due to the requirements of the project, this code has a Python wrapper around it, which interfaces with the required C functions through ctypes. Images are read from Python, and then transferred into C to be processed as a batch. In its current state, the code is very unoptimized: the images (640x360x3 each) are read using cv2.imread then stacked into a numpy array. For example, for a batch size of 16, the dimensions of this array are (16,360,640,3). Once this is done, a pointer to this array is passed through ctypes into C where the array is parsed, pixel values are normalized and rearranged into a 2D array. The dimensions of the 2D array are 16x691200 (16x(640*360*3)), arranged as follows. row [0]: Image 0: (B)r0(B)r1(B)r2.... (G)r0(G)r1(G)r2.... (R)r0(R)r1(R)r2.... row [1]: Image 1: (B)r0(B)r1(B)r2.... (G)r0(G)r1(G)r2.... (R)r0(R)r1(R)r2.... . . row [15]: Image 15: (B)r0(B)r1(B)r2.... (G)r0(G)r1(G)r2.... (R)r0(R)r1(R)r2.... ` The C code for doing this currently looks like this, where the pixel values are accessed through strides and arranged sequentially per image. nb is the total number of images in the batch (usually 16); h, w, c are 360,640 and 3 respectively. matrix ndarray_to_matrix(unsigned char* src, long* shape, long* strides) { int nb = shape[0]; int h = shape[1]; int w = shape[2]; int c = shape[3]; matrix X = make_matrix(nb, h*w*c); int step_b = strides[0]; int step_h = strides[1]; int step_w = strides[2]; int step_c = strides[3]; int b, i, j, k; int index1, index2 = 0; for(b = 0; b &lt; nb ; ++b) { for(i = 0; i &lt; h; ++i) { for(k= 0; k &lt; c; ++k) { for(j = 0; j &lt; w; ++j) { index1 = k*w*h + i*w + j; index2 = step_b*b + step_h*i + step_w*j + step_c*k; X.vals[b][index1] = src[index2]/255.; } } } } return X; } And the corresponding Python code that calls this function: (array is the original numpy array) for i in range(start, …
linked to: http://stackoverflow.com/q/33665241
tagged with: python
has title: Efficient way to read a set of 3 channel images from Python into a two dimensional array to be used in C
tagged with: http://stackoverflow.com/tag/c
score: 2
tagged with: numpy
linked to: http://stackoverflow.com/q/49582252
has answer: http://stackoverflow.com/a/50098112
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
type: Question
tagged with: ctypes

http://stackoverflow.com/comment/87170643
type: AnswerComment
score: 0
has text: Thank you @Megalng ! I usually do print to check if my code is working. Although I understand what your code is checking, I still get this error when I run it: "TypeError: is_narcissistic() takes 1 positional argument but 3 were given" - should I use try/ except?
comment on: http://stackoverflow.com/a/50077160
type: Comment

http://stackoverflow.com/comment/109209537
comment on: http://stackoverflow.com/a/51693060
has text: `ENCODING = 'utf8'`
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87359212
comment on: http://stackoverflow.com/q/50170967
score: 1
type: Comment
type: QuestionComment
has text: I can run your code without any error! what's version of your Python?

http://stackoverflow.com/a/50130691
answers question: http://stackoverflow.com/q/50101148
type: Answer
has body: I solved the above problem settings field as write_only = True. class ModelASerializer(serializers.ModelSerializer): username = serializers.CharField(write_only = True) login_type = serializers.IntegerField(write_only = True) platform = serializers.ChoiceField(choices=User.PLATFORM_CHOICES, write_only = True)
accepted answer of: http://stackoverflow.com/q/50101148
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50224637
favorite count: 0
has title: pip3 psutil cannot install newer version
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/87486902
downvote count: 1
linked to: http://stackoverflow.com/q/34857242
score: 3
tagged with: distutils
tagged with: python
has body: I am trying to install odoo 11.0 but when installing requirements it shows me this: Cannot uninstall 'psutil'. 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 How can I uninstall it or upgrade to other version? I already remove the files of psutil but it still sh.ows the same message
tagged with: psutil

http://stackoverflow.com/comment/87395345
score: 1
has text: Ok, i was able to get the 10 plotted using your code. Not sure why you're getting a blank map. Out of curiosity, does saving your map and opening it in the browser work? And what browser are you using?
comment on: http://stackoverflow.com/q/50162521
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87382711
has text: The advantage `fwd` provides is sequencing calls using ` \ (...) \ (...) ...` or arbitrary limit without having to nest parentheses `(...(...(...)))`. It's just an example to demonstrate you can invent your own convenience, of course within the boundaries set by python's parser :D
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50182047
type: AnswerComment

http://stackoverflow.com/q/50200097
tagged with: movefile
score: 0
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/87416944
type: Question
has title: Python - os.rename(), moving a *.sqlite ddbb form one folder to another
has comment: http://stackoverflow.com/comment/87416900
answer count: 0
has comment: http://stackoverflow.com/comment/87416919
type: UnansweredQuestion
has body: I am having some troubles moving one *.sqlite ddbb that I've created from one folder to another. this is my attempt: Import os Import sqlite3 Import pandas as pd #There is some code here to get my pandas dataframe Then the goal of the following code is: To create a sqlite ddbb from a pandas dataframe (dfGlobalProcess) and then move it to another subfolder named "Projects_ddbb".If I could save it directly to this another folder it would be great. This is the code: ddbbName='ExampleProject1' #I know this line does nothing right now... but in the future this should be an user input ddbbName2= ddbbName + '.sqlite' conn = sqlite3.connect('' + ddbbName2 +'') dfGlobalProcess.to_sql('ProcessesElemFlows', conn, index=False, if_exists='replace') conn.close() prevName='' + ddbbName2 + '' newName='Projects_ddbb/' + prevName + '' os.rename(prevName,newName) When I run this code I get the following error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'ExampleProject1.sqlite' -&gt; 'Projects_ddbb/ExampleProject1.sqlite' I've searched for solutions here in stackoverflow but I am not able to figure out how to solve it if I run the same code but moving a *.txt file that is in the same folder in which the ddbb is stored, the *.txt file is moved to the 'Projects_ddbb' folder as expected. It looks like I have the ddbb opened in some way, but as I am fairly new to Python and programming in general I don't have any idea how to proceed. I've also tried something like this, but I don't know if it makes any sense... probably not because it does not work: os.close('ExampleProject1.sqlite') Any help will be much appreciated.

http://stackoverflow.com/a/50123032
has body: There are several discussions of this, here and elsewhere. There is no direct way to do what you want. The recommended approach is to install pyenv via brew, and use pyenv to manage the different versions of Python on your system. The github repo has a very detailed and clear guide on usage: https://github.com/pyenv/pyenv
type: AcceptedAnswer
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/50121569
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/87344806
has comment: http://stackoverflow.com/comment/92413883
answers question: http://stackoverflow.com/q/50121569

http://stackoverflow.com/q/50125864
tagged with: python
tagged with: numpy
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87269795
has title: How to upgrade numpy on windows with out pip?
answer count: 1
tagged with: pip
has comment: http://stackoverflow.com/comment/87269914
has comment: http://stackoverflow.com/comment/87269749
type: Question
has comment: http://stackoverflow.com/comment/87269860
has body: I need to upgrade to numpy 1.14.3 on a Windows computer. I tried using pip install numpy --upgrade in the command line and got 'pip' is not recognized as an internal or external command, operable program or batch file. and the same message that pyton is not recognized when I try python pip install numpy. Based on some googling it seems the issue is because python or pip are not added to the path. However, I am using a school computer and cannot access any advanced settings in order to add pip to path. Is there an alternative command line upgrade method for numpy on windows?
accepted answer: http://stackoverflow.com/a/50126006
has answer: http://stackoverflow.com/a/50126006
tagged with: windows

http://stackoverflow.com/comment/87471618
type: Comment
has text: I just updated the question, Sorry for the misunderstanding. I hope now it is clearly.
type: AnswerComment
comment on: http://stackoverflow.com/a/50227226
score: 0

http://stackoverflow.com/comment/87241605
has text: Interesting, could you please post the complete error message trace. I am curious to see what is happening underneath
comment on: http://stackoverflow.com/a/50112159
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87233713
has text: @cjonesrun , I don't need a month to be displayed before a selection is made, I just want to know what types of things could be interfering with the button's appearance like in my screenshots
score: 0
comment on: http://stackoverflow.com/q/50092357
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87302853
type: AnswerComment
comment on: http://stackoverflow.com/a/50142126
score: 0
type: Comment
has text: @user490418: If you're interested in how to do this without renaming variables, I've added a function to my answer that generates the random walk quickly.

http://stackoverflow.com/comment/87428162
type: QuestionComment
comment on: http://stackoverflow.com/q/50205543
score: 0
has text: What have you tried so far? `data = {row[0]:row[1:] for row in (line.strip().split() for line in open(filename))}` may do the trick
type: Comment

http://stackoverflow.com/comment/87371363
has text: @ImportanceOfBeingErnest No, it won't be wrongly labelled. All I care is that the labels' boundary values are integers. It doesn't matter whether a certain region is labelled as the category A or B, if the categories are separated by the integer values. :)
comment on: http://stackoverflow.com/q/50152057
score: 0
type: Comment
type: QuestionComment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/50099151
tags question: http://stackoverflow.com/q/50090252
tag name: kivy-language
tags question: http://stackoverflow.com/q/50164535

http://stackoverflow.com/q/50088700
type: AnsweredQuestion
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50088791
downvote count: 1
accepted answer: http://stackoverflow.com/a/50088791
favorite count: 0
type: Question
tagged with: python
score: -1
has body: size = 3 for line in range (1, size +1): for asterisk in range(1, line +1): print ('*', end = '') print() This code produces * ** *** I have been asked to alter the code so that it reverses the asterisk 'triangle' like so: * ** *** I can't figure out how to do it and I'm really struggling to understand what the loops are doing and how I would alter the code to produce the correct triangle. I'm offered a hint of: "spaces can be produced using print(' ', end = '') and also: "Notice that we want the first line to start to start with two spaces, the second with a space and the last with none. We can get this value in each case by subtracting the number of the line from the size of the triangle (3) and adding 1" As far as I understand the second point, it should be size - line + 1 , right? What I don't understand is how to build this into the loop. As far as I can understand, I need to change the second nested loop but, I can't for life of me figure out how as every attempt I have made results in something like this: * * * * * *
has title: Nested Python Loops - How to create a reversed triangle
has comment: http://stackoverflow.com/comment/87193384

http://stackoverflow.com/comment/87281365
comment on: http://stackoverflow.com/a/50131178
score: 0
type: Comment
type: AnswerComment
has text: This worked for me

http://stackoverflow.com/comment/87514210
type: QuestionComment
comment on: http://stackoverflow.com/q/50177258
score: 0
has text: I see that now. The main problem is we can't *reproduce* your error. A description is great, but what would *really* help is if you were able to [edit](https://stackoverflow.com/posts/50177258/edit) your question with an example demonstrating the problem (either Wen's or mine, doesn't matter whose). I've tested my solution with your data and it seems to work.
type: Comment

http://stackoverflow.com/q/50079365
tagged with: pandas
has body: I have an example dataframe listed as below. Because we need to choose from the rows which E column is 1, so the result should be among the first 4 rows. Choosing from which A column is the largest, we have the first 3 rows. So we need to see among those which B column is the largest. Since we have a tie again, we should see the column C and find the largest. Finally we get the first column. A B C D E 4 4 3 1 1 4 2 0 0 1 4 4 1 1 1 3 0 0 0 1 5 0 0 1 0 So the desired output is like this: A B C D E 4 4 3 1 1
has answer: http://stackoverflow.com/a/50079446
accepted answer: http://stackoverflow.com/a/50079446
tagged with: dataframe
tagged with: python
has title: Python pandas dataframe: find the row which E column is 1 and A column is the largest, in case of ties, consider the largest of B, of C, of D column
type: Question
answer count: 1
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87232142
comment on: http://stackoverflow.com/q/50106609
type: Comment
type: QuestionComment
has text: Just feed that error to a random search engine or into the search field above.
score: 0

http://stackoverflow.com/a/77005147
downvote count: 0
has comment: http://stackoverflow.com/comment/137606037
score: 3
has body: Keeping here as a reference. In case one wants to kill all running processes on the gpu, following command would work: nvidia-smi --query-compute-apps=pid --format=csv,noheader | xargs -n1 kill -9
type: Answer
answers question: http://stackoverflow.com/q/50193538
upvote count: 3

http://stackoverflow.com/q/50106007
has answer: http://stackoverflow.com/a/50109919
has comment: http://stackoverflow.com/comment/87229303
type: Question
upvote count: 2
tagged with: django-orm
has comment: http://stackoverflow.com/comment/87230437
linked to: http://stackoverflow.com/q/35338867
tagged with: django
tagged with: django-models
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87229302
score: 2
tagged with: sql
has title: Django ORM - LEFT OUTER JOIN with two columns?
downvote count: 0
answer count: 1
favorite count: 0
has body: This is the relevant code: class Book(models.Model): name = models.CharField(max_length=50) class BookNote(models.Model): text = models.CharField(max_length=50) book = models.ForeignKey(Book) user = models.ForeignKey(settings.AUTH_USER_MODEL) class Meta: unique_together = [('book', 'user'), ] Now, for a specific user in the website: I want to query all the books (all the table). And, For each book object, If the user has a BookNote for the book - get it, otherwise booknote should be null. This is how I would do that with SQL (works): SELECT book.name, booknote.text FROM book LEFT OUTER JOIN booknote ON (book.id = booknote.book_id AND booknote.user_id = {user_id_here}) This is what I've tried, does not work: qs = Book.objects.filter(Q(booknote__user_id=user_id_here) | Q(booknote__isnull=True)) I examine qs.query and I see why - Django uses WHERE clause to filter by user_id, so I don't get all the books. How can I do the same query with django ORM? Without raw sql?

http://stackoverflow.com/q/50181642
tagged with: python
has comment: http://stackoverflow.com/comment/87389345
downvote count: 1
linked to: http://stackoverflow.com/q/46793110
type: AnsweredQuestion
score: 3
answer count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/87389401
accepted answer: http://stackoverflow.com/a/50206789
has comment: http://stackoverflow.com/comment/87401325
has title: Using VotingClassifier with other classifiers inside a Sklearn Pipeline
has body: I want to use the VotingClassifier inside a sklearn Pipeline, where I defined a set of classifiers .. I got some intuition from this question: Using VotingClassifier in Sklearn Pipeline to build the code below, but in this question each of the classifiers are defined in an independent Pipeline .. I don't want to use it in this way, where I have a set of features are prepared before and its not a good idea to repeat the generation of these features in multi Pipelines with different classsifiers (Time-consuming process)! How could I achieve that?! model = Pipeline([ ('feat', FeatureUnion([ ('tfidf', TfidfVectorizer(analyzer='char', ngram_range=(3, 5), min_df=0.01, lowercase=True, tokenizer=tokenizeTfidf)), ])), ('pip1', Pipeline([('clf1', GradientBoostingClassifier(n_estimators=1000, random_state=7))])), ('pip2', Pipeline([('clf2', SVC())])), ('pip3', Pipeline([('clf3', RandomForestClassifier())])), ('clf', VotingClassifier(estimators=["pip1", "pip2", "pip3"])) ]) clf = model.fit(X_train, y_train) but I got this error: ('clf', VotingClassifier(estimators=["pip1", "pip2", "pip3"])), File "C:\Python35\lib\site-packages\imblearn\pipeline.py", line 115, in __init__ self._validate_steps() File "C:\Python35\lib\site-packages\imblearn\pipeline.py", line 139, in _validate_steps "(but not both) '%s' (type %s) doesn't)" % (t, type(t))) TypeError: All intermediate steps of the chain should be estimators that implement fit and transform or sample (but not both) 'Pipeline(memory=None, steps=[('clf1', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.1, loss='deviance', max_depth=3, max_features=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=1000, presort='auto', random_state=7, subsample=1.0, verbose=0, warm_start=False))])' (type &lt;class 'imblearn.pipeline.Pipeline'&gt;) doesn't)
has answer: http://stackoverflow.com/a/50206789
tagged with: machine-learning
tagged with: imblearn

http://stackoverflow.com/q/50096368
has comment: http://stackoverflow.com/comment/87209013
answer count: 0
has body: say string = " hello world I am super happy today " Using BeautifulSoup, is there a way for me to get an array that store the indices of the char 'h' only if it was matched outside of a html tag? >>> [16, 46]
tagged with: string
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87209157
has comment: http://stackoverflow.com/comment/87213436
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87209171
has title: Get Array containing indecies of matched strings outside HTML Tags - Python
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/87208994
score: 0

http://stackoverflow.com/comment/87451728
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50162738
has text: @GrahamDumpleton I added another update (2) above after setting the `python-path` option
score: 0

http://stackoverflow.com/q/50090868
score: 33
has answer: http://stackoverflow.com/a/50304150
has body: This is not a duplicate of Assignment inside lambda expression in Python, i.e., I'm not asking how to trick Python into assigning in a lambda expression. I have some λ-calculus background. Considering the following code, it looks like Python is quite willing to perform side-effects in lambda expressions: #!/usr/bin/python def applyTo42(f): return f(42) def double(x): return x * 2 class ContainsVal: def __init__(self, v): self.v = v def store(self, v): self.v = v def main(): print('== functional, no side effects') print('-- print the double of 42') print(applyTo42(double)) print('-- print 1000 more than 42') print(applyTo42(lambda x: x + 1000)) print('-- print c\'s value instead of 42') c = ContainsVal(23) print(applyTo42(lambda x: c.v)) print('== not functional, side effects') print('-- perform IO on 42') applyTo42(lambda x: print(x)) print('-- set c\'s value to 42') print(c.v) applyTo42(lambda x: c.store(x)) print(c.v) #print('== illegal, but why?') #print(applyTo42(lambda x: c.v = 99)) if __name__ == '__main__': main() But if I uncomment the lines print('== illegal, but why?') print(applyTo42(lambda x: c.v = 99)) I'll get SyntaxError: lambda cannot contain assignment Why not? What is the deeper reason behind this? As the code demonstrates, it cannot be about “purity” in a functional sense. The only explanation I can imagine is that assignemts do not return anything, not even None. But that sounds lame and would be easy to fix (one way: make lambda expressions return None if body is a statement). Not an answer: Because it's defined that way (I want to know why it's defined that way). Because it's in the grammar (see above). Use def if you need statements (I did not ask for how to get statements into a function). “This would change syntax / the language / semantics” would be ok as an answer if you can come up with an example of such a change, and why it would be bad.
has comment: http://stackoverflow.com/comment/87198186
has answer: http://stackoverflow.com/a/50090883
upvote count: 36
downvote count: 3
has comment: http://stackoverflow.com/comment/87197947
linked to: http://stackoverflow.com/q/6282042
has comment: http://stackoverflow.com/comment/87215770
has answer: http://stackoverflow.com/a/50091199
has answer: http://stackoverflow.com/a/50269769
tagged with: lambda
answer count: 7
has answer: http://stackoverflow.com/a/50217880
favorite count: 0
tagged with: side-effects
has comment: http://stackoverflow.com/comment/87197893
has answer: http://stackoverflow.com/a/50090916
has title: Why are assignments not allowed in Python's `lambda` expressions?
has comment: http://stackoverflow.com/comment/87617174
has answer: http://stackoverflow.com/a/50191203
tagged with: python-internals
type: Question
has comment: http://stackoverflow.com/comment/87197942
has comment: http://stackoverflow.com/comment/87197968
tagged with: python
has comment: http://stackoverflow.com/comment/87198033
type: UnansweredQuestion

http://stackoverflow.com/q/50222747
has comment: http://stackoverflow.com/comment/87463136
linked to: http://stackoverflow.com/q/576169
has title: AttributeError: 'Application' object has no attribute 'tk'
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: attributeerror
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50223457
answer count: 1
has body: I have the following script, which uses Tkinter: import tkinter as tk class Application(tk.Frame): def __init__(self, master): frame = tk.Frame(master) frame.pack self.PRINT = tk.Button(frame, text = 'Print', fg = 'Red', command = self.Print()) self.PRINT.pack(side = 'left') self.QUIT = tk.Button(frame, text = 'Quit', fg = 'Red', command = self.quit()) self.QUIT.pack(side = 'left') def Print(self): print('at least somethings working') root = tk.Tk() b = Application(root) root.mainloop() When I run it, I get the following error: AttributeError: 'Application' object has no attribute 'tk' Why do I get this error?
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50223457
tagged with: tkinter
upvote count: 2
has comment: http://stackoverflow.com/comment/87463110

http://stackoverflow.com/comment/87173162
type: QuestionComment
has text: @Mr.Robot Try with my answer
comment on: http://stackoverflow.com/q/50077356
score: 0
type: Comment

http://stackoverflow.com/comment/87186556
comment on: http://stackoverflow.com/a/50085311
type: Comment
has text: it's only example. pos_tag must tagging oryginal words for example: NN, NNP, JJ etc. by word from col1 in sentence with different letter case (AAA1, aaa1, AaAa1 etc.)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87379111
type: Comment
type: QuestionComment
has text: Ask yourself if you are *linking* an instance of `A` to an instance of `B`, or *initializing* an instance of `B` with an instance of `A`. Whichever it is, add a comment to that effect.
score: 1
comment on: http://stackoverflow.com/q/50180005

http://stackoverflow.com/comment/87409624
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50196300
score: 0
has text: @abccd its pointed to the ":" right before "str, *args, **kwargs)"

http://stackoverflow.com/q/50137563
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50137592
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
has title: output of an if loop in different templates python
has comment: http://stackoverflow.com/comment/87293641
has comment: http://stackoverflow.com/comment/87293754
accepted answer: http://stackoverflow.com/a/50137592
type: Question
has body: My project is about shape detection, I have to detect the different rectangle in a given image and then import these data into a .qml file, I've been able to do so, but the problem is that the output in the console(I'm using Spyder) is n templates (.qml) with n is the number of the rectangles in the image, and in my folder there is only one .qml file ( the last one in the console) I don't knw where is my mistake. U'll find below an extract of my code: if shape == "rectangle": x,y,w,h = cv2.boundingRect(c) cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),0) myfile.write('The cordinations of the rectangle are :\n') myfile.write('x : '+str(x)+'\n') myfile.write('y : '+str(y)+'\n') myfile.write('width : '+str(w)+'\n') myfile.write('height : '+str(h)+'\n') # Open template file and pass string to 'data'. # Will be in QML syntax except with the string.Template replace tags # with the format of '$var'. The 'var' MUST correspond to the items # that will be calculated (i.e. coordinates, sizes, ids, etc.) with open('cordinations.txt', 'r') as my_template: data = my_template.read() # Print template for visual cue. print('Template loaded:') print(data) # Pass 'data' to string.Template object data_template. data_template = string.Template(data) cordinates=[] cordinates.append(dict(abscisse=x,ordonee=y,width=w,height=h)) t=Template(""" x: $abscisse y: $ordonee w: $width h: $height """) print " Rectangle:" print(" {") for data in cordinates: print (t.substitute(data)) print(" }") # Open QML output file and fill its contents by string substitution with open("main.qml", 'w') as output_file: # Run string.Template substitution on data_template # using data from 'values' as source and write to 'output_file'. output_file.write('import QtQuick 2.2') output_file.write('\nItem') output_file.write(" \n{") output_file.write(" id:\n") output_file.write(' height: '+str(height)+'\n') output_file.write(' width: '+str(width)+'\n') if shape == 'rectangle': output_file.write(' \n\n Rectangle') output_f…
has comment: http://stackoverflow.com/comment/87294200
answer count: 1

http://stackoverflow.com/a/50092991
score: 7
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50089400
upvote count: 7
has body: You can access parameter elements with operation.input.body.type.elements, which is a list of tuples containing element objects. These objects contain information such as the type. (Pdb) operation.input.body.type.elements [('MarketplaceDomain', &lt;Element(name='MarketplaceDomain', type=&lt;zeep.xsd.types.builtins.String object at 0x7f1bd8a4b320&gt;)&gt;), ('AWSAccessKeyId', &lt;Element(name='AWSAccessKeyId', type=&lt;zeep.xsd.types.builtins.String object at 0x7f1bd8a4b320&gt;)&gt;), ('AssociateTag', &lt;Element(name='AssociateTag', type=&lt;zeep.xsd.types.builtins.String object at 0x7f1bd8a4b320&gt;)&gt;), ('Validate', &lt;Element(name='Validate', type=&lt;zeep.xsd.types.builtins.String object at 0x7f1bd8a4b320&gt;)&gt;), ('XMLEscaping', &lt;Element(name='XMLEscaping', type=&lt;zeep.xsd.types.builtins.String object at 0x7f1bd8a4b320&gt;)&gt;), ('Shared', &lt;Element(name='Shared', type=&lt;zeep.xsd.dynamic_types.BrowseNodeLookupRequest object at 0x7f1bd8177e48&gt;)&gt;), ('Request', &lt;Element(name='Request', type=&lt;zeep.xsd.dynamic_types.BrowseNodeLookupRequest object at 0x7f1bd8177e48&gt;)&gt;)] (Pdb) operation.input.body.type.elements[0][1].name 'MarketplaceDomain' (Pdb) operation.input.body.type.elements[0][1].type.name 'string' (Pdb) operation.input.body.type.elements[0][1].is_optional True
type: Answer
accepted answer of: http://stackoverflow.com/q/50089400

http://stackoverflow.com/q/50165734
tagged with: python
has answer: http://stackoverflow.com/a/50165870
has title: Native coroutine and StopIteration
tagged with: asynchronous
type: Question
has body: Consider this simple coroutine In [9]: async def coro(): ...: print('hello world') ...: We know that that native coroutines are not iterators In [12]: type(c) Out[12]: coroutine In [13]: next(c) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-13-e846efec376d&gt; in &lt;module&gt;() ----&gt; 1 next(c) TypeError: 'coroutine' object is not an iterator However, if I run a coroutine, I get a StopIteration error. In [10]: c = coro() In [11]: c.send(None) hello world --------------------------- StopIteration Traceback (most recent call last) &lt;ipython-input-11-d9162d5dda48&gt; in &lt;module&gt;() ----&gt; 1 c.send(None) StopIteration: this answers that native co-routines are functionally equivalent to generated based coroutines. But another answer for the same question goes further and explains how they serve separate purposes as well. Is the only reason that native coros raise StopIteration error is that they share significant code with generator based coros? or there is some other reason as well?
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/32582573
accepted answer: http://stackoverflow.com/a/50165870
score: 1

http://stackoverflow.com/a/53717912
has body: So, apparently Sqlite3's CLI does not come installed with Python (Python 3.6). What comes pre-installed is Python's Sqlite3 library.So, you can access the Sqlite3 DB either through the library, or by manually installing Sqlite3 CLI.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50205804

python-3.5
tags question: http://stackoverflow.com/q/50139318
tags question: http://stackoverflow.com/q/50076325
type: Tag
tags question: http://stackoverflow.com/q/50186758
tags question: http://stackoverflow.com/q/50213285
tags question: http://stackoverflow.com/q/50102289
tags question: http://stackoverflow.com/q/50226701
tags question: http://stackoverflow.com/q/50132627
tags question: http://stackoverflow.com/q/50162139
tags question: http://stackoverflow.com/q/50225173
tag name: python-3.5
tags question: http://stackoverflow.com/q/50224895
tags question: http://stackoverflow.com/q/50113949

http://stackoverflow.com/comment/87304133
type: Comment
type: QuestionComment
score: 0
has text: Thanks for your comment @WarrenWeckesser, your assumption is correct. I will give it a try and let you know if it works.
comment on: http://stackoverflow.com/q/50140371

http://stackoverflow.com/a/53398262
type: Answer
answers question: http://stackoverflow.com/q/50086651
upvote count: 3
score: 3
has body: Since you allude to having used ggplot2 and facet_grid()/facet_wrap(), you should check out plotnine. From the homepage: (ggplot(mtcars, aes('wt', 'mpg', color='factor(gear)')) + geom_point() + stat_smooth(method='lm') + facet_wrap('~gear')) I was a long time R user and frankly found the python plotting landscape to be sort of a mess. I love being able to use plotnine to leverage past R experience vs. re-learning the wheel. Now, the caveat is I came to this answer looking for a true grid.arrange(), as facets aren't as flexible. I want 6 mini-plots one one side and a true separate plot on the canvas on the other. This won't do that for me, but figured I'd add an answer here anyway while swinging by :)
downvote count: 0

http://stackoverflow.com/comment/87246151
has text: There is a discussion on the website you link - explore the data first. Look out for things like 3+ in there.
type: QuestionComment
comment on: http://stackoverflow.com/q/50114546
score: 0
type: Comment

http://stackoverflow.com/q/50146327
has answer: http://stackoverflow.com/a/50146423
downvote count: 0
has comment: http://stackoverflow.com/comment/87310823
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50146497
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50146375
has body: I'm making a program where a user can upload a .csv file, then the contents will be displayed, then the file will be manipulated, then the manipulated file will be sent as an attachment to an email. My problem is, python is not recalling the 'fname' in the SortingCSV and UploadAction functions. So I can't do anything with the displayed .csv file content. Here's the error I get: NameError: name 'fname' is not defined def load_file(self): #Upload a CSV file and display its contents fname = askopenfilename(filetypes=(("CSV files", "*.csv"), ("HTML files", "*.html;*.htm"), ("All files", "*.*") )) print(fname) print('The file has been uploaded, contents are displayed below') import csv with open(fname) as f: reader = csv.reader(f) for row in reader: print(" ".join(row)) def SortingCSV(self): #Allows user to switch the contents of the file to the desired ings print(fname) print("Tkinter is easy to use!") def UploadAction(self): #Allows user to send the converted file to website import smtplib content = 'Here is your completed file' attach = (fname.csv) mail = smtplib.SMTP('smtp.gmail.com',587) mail.ehlo() mail.starttls() mail.login('[insert email]','[insert password]') mail.sendmail('[insert email]','[insert recipient]',content) mail.close() print("The file has been sent to your inbox") if __name__ == "__main__": MyFrame().mainloop()
has comment: http://stackoverflow.com/comment/87310867
has comment: http://stackoverflow.com/comment/87310855
has title: Python Program is not remembering a variable
upvote count: 1
tagged with: python
answer count: 3
has comment: http://stackoverflow.com/comment/87310799
score: 1

http://stackoverflow.com/a/50091956
upvote count: 1
type: AcceptedAnswer
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50091793
has body: #!/usr/bin/env python list_1 = [[5, 3, 4], [1, 5, 8], [6, 4, 2]] list_2 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]] difflist = [a[i][j] for a in zip(list_1, list_2) for i in range(len(a)) for j in range(len(a[i])) if a[i][j] != a[i-1][j]] print(difflist) Which prints: [5,8,8,9,4,7]
answers question: http://stackoverflow.com/q/50091793
score: 0

http://stackoverflow.com/q/50103549
answer count: 2
downvote count: 0
tagged with: pandas
has body: This question builds on Pandas melt several groups of columns into multiple target columns by name. However, my data is organised in an annyoing way import pandas as pd df = pd.DataFrame([(101, 'a', 'b', 'c', 'd', 'e', 'f', 1, 2, 3, 4, 5, 6, 'aa', 'bb', 'cc', 'dd', 'ee', 'ff'), (102,'g', 'h', 'i', 'j', 'k', 'l' , 7, 8, 9, 10, 11, 12, 'gg', 'hh', 'ii', 'jj', 'kk', 'll')], columns=['id','a__1', 'a__2', 'a__3', 'a_1', 'a_2', 'a_3','b__1', 'b__2', 'b__3', 'b_1', 'b_2', 'b_3','c__1', 'c__2', 'c__3', 'c_1', 'c_2', 'c_3']) df And the dataframe looks like this: id a__1 a__2 a__3 a_1 a_2 a_3 b__1 b__2 b__3 b_1 b_2 b_3 c__1 c__2 \ 0 101 a b c d e f 1 2 3 4 5 6 aa bb 1 102 g h i j k l 7 8 9 10 11 12 gg hh c__3 c_1 c_2 c_3 0 cc dd ee ff 1 ii jj kk ll As you can see instead of all the seperators only being one underscore they are sometimes two underscores. In the end I would like to organise my data to be in the following way, note that the a__1 should come before a_1 and so on: id a b c 0 101 a 1 aa 1 101 b 2 bb 2 101 c 3 cc 3 101 d 4 dd 4 101 e 5 ee 5 101 f 6 ff 6 102 g 7 gg 7 102 h 8 hh 8 102 i 9 ii 9 102 j 10 jj 10 102 k 11 kk 11 102 l 12 ll Basically my problem is that instead of only one underscore I sometimes have 2. Now this doesn't work with the pd.wide_to_long function since I cannot set the separator argument as '_' or '__'. I hope you understand my question.
has title: Melt group of columns into target columns by name
favorite count: 0
has comment: http://stackoverflow.com/comment/87224344
type: Question
tagged with: transform
has answer: http://stackoverflow.com/a/50103981
has answer: http://stackoverflow.com/a/50103771
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/38862832
score: 2
possible better answer: http://stackoverflow.com/a/50103771
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50103981

http://stackoverflow.com/q/50089210
has title: Socket Python(Server) to Java(Client) connection Java is not able to receive data from host
tagged with: java
answer count: 1
has answer: http://stackoverflow.com/a/50106628
has comment: http://stackoverflow.com/comment/87201704
type: Question
type: UnansweredQuestion
tagged with: sockets
tagged with: python
tagged with: readline
has body: The Server receives String requests from the Client and replies with a String message to the Client. I think the Server has to send the reply differently from how it is right now, so I think this line should be altered: c.sendall('Server: '+str.encode(reply)) Python Server: # This Python file uses the following encoding: utf-8 import socket def setupServer(port): serv=socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("socket ist da") try: # https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib host=socket.gethostbyname(socket.gethostname()) print('Host ip: '+host) serv.bind((host, port)) except socket.error as msg: print(msg) print("socket bind fertig") return serv def setupConnection(s): # Erlaubt 1 Verbindung gleichzeitig s.listen(1) connection, address=s.accept() print("Verbunden zu: "+address[0]+":"+str(address[1])) return connection def gET(): reply='GET ausgefuehrt' return reply def rEPEAT(te): reply=te[1] return reply def dataTransfer(c,s): # sendet und erhält Daten bis es stoppen soll while True: # Daten erhalten data=c.recv(1024)#daten erhalten 1024 Buffer size data=data.decode('utf-8')#nötig? # Teilt die Datei in Befehl/Command und data auf dataMessage=data.split(' ',1) command=dataMessage[0] if command=='GET'or command=='get': reply=str(gET()) elif command=='REPEAT'or command=='repeat': reply=str(rEPEAT(dataMessage)) elif command=='EXIT'or command=='exit': print("Er ist geganngen") break elif command=='KILL'or command=='kill': print("Server wird geschlossen!") s.close() break else: print("was?") reply="Nicht Vorhandener Befehl" # NAchricht senden c.sendall('Server: '+str.encode(reply)) print(reply) print('Klint: '+data) print("Daten wurden geschickt") c.close() def main(): #print("hello") #host='192.168.1.120' #host='192.168.2.110' #print('Host ip: '+str(host)) port=8999 print('Port: '+str(port)) s=setupServer(port) while True: try: conn=setupConnection(s) dataTransfer(conn,s) except: break if __name__=="__main__…
tagged with: transfer
linked to: http://stackoverflow.com/q/166506
has comment: http://stackoverflow.com/comment/87198730
score: 0

http://stackoverflow.com/comment/87191606
score: 0
has text: And could you also show the output of `echo %VCINSTALLDIR% ` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50080459

http://stackoverflow.com/comment/122045940
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50156706
type: AnswerComment
has text: This official doc might be helpful: [pytest import mechanisms and sys.path/PYTHONPATH](https://docs.pytest.org/en/latest/explanation/pythonpath.html)

http://stackoverflow.com/a/50119999
has body: In side else part write this: else: form = ProfileForm() return render (request, 'edit_view.html',{'form......
has comment: http://stackoverflow.com/comment/87268105
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50118542
score: 1
type: Answer

http://stackoverflow.com/q/50185696
tagged with: python
tagged with: pass-by-reference
accepted answer: http://stackoverflow.com/a/50185856
has comment: http://stackoverflow.com/comment/87388432
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50185856
score: 0
answer count: 1
has body: I have this Hero object in python class Hero: def __init__(self, json_def, player_index): self._alive = True ... # other attributes Then, I have list of Hero object, i.e. Heroes = [HeroObj1, HeroObj2, HeroObj3, HeroObj4] What I would like to do is filter the list and get the object reference, instead of the copies of the object. I know that I can do filtering like below. filtered_list = [x for x in Heroes if x.alive] However, this approach will result in copying the filtered objects to filtered_list. I would like to do reference so I could modify the initial list (Heroes) when I modified this filtered version/filtered_list (for example, only modifying the hero that is alive). Is there any solution to achieve what I am looking for? Any help would be appreciated! Cheers!
tagged with: reference
has comment: http://stackoverflow.com/comment/87388546
type: Question
has title: Python - reference of objects in filtered list
has comment: http://stackoverflow.com/comment/87388405

http://stackoverflow.com/q/50205692
duplicate of: http://stackoverflow.com/q/22937618
accepted answer: http://stackoverflow.com/a/50205755
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50205755
has title: regex positioning confusion
score: 1
upvote count: 1
answer count: 1
downvote count: 0
has body: I have a question about the positioning of the "do not include operator in regex in python" shown below [^] If I have the following expression print(re.findall(r'^[^_][-\w\d]+[^:/)]$',x)) does it matter where i place [^:/)] or will it only exclude : and / at the end of the string since i placed it at the end
linked to: http://stackoverflow.com/q/22937618
favorite count: 0
type: Question

http://stackoverflow.com/q/50110804
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
has title: Find sum of row items where the index contains a string
has answer: http://stackoverflow.com/a/50110949
has comment: http://stackoverflow.com/comment/87238978
answer count: 1
has comment: http://stackoverflow.com/comment/87238915
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50110949
has comment: http://stackoverflow.com/comment/87238898
has body: In python, I have a panda Data Frame named data. We have a row for each index. How can I find the sum of the values in the third column for all rows whose index contains a keyword 'key'? I can do it by a for loop, but it is not smart: count = 0 for i in range(1,10): if 'key' in data.index[i]: count += data.iloc[i,3]
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87238889

http://stackoverflow.com/q/50139858
tagged with: matlab
tagged with: http://stackoverflow.com/tag/r
score: 0
tagged with: python
type: Question
has title: Methods for determining temporal covariance among many time series?
tagged with: time-series
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50140756
tagged with: covariance
has body: We are trying to quantify synchrony in water chemistry variation among several hundred sites. For each site we have a time-series of concentration. We'd like to quantify the overall temporal covariance (are concentrations going up and down at the same time) among the sites and are interested in different statistical approaches to to do this. The different chemistry parameters have very different absolute concentrations (e.g. 1-100 ppm for carbon, 0.001 to 1 ppm for phosphorus) so a relative metric is necessary. We have done this previously with the mean of pairwise scaled covariances, but there surely is a more elegant method. We are happy to use R, Pyton, or Matlab. Thanks!

http://stackoverflow.com/q/50182174
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87769293
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87381724
score: 0
tagged with: primary-key
has comment: http://stackoverflow.com/comment/87417550
has comment: http://stackoverflow.com/comment/87383854
answer count: 1
has comment: http://stackoverflow.com/comment/87383817
has comment: http://stackoverflow.com/comment/87404876
has title: django exception: Reverse for 'comment_new' with keyword arguments '{'pk': ''}' not found
has answer: http://stackoverflow.com/a/50376667
has comment: http://stackoverflow.com/comment/87415273
type: Question
has comment: http://stackoverflow.com/comment/87769450
has comment: http://stackoverflow.com/comment/87405325
has comment: http://stackoverflow.com/comment/87404945
has body: im quite new to python/Django and i currently want to implement that every of my blogposts can have a comment. but i dont get the trick. i created everything the same way as for my post model expect that i Exception Type: NoReverseMatch Exception Value: Reverse for 'comment_new' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['comment/new/$'] urls.py: from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', (admin.site.urls)), url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'), url(r'^comment/new/$', views.comment_new, name='comment_new'), url(r'^comment/(?P<pk>\d+)/edit/$', views.comment_edit, name='comment_edit'), ] views.py: from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from .models import Post from .models import Comment from .forms import PostForm, CommentForm def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'quickblog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'quickblog/post_detail.html', {'post': post}) def post_new(request): form = PostForm() return render(request, 'quickblog/post_edit.html', {'form': form}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'quickblog/post_new.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance…
has comment: http://stackoverflow.com/comment/87769508
has comment: http://stackoverflow.com/comment/87383761
accepted answer: http://stackoverflow.com/a/50376667
has comment: http://stackoverflow.com/comment/87769359
has comment: http://stackoverflow.com/comment/87769431

http://stackoverflow.com/comment/87284862
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50133138
has text: @jezrael please answer this if possible I am not able to find the answer in given example

http://stackoverflow.com/comment/87379355
has text: Thanks for your feedback. I already used this function : The problem is that it create 2 attributes : for example "PurchaseLine02_water" and "PurchaseLine04_water" and I want just only one attribute ("water") with "TRUE" (or "1"), in the right row.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50180820
type: AnswerComment

http://stackoverflow.com/comment/87342328
has text: You're right, the set was a bad idea. But more importantly, the code is much cleaner if you only use the dict for lookup, and not as the output. Isn't [this](http://dpaste.com/0VW12HZ) more readable _and_ efficient? (You can use that code btw, I don't mind)
comment on: http://stackoverflow.com/a/50161547
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50134704
tagged with: docker
type: AnsweredQuestion
score: 0
tagged with: docker-compose
has title: executing commands in containers from within a container using docker-compose up vs docker-compose run
answer count: 1
has body: I'll try to explain this as simply as possible. I have a dockerised python app. Within this python app at some point I try to run a docker command in another (libreoffice) container as such: import subprocess file_path = 'path_to_file' args = ['docker', 'run', '-it', '-v', '/tmp:/tmp', 'lcrea/libreoffice-headless', '--headless', '--convert-to', 'pdf', file_path, '--outdir', '/tmp'] process = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout) I end my python app's Dockerfile with a command which starts the server: CMD python3 -m app.run_app What is interesting is when I start the python app like this it works fine: docker-compose run -p 9090:9090 backend /bin/bash root@74430c3f1f0c:/src python3 -m app.run_app But when I start it just using docker-compose up, the libreoffice container is never called. I am sure of it because when I do docker ps -a in the first instance a libreoffice container has been created while in the second there is none. What is going on here?
type: Question
has answer: http://stackoverflow.com/a/50140325
accepted answer: http://stackoverflow.com/a/50140325
tagged with: subprocess
tagged with: python
tagged with: dockerfile

http://stackoverflow.com/comment/87326717
score: 0
has text: It seems likely to be due to something odd in the training text. Try inserting `print(data)` before the line where the error occurs, and see if there are very long strings in it? Try setting `train_text=["This is a simple test"]` and see if you still get the error?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50153832

http://stackoverflow.com/a/50174326
upvote count: 21
answers question: http://stackoverflow.com/q/50174325
has body: Ideally we want the validation to be applied both at the database layer via a constraint and also in our model by rejecting attempts to set the property to a string that's too short even before trying to save it to the database. We can do the former with a CheckConstraint using the char_length function, and the latter by adding a validator. Below is an example that enforces a minimum length of 3 characters on some_string: from sqlalchemy import Column, String, BigInteger from sqlalchemy.schema import CheckConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import validates Base = declarative_base() class MyTable(Base): __tablename__ = 'my_table' id = Column('id', BigInteger, primary_key=True) some_string = Column('some_string', String(256), nullable=False) __table_args__ = ( CheckConstraint('char_length(some_string) &gt; 2', name='some_string_min_length'), ) @validates('some_string') def validate_some_string(self, key, some_string) -&gt; str: if len(some_string) &lt;= 2: raise ValueError('some_string too short') return some_string
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50174325
type: Answer
score: 21
downvote count: 0

http://stackoverflow.com/q/50126891
has answer: http://stackoverflow.com/a/50127838
score: 0
tagged with: python
has title: Multi-Threading Tkinter Python
tagged with: tkinter
type: UnansweredQuestion
tagged with: multithreading
has body: I am trying to create an instrumental cluster using the OBDII and the tkinter as the GUI. The problem is that, the GUI is non responsive and the draw time is very bad as I have only 1 thread. I am new to python and the OOP concepts and is the reason I am not sure how to proceed here. This is what I want to do, I want two threads one for the drawing while other too process the data. Also can I use multiple threads to draw the objects too? Any help is appreciated import tkinter as tk from PIL import ImageTk from PIL import Image import datetime import obd class SimpleApp(object): def __init__(self, master, **kwargs): self.master = master self.canvas = tk.Canvas(width=1400, height=800) self.canvas.pack() self.update = self.draw().__next__ master.after(1, self.update) def draw(self): image_bk = Image.open("img/1.png") image = Image.open("img/2.png") image1 = Image.open("img/3.png") image_prnd = Image.open("img/4.png") angle = 2 # 0 -&gt; 270 angle1 = 0 # 0 -&gt; 89 Speed = 0 RPM = 0 Fuel = 0 Temp = 0 Time = ' ' tkimage_bk = ImageTk.PhotoImage(image_bk) self.canvas.create_image(700, 400, image=tkimage_bk) self.canvas.create_text(100, 770, fill="white", font="BatmanForeverOutline 20 bold", text=" 70 F") tkimage_prnd = ImageTk.PhotoImage(image_prnd) while True: tkimage = ImageTk.PhotoImage(image.rotate(angle)) tkimage1 = ImageTk.PhotoImage(image1.rotate(angle1)) canvas_obj = self.canvas.create_image(690, 400, image=tkimage) canvas_obj1 = self.canvas.create_image(700, 400, image=tkimage1) self.canvas.create_image(700, 400, image=tkimage_prnd) self.canvas.create_text(700, 350, fill="white", font="BatmanForeverAlternate 20 bold ", text="MPH") self.canvas.create_text(700, 525, fill="white", font="BatmanForeverAlternate 20 bold ", text="RPM") self.canvas.create_text(700, 655, fill="white", font="BatmanForeverOutline 22 bold ", text="P R N S") self.canvas.create_text(760, 655, fill='white', font="BatmanForeverAlternate 45 ", text="D") speed = self.canvas.create_text(700, 290, fi…
answer count: 1
type: Question

http://stackoverflow.com/comment/87326333
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50114993
has text: @Leon to a web resource
type: Comment

http://stackoverflow.com/q/50076552
downvote count: 0
tagged with: django
score: 1
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
has body: hi i have url like this: path('api/v1/store/download/&lt;str:ix&gt;/', DownloadVideoAPI.as_view(), name='download'), it accept long string . I want to keep allthing after download key in above URL as the parameter. but when I enter a long string that contains some slash Django says page not found for example when if enter "/api/v1/store/download/asdasd2asdsadas/asdasd" will give me 404 not found ... how can I do that? this is my view: class DownloadVideoAPI(APIView): def get(self, request, ix): pre = ix.split(",") hash = pre[0] dec = pre[1] de_hash = decode_data(hash, dec)
accepted answer: http://stackoverflow.com/a/50076692
type: Question
has title: django ignore slash in url and take parameter
has answer: http://stackoverflow.com/a/50076692
tagged with: python
possible better answer: http://stackoverflow.com/a/50076612
has answer: http://stackoverflow.com/a/50076612
has answer: http://stackoverflow.com/a/50076627
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/87456161
score: 0
comment on: http://stackoverflow.com/q/50219578
type: QuestionComment
type: Comment
has text: I think you should open up business logic of this case more...

http://stackoverflow.com/comment/87495707
comment on: http://stackoverflow.com/q/50207218
type: Comment
type: QuestionComment
has text: Why the double post? https://stackoverflow.com/questions/50237534/how-do-i-convert-this-sql-into-a-django-query
score: 2

http://stackoverflow.com/comment/87466033
has text: This _still_ creates a new list, doesn't it?
score: 1
comment on: http://stackoverflow.com/a/50224237
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87181713
has text: I'm sorry I don't understand the question, could you clarify?
comment on: http://stackoverflow.com/q/50082938
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50075541
answer count: 0
type: UnansweredQuestion
downvote count: 0
has title: Calculating precision, recall and F1 in Keras v2, am I doing it right?
upvote count: 1
tagged with: keras
favorite count: 0
has body: There is already a question on how to obtain precision, recall and F1 scores in Keras v2, here is the method I'm using but the question is: am I doing it right? First of all, F. Chollet says he removed these three metrics from version 2 of Keras because they were batch-based and hence not reliable. I'm following an idea by basque21 using a Callback with method on_epoch_end, isn't this normally batch-independent since calculated at epoch end (= after all batches have finished)? Here is the code I'm using. In the model.fit method I add the argument callbacks=[metrics] and I define a dictionary myhistory and a class Metrics as follows (code adapted from basque21): myhistory={} myhistory['prec']=[] myhistory['reca']=[] myhistory['f1']=[] class Metrics(keras.callbacks.Callback): def on_epoch_end(self, batch, logs={}): predict = numpy.asarray(self.model.predict(self.validation_data[0])) predict = a=numpy.array(predict.flatten()&gt;=0.5,dtype=int) targ = self.validation_data[1] targ=numpy.array(targ.flatten()&gt;=0.5,dtype=int) self.prf=precision_recall_fscore_support(targ, predict) print("Precision/recall/f1 class 0 is {}/{}/{}, precision/recall/f1 class 1 is {}/{}/{}".format(self.prf[0][0], self.prf[1][0], self.prf[2][0], self.prf[0][1], self.prf[1][1], self.prf[2][1])) myhistory['prec'].append(self.prf[0][1]) myhistory['reca'].append(self.prf[1][1]) myhistory['f1'].append(self.prf[2][1]) return metrics = Metrics() Once fitting is finished I display everything on a common plot as follows: import matplotlib.pyplot as plt loss = history.history['loss'] val_loss = history.history['val_loss'] precision = [1-x for x in myhistory['prec']] recall = [1-x for x in myhistory['reca']] f_one = [1-x for x in myhistory['f1']] epochs = range(1, len(loss) + 1) # "bo" is for "blue dot" plt.plot(epochs, loss, 'bo', label='Training loss') # b is for "solid blue line" plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.plot(epochs, precision, 'r', label='One minus precision') plt.p…
score: 1
linked to: http://stackoverflow.com/q/50065484
tagged with: python
tagged with: precision-recall
has comment: http://stackoverflow.com/comment/109106088
tagged with: keras-2
type: Question

http://stackoverflow.com/q/50195902
has comment: http://stackoverflow.com/comment/87544470
has comment: http://stackoverflow.com/comment/87563762
has title: Find probaility of failure using logistic regression in python
answer count: 0
has comment: http://stackoverflow.com/comment/87409104
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87463865
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: pandas
has body: I am trying to get some insights from a dataset using Logistic Regression. The starting dataframe has the information of if something was removed unscheduled (1 = Yes and 0 = No) and some data which was provided with this removal. This looks like this: This data is then 'dummyfied' using pandas.get_dummies, where the result is as expected. Then I normalized the found coefficients (using coef_) to scale everything the same. I put this in a dataframe with the column 'Parameter' (which is the column name of the dummy dataframe) and the column 'Value' (which is the value obtained using the coefficients). Now I will get the following result. Now this result shows that the On-wing Time is the biggest contributor in the unscheduled removal. Now the question: how can I predict what the chance is that there will be an unscheduled removal for this reason (this column)? So, what is the chance that I will get another unscheduled removal which is caused by the On-wing Time? Note that these parameters can change since this data is fake data and data may be added later on. So when the biggest contributor changes, the prediction should also focus on the new biggest contributor. I hope you understand the question. EDIT The complete code and dataset (fake one) can be found here: 1drv.ms/u/s!AjkQWQ6EO_fMiSEfu3vYgSTBR0PZ Ganesh
tagged with: python
has comment: http://stackoverflow.com/comment/87408986

http://stackoverflow.com/comment/104096026
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50272109
type: AnswerComment
has text: With current (4.x) versions, the syntax for upstream proxy is different. Instead of `-U http://....`, use `--mode upstream:http://foo.bar:9999`.

http://stackoverflow.com/q/50110774
has title: binascii.Error odd length string when reading hex string from the file
has comment: http://stackoverflow.com/comment/87239249
type: Question
has comment: http://stackoverflow.com/comment/87239103
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87239848
has body: This the line which the program is suppose to read from the file (when the user inputs the file name Encrypted string: b'c0e4c042ab06829bf3ef1763d33b9671cf165356c9cef18c5c201d2e173e892e' with open(u_input) as fp: read_lines = fp.readlines() read_message = read_lines[0].split() message = read_message[2] print("Message: %s"% message) uncombine = binascii.unhexlify(message) print("decrypt: %s"%uncombine) Once the line is read the program is suppose to pick the hex string from the line (which is already happening) But just when I unhex the hex it gives me the error: binascii.Error: Odd-length string NOTE: I have tried .strip() that doesn't help.
has comment: http://stackoverflow.com/comment/87239245
tagged with: hex
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87239226
tagged with: encryption

http://stackoverflow.com/comment/87335218
comment on: http://stackoverflow.com/q/50157862
has text: It is! I have both files, I remove Pipfile and it's done! Thanks!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87197947
comment on: http://stackoverflow.com/q/50090868
score: 0
has text: See this explanation: http://effbot.org/pyfaq/why-can-t-lambda-forms-contain-statements.htm
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50132852
has body: I am using GCP Cloud Vision API with Python to retrieve some information from images. Specifically, I am sending a photo of a product to this API and I retrieve the web entities related to it; one of them is almost always the brand. My basic Python script that does this job is the following: import io from google.cloud import vision from google.cloud.vision import types import os import cv2 import numpy as np os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/User/PycharmProjects/Project_name.json" def detect_text(file): client = vision.ImageAnnotatorClient() with io.open(file, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) web_detection = client.web_detection(image=image).web_detection print(web_detection) file_name = "/Users/User/Desktop/Image.jpg" img = cv2.imread(file_name) detect_text(file_name) The Project_name.json file contains some authorisation credentials so that I can have access to the Google Cloud API Client. I want to do the same thing with PHP. For this reason I have written the the following PHP script so far: &lt;?php namespace Google\Cloud\Samples\Vision; use Google\Cloud\Vision\V1\ImageAnnotatorClient; function detect_web($path) { $imageAnnotator = new ImageAnnotatorClient(); $image = file_get_contents($path); $response = $imageAnnotator-&gt;webDetection($image); $web = $response-&gt;getWebDetection(); print($web); } $path = '/Users/User/Desktop/Image.jpg'; detect_web($path); ?&gt; But when I run this I get the following error: Fatal error: Uncaught Error: Class 'Google\Cloud\Vision\V1\ImageAnnotatorClient' not found in /opt/lampp/htdocs/index.php:12 Stack trace: #0 /opt/lampp/htdocs/index.php(26): Google\Cloud\Samples\Vision\detect_web('/Users/User...') #1 {main} thrown in /opt/lampp/htdocs/index.php on line 12 Obviously, this error appears because (first of all) I have not provided the Google Authorisation Credentials as I did in Python above (os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/Users/User/P…
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50646607
has comment: http://stackoverflow.com/comment/87283630
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87283882
has title: Convert Python to PHP - GCP Authorisation Credentials
has comment: http://stackoverflow.com/comment/87283842
tagged with: python
score: -1
tagged with: php
has comment: http://stackoverflow.com/comment/87283961
has comment: http://stackoverflow.com/comment/87283813
tagged with: google-cloud-platform
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/87401600
comment on: http://stackoverflow.com/a/50190837
type: Comment
score: 0
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170431/discussion-between-mt-drip-and-ajax1234).

http://stackoverflow.com/comment/87199199
comment on: http://stackoverflow.com/a/50091254
type: AnswerComment
score: 0
has text: @jedwards @Jean-François Fabre Is it maybe possible to inherit `FakeStdout` from clasic one and only redefine `__exit__` ?
type: Comment

http://stackoverflow.com/comment/140258004
type: AnswerComment
comment on: http://stackoverflow.com/a/50187147
type: Comment
has text: To clarify my point: yes, one needs functionality to recursively remove directories. Its just pretty delicate to do so, which is why I (personaly) do not mind to *not* have a `Path` method for this and instead have to use `shutil.rmtree(path)`. Reminds me to stay very carefull with this - and as mentioned earlier: I try to avoid recursive rm at (almost) all cost in my code. And yes, if I had written pathlib, I think I would have implemented recursive rm
score: 0

http://stackoverflow.com/comment/87424056
type: QuestionComment
has text: Index([u'VendorID', u'lpep_pickup_datetime', u'Lpep_dropoff_datetime', u'Dropoff_latitude', u'Passenger_count', u'Trip_distance', u'Fare_amount', u'Extra', u'MTA_tax', u'Tip_amount', u'Tolls_amount', u'Ehail_fee', u'improvement_surcharge', u'Total_amount', u'Payment_type', u'Trip_type ', u'Pickup_dt', u'date', u'maximum temperature', u'minimum temperature', u'averagetemperature', u'precipitation', u'snowfall', u'snow depth', u'pdate'], dtype='object')
comment on: http://stackoverflow.com/q/50203321
type: Comment
score: 0

wget
tags question: http://stackoverflow.com/q/50192674
tag name: wget
type: Tag

http://stackoverflow.com/comment/87231834
has text: can you help me
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50106975

http://stackoverflow.com/q/50191648
answer count: 2
downvote count: 0
tagged with: geolocation
score: 6
has title: GIS / GEOTiff / GDAL / Python How to get coordinates from pixel
has answer: http://stackoverflow.com/a/65068312
possible better answer: http://stackoverflow.com/a/65068312
favorite count: 0
has body: I'm working on the project to detect the object from GEOTiff files and return coordinates of the objects and those output will use for drone to fly to those coordinate I use tensorflow with YOLO v2(image detector framework) and OpenCV to detect the objects that I need in GEOTiff import cv2 from darkflow.net.build import TFNet import math import gdal # initial stage for YOLO v2 options = { 'model': 'cfg/yolo.cfg', 'load': 'bin/yolov2.weights', 'threshold': 0.4, } tfnet = TFNet(options) # OpenCV read Image img = cv2.imread('final.tif', cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #Predict the image result = tfnet.return_predict(img) #Calculate the center and radius of each objects i = 0 while i &lt; len(result): tl = (result[i]['topleft']['x'], result[i]['topleft']['y']) br = (result[i]['bottomright']['x'], result[i]['bottomright']['y']) point = (int((result[i]['topleft']['x']+result[i]['bottomright']['x'])/2), int((result[i]['topleft']['y']+result[i]['bottomright']['y'])/2)) radius = int(math.hypot(result[i]['topleft']['x'] - point[0], result[i]['topleft']['y'] - point[1])) label = result[i]['label'] result[i]['pointx'] = point[0] result[i]['pointy'] = point[1] result[i]['radius'] = radius i += 1 print(result) So the results come out like set of JSON [{'label': 'person', 'confidence': 0.6090355, 'topleft': {'x': 3711, 'y': 1310}, 'bottomright': {'x': 3981, 'y': 1719}, 'pointx': 3846, 'pointy': 1514, 'radius': 244}] as you can see the location of the object is return in pixel (x,y) and I want to use these x,y to convert to coordinate in lat,lng so I try to use GDAL (the library use for read the GEO infomation that contain inside the image) so here's the GEO infomation of the image by using gdalinfo in terminal Driver: GTiff/GeoTIFF Files: final.tif Size is 8916, 6888 Coordinate System is: PROJCS["WGS 84 / UTM zone 47N", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIM…
type: Question
has answer: http://stackoverflow.com/a/50196761
tagged with: geotiff
tagged with: python
tagged with: geocoding
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50196761
tagged with: gdal

http://stackoverflow.com/comment/87230196
type: QuestionComment
type: Comment
score: 2
has text: @dthed: Can you explain why it's not possible? All you need to do is cut down your dataset repeatedly until you find a minimal one that exhibits this behaviour. E.g., what happens if you take the first half of your existing dataset? What about the first half of *that*? Etc.
comment on: http://stackoverflow.com/q/50105629

http://stackoverflow.com/a/50169952
score: 2
has body: Use numpy.repeat: c = df.columns[1:] df = pd.DataFrame(np.repeat(df.values, df['#'], axis=0)[:, 1:], columns=c) print (df) X Y Z 0 a a a 1 b b b 2 b b b 3 c d c 4 d e d 5 d e d 6 d e d Similar: df = pd.DataFrame(np.repeat(df.values, df['#'], axis=0), columns=df.columns) print (df) # X Y Z 0 1 a a a 1 2 b b b 2 2 b b b 3 1 c d c 4 3 d e d 5 3 d e d 6 3 d e d But if order is important: dfs = [] for i in range(df['#'].max()): df = df[df['#'] &gt; 0].copy() df['#'] -= 1 dfs.append(df.iloc[:, 1:]) df1 = pd.concat(dfs, ignore_index=True) print (df1) X Y Z 0 a a a 1 b b b 2 c d c 3 d e d 4 b b b 5 d e d 6 d e d
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50169882
answers question: http://stackoverflow.com/q/50169882
type: Answer
upvote count: 2

http://stackoverflow.com/comment/87438554
comment on: http://stackoverflow.com/a/50179337
type: Comment
score: 0
type: AnswerComment
has text: Thank you very much! My issue has been resolved because of your answer and also because of your way of explaining things(concepts).

http://stackoverflow.com/a/50130912
downvote count: 1
answers question: http://stackoverflow.com/q/50130781
has comment: http://stackoverflow.com/comment/87279626
type: Answer
score: -1
has body: import random a = [1, 4, 5, 7, 10] b = random.sample(a, len(a)) for i in range(len(b)): if b[i] != a[i]: b[i] = 0 print('a:', a) print('b:', b)
has comment: http://stackoverflow.com/comment/87279596
upvote count: 0
has comment: http://stackoverflow.com/comment/87279638

http://stackoverflow.com/a/50108043
score: 0
answers question: http://stackoverflow.com/q/50107824
type: Answer
has body: One method: start_index = string.lower().index(target) new_string = target+string[0:start_index]+string[start_index+len(target):] This will throw an error if target is not in string, and will only move the first instance if there are multiple.

http://stackoverflow.com/comment/87389139
score: 0
type: Comment
has text: Possible duplicate of [Unable to set default python version to python3 in ubuntu](https://stackoverflow.com/questions/41986507/unable-to-set-default-python-version-to-python3-in-ubuntu)
type: QuestionComment
comment on: http://stackoverflow.com/q/50186129

http://stackoverflow.com/comment/87201612
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50092682
type: QuestionComment
has text: you can use `%timeit`

http://stackoverflow.com/comment/87415937
has text: IndexError: too many indices for array
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50199320

http://stackoverflow.com/a/50137770
has comment: http://stackoverflow.com/comment/87294090
type: Answer
has comment: http://stackoverflow.com/comment/87294069
score: 2
upvote count: 3
has body: IF you are open to using a 3rd party library, you can use numpy for a vectorised solution: Setup import numpy as np lst = [ [ [ [100, 200, 300], [230, 133, 234] ], [ [234, 232, 523], [231, 234, 554] ] ], [ [ [701, 704, 204], [331, 833, 634] ], [ [734, 632, 523], [131, 434, 154] ] ] ] Solution res = np.array(lst)/100 array([[[[ 1. , 2. , 3. ], [ 2.3 , 1.33, 2.34]], [[ 2.34, 2.32, 5.23], [ 2.31, 2.34, 5.54]]], [[[ 7.01, 7.04, 2.04], [ 3.31, 8.33, 6.34]], [[ 7.34, 6.32, 5.23], [ 1.31, 4.34, 1.54]]]])
answers question: http://stackoverflow.com/q/50137159
downvote count: 1

http://stackoverflow.com/q/50200746
has answer: http://stackoverflow.com/a/50202947
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87421735
downvote count: 0
has title: Nested lists of dictionaries
favorite count: 0
type: Question
has body: I have 3 objects that I am populating into a JSON file format. The objects come from an API which needs rolled out to access as such: my_dict = {} for elem_a in list_a: for elem_b in elem_a: for elem_c in elem_b: elem_c_info = { "name" : elem_c.prop1, "ID" : elem_c.prop2, "GPA" : elem_c.prop3 } my_dict.setdefault("university", {}) \ .setdefault(str(elem_a), {}) \ .setdefault(str(elem_b), {}) \ .setdefault("student", []).append(elem_c_info) Produces output like this: { "university": { "universityA": { "class_1": { "student": [ { "name": "student_1", "ID": "1234", "GPA": "3.8" }, My desired output: { "university": [{ "name": "universityA", "class": [{ "name": "class_1", "student": [{ "name": "student_1", "ID": "1234", "GPA": "3.8" }, { "name": "student_2", "ID": "12345", "GPA": "3.4" } ] }, { "name": "class_2", "student": [{ "name": "student_3", "ID": "14", "GPA": "3.0" }] } ] }] } As you can see, I need each nested dictionary enclosed in a list at each level and I need to add a key/value pair at each level (except the inner-most). I was successful at handling the inner-most nest with .append but it's not working higher up. Any suggestions on adding these elements to the data structure? Accepting solutions to either or both issues. Here is what the input data structures look like running a simple nested loop (credit to @PM_2Ring for the suggestion): In my example above: list_a = [obj_1, obj_2, ..., obj_n] for elem_a in list_a: print('A', elem_a.name) for elem_b in elem_a: print(' B', elem_b.name) for elem_c in elem_b: print(' C', elem_c.prop1, elem_c.prop2, elem_c.prop3) ('A', universityA) (' B', class_1) (' C', student_1, 12345, 3.8) (' B', class_2) (' C', student_2, 145, 3.6) ('A', universityB) (' B', class_1) (' C', student_1, 12345, 3.8) (' C', student_2, 1235, 3.6) (' C', student_3, 12345, 3.4) (' B', class_2) (' C', student_1, 145, 3.6) .... elem_a = [universityA, universityB, universityC] # Top tier elem_b = [universityA.class_1, universityA.class_2, university…
has comment: http://stackoverflow.com/comment/87422061
score: 5
upvote count: 5
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50202947
has comment: http://stackoverflow.com/comment/87422588
has comment: http://stackoverflow.com/comment/87421646
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/50114642
type: Answer
has body: You can do it using this way: All you have to do is keep your desired quantiles, in a list: as shown below: You will have your result in final_df quantile_list = [0.1,0.5,0.4] final_df = pd.DataFrame(columns = df.columns) for i in quantile_list: temp = df[df['c'] == df['c'].quantile(q = i)] final_df = pd.concat([final_df,temp]) final_df.reset_index(drop=True,inplace=True) #optional incase you want to reset the index
upvote count: 1
answers question: http://stackoverflow.com/q/50114299
downvote count: 0
score: 1

http://stackoverflow.com/comment/87220767
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50101833
has text: I see, this is a rather interesting question ill try and tackle it later, and following either way.

putty
tags question: http://stackoverflow.com/q/50136894
tag name: putty
type: Tag

http://stackoverflow.com/q/50158267
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: Dynamic querySelector with Dynamic Jinja HTML
score: 1
upvote count: 1
has body: I have forms that are rendered dynamically based on values in a dictionary. They are given an ID based on the key value. They are all initially hidden. {%for k, v in options.items() %} {{k}}: {% for option in v %} {{option}} {% endfor %} {% endfor %} I now create an input list with those same keys: {% for key in options.keys() %} {% endfor %} Last I have Javascript used to listen to the tablelist element and select a form based on the inputlist's value. const tables = document.getElementById("tablelist") const subform_block = document.getElementById("subform_display") const forms = document.getElementById("subforms") tables.oninput = () => { let form = forms.querySelector('form[id="${tables.value}"]'); if(form){ subform_block.innerHTML = form.outerHTML; } else { subform_block.innerHTML = "not found"; } } The querySelector is not working. I confirmed that the HTML is rendered correctly and the IDs are consistent, but my querySelector is unable to find any of the forms. What is wrong?
answer count: 1
tagged with: jinja2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50158907
accepted answer: http://stackoverflow.com/a/50158907
tagged with: http://stackoverflow.com/tag/html
tagged with: javascript

http://stackoverflow.com/q/50115626
has body: It's showing this error on calculating expressions with parenthesis like-> 86*4(3+5)88 : TypeError: 'int' object is not callable when I don't use the calculator buttons and type using my keyboard buttons it doesn't show any error but on pressing equal it gives wrong answer. Please check my code and point out the error. from tkinter import * cal = Tk() cal.title("Smart Calculator") txtDisplay = Entry(cal, font=('arial', 20, 'bold'), bd=30, insertwidth=4, bg="powder blue", justify='right') class Calculator: def __init__(self): self.result = 0 self.current = 0 self.operator = "" def btnClick(self, num): self.operator = self.operator + str(num) txtDisplay.delete(0, END) txtDisplay.insert(0, self.operator) self.expOutput(self.operator) def expOutput(self, operator): try: self.result = str(eval(operator)) txtDisplay.delete(0, END) txtDisplay.insert(0, string=self.operator + "=" + self.result) self.current = 0 except SyntaxError: txtDisplay.delete(0, END) txtDisplay.insert(0, self.operator) def oprtrClick(self, op): if self.current is 0: self.current = 1 self.operator = self.operator + op txtDisplay.delete(0, END) txtDisplay.insert(0, string=self.operator) else: self.operator = self.operator + op self.expOutput(self.operator) def equals(self): self.operator = self.result txtDisplay.delete(0, END) txtDisplay.insert(0, string=self.operator) def clear(self): self.__init__() txtDisplay.delete(0, END) def delete(self): self.operator = self.operator[: -1] txtDisplay.delete(0, END) txtDisplay.insert(0, string=self.operator) smartCal = Calculator() btn0 = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="0",bg="powder blue", command=lambda: smartCal.btnClick(0)) btn1 = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="1", bg="powder blue", command=lambda: smartCal.btnClick(1)) btn2 = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="2",bg="powder blue", command=lambda: smartCal.btnClick…
has answer: http://stackoverflow.com/a/50116901
tagged with: python
has comment: http://stackoverflow.com/comment/87249047
has comment: http://stackoverflow.com/comment/87248439
has comment: http://stackoverflow.com/comment/87248961
upvote count: 3
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/50127856
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/87248545
tagged with: calculator
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/35929640
has comment: http://stackoverflow.com/comment/87251692
has title: I am making a calculator using python and it shows error on calculating expressions with parenthesis
has comment: http://stackoverflow.com/comment/87250069
score: 1

http://stackoverflow.com/comment/87351843
score: 0
comment on: http://stackoverflow.com/q/50162459
type: QuestionComment
type: Comment
has text: I can't even remember. I've run into more errors than I can count.

http://stackoverflow.com/q/50152764
favorite count: 0
type: Question
has title: I get an error when return a queryset objects: Cannot resolve expression type, unknown output_field
score: 20
upvote count: 20
accepted answer: http://stackoverflow.com/a/50152816
has body: I'm need annotation each object in queryset. I used annotation, but when return modified object, I get this error: Cannot resolve expression type, unknown output_field. How can I solve this problem? def get_queryset(self): get_cinema = Ciname.objects.filter(active_cinema='t') distation = 54.87 #for example queryset = get_cinema.annotate(distance=models.Max(distation)) return queryset
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50152816
type: AnsweredQuestion
answer count: 1
downvote count: 0
tagged with: django-rest-framework

http://stackoverflow.com/q/50189726
answer count: 1
has answer: http://stackoverflow.com/a/50189811
accepted answer: http://stackoverflow.com/a/50189811
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87396268
linked to: http://stackoverflow.com/q/826948
has comment: http://stackoverflow.com/comment/87396278
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87396328
has comment: http://stackoverflow.com/comment/87397101
has comment: http://stackoverflow.com/comment/87396358
has comment: http://stackoverflow.com/comment/87396306
has body: Hello I'm a noob and just started using python so I wanted to have fun using raw_input , adding random questions and stuff but I came across an error. It says the invalid syntax is ". I've been trying to put it to different places but didnt succeed I'm sorry if this is a really dumb question but can someone help me out. Heres a line with the error print " Oh okay then %s . You came from %s , right? Oh i see you came here to %s" % (name,so,fun) It's pointing at the closing " next to %s I'm using atom edit: heres the error File "C:\Users\USER\AppData\Local\atom\app-1.26.1\Testing.py", line 10 print " Oh okay then %s . You came from %s , right? Oh i see you came here %s. " % (name, so, fun) ^ SyntaxError: invalid syntax Heres the full code : name = raw_input("Hello whats your name?") so = raw_input("From where did you come from") fun = raw_input("Interesting, why did you come here?") #start the sentence with "for" print " Oh okay then %s . You came from %s , right? Oh i see you came here %s. " % (name, so, fun) If I can't use raw_input what can I use then? I learned with using that.
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87396270
has title: Python syntax error with "

http://stackoverflow.com/a/50101967
has comment: http://stackoverflow.com/comment/87221943
score: 2
has body: Here is a workaround using np.rec.fromarrays: &gt;&gt;&gt; dtype = [('width', '&lt;i4'), ('height', '&lt;i4'), ('depth', '&lt;i4'), ('score', '&lt;f4'), ('auc', '&lt;f4')] &gt;&gt;&gt; np.rec.fromarrays(a.T, dtype=dtype) rec.array([( 0, 1, 2, 3., 4.), ( 5, 6, 7, 8., 9.), (10, 11, 12, 13., 14.), (15, 16, 17, 18., 19.), (20, 21, 22, 23., 24.)], dtype=[('width', '&lt;i4'), ('height', '&lt;i4'), ('depth', '&lt;i4'), ('score', '&lt;f4'), ('auc', '&lt;f4')]) This is a recarray, but we can cast to ndarray if need be. In addition, the dtype is np.record we need to (view-) cast that to void to get a "clean" numpy result. &gt;&gt;&gt; np.asarray(np.rec.fromarrays(a.T, dtype=dtype)).view(dtype) array([( 0, 1, 2, 3., 4.), ( 5, 6, 7, 8., 9.), (10, 11, 12, 13., 14.), (15, 16, 17, 18., 19.), (20, 21, 22, 23., 24.)], dtype=[('width', '&lt;i4'), ('height', '&lt;i4'), ('depth', '&lt;i4'), ('score', '&lt;f4'), ('auc', '&lt;f4')])
has comment: http://stackoverflow.com/comment/87221876
type: Answer
answers question: http://stackoverflow.com/q/50100246
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/50088143
has title: How make text file into desired format in CSV using Python
tagged with: text
tagged with: numpy
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
has body: I am currently working on generating some graphs and such for a dataset that I have generated using another Python script. The goal is to have these graphs generated automatically after running the other program so manual editing is not an option here. The original code generates a text file in the format of: center_freq 791125000.0 freq 790625000.0 power_db 0.211535437034 noise_floor_db -100.913246571 There are approximately 50 of these lines that come from the code with different results each time I have managed to separate this into a list of each individual item and make it into a CSV file in which each string or integer is in its own row. However, working with numpy it seems it would be easier if there was only the titles for the category at the top of each column followed by all of the data. I am not sure how to modify from its current state, this is my code as of now: To take the textfile and generate a list: import sys open_file = open("usrp_official_jamming.txt","r") f = open("datafiles.txt","w+") lst = list() sys.stdout = f for line in open_file: words = line.split() for word in words: lst.append(word) n = 27 lst2 = lst[n:-1] print(lst2) Then to take the list and generate the CSV: import csv from itertools import izip_longest with open('datafiles.txt') as f: with open('usrpcsv.csv', 'wb') as csv_file: writer = csv.writer(csv_file) for line in f.readlines(): data = line.split(', ') chunks= [data[x:x+8] for x in xrange(0, len(data), 8)] for chunk in chunks: writer.writerow(chunk)
tagged with: python

http://stackoverflow.com/comment/87207294
type: Comment
type: QuestionComment
score: 0
has text: @BearBrown i add it
comment on: http://stackoverflow.com/q/50095233

http://stackoverflow.com/comment/88168475
score: 0
has text: just replacing `readlines()` by 2 off `readline()` made an incredible difference in this case.
type: Comment
comment on: http://stackoverflow.com/a/50212980
type: AnswerComment

http://stackoverflow.com/comment/87473560
type: Comment
comment on: http://stackoverflow.com/a/50179539
type: AnswerComment
has text: It seems that monkeypatch makes the threading id of green threadings (coroutines) different from each other. Without monkeypatch the threading id of green threadings (coroutines) are all the same. I thought the (green threadings) coroutines should always be in the same threading, thus the threading ids of green threadings (coroutines) should be the same. I think I have figured out my question. The green threading is still coroutines, they are just seems like different threading with different threading ids (since they are patched).
score: 0

http://stackoverflow.com/q/50223255
downvote count: 0
score: 1
upvote count: 1
tagged with: pyodbc
has answer: http://stackoverflow.com/a/50583744
favorite count: 0
has comment: http://stackoverflow.com/comment/87466976
tagged with: python
type: Question
has title: Inserting into SQL with pyodbc from remote computer
has body: Hello I am using my second computer to gather some data and insert it into the SQL database. I set up everything when it comes to reading and writing the database remotely, and I can insert new rows just by using the normal SQL. With pyodbc I can read tables, but when I insert new data, nothing happens. No error message, but also no new rows in the table. I wonder if anyone has faced this issue before and knows what the solution is.
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/87372863
type: Comment
score: 0
type: AnswerComment
has text: @EduardoRibeiro, also, if you plan to implement a full-fledged Lisp, you might be better of using regular expressions to do the parsing.
comment on: http://stackoverflow.com/a/50177265

http://stackoverflow.com/comment/87455572
score: 0
comment on: http://stackoverflow.com/a/50218495
type: Comment
has text: Thank you Brandon. `lst = ('a', 'b', 'c'), ('d', ('e1' , 'e2'), 'f')` It should look like this, with e2 as the value I'm looking for. I also updated my original post with a sample.
type: AnswerComment

http://stackoverflow.com/a/50147685
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50139712
downvote count: 0
score: 1
upvote count: 1
has body: As you are asking several questions and I'm not an animation expert, please let me give a first hint for reading in the data: Perhaps it's faster to rely on importer functions of available python packages, which are optimized for those tasks like the ones of pandas. import pandas as pd That would be for your '.out'-files quite simple: In:pd.read_csv(filename, skiprows=1, sep=' ') Out: Iteration Vertex Average Static Temperature 0 10 358.316254 1 20 369.484375 2 30 375.386780 3 40 378.820923 4 50 380.588043 5 60 381.466766 6 70 381.853149 7 80 381.944031 The '.res'-files look more complex, but you can first have a look at them like: pd.read_table(filename, names=None, sep='[{}\s]+', engine='python') 1 continuity 1.0000e+00 x-velocity 0.0000e+00 y-velocity 4.3827e-02 \ 0 2 continuity 1.000000 x-velocity 0.000781 y-velocity 16.308000 1 3 continuity 0.235090 x-velocity 0.001285 y-velocity 0.012352 2 4 continuity 0.080945 x-velocity 0.001665 y-velocity 0.013073 z-velocity 1.9319e-03 energy 1.2276e-07 Unnamed: 11 0 z-velocity 0.001032 energy 2.929600e-06 NaN 1 z-velocity 0.010337 energy 2.271500e-06 NaN 2 z-velocity 0.010491 energy 3.299300e-07 NaN From this result you can retrieve the column numbers you're interested in and use this information for the import in the future: pd.read_table(filename, usecols=[2,4,6,8,10], names=['x', 'x-vel', 'y-vel', 'z-vel', 'energy'], sep='[{}\s]+', engine='python') x x-vel y-vel z-vel energy 0 1.000000 0.000000 0.043827 0.001932 1.227600e-07 1 1.000000 0.000781 16.308000 0.001032 2.929600e-06 2 0.235090 0.001285 0.012352 0.010337 2.271500e-06 3 0.080945 0.001665 0.013073 0.010491 3.299300e-07 The results are pandas dataframes, which provide a very large set of functions for further processing, including just accessing a np.array-representation of their values if you prefer. Perhaps this helps a little.
has comment: http://stackoverflow.com/comment/87361280
has comment: http://stackoverflow.com/comment/87332884
type: Answer
has comment: http://stackoverflow.com/comment/87346639
answers question: http://stackoverflow.com/q/50139712
has comment: http://stackoverflow.com/comment/87335817

http://stackoverflow.com/comment/87439186
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50210791
has text: @ner `csv.reader` will read everything as strings (which gets classed as an object) - you don't want to be using that... use `pd.read_csv('your_file.csv')` directly instead and then you'll get a header row naming your columns and pandas will try and auto-type your columns where possible. So use literally: `df = pd.read_csv("/home/***/Documents/Table3.csv")` and then you can access `df.columns` and `df.dtypes`
type: AnswerComment

http://stackoverflow.com/q/50097482
has comment: http://stackoverflow.com/comment/87211337
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/csv
score: 0
has comment: http://stackoverflow.com/comment/87211513
tagged with: netcdf
tagged with: file
has title: From NetCDF file to csv by Python
downvote count: 1
has body: Sorry for my bad English. I am in an internship, I never have used Python before this. I need to extract data from a NetCDF file. I already have created a loop which creates a DataFrame, but when I try to extract this DataFrame I only have 201 values on 41000. import csv import numpy as np import pandas as pd import netCDF4 from netCDF4 import Dataset, num2date nc = Dataset('Q:/QGIS/2011001.nc', 'r') chla = nc.variables['chlorophyll_a'][0] lons = nc.variables['lon'][:] lat = nc.variables['lat'][:] time = nc.variables['time'][:] nlons=len(lons) nlat=len(lat) The first loop give me the 41000 values in ArcGIS python console for i in range(0,nlat) : dla = {'lat':lat[i],'long':lons,'chla':chla[i]} z = pd.DataFrame(dla) print (z) z.to_csv('Q:/QGIS/fichier.csv', sep =',', index= True) But when I do the to.csv I only get 201 values in the csv file. for y in range(0,nlat): q[y].to_csv('Q:/QGIS/fichier.csv', sep =',', index= True) for i in range(0,nlat): dlo ={'lat':lat[i],'long':lons,'chla':chla[i]} q[y] = pd.DataFrame(dlo) print(q) I hope that you will have an answer to solve this, moreover if you have any script to extract values for create an shp file I would be very grateful if you can share it! Best regards Thank you in advance
favorite count: 0
tagged with: shapefile
type: Question
has comment: http://stackoverflow.com/comment/87211817

music21
type: Tag
tags question: http://stackoverflow.com/q/50187387
tag name: music21

http://stackoverflow.com/q/50097431
has comment: http://stackoverflow.com/comment/87211365
has comment: http://stackoverflow.com/comment/87211186
has title: How to make an IF inside a FOR loop work on a DataFrame? Python
tagged with: pandas
has answer: http://stackoverflow.com/a/50107820
has comment: http://stackoverflow.com/comment/87213029
downvote count: 2
linked to: http://stackoverflow.com/q/6981717
has comment: http://stackoverflow.com/comment/87211630
has answer: http://stackoverflow.com/a/50097861
has comment: http://stackoverflow.com/comment/87211236
favorite count: 0
has comment: http://stackoverflow.com/comment/87213094
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87211386
tagged with: if-statement
type: UnansweredQuestion
score: -2
has body: I am trying to select segments/ clauses of sentences, based on word pairs with which the segments should start. For example, I am interested in sentence segments that start with "what does" or "what is', etc. To do this, I am looping over two DataFrames, using an if statement inside a for loop as shown below. The first DataFrame df1['Sentence'] contains the sentences. The other df2['First2'] contains the pairs of starting words. However, the function seems to loop only over the first word pair in the for loop - after the first item, it does not return to the for loop. My code seems to work when I would pass lists to it, but not when I pass DataFrames. I have tried the solutions mentioned in Pythonic way to combine FOR loop and IF statement. But they do not work for my DataFrame. I would love to know how to solve this. DataFrames: 'Sentence' 'First2' 0 If this is a string what does it say? 0 what does 1 And this is a string, should it say more? 1 should it 2 This is yet another string. 2 My code looks as follows: import pandas as pd a = df1['Sentence'] b = df2['First2'] #The function seems to loop over all r's but not over all b's: def func(r): for i in b: if i in r: # The following line selects the sentence segment that starts with # the words in `First2`, up to the end of the sentence. q = r[r.index(i):] return q else: return '' df1['Clauses'] = a.apply(func) This is the result: what does it say? This is correct but incomplete. The code seems to loop over all r's but not over all b's. How to get the desired result, as below? what does it say? should it say more?
has comment: http://stackoverflow.com/comment/87213626
has comment: http://stackoverflow.com/comment/87212925
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87213328
linked to: http://stackoverflow.com/q/50106176
has comment: http://stackoverflow.com/comment/87240147
upvote count: 0
answer count: 2

http://stackoverflow.com/comment/87447233
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50215145
has text: @Fern_2018, you can also use `isalnum` method like in my answer.

http://stackoverflow.com/q/50180086
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87385374
accepted answer: http://stackoverflow.com/a/50849447
possible better answer: http://stackoverflow.com/a/50180820
has comment: http://stackoverflow.com/comment/87383322
tagged with: data-transform
has title: Data Transformation / Preparation
downvote count: 2
has comment: http://stackoverflow.com/comment/87385213
has comment: http://stackoverflow.com/comment/87387580
tagged with: python
score: -1
type: AnsweredQuestion
has body: I'm beginner in Python. In order to perform data mining, I would like to transform a raw dataset: PurchaseLine01 PurchaseLine02 PurchaseLine03 PurchaseLine04 milk egg sausage butter water egg sugar cake water Into this dataset: milk egg sausage butter sugar cake water 1 TRUE TRUE TRUE FALSE FALSE FALSE FALSE 2 FALSE FALSE FALSE TRUE FALSE FALSE TRUE 3 FALSE TRUE FALSE FALSE TRUE TRUE TRUE Is there a simple way in Python to achieve this task?
has comment: http://stackoverflow.com/comment/87384427
has answer: http://stackoverflow.com/a/50849447
has answer: http://stackoverflow.com/a/50180820
answer count: 2
has comment: http://stackoverflow.com/comment/87384482
upvote count: 1
has comment: http://stackoverflow.com/comment/87384997
has comment: http://stackoverflow.com/comment/87385408

http://stackoverflow.com/comment/87305218
has text: @P.Camilleri agree with first - bad habit... Sorry. Agree with the second too (as I stated, I like your approach). But your broadcast is a bit less readable for naive eyes, isn't it?
type: Comment
comment on: http://stackoverflow.com/a/50143448
type: AnswerComment
score: 0

http://stackoverflow.com/q/50081067
answer count: 0
has body: I have a Python script that amongst other things opens a pygame window at one point. If this window is closed it can be reopened. If the pygame window gets opened again I get a pygame.error: display Surface quit in the background. Everything works perfectly fine, I can just see all the errors when I finally quit the parent script. parent.py: from game import game def launch_game(): game = Game() # Now I am in the pygame window until I quit it # Do a bunch of other stuff # At some point launchGame() game.py class Game(): def __init__(self): pygame.display.init() self.screen = pygame.display.set_mode((640, 480)) # Set up a bunch of GPIO Controls including a quit button self.playing = True while self.playing: self.check_events() sleep(.1) pygame.quit() def check_events(self, current_station): if GPIO.input(self.quitButton) == 0: self.playing = False if GPIO.input(self.upButton) == 0: self.playing = moveUp() if GPIO.input(self.downButton) == 0: self.playing = moveDown() So the first time I launchGame() happens everything works fine. The next time I start seeing the display Surface quit in the background. One error for every time I hit one of the other buttons . The moveUp() and moveDown() functions both end with screen drawing function and that starts with self.screen.fill(bg_color) this is what is throwing the error. If I open can close the game twice, I get two error message per button push, three times, three error messages. It is like the screen objects are still being kept in memory somewhere even after the pygame.quit() is called.
has comment: http://stackoverflow.com/comment/87178209
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/68765971
has comment: http://stackoverflow.com/comment/87178719
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/101846470
duplicate of: http://stackoverflow.com/q/68765971
has title: Destroying and Relaunching a PyGame object
score: 0

http://stackoverflow.com/q/50111642
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87240592
has comment: http://stackoverflow.com/comment/87240513
has answer: http://stackoverflow.com/a/50111677
linked to: http://stackoverflow.com/q/45766829
upvote count: 3
answer count: 2
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/87504692
tagged with: sorting
has comment: http://stackoverflow.com/comment/87240610
favorite count: 0
has title: Pythonic custom sort for letter grades 'D', 'C-' ,..., 'A+'?
has body: Is there a more Pythonic, compact, intuitive way to sort letter-grades than this (without using a custom dict)? grades = ['B-','C','B','C+','A','D+','B+','C-','A+','D','A-'] sorted(grades, key=lambda g: (g[0], '+ -'.index((g+' ')[1])) ) ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'] In order to get the comparative numerical order of 'X-','X','X+', I do a hacky append of a space ' ' so that g[1] always exists, so then I can use .index() to get the rank of the modifier '+ -'. (Motivated by this question)
tagged with: idioms
has comment: http://stackoverflow.com/comment/87240549
type: Question
score: 3
has answer: http://stackoverflow.com/a/64921678
has comment: http://stackoverflow.com/comment/87240553
has comment: http://stackoverflow.com/comment/87240498
tagged with: python

http://stackoverflow.com/comment/87272390
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50127206
type: Comment
has text: I tried localhost:8000 and it said the site is not working. same with the second one...

http://stackoverflow.com/comment/90655439
type: AnswerComment
comment on: http://stackoverflow.com/a/50149772
has text: @Munesh ```items = client.folder(folder_id=FOLDER_ID).get_items(limit=100, offset=0) FILENAME = "NAME_OF_YOUR_FILE.csv" FILE_ID = [x.id for x in items if x.name == FILENAME] ``` Of course you need the folder id, which is in the URL when you navigate to the folder.
score: 0
type: Comment

http://stackoverflow.com/comment/87456635
type: Comment
score: 0
type: AnswerComment
has text: I am working on a Jetson TX2 (ARM processor), so it's not exactly the greatest. I will test out your solution: would Cython be faster than this (closer to pure C for example)?
comment on: http://stackoverflow.com/a/50210508

optimization
tags question: http://stackoverflow.com/q/50120062
tags question: http://stackoverflow.com/q/50081859
tags question: http://stackoverflow.com/q/50210580
tags question: http://stackoverflow.com/q/50155277
tag name: optimization
tags question: http://stackoverflow.com/q/50182681
tags question: http://stackoverflow.com/q/50110269
tags question: http://stackoverflow.com/q/50164830
tags question: http://stackoverflow.com/q/50123308
tags question: http://stackoverflow.com/q/50206412
tags question: http://stackoverflow.com/q/50124619
tags question: http://stackoverflow.com/q/50202622
tags question: http://stackoverflow.com/q/50110619
type: Tag
tags question: http://stackoverflow.com/q/50225801

http://stackoverflow.com/comment/87396346
comment on: http://stackoverflow.com/a/50187397
type: Comment
has text: my bad, I had python 2 as default interpreter and it didn't work, with python3 it work nicely, thanks
score: 0
type: AnswerComment

http://stackoverflow.com/a/50163736
answers question: http://stackoverflow.com/q/50162964
score: 0
has body: import json from collections import defaultdict data = json.loads( '[{"id": 1, "parent_id": null}, {"id": 2, "parent_id": 1}, {"id": 6, "parent_id": null}, {"id": 16, "parent_id": 2}, {"id": 7, "parent_id": 1}, {"id": 3, "parent_id": 6}]') parents = {d['id']: d['parent_id'] for d in data} class RootsDict(dict): def __missing__(self, key): parent = parents[key] if parent is None: return key else: return self[parent] roots_dict = RootsDict() descendants = defaultdict(list) for d in data: id_ = d['id'] if d['parent_id'] is not None: descendants[roots_dict[id_]].append(id_) print(descendants) # {1: [2, 16, 7], 6: [3]} roots_dict is designed so that roots_dict[node] will return the top level parent of node, or node itself if it's already a root. __missing__ is a special method that can be overridden for dicts. It's called when key is requested from the dict but isn't present. Whatever the method returns will then be placed in the dict at that value. So for example roots_dict[16] when first accessed will be set to equal roots_dict[2], which in turn will ask for roots_dict[1], which is just 1. The rest is pretty straightforward.
type: Answer

http://stackoverflow.com/q/50090347
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50094379
has comment: http://stackoverflow.com/comment/87198304
has comment: http://stackoverflow.com/comment/87198380
tagged with: python
score: -1
has title: need help determining why output is always leonard wins all games
upvote count: 0
has comment: http://stackoverflow.com/comment/87198880
has body: #!/usr/bin/python3 # Constants - These constants will help improve the readability of your code SHELDON = "Sheldon" LEONARD = "Leonard" LEONARD_WINS = 0 SHELDON_WINS = 1 TIE = 2 ROCK = 0 PAPER = 1 SCISSORS = 2 LIZARD = 3 SPOCK = 4 # Variables - Use these variables in your code to track the program's progress leonardsShape = 0 sheldonsShape = 0 roundsToPlay = 0 leonardsWinCount = 0 sheldonsWinCount = 0 tieCount = 0 def convertShapeToText(shape): choices = {ROCK : "Rock", PAPER : "Paper", SCISSORS : "Scissors", LIZARD : "Lizard", SPOCK : "Spock"} return choices.get(shape, "default") # ======================================================================================================= # DO NOT MODIFY any of the code above this point # ======================================================================================================== # It's OK to change these constants (use the shape names above - ROCK, SCISSORS, PAPER, LIZARD, SPOCK) # See the Initial Values in the provided examples SHELDONS_FIRST_SHAPE = ROCK LEONARDS_FIRST_SHAPE = ROCK NUMBER_OF_ROUNDS = 4 print ("Jason Bolling") print ("project 4: Rock Paper Scissors Lizard Spock") def determineLeonardsNextShape(roundOutcome) : global leonardsShape global sheldonsShape if leonardsShape == 0 : if roundOutcome == 0 : return determineLeonardsNextShape == 0 elif roundOutcome == 1 : if sheldonsShape == 4 : return determineLeonardsNextShape == 3 elif sheldonsShape == 3 : return determineLeonardsNextShape == 0 elif sheldonsShape == 0 : return determineLeonardsNextShape == 1 elif sheldonsShape == 1 : return determineLeonardsNextShape == 2 elif sheldonsShape == 2 : return determineLeonardsNextShape == 4 elif roundOutcome == 2 : if leonardsShape == 0 : return determineLeonardsNextShape == 1 elif leonardsShape == 2 : return determineLeonardsNextShape == 2 elif leonardsShape == 2 : return determineLeonardsNextShape == 4 elif leonardsShape == 3 : return determineLeonardsNextShape == 0 elif leonardsShape == 4 : return det…
answer count: 1
tagged with: output
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50203984
has answer: http://stackoverflow.com/a/50204202
has comment: http://stackoverflow.com/comment/87425014
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87425332
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/87425531
has comment: http://stackoverflow.com/comment/87425452
has comment: http://stackoverflow.com/comment/87425071
tagged with: python
has body: I'm quite new to coding and don't have a proper education on the subject (most of my experience has been just stumbling through google searches) and I have a task that I would like assistance with. I have 38 files which look something like this: NGANo: 000a16d_1 Zeta: 0.050000 Ds5-95: 5.290000 Comments: Period, SD, SV, SA 0.010000 0.000433 0.013167 170.812839 0.020000 0.001749 0.071471 172.720229 0.030000 0.004014 0.187542 176.055129 0.040000 0.007631 0.468785 189.322248 0.050000 0.012815 0.912067 203.359441 0.060000 0.019246 1.556853 210.602517 0.070000 0.025400 1.571091 206.360018 They're all .DAT files and are four columns of data (Period, SD, SV, SA) that are single space delimited in each row, additionally there are two spaces at the end of each line of data. The only important data for me is the SA data, and I'd like to take the SA data and the title (this particular example being 000a16d_1) from each of these 38 files and put them all on the same sheet of an excel spreadsheet (one column after the next) with just the title followed by the SA data. I've tried a few different things, but I'm stuck on how to separate the rows of data from one column into 4. I'm not too knowledgeable on whether I should use numpy or pandas. I know that everything up to the second to last line is correct, as when I have print(table) it does print the rows of data, I just don't understand how to separate the single column into multiple. Here is my current code, all assistance is appreciated. import pandas as pd import numpy as np import os import xlsxwriter # path = "C:/Users/amihi/Downloads/Plotter_Output" dirs = os.listdir(path) # # for file in dirs: table = pd.read_table(file, skiprows=4) SA = table.loc[:,"SA"] print(SA)
has title: How to extract multiple columns from a space delimited .DAT file in python
accepted answer: http://stackoverflow.com/a/50204202
type: Question
tagged with: numpy

http://stackoverflow.com/q/50110619
has comment: http://stackoverflow.com/comment/87356471
has body: I have a following pice of code, which basically sets certain elements of a long numpy array to zero. import numpy as np a = np.array([[[1, 2, 3, 4], [0, 1, 2, 3], [1, 2, 3, 4]], [[0, 1, 2, 3], [0, 0, 1, 2], [0, 2, 3, 4]]]) aup = a + 2 b = np.array([[[0, 1, 2], [3, 4, 5], [0, 2, 3], [5, 6, 7], [0, 1, 2]], [[3, 4, 5], [0, 2, 3], [5, 6, 7], [0, 1, 2], [3, 4, 5]], [[0, 1, 2], [3, 4, 5], [0, 2, 3], [5, 6, 7], [0, 1, 2]], [[3, 4, 5], [0, 2, 3], [5, 6, 7], [0, 1, 2], [3, 4, 5]], [[0, 1, 2], [3, 4, 5], [0, 2, 3], [5, 6, 7], [0, 1, 2]]]) for i in range(3): for j in range(4): for row_t in range(a[0, i, j], aup[0, i, j]): for col_t in range(a[1, i, j], aup[1, i, j]): row = row_t%5 col = col_t%5 b[row, col, i] = 0 The main problem is the run time, which can be a lot because of the 4 for loops I have. Is there any numpy trick to avoid these for-loops and basically attain the same? Update: I think it all boils down to the following problem. First find the minimum of a and maximum of aup over axis 2, i.e. min_a = np.min(a, axis=2)%5 \\ [[1 0 1], [0 0 0]] max_aup = np.max(aup, axis=2)%5 \\ [[1 0 1], [0 4 1]] Npw list all the element wise tuples that form between min_a and min_aup. with corresponding index element: tuples = [[1, 1, 0], [0, 0, 1], [0, 1, 1], [0, 2, 1], [0, 3, 1], [0, 4, 1], [1, 0, 2], [1, 1, 2]] and set the elements of b at those tuples to be 0: b[tuples] = 0 So, the entire problem is basically efficiently finding these tuples.
tagged with: python
has title: Is there any numpy tricks to avoid for loops in this piece of code?
has comment: http://stackoverflow.com/comment/87238666
has comment: http://stackoverflow.com/comment/87238757
has answer: http://stackoverflow.com/a/50112867
accepted answer: http://stackoverflow.com/a/50112867
tagged with: numpy
has comment: http://stackoverflow.com/comment/87239078
has comment: http://stackoverflow.com/comment/87239427
tagged with: for-loop
downvote count: 2
has comment: http://stackoverflow.com/comment/87239121
score: 1
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/87387014
favorite count: 0
tagged with: optimization
type: Question
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/87300226
has text: when you run `pip freeze`? that doesn't sound correct
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50140969

http://stackoverflow.com/comment/87413727
type: Comment
has text: Thanks. I know in general how to evaluate and run the code for test data. I was just curious if this is different if you restore your pre-trained model as you mentioned in the second option. I guess it's the same.
type: AnswerComment
comment on: http://stackoverflow.com/a/50157899
score: 0

http://stackoverflow.com/q/50226259
downvote count: 0
answer count: 7
upvote count: 1
has body: My question is to find the highest value of the 9am humidity (stored in column 12, starting from zero) for each state. The data set looks like this: Date,State,City,Station Code,Minimum temperature (C),Maximum temperature (C),Rainfall (mm),Evaporation (mm),Sunshine (hours),Direction of maximum wind gust,Speed of maximum wind gust (km/h),9am Temperature (C),9am relative humidity (%),3pm Temperature (C),3pm relative humidity (%) 2017-12-01,NSW,Wollongong,068228,19.0,22.9,0,,,NE,59,21.4,81,21.9,80 2017-12-01,QLD,Brisbane,040913,21.8,28.0,0.2,5.6,12.4,E,26,26.6,65,27.1,64 2017-12-01,VIC,Melbourne,086338,21.5,23.5,1.8,11.4,0.0,N,41,21.8,92,18.9,98 2017-12-02,QLD,Gold Coast,040764,22.4,28.4,0,,,N,44,27.6,69,28.0,72 2017-12-02,NSW,Wollongong,068228,17.7,26.6,0,,,W,87,19.9,82,18.1,83 2017-12-02,QLD,Brisbane,040913,22.3,29.4,0,8.0,9.2,NNE,31,26.9,64,26.8,65 2017-12-02,NSW,Canberra,070351,17.7,19.6,35.2,,,NNW,65,17.8,99,16.0,88 2017-12-02,NSW,Newcastle,061055,19.3,28.2,0,,,NW,54,24.0,100,27.3,90 2017-12-02,VIC,Melbourne,086338,14.7,16.4,20.6,3.0,0.0,SSW,56,15.1,97,16.1,93 2017-12-02,SA,Adelaide,023034,15.0,20.4,0.2,4.6,5.0,SSW,57,17.8,52,18.1,59 2017-12-02,NSW,Albury,072160,18.4,20.6,49.6,,,NNE,39,18.5,96,20.1,76 2017-12-03,VIC,Ballarat,089002,8.1,14.4,13.6,,,S,50,10.1,94,13.3,68 2017-12-03,NSW,Wollongong,068228,16.7,24.7,7.2,,,WNW,44,19.7,63,20.7,70 2017-12-03,VIC,Geelong,087184,11.5,17.5,5.8,,,SSW,50,14.0,93,13.6,86 2017-12-03,VIC,Bendigo,081123,10.5,19.8,2.4,,,SSW,48,13.8,65,17.4,46 2017-12-03,WA,Perth,009021,20.1,36.0,0,15.8,4.6,E,70,29.0,19,34.8,12 2017-12-03,QLD,Toowoomba,041529,17.0,25.5,19.8,,,NNW,31,20.0,80,24.3,55 2017-12-03,NSW,Canberra,070351,12.2,19.9,18.4,,,NW,48,13.8,85,19.3,61 2017-12-03,NSW,Newcastle,061055,16.8,27.2,9.4,,,NNW,52,20.7,100,26.3,78 2017-12-03,QLD,Sunshine C,040861,22.1,28.1,3.0,,,NE,35,26.9,68,24.6,91 2017-12-03,QLD,Gold Coast,040764,22.2,27.8,4.0,,,NNW,41,25.5,78,25.3,86 2017-12-03,SA,Adelaide,023034,12.8,19.9,0.6,6.2,5.7,S,50,16.2,52,15.9,65 …
has answer: http://stackoverflow.com/a/50226714
type: Question
accepted answer: http://stackoverflow.com/a/50226439
has answer: http://stackoverflow.com/a/50226861
linked to: http://stackoverflow.com/q/613183
score: 1
has answer: http://stackoverflow.com/a/50226439
has title: Creating a dictionary and aggregate the values with the corresponding key
possible better answer: http://stackoverflow.com/a/50226445
tagged with: python
has comment: http://stackoverflow.com/comment/87469913
has answer: http://stackoverflow.com/a/50226625
linked to: http://stackoverflow.com/q/11041405
has answer: http://stackoverflow.com/a/50226720
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50226445
has comment: http://stackoverflow.com/comment/87470094
has answer: http://stackoverflow.com/a/50226580
has comment: http://stackoverflow.com/comment/87469978
favorite count: 0

http://stackoverflow.com/comment/87342997
type: Comment
type: QuestionComment
score: 0
has text: Better in what sense? Does the code do what you want? What do you think should be improved? Numpy and other libraries can do a good job at printing matrices but making your code depend on them just for this is not necessarily better.
comment on: http://stackoverflow.com/q/50162424

http://stackoverflow.com/q/50179485
answer count: 1
accepted answer: http://stackoverflow.com/a/50179649
type: AnsweredQuestion
has title: Convert table to aggregated table
tagged with: pandas
has body: I'm new to python pandas, and I wanna convert the following dataFrame : AutomationStatus TestPriority 0 Done 4 1 Done 4 2 Done 4 3 Done 4 4 Done 4 5 Done 4 6 Done 4 7 Done 4 8 Done 4 9 Will Not Automate 3 10 Done 4 11 Review for Automation 3 12 Review for Automation 3 13 Review for Automation 3 14 Review for Automation 3 15 Review for Automation 3 16 Review for Automation 3 17 Review for Automation 3 18 Review for Automation 3 19 Review for Automation 3 20 Review for Automation 3 21 Review for Automation 3 22 Review for Automation 3 23 Review for Automation 3 24 Review for Automation 3 25 Review for Automation 3 26 Review for Automation 3 27 Review for Automation 3 to a format where it shows aggregate numbers for AutomationStatus like this: TestPriority 3 4 Automated 0 10 Manual Test 16 2 Basically I want to mark AutomationStatus=Done as Automated and everything els as Manual Test and show number of related tests (with priority) I think I should use pivot_table but not an expert. any suggestion (and pointing to documentation) would be appreciated
tagged with: python
has answer: http://stackoverflow.com/a/50179649
type: Question
score: 0

http://stackoverflow.com/q/50180881
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87380530
has body: I'm new to Python and have been assigned the task of parsing a text file to search for certain information and add that information to an array. Here is an example of what I need to do: Read file Check for "*test, test =_" Skip that line While next lines only contains numbers, commas, and space Add numbers from that line to an array named Bnodes File Contains Following Lines: *test, test=_TestSet312, internal, instance=Test_LM_3Z1-1 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 240, 241, 242, 243 I read the file and passed it in as an object named f so I can iterate over with open(BoundaryFile, 'r') as f: So far my code uses "*test, test = " to identify which line to skip. I skip that current line and I want to add all of the following lines to an array as long as they only contain digits, comma, and a space (this is where I am having trouble). I am not sure how to check if the next line only contains numbers, comma, and a space. So far I came up with something like this: Section of Code I am having trouble on: pattern = re.compile("/\d(, +\d)?/") Bnodes = [] while(pattern.match(next(f))): Bnodes.append(next(f)) I know this is probably not the best way to approach this. Are there any better ways that provide an efficient solution?
tagged with: python
tagged with: regex
score: 0
has answer: http://stackoverflow.com/a/50183279
has answer: http://stackoverflow.com/a/50181743
answer count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87381668
has title: How to use an iterator in Python to grab next line from file, check if it matches regex, and add to an array if it matches?
has answer: http://stackoverflow.com/a/50183087

http://stackoverflow.com/comment/87447633
type: AnswerComment
comment on: http://stackoverflow.com/a/50214592
score: 0
type: Comment
has text: Very interesting technique indeed. Thanks for helping out!

http://stackoverflow.com/a/50205854
type: Answer
has comment: http://stackoverflow.com/comment/87494945
accepted answer of: http://stackoverflow.com/q/50205842
has body: By using your own function you just need to pass a Boolean, and filter the original dataframe percentChange = abs(data['Ask'].pct_change())&gt;0.05 morethan5=data[percentChange] Date=morethan5['Time (UTC)']
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50205842

http://stackoverflow.com/q/50081859
type: Question
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19837486
has comment: http://stackoverflow.com/comment/87195074
tagged with: optimization
score: 0
has body: I am trying to use scipy to solve a non-trivial optimisation. I have a 6 dimensional problem. The function I am trying to optimize is not linear. I think that this non-linear optimization problem can be solved with scipy.optimize.minimize, see https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize The documentation shows that the constraints can be handled one by one by: cons = ({'type': 'eq', 'fun' : lambda x: np.array([x[0]**3 - x[1]]), 'jac' : lambda x: np.array([3.0*(x[0]**2.0), -1.0])}, {'type': 'ineq', 'fun' : lambda x: np.array([x[1] - 1]), 'jac' : lambda x: np.array([0.0, 1.0])}) In my case I need 12 constraints: one max and one min for each dimension. I also want something that I could generalise to more or fewer dimensions, so I do not want to type all the constraints by hand. Assuming that my mins and maxs are in two arrays. If I use a loop such as: for i in range(6): grad_min = np.zeroes(6) grad_max = np.zeroes(6) grad_min[i] = +1. grad_max[i] = -1 cons_min = {'type': 'ineq', 'fun' : lambda x: np.array([x[i] - min[i]), 'jac' : lambda x : grad_min}) cons_max = {'type': 'ineq', 'fun' : lambda x: np.array([-x[i] + max[i]), 'jac' : lambda x : grad_max}) cons = cons + (cons_min,cons_max) But because of the lack of closure of lambda functions in Python this would fail, only the last (i=5) would be enforced. I am looking for another design where I can defined all constraints simultaneously, I need to use something with closure..
has title: Defining optimization constraints: need for function closure
tagged with: closures
has comment: http://stackoverflow.com/comment/87195116
tagged with: python
tagged with: scipy

http://stackoverflow.com/a/61197320
accepted answer of: http://stackoverflow.com/q/50096645
type: AcceptedAnswer
downvote count: 0
has body: The question might be outdated, but looks like the following function from scipy.ndimage might solve your issue. What scipy.ndimage.interpolation.rotate does is it rotates the full 3d array around either of the 3 axes by a certain angle interpolating the stored values to the new "cells". It also resizes (extends) the new array accordingly, filling the new empty cells by a value you specify. After that you can take slice as you would normally do, say: array[:,sy//2,:]. So in short, here's a central cut around a diagonal parallel to the z-axis (for simplicity): sz, sy, sx = array.shape array[:,sy//2,:] # this is a cut in the x-z plane ... # ... passing through the middle of the y-axis # rotating by 45 degrees around the z axis ... # ... `(2,1)` is `(x,y)` which defines the rotation plane array_rotated = scipy.ndimage.interpolation.rotate(array, angle=45, axes=(2,1)) sz, sy, sx = array_rotated.shape # now you'll notice that `sz` is the same ... # ... but `sx` and `sy` have increased because the diagonal is longer array_rotated[:,sy//2,:] # this slice is now in the new x'-z' plane ... # ... but in terms of the original array ... # ... it passes through the diagonal of x-y along z You can actually think a bit further and extend this to an arbitrary slice by rotating it around different axes several times. PS. If you feel it takes too much time, you can sacrifice the quality of interpolation by passing the order=0 (default is order=3). This will run faster.
upvote count: 1
answers question: http://stackoverflow.com/q/50096645
score: 1
type: Answer

http://stackoverflow.com/comment/87422721
score: 1
has text: `itertools.product` itself runs in O(1) time; the elements of the product are produced as you iterate over the result.
type: Comment
comment on: http://stackoverflow.com/a/50202890
type: AnswerComment

http://stackoverflow.com/q/50134883
possible better answer: http://stackoverflow.com/a/50134963
tagged with: bubble-sort
has comment: http://stackoverflow.com/comment/87287862
has answer: http://stackoverflow.com/a/50135130
has answer: http://stackoverflow.com/a/50134963
accepted answer: http://stackoverflow.com/a/50135130
tagged with: object
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87287918
tagged with: python
has comment: http://stackoverflow.com/comment/87287907
favorite count: 0
type: Question
answer count: 2
has body: I don't understand the reason that in the first example, b is considered as a copy of a and it will change with a but not in the second example def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]&gt;alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp return alist a=[3,2,1] b=a a=bubbleSort(a) print(a) print(b) The output: [1, 2, 3] [1, 2, 3] a=[3,2,1] b=a a=[1,2,3] print(a) print(b) Output: [1, 2, 3] [3, 2, 1]
has title: assigned in python considered as a copy of an object

http://stackoverflow.com/comment/87468634
comment on: http://stackoverflow.com/q/50225497
type: Comment
type: QuestionComment
has text: @Klaus.D they imported `arrow` which is a "human friendly date time library", sort of like `requests` vs `urllib`
score: 0

http://stackoverflow.com/a/50220058
has body: IIUC, you can leverage the errors='coerce' argument of pd.to_datetime, which will set unformattable strings to NaT. Take the following df for an example: df = pd.DataFrame({'date':['1999-01-01', 'xyz', '2000-05-05']}) &gt;&gt;&gt; df date 0 1999-01-01 1 xyz 2 2000-05-05 You can create your timedelta-like column using: df['my_timedelta'] = pd.to_datetime('today') - pd.to_datetime(df['date'], errors='coerce') Which results in: &gt;&gt;&gt; df date my_timedelta 0 1999-01-01 7066 days 1 xyz NaT 2 2000-05-05 6576 days
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50219969
has comment: http://stackoverflow.com/comment/87457996
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87457255
has comment: http://stackoverflow.com/comment/87457778
has comment: http://stackoverflow.com/comment/87457679
type: Answer
answers question: http://stackoverflow.com/q/50219969

http://stackoverflow.com/q/50092682
has comment: http://stackoverflow.com/comment/87201617
type: Question
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/7370801
tagged with: sorting
has answer: http://stackoverflow.com/a/50092807
has body: I am not sure on how to time a bubble sort like this, any input is appreciated! In addition i'd like to be able to 'print' how long it took in seconds after sorting. Also any comments on the code itself are welcome! def bubbleSort(list): needNextPass = True k = 1 while k &lt; len(list) and needNextPass: # List may be sorted and next pass not needed needNextPass = False for i in range(len(list) - k): if list[i] &gt; list[i + 1]: # swap list[i] with list[i + 1] temp = list[i] list[i] = list[i + 1] list[i + 1] = temp needNextPass = True # Next pass still needed # A test method def main(): list = [5000, 200000, 250000, 10000, 150000, 300000] bubbleSort(list) for v in list: print("Bubble sort list: ",v, end = ",") main()
score: 0
has title: How to time a bubble sort
has comment: http://stackoverflow.com/comment/87201612
answer count: 1
has comment: http://stackoverflow.com/comment/87201855

http://stackoverflow.com/q/50075650
tagged with: qtextedit
score: 0
has comment: http://stackoverflow.com/comment/87167646
has title: what is wrong in my function that not parse the hall content of JSON file using python
tagged with: http://stackoverflow.com/tag/json
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87167536
linked to: http://stackoverflow.com/q/13559990
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50075788
tagged with: python-3.x
type: UnansweredQuestion
has body: I have a function that read from a JSON file and display the content in a QtextEdit using Pyqt5. Problem is that when i tried to parse the content in the TextEdit the last record of the File Name is displayed. while if i print to the console all the records of the File Name are printed as it should. at the end i need to display the result as the comment print def displayReport(self,item): searchRes=os.path.join(os.getcwd(),"search_result") path = os.listdir(searchRes) data =[] try: for file in path: rpjson = json.load(open(os.path.join(searchRes,item))) for js in rpjson: fileName = js["File Name"] srchwRD = js["Searched Word"] nbrOfOccur = str(js["Number Of Occurence"]) result = [fileName + srchwRD + nbrOfOccur] print("this is file name {}".format(fileName)) data.append(result) #print("****************" + "\n" + "File Name: " + #js["File Name"] + "\n" + "Searched Word: " + #js["Searched Word"] + "\n" + "Number Of Occurence: " + #str(js["Number Of Occurence"])) except Exception as e: print("can't read JSON because {}".format(e)) self.textEdit.setHtml("\n".join (data))
has comment: http://stackoverflow.com/comment/87167534
tagged with: python

http://stackoverflow.com/q/50092608
tagged with: http://stackoverflow.com/tag/json
tagged with: python
possible better answer: http://stackoverflow.com/a/50092616
has comment: http://stackoverflow.com/comment/87201505
has body: I've defined a helper method to load json from a string or file like so: def get_json_from_string_or_file(obj): if type(obj) is str: return json.loads(obj) return json.load(obj) When I try it with a file it fails on the load call with the following exception: File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 291, in load **kw) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I have triple checked my json file and it is definitely not empty, it just has a simple foo bar key value mapping. Also, I'm feeding the json file into the method like so: os.path.join(os.path.dirname(__file__), "..", "test.json") Any idea whats going on here? EDIT: I changed my helper method to the following to fix up the mistakes addressed in the answers and comments and it's still not working, i'm getting the same error when I pass in an already open file. def get_json_from_file(_file): if type(_file) is str: with open(_file) as json_file: return json.load(json_file) return json.load(_file) EDIT #2: I FOUND THE PROBLEM! this error occurs if you call json.load on an open file twice in a row. It turns out that another part of my application had already got that file open. Here is some reproduction code: with open("/test.json") as f: json.load(f) json.load(f)
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/50092660
has answer: http://stackoverflow.com/a/50092660
downvote count: 0
upvote count: 1
has title: Python load json helper method not working
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50092616
has comment: http://stackoverflow.com/comment/87201545
score: 1

http://stackoverflow.com/a/50103949
accepted answer of: http://stackoverflow.com/q/50103637
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50103637
has comment: http://stackoverflow.com/comment/87232471
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: The problem was using python 32-bit on a 64-bit machine. Python x64 opens the file as expected.

http://stackoverflow.com/comment/87237189
comment on: http://stackoverflow.com/q/50109634
score: 0
type: Comment
type: QuestionComment
has text: @abarnert The opened issues were for python3 while I am using python2.7 on a 64 bit platform. I guess it's a hashing problem too.

http://stackoverflow.com/comment/87311865
comment on: http://stackoverflow.com/a/50128868
type: Comment
has text: Thanks for the response ! Can you please tell me what is value_count() method? i am not able to get it
score: 0
type: AnswerComment

http://stackoverflow.com/q/50097688
has answer: http://stackoverflow.com/a/50097793
has comment: http://stackoverflow.com/comment/87211780
type: Question
has answer: http://stackoverflow.com/a/50098505
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50097740
tagged with: django
tagged with: django-models
tagged with: python
has title: Only Want a user to 'like' a comment once. My code is not working
has body: I have Post model, that has a field likes_total on it. I only want a user to be able to like a post once, but the code for this in the view is not working. here is the code: views.py def like(request, post_id, group_id): group = get_object_or_404(Group, pk= group_id) post = get_object_or_404(Post, pk= post_id) likers = [] if request.method == 'POST': if request.user in likers: return render(request, 'groups/detail.html', {'group':group, 'error': "you have already liked this post"} ) else: post.likes_total += 1 post.save() likers.append(request.user) return redirect('/groups/' + str(group_id) ) # post.save() else: return render(request, 'groups/detail.html', {'group':group}) this code seems right to me, cant tell what the problem is.. any help would be really appreciated!
score: 0
tagged with: django-views
answer count: 3

http://stackoverflow.com/q/50109699
upvote count: 1
has title: Pandas read_csv with multilined header xls file
answer count: 1
has answer: http://stackoverflow.com/a/50110008
has body: How can I read the header of the following xls file using pandas? All column headers such as DATE, BENCHMARK NAME are on line 3 but the percentile values "1ST (PERCENT)" are on line 4. When I try: df = pd.read_csv(xls_url, skiprows=[0,1,7], header=3) # or header=[3,4] I get the following error: ParserError: Error tokenizing data. C error: Expected 1 fields in line 13, saw 2
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/50110008
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/q/50102426
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87222235
score: 0
has comment: http://stackoverflow.com/comment/87222000
answer count: 0
has body: When I use pickle to load a GB file, it report a Memory Error, how can I solve it? My code is like this: model_file_path = os.path.join(model_directory, model_file_name) with open(model_file_path, 'rb') as fh: return pickle.load(fh) My python bit is 64, version is 3.4.4.
upvote count: 1
tagged with: pickle
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87222889
downvote count: 1
has comment: http://stackoverflow.com/comment/87224278
type: Question
tagged with: out-of-memory
has comment: http://stackoverflow.com/comment/87222157
has title: MemoryError: Python uses pickle to load GB level file
has comment: http://stackoverflow.com/comment/87222127
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87221778
has comment: http://stackoverflow.com/comment/87221980

http://stackoverflow.com/comment/87300872
has text: thanks for the help, it was such a simple error!?! but why do the curly brackets pull in the value from clock?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50124624

http://stackoverflow.com/q/50141318
tagged with: google-cloud-dataflow
score: 4
type: AnsweredQuestion
has title: Apache Beam DynamicDestinations Python equivalent
possible better answer: http://stackoverflow.com/a/57542766
has answer: http://stackoverflow.com/a/57542766
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has body: The Apache Beam Java SDK has a DynamicDestinations class that allows writing to different big query tables based on the input element. I don't see anything in the Python SDK that looks equivalent. Is there some class that allows writing to dynamically chosen destination tables in the Python SDK?
accepted answer: http://stackoverflow.com/a/50150829
downvote count: 0
tagged with: apache-beam
tagged with: python
has answer: http://stackoverflow.com/a/50150829

http://stackoverflow.com/comment/87296947
score: 0
has text: Not possible. `+` is a binary operator (i.e. it takes 2 arguments) and there's nothing you can do about it.
type: QuestionComment
comment on: http://stackoverflow.com/q/50139189
type: Comment

http://stackoverflow.com/comment/116920145
comment on: http://stackoverflow.com/a/50276746
has text: @Kaszanas you should open a new question and provide more information of your use case for getting answer. Good luck.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50083093
upvote count: 1
has body: I am not sure I understand your comment correctly. You can use random.randint(a,b) to get integer, not decimal number. (https://docs.python.org/3/library/random.html#random.randint) import random guess = '0' answer = random.randint(1, 100) while (guess) != 'exit': answer = str(answer) guess = input('Enter a number between 1 and 100 or enter exit to exit: ') if not guess.isdigit(): if guess == "exit": print('Game closed') break else: print('Your guess was not a digit, try again') guess = (guess) if guess == answer: print('Correct') answer = random.randint(1, 100) #make new random number if guess is correct elif guess &gt; answer : print('Too high, try again') elif guess &lt; answer : print('Too low, try again')
has comment: http://stackoverflow.com/comment/87182062
has comment: http://stackoverflow.com/comment/87182079
answers question: http://stackoverflow.com/q/50082965
has comment: http://stackoverflow.com/comment/87182110
score: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/87182069

http://stackoverflow.com/a/54748073
has body: Ok, don't be worried. If you use the virtual environment to manage the python version. So you can solve this problem by the following: cd $PYMESH_PATH mkdir build cd build cmake -DPYTHON_LIBRARY=/Users/user/.pyenv/versions/anaconda3-5.2.0/lib/libpython3.6m.dylib -DPYTHON_INCLUDE_DIR=/Users/user/.pyenv/versions/anaconda3-5.2.0/include/python3.6m -DPYTHON_EXECUTABLE:FILEPATH=/Users/user/.pyenv/versions/anaconda3-5.2.0/bin/python .. make -j cd .. python setup.py install You can also refer to this. This solved my problem. Good Luck!!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50205891

http://stackoverflow.com/q/50110868
tagged with: python-3.x
type: AnsweredQuestion
score: 0
tagged with: aiml
has answer: http://stackoverflow.com/a/50922487
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50922487
tagged with: python
has body: My AIML pattern "HI" bot answer "HI TOO" My code text = input.("ASK?") if text == text: try: print(k.respond(text)) except: print('NOT FOUND') if i input wrong pattern like "WRONG" except massage doesnt apper
has title: Except method python pyAIML
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/comment/87185176
comment on: http://stackoverflow.com/a/50084412
has text: Works perfectly. Thanks.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87491406
type: QuestionComment
has text: how do I convert each text line to JSON. I have tried textFile("/path/filename.jsonl") but how do I parse this texFile as JSON in Python Spark (PySpark).
comment on: http://stackoverflow.com/q/50219200
score: 0
type: Comment

http://stackoverflow.com/q/50110153
answer count: 1
has body: I'm currently trying to get the cv2 library on python so I could play some videos using python. Whenever I try to install cv2 from pycharm I get this error: Collecting cv2 Could not find a version that satisfies the requirement cv2 (from versions: ) No matching distribution found for cv2 I looked around and read that I should installopencv-python using pip, and I did, but pycharm still does not recognise cv2.
type: Question
tagged with: python-3.x
tagged with: pycharm
has title: How to get cv2 running on python3.6?
has comment: http://stackoverflow.com/comment/87237641
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87237623
tagged with: python
has answer: http://stackoverflow.com/a/50110728
tagged with: opencv
score: 0

http://stackoverflow.com/q/50085283
tagged with: multilabel-classification
score: 2
has comment: http://stackoverflow.com/comment/87559053
answer count: 0
upvote count: 2
has body: I'm using tensorflow on MSCOCO dataset which has 80 different classes and each image can contain more than one class (multilabels), this is modeled in my input as a list of 80 elements for each image, containing 1s at the right classes and 0s at he wrong classes. I'm trying to calculate accuracy by checking the number of 1s in the predicted logits layer and comparing it element wise with the input true labels. Using tf.equal(logits , truelabels) is not applicable because there are 80 classes with lots of zeros that are predicted correctly. So I end up with a high accuracy number and wrong predictions. I tried to use tf.map_fn to break down the tensor into elements but apparently I can't use a counter like variable inside the function to choose the current true labels from a the true label batch (Y_). here is my code: rounded = tf.round(Y) C = 0 V = 0 sumseen = 0. sumtrue = 0. avgg = 0. def avgfunc(elm): global C global V global sumseen global sumtrue global avgg tru = Y_[C] ***tf.add(V,1)*** cond1 = tf.count_nonzero(tf.cast(tf.equal(elm,tf.constant(1.,tf.float32)),tf.float32)) cond2 = tf.count_nonzero(tf.cast(tf.equal(elm,tru[V]),tf.float32)) if(cond1 == 1): sumseen+=1 if(cond2 == 1): sumtrue+=1 ***if(V &gt;= 79): V = 0 avgg = ((sumtrue/sumseen)*100) if sumseen !=0 else 0*** return sumseen def _comparefunc(elem_probs): global C tru = Y_[C] mapout = tf.map_fn(avgfunc, elem_probs) ***C = C+1 if(C == 49): C = 0*** return avgg outputafter = tf.map_fn(_comparefunc, rounded) accuracyofbatch = tf.reduce_mean(outputafter)
has title: Accuracy calculation in multilabel classification
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50175143
linked to: http://stackoverflow.com/q/49706066
tagged with: facebook-sdk-4.0
tagged with: python
duplicate of: http://stackoverflow.com/q/49706066
has body: I am trying do download information about events using Facebook in a Python code. Firstly I tried to extract all the events linked to "Rock". This is how the code looks like: import urllib3 import facebook import requests token = "xyz" graph = facebook.GraphAPI(access_token = token, version = 2.7) events = graph.request('/search?q=Cinema&amp;type=event&amp;limit=10000') print('Print if token O.K.') eventList = events['data'] print('Everything is still ok.') if len(eventList) != 0: print('Works.') else: print('Something strange happened.') The first string was printed so everything is alright with the token and the permission. However the list is empty. I wonder why? My second question is if it is possible to download events from a certain city only?
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50175199
answer count: 1
upvote count: 1
tagged with: facebook-graph-api
has answer: http://stackoverflow.com/a/50175199
downvote count: 1
has title: Empty list of events while downloading data from Facebook
favorite count: 0
type: Question

http://stackoverflow.com/a/50186392
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87389563
has comment: http://stackoverflow.com/comment/87389685
accepted answer of: http://stackoverflow.com/q/50186374
has comment: http://stackoverflow.com/comment/87389628
type: Answer
answers question: http://stackoverflow.com/q/50186374
upvote count: 2
score: 2
has body: Just use set method because the items order in the lists are different and that's why you've received False as result. print (set(c) == set(list(set(b).union(c)))) Another solution is to use Counter class. The Counter approach should be more efficient for big lists since it has linear time complexity (i.e. O(n)) from collections import Counter Counter(c) == Counter(list(set(b).union(c))))

http://stackoverflow.com/a/50181371
answers question: http://stackoverflow.com/q/50181332
has comment: http://stackoverflow.com/comment/87380283
downvote count: 0
has body: is tests for identity. The status code is indeed not the same object as 403 or codes.forbidden. The status value is an integer, not a singleton enumeration object. Use == to test if the value is the same: if addresses.status_code == 403: # ... assert addresses.status_code != 403 assert addresses.status_code != codes.forbidden assert addresses.status_code == codes.ok or just use addresses.raise_for_status() # raises an exception if not 1xx, 2xx or 3xx The Response.raise_for_status() method raises a requests.exceptions.HTTPError exception (a subclass of requests.exceptions.RequestException, in turn a OSError subclass). Note that sometimes is will work with integers, or any number of other types. But unless there is specific documentation that you can use identity tests, you have instead found an implementation detail where Python will have re-used objects for performance reasons. Such is the case for small integers (from -5 through to 256), and for strings in certain cases, and many other corner cases. So address.status_code is 200 just happens to work in current CPython interpreters, but this is not a given and should not be relied upon.
score: 5
has comment: http://stackoverflow.com/comment/87380160
type: AcceptedAnswer
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50181332

http://stackoverflow.com/q/50227854
score: 1
tagged with: python
has body: I have a treeview that displays my data from a sqlite database. Everything works fine so far, but now I want that the user can manipulate the data directly in the treeview and save it back to the database. But I cant find a way to do that. The part that I not working for me is to make the cell editable directly within the tree! I have shortened my code for this post to this: import tkinter.ttk as ttk self.tree = ttk.Treeview(master, height=10) #Tree Config self.tree["columns"] = ("One","Two","Three") self.tree.column("One",width = 100) self.tree.column("Two",width = 100) self.tree.heading("One",text="One", anchor=W) self.tree.heading("Two",text="Two", anchor=W) #Bind Doubleclick to the Tree self.tree.bind("&lt;Double-1&gt;", self.tree_selectItem) #Add the Tree to the grid self.tree.grid(row=1,column=1,columnspan=4, rowspan=5, sticky=N+E+S, pady=0, padx=25)
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87473246
downvote count: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87473171
tagged with: treeview
has comment: http://stackoverflow.com/comment/87489251
linked to: http://stackoverflow.com/q/18562123
favorite count: 0
type: Question
has title: Tkinter Treeview manipulate values in the cell

http://stackoverflow.com/q/50077698
has answer: http://stackoverflow.com/a/50078253
tagged with: search
type: AnsweredQuestion
score: 0
tagged with: tkinter
tagged with: treeview
answer count: 1
has body: I use a treeview to show all items a folder contains. I create all entries with this function: def SUBS(path, parent): for p in os.listdir(path): abspath = os.path.join(path, p) parent_element = tree.insert(parent, 'end', text=p, open=True) if os.path.isdir(abspath): SUBS(abspath, parent_element) and now i want to search through it with this function: def search(event, item=''): children = tree.get_children(item) for child in children: text = tree.item(child, 'text') if text.startswith(entry.get()): tree.selection_set(child) The Problem is that the search function only search through the first "nodes". Not all. So how do i search throug the children of a child? And how are they called?
type: Question
tagged with: python-3.x
has title: Python Tkinter Treeview search all entries
tagged with: python
accepted answer: http://stackoverflow.com/a/50078253

http://stackoverflow.com/q/50109822
has body: I have created a xarray dataarray using the xarray concat command. This has resulted in a dataarray with name __xarray_dataarray_variable__. However, I cannot seem to rename it using the rename command. Is there some other way to rename it? I tried this: da.rename({'__xarray_dataarray_variable__': 'new'}) but I get this error: *** ValueError: cannot rename '__xarray_dataarray_variable__' because it is not a variable or dimension in this dataset This is what the dataarray looks like: &lt;xarray.DataArray (time: 2, band: 1, y: 2334, x: 4258)&gt; dask.array&lt;shape=(2, 1, 2334, 4258), dtype=float32, chunksize=(1, 1, 2334, 4258)&gt; Coordinates: * band (band) int32 1 * y (y) float64 4.406e+06 4.406e+06 4.406e+06 4.406e+06 4.406e+06 ... * x (x) float64 1.125e+05 1.126e+05 1.127e+05 1.128e+05 1.129e+05 ... * time (time) datetime64[ns] 2005-12-31 2006-12-31 Attributes: transform: (90.0, 0.0, 112500.0, 0.0, -90.0, 4406400.0, 0.0, 0.0, 1.0) crs: +ellps=GRS80 +no_defs +proj=utm +towgs84=0,0,0,0,0,0,0 +unit... res: (90.0, 90.0) is_tiled: 1 nodatavals: (-9999.0,) From http://xarray.pydata.org/en/stable/generated/xarray.DataArray.to_netcdf.html, Only xarray.Dataset objects can be written to netCDF files, so the xarray.DataArray is converted to a xarray.Dataset object containing a single variable. If the DataArray has no name, or if the name is the same as a co-ordinate name, then it is given the name ‘xarray_dataarray_variable’.
has comment: http://stackoverflow.com/comment/87270167
has comment: http://stackoverflow.com/comment/87239750
has comment: http://stackoverflow.com/comment/87236997
has comment: http://stackoverflow.com/comment/87237031
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87265908
downvote count: 0
has answer: http://stackoverflow.com/a/50124025
accepted answer: http://stackoverflow.com/a/50124025
has comment: http://stackoverflow.com/comment/87237017
answer count: 1
has title: renaming __xarray_dataarray_variable__ in xarray dataarray
tagged with: python
upvote count: 4
score: 4
linked to: http://stackoverflow.com/q/46899337
tagged with: python-xarray
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87269798

http://stackoverflow.com/comment/87600598
has text: @ jonyfries thanks. Yes i want only 1 scroll for two columns
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50219281

google-oauth
type: Tag
tag name: google-oauth
tags question: http://stackoverflow.com/q/50101565

http://stackoverflow.com/comment/87173061
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50077995
has text: You should use a different variable for each article `words1.extend(art1.split())`, `words2.extend(art2.split())`. You use the same so I guess you are getting the count of all articles. Also, there's a length tag, might help to check your total count ` 1206 words `

http://stackoverflow.com/q/50077212
score: -2
has title: Subscribe to bitFlyer WebSocket
tagged with: python
accepted answer: http://stackoverflow.com/a/50225222
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50225222
upvote count: 0
downvote count: 2
answer count: 1
tagged with: websocket
has body: I have set up websocket connections to multiple cryptocurrency exchanges but I'm having difficulty connecting to bitFlyer's. My code is as follows: import websocket import json def on_message(ws, message): msg = json.loads(message) print(msg) def on_error(ws, error): print(error) def on_close(ws): print("### closed ###") def on_open(ws): ws.send(json.dumps({"method":"subscribe", "channel":"lightning_executions_FX_BTC_JPY"})) while True: if __name__ == "__main__": #websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://ws.lightstream.bitflyer.com/json-rpc", on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever() I have tried many many variations of my on_open() message and most result in a ### closed ### Invalid close opcode. error. Unfortunately their documentation does not contain a Python sample located HERE. Any help in sending the correct message is much appreciated.
favorite count: 0
type: Question

http://stackoverflow.com/comment/92603947
has text: @oya163 it should grab it using grep from nvidia-smi. No need to manually add it.
type: AnswerComment
comment on: http://stackoverflow.com/a/50193539
score: 0
type: Comment

http://stackoverflow.com/a/50083454
type: AcceptedAnswer
has body: A code block is a group of statements that will be run as a unit. For example: if (condition): # Statement 1 # Statement 2 # Statement 3 else: # Statement 4 # Statement 5 # Statement 6 You will find that statements 1,2,3 will have the same indentation and therefore is of the same block. And similarly, statements 4,5,6 is of a another block. You may refer to: Execution model Flow of Control in Python
answers question: http://stackoverflow.com/q/50083391
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/50083391
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/50084539
has answer: http://stackoverflow.com/a/50084631
answer count: 2
upvote count: 2
has body: I know this may seem like a duplicate of docker-compose with multiple databases, but I still can't manage to get it working after going through the answers. Here is my docker-compose.yml: version: '3' services: backend: image: backend:1.0 build: ./backend ports: - "9090:9090" depends_on: - db - ppt environment: - DATABASE_HOST=db db: image: main_db:26.03.18 restart: always build: ./db ports: - "5432:5432" ppt: image: ppt_generator:1.0 build: ./ppt ports: - "6060:6060" login: image: login:1.0 build: ./login ports: - "7070:7070" depends_on: - login_db login_db: image: login_db:27.04.2018 restart: always build: ./login_db ports: - "5433:5433" Notice that I have one db on port 5433 and the other on 5432. However, when I run docker ps after starting the containers I get the following. I don't fully understand what is going on with the ports. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 997f816ddff3 backend:1.0 "/bin/sh -c 'pytho..." About a minute ago Up About a minute 0.0.0.0:9090-&gt;9090/tcp backendservices_backend_1 759546109a66 login:1.0 "/bin/sh -c 'pytho..." About a minute ago Up About a minute 0.0.0.0:7070-&gt;7070/tcp, 9090/tcp backendservices_login_1 a2a26b72dd0c login_db:27.04.2018 "docker-entrypoint..." About a minute ago Up About a minute 5432/tcp, 0.0.0.0:5433-&gt;5433/tcp backendservices_login_db_1 3f97de7fc41e main_db:26.03.18 "docker-entrypoint..." About a minute ago Up About a minute 0.0.0.0:5432-&gt;5432/tcp backendservices_db_1 1a61e741ccba ppt_generator:1.0 "/bin/sh -c 'pytho..." About a minute ago Up About a minute 0.0.0.0:6060-&gt;6060/tcp backendservices_ppt_1 Both my db dockerfiles are essentially identical except for the port number I expose: FROM postgres:9.6.3 ENV POSTGRES_USER ludo ENV POSTGRES_PASSWORD password ENV POSTGRES_DB login EXPOSE 5433 ADD db_dump.sql /docker-entrypoint-initdb.d This is the error I get: backend_1 | Traceback (most recent call last): backend_1 | File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/…
downvote count: 0
tagged with: python
tagged with: dockerfile
has title: docker-compose with multiple postgres databases from sql dumps
favorite count: 0
possible better answer: http://stackoverflow.com/a/50084631
accepted answer: http://stackoverflow.com/a/50085774
tagged with: docker
score: 2
tagged with: postgresql
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50085774
tagged with: docker-compose
linked to: http://stackoverflow.com/q/39204142
type: Question

http://stackoverflow.com/q/50194353
has comment: http://stackoverflow.com/comment/87407587
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87426543
answer count: 1
downvote count: 1
favorite count: 0
has body: I am attempting to scrape Kickstarter based on the project names alone. Using the project name and the base URL I can get to the search page. In order to scrape the project page, I need to use Selenium to click on the URL. However, I cannot point Selenium to the correct element to click on. I would also like this to be dynamic so I do not need to put the project name each time. Knife block - Designed by IF and Red dot winner JLE Design ` driver = webdriver.Chrome(chrome_path) url = 'https://www.kickstarter.com/discover/advanced?ref=nav_search&term=Knife block - Designed by IF and Red dot winner JLE Design' driver.get(url) elem = driver.find_elements_by_link_text('Knife block - Designed by IF and Red dot winner JLE Design') elem.click() How can I get the elem to point to the correct link?
type: Question
accepted answer: http://stackoverflow.com/a/50204983
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50204983
has comment: http://stackoverflow.com/comment/87426866
has title: Click link in Kickstarter using Selenium
tagged with: selenium-webdriver

http://stackoverflow.com/a/50101641
answers question: http://stackoverflow.com/q/50101117
type: Answer
has comment: http://stackoverflow.com/comment/88643956
has comment: http://stackoverflow.com/comment/87272775
has comment: http://stackoverflow.com/comment/88644062
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87263361
has body: You are supplying 'all' as a param in SelectKBest. But according to the documentation, if you want to pass 'all', you need to specify it as: SelectKBest(k='all') The reason is that its a keyword argument, it should be specified with the keyword. Because the first argument to SelectKBest is a positional argument for the scoring function. So when you do not specify the param, 'all' is considered an input for the function and hence the error. Update: Now about the shape, the original X will not be changed. So it will print (150,4). The data will be changed on the fly and on my pc the best_param_ is n_components=1, so final shape that goes to svm is (150, 5), 1 from PCA and 4 from SelectKBest.
has comment: http://stackoverflow.com/comment/88652847
accepted answer of: http://stackoverflow.com/q/50101117
score: 0

http://stackoverflow.com/a/55528660
answers question: http://stackoverflow.com/q/50216508
downvote count: 2
has comment: http://stackoverflow.com/comment/97771482
score: -2
type: Answer
has body: First, save your Jupyter Notebook. Second, locate the directory your Jupyter Notebook is stored in. Thirdly, ensure that your Jupyter Notebook and CSV file are in the same place.
upvote count: 0

http://stackoverflow.com/comment/87443379
comment on: http://stackoverflow.com/q/50212950
has text: @WiktorStribiżew I think python is more wiser than that :)
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87373369
score: 2
comment on: http://stackoverflow.com/q/50178055
type: QuestionComment
has text: check str.split
type: Comment

http://stackoverflow.com/comment/87247008
type: QuestionComment
type: Comment
has text: could you give me an example please?
score: 0
comment on: http://stackoverflow.com/q/50114882

http://stackoverflow.com/a/50141661
type: Answer
has body: You can modify coldspeed's comment to use: df = pd.concat([ df, df.groupby([df.name, df.visit]).apply(lambda g: g.groupby('foo').ngroup() + 1).reset_index().rename(columns={0: 'enum'})['enum']], axis=1) &gt;&gt;&gt; df name visit foo enum 0 andrew BL a 1 1 andrew BL a 1 2 andrew BL b 2 3 andrew BL b 2 4 bob BL c 1 5 bob BL c 1 6 bob BL d 2 7 bob BL d 2 8 bob M12 e 1 9 bob M12 e 1 10 bob M12 f 2 11 bob M12 g 3 12 carol BL h 1 13 carol BL i 2 14 carol BL j 3 15 carol BL k 4
answers question: http://stackoverflow.com/q/50141501
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/50157862
upvote count: 2
tagged with: heroku
score: 2
has title: ModuleNotFoundError: No module named 'django' in Heroku
has answer: http://stackoverflow.com/a/55437772
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87334948
has comment: http://stackoverflow.com/comment/87333970
favorite count: 0
has answer: http://stackoverflow.com/a/50158783
has comment: http://stackoverflow.com/comment/87334440
has body: I trying deploy my App In Heroku, and this error appears: 2018-05-03T14:35:40.682441+00:00 heroku[web.1]: Starting process with command `python manage.py runserver` 2018-05-03T14:35:41.960741+00:00 app[web.1]: Traceback (most recent call last): 2018-05-03T14:35:41.960765+00:00 app[web.1]: File "manage.py", line 8, in &lt;module&gt; 2018-05-03T14:35:41.960858+00:00 app[web.1]: from django.core.management import execute_from_command_line 2018-05-03T14:35:41.960872+00:00 app[web.1]: ModuleNotFoundError: No module named 'django' 2018-05-03T14:35:41.960873+00:00 app[web.1]: 2018-05-03T14:35:41.960875+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2018-05-03T14:35:41.960876+00:00 app[web.1]: 2018-05-03T14:35:41.960879+00:00 app[web.1]: Traceback (most recent call last): 2018-05-03T14:35:41.960895+00:00 app[web.1]: File "manage.py", line 14, in &lt;module&gt; 2018-05-03T14:35:41.961003+00:00 app[web.1]: ) from exc 2018-05-03T14:35:41.961016+00:00 app[web.1]: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2018-05-03T14:35:42.013265+00:00 heroku[web.1]: State changed from starting to crashed 2018-05-03T14:35:42.008966+00:00 heroku[web.1]: Process exited with status 1 My requirements.txt: dj-database-url==0.5.0 django-heroku==0.3.1 gunicorn==19.8.1 numpy==1.14.2 psycopg2==2.7.4 python-decouple==3.1 pytz==2018.4 scipy==1.0.1 whitenoise==3.3.1 My runtime.txt python-3.6.5 My Procfile (in 'myapphere' is my app name) web: gunicorn myapphere.wsgi web: python manage.py runserver The problem is I make "git push heroku master' and the error appears, I don't know that happens... Deploy Log: Counting objects: 13, done. Delta compression using up to 4 threads. Compressing objects: 100% (11/11), done. Writing objects: 100% (13/13), 1.11 KiB | 0 bytes/s, done. Total 13 (delta 7), reused 0 (delta 0) remote: Compressing source file…
has comment: http://stackoverflow.com/comment/87333712
has comment: http://stackoverflow.com/comment/87333593
has comment: http://stackoverflow.com/comment/87334477
type: Question
has comment: http://stackoverflow.com/comment/87335068
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87334560
has comment: http://stackoverflow.com/comment/87335218
tagged with: python
has comment: http://stackoverflow.com/comment/87334630

http://stackoverflow.com/a/51016425
downvote count: 0
upvote count: 1
has body: I've revisited this problem recently, replaced one or two hundred lines of code with five or ten, and thought it might one day be useful to someone to find what I did here. There are several elements to the problem I had - first, many answer types to be created, saved and retrieved when required; second, the GET vs POST dichotomy (and my idiosyncratic solution of always creating an answer, sending it to a form); third, some of the types have different logic (the Brainstorm can have multiple answers per user, the FeedBack does not even need a response - if it is created for a user, it has been presented.) These elements probably obscured some opportunity to remove repetition, which make the visitor pattern quite appropriate. Solution for elements 1 &amp; 2 A dictionary of question.answer_type codes that map to the relevant Answer sub-class, is created in views.py (because its hard to place it in models.py and resolve dependencies): # views.py: ANSWER_CLASS_DICT = { 'CH': Vote, 'SA': Short_Answer, 'LA': Long_Answer, 'E3': EJ_three_field, 'E4': EJ_four_field, 'BS': Brainstorm, 'FB': FB,} Then I can get the class of Answer that I want 'get_or_created' for any question with: ANSWER_CLASS_DICT[question.answer_type] I pass it as a parameter to the class method: # models.py: def get_or_update_answer(self, user, question, Cls, submitted_value=None, pk_ans=None): if not submitted_value: answer, _created = Cls.objects.get_or_create(user=user, question=question) elif isinstance(submitted_value, dict): answer, _created = Cls.objects.get_or_create(user=user, question=question) for key, value in submitted_value.items(): setattr(answer, key, value) else: pass So the same six lines of code handles get_or_creating any Answer when submitted_value=None (GET) or not (submitted_value). Solution for element 3 The solution for element three has been to extend the model to separate at least three types of handling for users revisiting the same question: 'S' - single, which allows them to re…
answers question: http://stackoverflow.com/q/50112241
score: 1
type: Answer

http://stackoverflow.com/q/50181217
linked to: http://stackoverflow.com/q/28447522
has comment: http://stackoverflow.com/comment/87379990
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87381714
has comment: http://stackoverflow.com/comment/87379728
has comment: http://stackoverflow.com/comment/87380644
score: 0
has comment: http://stackoverflow.com/comment/87380245
upvote count: 1
has comment: http://stackoverflow.com/comment/87381630
downvote count: 1
has body: I have decided to view a website's source code, and chose a class, which is "expanded". I wanted to print out all of its contents, with this code: import requests from bs4 import BeautifulSoup page = requests.get("https://www.quora.com/How-can-I-write-a-bot-using-Python") soup = BeautifulSoup(page.content, 'html.parser') print soup.find_all(class_='expanded') but it simply prints out: [] Please help me detect what's wrong. I already saw this thread and tried following what the answer said but it did not help me since this error appears in the terminal: bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?
favorite count: 0
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/50181460
has comment: http://stackoverflow.com/comment/87379909
has title: Why isn't beautifulsoup's find_all not working
has comment: http://stackoverflow.com/comment/87380082
type: UnansweredQuestion

http://stackoverflow.com/q/50214629
has answer: http://stackoverflow.com/a/50214768
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87445970
has title: HOW TO MAKE ATTRIBUTE FOR "PRINT" OUTPUT
score: 0
tagged with: printing
answer count: 3
tagged with: xlrd
has answer: http://stackoverflow.com/a/50214734
has comment: http://stackoverflow.com/comment/87446051
has answer: http://stackoverflow.com/a/50214705
type: Question
has body: I'm just new to python and even codings. This is my Python code: &gt;&gt;&gt; import xlrd &gt;&gt;&gt; file_name = "D:/Uber/reviews" &gt;&gt;&gt; workbook = xlrd.open_workbook(file_name) &gt;&gt;&gt; sheet = workbook.sheet_by_index(0) &gt;&gt;&gt; for row in range(sheet.nrows): print(sheet.cell_value(row, 1) I got the output of that "print" command. However, I don't know how to make a variable for that output (I need that variable for nltk tokenize) Thank you for your help.

http://stackoverflow.com/q/50203452
has comment: http://stackoverflow.com/comment/87464405
tagged with: python
has comment: http://stackoverflow.com/comment/87484089
linked to: http://stackoverflow.com/q/47102004
linked to: http://stackoverflow.com/q/13238736
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50745283
downvote count: 0
has comment: http://stackoverflow.com/comment/87578775
tagged with: read-the-docs
tagged with: pyqt
linked to: http://stackoverflow.com/q/48356987
linked to: http://stackoverflow.com/q/36283829
answer count: 1
has comment: http://stackoverflow.com/comment/87442237
has comment: http://stackoverflow.com/comment/87474000
linked to: http://stackoverflow.com/q/28178644
favorite count: 0
has title: How to correctly setup for PyQt5 imports on readthedocs?
type: Question
has body: Building the sphinx documentation of a project importing PyQt5 fails (build log) with QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-docs' qt.qpa.screen: QXcbConnection: Could not connect to display Could not connect to any X display. In tox.ini the following was needed: [testenv:docs] # avoid QStandardPaths: XDG_RUNTIME_DIR not set passenv = XDG_RUNTIME_DIR # xvfb-run prevents Could not connect to any X display commands = /usr/bin/xvfb-run sphinx-build --color -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html How to do that on readthedocs ? This is closely related to PyQt 4 import in read-the-docs, which unfortunately did not contain the error messages. And PyQt5 is installable from pip. Notes: in the advanced settings, Install your project inside a virtualenv using setup.py install is checked (but unchecking did not help). the reference geoptics snapshot for the following tentatives is f33d233bf67bd7922ec864635e7589e7f4feb40f Tentatives 1. With mock module Maybe mocking PyQT5 could work. But this seems a bit cumbersome. Adapting from this answer, adding import mock MOCK_MODULES = ['sip', 'PyQt5', 'PyQt5.QtGui', 'PyQt5.QtCore', 'PyQt5.QtWidgets'] sys.modules.update((mod_name, mock.MagicMock()) for mod_name in MOCK_MODULES) to conf.py yields class _GRay(GCounterPart, QGraphicsPathItem): TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases 2. With the sphinx built-in autodoc_mock_imports same error with the simpler (just one line added to conf.py) autodoc_mock_imports = ['sip', 'PyQt5', 'PyQt5.QtGui', 'PyQt5.QtCore', 'PyQt5.QtWidgets'] 3. With custom Mock Using julen's custom Mock class class Mock(object): def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return Mock() @classmethod def __getattr__(cls, name): if name in ('__file__', '__path__'): return '/dev/null' elif name[0] == name[0].upper(): mockType = type(name, (), {}) mockType.…
accepted answer: http://stackoverflow.com/a/50745283
has comment: http://stackoverflow.com/comment/87473910

http://stackoverflow.com/comment/87452650
comment on: http://stackoverflow.com/a/50217779
score: 1
type: Comment
type: AnswerComment
has text: Either it's not the same algo. Or it's not on the same dataset (the order of the phone numbers come differently). If the one you want comes first in your other program, then it'll look as if your algo is correct. But it's still not. Implement proper unit tests and you'll understand the mistake (that I'm pointing out) ;-)

http://stackoverflow.com/comment/111961629
score: 1
comment on: http://stackoverflow.com/a/50161387
type: Comment
has text: You can change the format of the number to {:.0%} as well
type: AnswerComment

http://stackoverflow.com/comment/87276657
has text: I'm sorry, I think I can't explain clear enough what my problem is.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50128490

http://stackoverflow.com/comment/87182826
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50083498
has text: Which operating system (Windows is different than unixy systems)? What error do you get?
type: Comment

http://stackoverflow.com/q/50158290
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/51622735
has body: After obtaining accuracy metric from my keras binary classification model, I need know what the model made the predictions. So, I'm interested in variable importance. I use lime package. library(lime) explainer &lt;- lime ( x = x_train, model = model_keras, bin_continuous = FALSE) explanation &lt;- explain ( x_test[1:20,], # Show first 20 samples explainer = explainer, n_labels = 1, n_features = 5) Explain function gives me the following error in py_get_attr_impl function: AttributeError: 'function' object has no attribute 'func_name'. I have compiled keras model with R, but this Issue seems to be that error comes from Python version. Problems with Reticulate package?
score: 1
tagged with: python
tagged with: reticulate
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87810701
tagged with: deep-learning
has title: Explain features from my keras object with lime R package
linked to: http://stackoverflow.com/q/5963269
answer count: 1
has comment: http://stackoverflow.com/comment/87963685
downvote count: 0
upvote count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/89384273
accepted answer: http://stackoverflow.com/a/51622735
favorite count: 0
type: Question

http://stackoverflow.com/q/50144595
answer count: 0
linked to: http://stackoverflow.com/q/37531846
downvote count: 0
linked to: http://stackoverflow.com/q/50139483
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
has title: scipy + (numpy.distutils-based) setup.py + ctypes: undefined symbol
has body: Intro As a follow-up to my earlier question here, i still try to: add new functionality to one of scipy's modules (e.g. scipy.optimize) based on C++-code which defines an interface-function to be called with ctypes automatically setup through setup.py in scipy/optimize Code incorporation To keep it simple, let's assume we got the following (dumb and) simple C++-code: extern "C" void hallo() { int a = 0; } where we use the extern keyword to handle name-mangling. We introduce new files and folders in scipy.optimize: scipy/optimize/__init__py scipy/optimize/lbfgsb/... scipy/optimize/lbfgsb.py ... scipy/optimize/_mylib/README.md # new scipy/optimize/_mylib/LICENSE # new scipy/optimize/_mylib/src/debug.cpp # new scipy/optimize/mylib.py # new Setup preparation We prepare the module-setup in scipy/optimize/setup.py: from __future__ import division, print_function, absolute_import from os.path import join from scipy._build_utils import numpy_nodepr_api def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('optimize',parent_package, top_path) # MODIFICATION START # OTHER EXTENSIONS OMITTED # INSPIRED BY scipy.spatial: ckdtree/src &amp; setup.py mylib_src = ['debug.cpp'] mylib_src = [join('_mylib', 'src', x) for x in mylib_src] mylib_headers = [] mylib_headers = [join('_mylib', 'src', x) for x in mylib_headers] mylib_dep = mylib_headers + mylib_src config.add_extension('_mylib', sources=mylib_src, depends=mylib_dep, include_dirs=[join('_mylib', 'src')]) # MODIFICATION END return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) Run scipy install Installing scipy now (from base-dir) with: python3 setup.py build_ext --inplace works and we will see those shared-libraries in scipy/optimize/: _lbfgsb.cpython-35m-x86_64-linux-gnu.so ... _mylib.cpython-35m-x86_64-linux-gnu.so Let's try to use it …
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: shared-libraries
tagged with: c++
score: 2

http://stackoverflow.com/a/50162355
answers question: http://stackoverflow.com/q/50162027
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/87343166
has body: From the docs on unittest: https://docs.python.org/2/library/unittest.html The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method. Meaning that your setUp() code is runs twice in your example. If you want to re use the same browser instance move your driver initialization to a setUpClass() method that will only run once per test class
type: Answer
accepted answer of: http://stackoverflow.com/q/50162027

http://stackoverflow.com/q/50092497
score: 3
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50092603
has body: All I have a text file formatted like below which I am bringing into Python: hammer#9.95 saw#20.15 shovel#35.40 Ultimately I want to develop a dynamic query that allows me to remove the '#' symbol and replace with a '$' symbol, and then add up the values within the text file/count the number of items within. I came up with this through some trial and error, but it isn't dynamic to handle changes in the text file: # display header line for items list print('{0: &lt;10}'.format('Item'), '{0: &gt;17}'.format('Cost'), sep = '' ) # add your remaining code below with open('invoice.txt','rt') as infile: for line in infile: print("{:&lt;21} {}".format(line.strip().split('#')[0],"$"+line.strip().split("#")[1])) print(' ') str1 = 'Total cost\t' +' ' + '$65.50' print(str1) str2 = 'Number of tools\t' + ' ' +'3' print(str2) Any suggestions? Thanks ahead of time for reading.
upvote count: 3
has answer: http://stackoverflow.com/a/50093259
has answer: http://stackoverflow.com/a/50092529
downvote count: 0
has answer: http://stackoverflow.com/a/50092590
has title: Python: Splitting numbers from text and then summing them
has answer: http://stackoverflow.com/a/50092613
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87201202

http://stackoverflow.com/q/50197027
has comment: http://stackoverflow.com/comment/87411265
type: Question
has title: PyCharm Edu: How to fix "solution can't be loaded"?
tagged with: python
accepted answer: http://stackoverflow.com/a/50404164
has answer: http://stackoverflow.com/a/50404164
tagged with: pycharm
type: AnsweredQuestion
score: 0
answer count: 1
has body: I've been taking the Introduction to Python course on PyCharm Edu. It has been going well for most of the time, except there's this weird bug that I can't seem to fix. I messed up on one of the tasks, and now whenever I try to check the task, it says: Solution can't be loaded. Reset task to solve it again. Now, this button right here is supposed to reset the task. It does, however, even after clicking it, I still get the same error. This has happened on two tasks so far: the Undefined variable task and the return keyword task. I am extremely confused on why this is happening. If someone could help me fix this I would be very grateful! Thank you for reading. EDIT: This is the code under the Undefined variable task: variable = 1 print(other_variable) This is also what answer.py for this task contains as well.
has comment: http://stackoverflow.com/comment/87421956

http://stackoverflow.com/comment/87349086
type: AnswerComment
has text: try `map(int ...` instead of `(map(str ...` or just don't call the `join` to get a list.
comment on: http://stackoverflow.com/a/50165455
type: Comment
score: 0

http://stackoverflow.com/comment/87261856
has text: Many thanks! I ask a new question about how to replace my one another for loop, could you help my find a numpy way?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50120820
type: Comment

http://stackoverflow.com/a/50115138
type: Answer
score: 4
upvote count: 4
has body: You are looking for np.argmax, which would return the index of the maximum value: &gt;&gt;&gt; countries[employment.argmax()] 'Angola'
answers question: http://stackoverflow.com/q/50115081
downvote count: 0

http://stackoverflow.com/comment/87369567
type: Comment
type: AnswerComment
has text: @tgordon18 as Tony Tannous commented on the question, either use bit operations and limit the size O(1), or you need to do at least a for and that's O(n).
comment on: http://stackoverflow.com/a/50175924
score: 0

http://stackoverflow.com/comment/87364109
score: 0
comment on: http://stackoverflow.com/q/50133294
type: Comment
type: QuestionComment
has text: Any leads or improvements to my above logic is most welcome.

http://stackoverflow.com/q/50185236
score: -1
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87389021
accepted answer: http://stackoverflow.com/a/50187005
downvote count: 2
upvote count: 1
tagged with: firefox
answer count: 1
tagged with: selenium
favorite count: 0
type: Question
has body: I'm using python (v 3.65) selenium (v3.11.0) on Mac OS X (v 10.11.6) with firefox (v 59.0.3) and geckodriver (v 0.20.1). I have my usual firefox in the Applications folder and a second firefox in another folder. How can I tell python selenium to use the second firefox instead of going to the one in Applications? I'd prefer an answer that generalises to other browsers besides firefox/geckodriver, if possible.
has comment: http://stackoverflow.com/comment/87387961
linked to: http://stackoverflow.com/q/40208051
has answer: http://stackoverflow.com/a/50187005
has title: How can I choose which firefox executable to use among multiple firefox binaries through Python selenium
tagged with: geckodriver
tagged with: python

http://stackoverflow.com/comment/87181278
comment on: http://stackoverflow.com/a/50082568
has text: @laughingllama42, Yes. There are many different formats you can incorporate, [this link](http://strftime.org/) is a complete guide. See [here](https://stackoverflow.com/questions/17978092/combine-date-and-time-columns-using-python-pandas) for how to combine 2 columns.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50088189
favorite count: 0
accepted answer: http://stackoverflow.com/a/50088495
type: Question
has title: Why is the hash considering the same value for every new temp file created for the input file in the API call?
tagged with: python
has body: I have an API call which takes file input from the form and generates the hash key for the temporary file created. But again when a different file is selected as input file, the same hash is getting generated.Code snippet of the API call is below: (excluded other unrelated code) def gen_hash(): for attr, document in request.files.iteritems(): orig_filename = document.filename new_doc = add_doc(orig_filename, orig_filename) #mhash = None ############## # hashing algorithm checks the contents of the file if # modified before uploading to destination, NOT file name try: tmp1 = tempfile.NamedTemporaryFile(delete=False) tmp1.write(document.read()) tmp1.seek(0) # for chunk in iter(lambda: tmp1.read(128* sha1().block_size), # b""): for chunk in iter(lambda: tmp1.read(128), b""): sha1().update(chunk) mhash1 = sha1().hexdigest() print mhash1 finally: #print e os.unlink(tmp1.name) Using flask v.0.12, python 2.7. Why is the hash key same for the different file contents?
has answer: http://stackoverflow.com/a/50088495
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87192395
score: 1
upvote count: 1
tagged with: flask
answer count: 1
has comment: http://stackoverflow.com/comment/87192609

http://stackoverflow.com/q/50118368
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/50118519
has body: For a given class, is it better/fancier/more in accordance with Python Zen to overwrite a method (I.e., assign another function to it) or derive from that class and overwrite it in the new class. So this: from foo import Bar def mybaz(self): pass Bar.baz = mybaz Or: from foo import bar class Mybar(Bar): def baz(self): pass If it makes a difference, please refer to Python3 Follow up: is the answer different for magic methods?
type: AnsweredQuestion
tagged with: oop
score: 1
upvote count: 1
answer count: 1
has title: Overwrite method or derive?
downvote count: 0
has answer: http://stackoverflow.com/a/50118519
favorite count: 0
type: Question

http://stackoverflow.com/q/50095975
downvote count: 2
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50096322
tagged with: combinations
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50096322
has body: I have equations with multiple unknowns, and a number range: eq1 = (x + 5 + y) # ans = 15 no_range = [1..5] I know that I can solve the equation by checking all possible combinations: solved = False for i in range(1, 5+1) # for x for j in range(1, 5+1) # for y if i + 5 + j == ans: solved = True So, the problem is that I want a function to deal with unknown_count amount of unknowns. So that both the following equations, or any, can be solved in the same manner above: eq1 = (x + 5 + y) ans = 15 eq2 = (x + 5 + y + z * a + 5 * b / c) ans = 20 I just cannot think of a way, since for each unknown you need a for loop.
has comment: http://stackoverflow.com/comment/87208620
linked to: http://stackoverflow.com/q/287085
has title: Solve equations with combinations and for loops
favorite count: 0
type: Question
tagged with: for-loop
upvote count: 0
score: -2

http://stackoverflow.com/comment/87166950
type: Comment
score: 0
type: QuestionComment
has text: Is that first column with numbers a part of the file? Looks like you have 3 values in each row, so unpacking into two would throw an error.
comment on: http://stackoverflow.com/q/50075351

http://stackoverflow.com/comment/87369259
has text: I just saw that you use 0.4.0, in which case you don't need Variable anymore anyway (https://pytorch.org/2018/04/22/0_4_0-migration-guide.html).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50175711
score: 0

http://stackoverflow.com/comment/87426880
has text: Yes. Don't use kmeans here.
comment on: http://stackoverflow.com/q/50177981
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87340682
score: 0
type: Comment
type: QuestionComment
has text: sure: /usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin
comment on: http://stackoverflow.com/q/50160769

http://stackoverflow.com/comment/87172791
comment on: http://stackoverflow.com/q/50078269
score: 0
has text: They're initialized on the top of the script.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87464705
has text: Thank you, I’ll delete the bot or reset the token
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50223331

http://stackoverflow.com/q/50218281
has body: I am using nltk FreqDist to create frequency distribution using python3. I want to compare frequency distribution of whole corpus with frequency distribution of many text files one by one. In addition, I want to output some numerical values of the comparison. corpusTokens = [] for document in documents_set: corpusTokens.extend(document) fdist = FreqDist(self.corpusTokens) How to compare fdist of the whole corpus with fdist of some text file?
answer count: 0
score: 2
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: nltk
type: UnansweredQuestion
has title: How to compare two frequency distribution (created using nltk FreqDist) in python3?
tagged with: python

http://stackoverflow.com/comment/87300013
has text: I was surprised, but you're right: https://meta.stackexchange.com/questions/25209/what-is-the-official-etiquette-on-answering-a-question-twice
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50140758

http://stackoverflow.com/a/50075269
type: Answer
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50075259
has body: You forgot to return the result of func(*s, **gs) in wrapper.
upvote count: 4
answers question: http://stackoverflow.com/q/50075259
downvote count: 0

http://stackoverflow.com/q/50083583
type: Question
has answer: http://stackoverflow.com/a/72092574
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/63887234
answer count: 4
has body: I'm splitting a large CSV (containing stock financial data) file into smaller chunks. The format of the CSV file is different. Something like an Excel pivot table. The first few rows of the first column contain some headers. Company name, id, etc. are repeated across the following columns. Because one single company has more than one attribute, not like one company has one column only. After the first few rows, the columns then start resembling a typical data frame where headers are in columns instead of rows. Anyways, what I'm trying to do is to make Pandas allow duplicate column headers and not make it add ".1", ".2", ".3", etc after the headers. I know Pandas does not allow this natively, is there a workaround? I tried to set header = None on read_csv but it throws a tokenization error which I think makes sense. I just can't think of an easy way. import pandas as pd csv_path = "C:\\Users\\ThirdHandBD\\Desktop\\Data Splitting\\pd-split\\chunk4.csv" #df = pd.read_csv(csv_path, header=1, dtype='unicode', sep=';', low_memory=False, error_bad_lines=False) df = pd.read_csv(csv_path, header = 1, dtype='unicode', sep=';', index_col=False) print("I read in a dataframe with {} columns and {} rows.".format( len(df.columns), len(df) )) filename = 1 #column increment x = 30 * 59 for column in df: loc = df.columns.get_loc(column) if loc == (x * filename) + 1: y = filename - 1 a = (x * y) + 1 b = (x * filename) + 1 date_df = df.iloc[:, :1] out_df = df.iloc[:, a:b] final_df = pd.concat([date_df, out_df], axis=1, join='inner') out_path = "C:\\Users\\ThirdHandBD\\Desktop\\Data Splitting\\pd-split\\chunk4-part" + str(filename) + ".csv" final_df.to_csv(out_path, index=False) #out_df.to_csv(out_path) filename += 1 # This should be the same as df, but with only the first column. # Check it with similar code to above. EDIT: From, https://github.com/pandas-dev/pandas/issues/19383, I add: final_df.columns = final_df.iloc[0] final_df = final_df.reindex(final_df.index.drop(0)).reset_index(…
has answer: http://stackoverflow.com/a/50341520
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/72810428
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/50353740
has title: Allow duplicate columns in Pandas
has comment: http://stackoverflow.com/comment/92459059
favorite count: 0

http://stackoverflow.com/comment/87250202
comment on: http://stackoverflow.com/q/50114964
type: QuestionComment
type: Comment
has text: Please move your code out of the comment and into your question. That makes it much easier for us to read and you are more likely to get help that way.
score: 0

http://stackoverflow.com/comment/87330432
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50136880
score: 0
has text: Did you check missing values?

http://stackoverflow.com/comment/96311760
comment on: http://stackoverflow.com/a/50141290
type: AnswerComment
score: 1
has text: I had the same problem. As of Feb2019, I only got Pyinstaller v3.4 working when using Django 1.8, not with any higher version of Django. In case it matters, I used Python 3.5
type: Comment

http://stackoverflow.com/a/50156085
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: You can select email only from active users using this query. from django.contrib.auth.models import User emails = User.objects.filter(is_active=True).values_list('email', flat=True)
answers question: http://stackoverflow.com/q/50155886

http://stackoverflow.com/a/50212230
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87442582
has comment: http://stackoverflow.com/comment/87441688
score: 4
has body: As Jon and Patrick mention, that's not an error, it's what happens when you print the __repr__ of a generator expression. So you just need to "splat" that generator. :) print(*(i**2 for i in range(int(input()))), sep='\n') demo output 10 0 1 4 9 16 25 36 49 64 81 In that demo I entered 10 at the input prompt. In the comments I wondered how the speed of i * i compares to i ** 2. On my old 2GHz 32 bit single core machine, running Python 3.6.0, i * i is around 3 or 4 times faster than i ** 2. Here's some timeit code. from timeit import Timer commands = {'mul' : 'num * num', 'pow' : 'num ** 2'} def time_test(num, loops, reps): timings = [] setup = 'num = {}'.format(num) for name, cmd in commands.items(): result = Timer(cmd, setup).repeat(reps, loops) result.sort() timings.append((result, name)) timings.sort() for result, name in timings: print(name, result) loops, reps = 100000, 3 num = 1 for _ in range(10): print('num =', num) time_test(num, loops, reps) num &lt;&lt;= 1 output num = 1 mul [0.02114695899945218, 0.02127135100090527, 0.02303983199817594] pow [0.08504067399917403, 0.08687452600133838, 0.12349813100081519] num = 2 mul [0.02089159800016205, 0.021789606998936506, 0.02889108999806922] pow [0.08612996800002293, 0.09132789800059982, 0.09559987299871864] num = 4 mul [0.021155500999157084, 0.02333696799905738, 0.028521009000542108] pow [0.08492234799996368, 0.08499632499660947, 0.08537705599883338] num = 8 mul [0.02173021600174252, 0.021955170999717666, 0.02823427400289802] pow [0.08423048700205982, 0.08541251700080466, 0.08654486299928976] num = 16 mul [0.02176373900147155, 0.02222509399871342, 0.02816650199747528] pow [0.08528696699795546, 0.09080051600176375, 0.0968476650014054] num = 32 mul [0.03118283900039387, 0.03388790600001812, 0.03745272100059083] pow [0.0943321790000482, 0.09484523300125147, 0.09691544299857924] num = 64 mul [0.030481540998152923, 0.03292956899895216, 0.03887743200175464] pow [0.09454960600123741, 0.09569520199875114, 0.0992606389991124…
accepted answer of: http://stackoverflow.com/q/50212167
has comment: http://stackoverflow.com/comment/87441553
type: Answer
has comment: http://stackoverflow.com/comment/87443966
answers question: http://stackoverflow.com/q/50212167

http://stackoverflow.com/a/52974437
has comment: http://stackoverflow.com/comment/136968978
score: 50
downvote count: 0
upvote count: 50
answers question: http://stackoverflow.com/q/50203106
has comment: http://stackoverflow.com/comment/104856864
accepted answer of: http://stackoverflow.com/q/50203106
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/108928883
has comment: http://stackoverflow.com/comment/98484680
has body: recall_average = recall_score(Y_test, y_predict, average="binary", pos_label="neg") Use "neg" or "pos" as pos_label and this error won't raise again.

http://stackoverflow.com/a/50076046
has comment: http://stackoverflow.com/comment/87168711
answers question: http://stackoverflow.com/q/50075970
type: Answer
has comment: http://stackoverflow.com/comment/87168731
has comment: http://stackoverflow.com/comment/87168313
upvote count: 1
score: 1
type: AcceptedAnswer
has body: This code goes in and fetches all posts from users whom the current user follows (ie, for whom the current user is a follower): Posts.objects.filter(user__following__follower=ProfileDetails.objects.get(user=self.request.user))
accepted answer of: http://stackoverflow.com/q/50075970
downvote count: 0

http://stackoverflow.com/comment/87367943
comment on: http://stackoverflow.com/a/50175231
has text: Please see updated code, and output. This still isnt working.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50083227
upvote count: 1
tagged with: python
has title: tensorflow lite: error when converting retrained graph model to lite format
tagged with: deep-learning
score: 1
has answer: http://stackoverflow.com/a/57842394
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51653188
answer count: 2
has body: Followed Steps Step1- Clone the git repository: git clone https://github.com/googlecodelabs/tensorflow-for-poets-2 cd tensorflow-for-poets-2 Step2- Download the training images or gather the custom images: curl http://download.tensorflow.org/example_images/flower_photos.tgz \ | tar xz -C tf_files Step3- set the image size and architecture: IMAGE_SIZE=224 ARCHITECTURE="mobilenet_0.50_${IMAGE_SIZE}" Step4- Retrain the model python -m scripts.retrain \ --bottleneck_dir=tf_files/bottlenecks \ --model_dir=tf_files/models/"${ARCHITECTURE}" \ --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" \ --output_graph=tf_files/retrained_graph.pb \ --output_labels=tf_files/retrained_labels.txt \ --architecture="${ARCHITECTURE}" \ --image_dir=tf_files/flower_photos Step5- Using retrained model check the classify image python -m scripts.label_image \ --graph=tf_files/retrained_graph.pb\ -- image=tf_files/flower_photos/daisy/3475870145_685a19116d.jpg Evaluation time (1-image): 0.281s daisy 0.725841 dandelion 0.200525 tulips 0.0411526 roses 0.0318613 sunflowers 0.000619742 Step6:Optimize the model IMAGE_SIZE=224 toco \ --input_file=tf_files/retrained_graph.pb \ --output_file=tf_files/optimized_graph.pb \ --input_format=TENSORFLOW_GRAPHDEF \ --output_format=TENSORFLOW_GRAPHDEF \ --input_shape=1,${IMAGE_SIZE},${IMAGE_SIZE},3 \ --input_array=input \ --output_array=final_result Step7- Verify the optimized model of classifying image python -m scripts.label_image \ --graph=tf_files/optimized_graph.pb \ --image=tf_files/flower_photos/daisy/3475870145_685a19116d.jpg Evaluation time (1-image): 0.126s daisy 0.725845 dandelion 0.200523 tulips 0.0411517 roses 0.031861 sunflowers 0.00061973 Step8- Convert to model to TFlite format IMAGE_SIZE=224 toco \ --input_file=tf_files/retrained_graph.pb \ --output_file=tf_files/optimized_graph.lite \ --input_format=TENSORFLOW_GRAPHDEF \ --output_format=TFLITE \ --input_shape=1,${IMAGE_SIZE},${IMAGE_SIZE},3 \ --input_array=input \ --output_array=fina…
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/57041234
accepted answer of: http://stackoverflow.com/q/50169242
answers question: http://stackoverflow.com/q/50169242
has body: You can use the pyzipper library for unpacking AES-encrypted zip files.
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50205209
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50205141
has comment: http://stackoverflow.com/comment/87427628
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50205141
has body: I am biased against %s for something like this. You could try: name = 'kbball' start = '2017' end = '2018' field = 'field' sql = "SELECT `xyz` FROM `checkins` WHERE `name`= " + name + " AND `timestamp` &gt;= " + start + " AND `timestamp` &lt; " + end + " ORDER BY `"+ field + "` DESC LIMIT 1" print(sql) #output SELECT `xyz` FROM `checkins` WHERE `name`= kbball AND `timestamp` &gt;= 2017 AND `timestamp` &lt; 2018 ORDER BY `field` DESC LIMIT 1

relative-path
type: Tag
tags question: http://stackoverflow.com/q/50160290
tag name: relative-path

http://stackoverflow.com/q/50201913
tagged with: binary-data
has answer: http://stackoverflow.com/a/53210778
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87420544
has body: I have a dataset which follows the one-hot encoding pattern and my dependent variable is also binary. The first part of my code lists the important variables for the entire dataset. I used the method as mentioned in this stackoverflow post, "Using scikit to determine contributions of each feature to a specific class prediction". I am unsure as to what output I am getting. The feature importance ranks the most important feature for the entire model, "Delay Related DMS With Advice", in my case. I interpret it as that, this variable should be important either in Class 0 or Class 1 but from the output I get, it is unimportant in both Classes. The code in the stackoverflow I shared above, also shows that when the DV is binary, the output of Class 0 is the exact opposite (in terms of sign +/-) of Class 1. In my case, the values are different in both classes. Here is how the plots look like:- Feature Importance - Overall Model Feature Importance - Class 0 Feature Importance - Class 1 The 2nd part of my code shows cumulative feature importances but looking at the [plot] shows that none of the variables are important. Is my formula wrong or my interpretation wrong or both? plot Here is my code; import pandas as pd import numpy as np import json import matplotlib.pyplot as plt %matplotlib inline from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import confusion_matrix from sklearn.preprocessing import scale from sklearn.ensemble import ExtraTreesClassifier ##get_ipython().run_line_magic('matplotlib', 'inline') file = r'RCM_Binary.csv' data = pd.read_csv() print("data loaded successfully ...") # Define features and target X = data.iloc[:,:-1] y = data.iloc[:,-1] #split to training and testing X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=41) # define classifier and fitting data forest = ExtraTreesClassifier(random_state=1) forest.fit(X_train, y_train) # predict and get confusion matrix y_pred = fo…
upvote count: 9
tagged with: random-forest
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87421398
has answer: http://stackoverflow.com/a/64390742
score: 9
answer count: 2
downvote count: 0
tagged with: machine-learning
has title: Using Scikit-learn to determine feature importances per class in a RF model
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/35249760

http://stackoverflow.com/a/50082560
has comment: http://stackoverflow.com/comment/90846742
accepted answer of: http://stackoverflow.com/q/50082440
upvote count: 6
has comment: http://stackoverflow.com/comment/90847588
answers question: http://stackoverflow.com/q/50082440
type: AcceptedAnswer
downvote count: 0
has body: print(df) Output: A B C D 1 CL0 CL1 CL2 CL0 2 CL2 CL1 CL1 CL3 3 CL3 CL2 CL0 CL1 Using .apply() counts = df.apply(lambda x: x.value_counts() / len(x)).transpose() fig = plt.figure() ax = fig.add_subplot(111) counts.plot(ax=ax,kind='bar', stacked=True, rot=0) vals = ax.get_yticks() ax.set_yticklabels(['{:3.2f}%'.format(x*100) for x in vals]) ax.yaxis.grid(True) ax.set_axisbelow(True) plt.show() Output:
type: Answer
score: 6

http://stackoverflow.com/q/50204124
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50204182
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87425574
favorite count: 0
has comment: http://stackoverflow.com/comment/87425392
type: Question
has body: I was looking for a python script to kill particular running process(s). I got a script to get list of all currently running processes. So I did some modifications and it works as follows: A list named blackList stores all the unwanted processes which needs to be killed. The script iterates through fetched process names and compares with the blackList's content. If it matches, then that process is terminated. Code: import psutil blackList = ["SkypeHost.exe", "Music.UI.exe", "SearchUI.exe", "Video.UI.exe", "backgroundTaskHost.exe"] while True: for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'username']) except psutil.NoSuchProcess: pass else: for i in blackList: if pinfo["name"] == i: proc.kill() The script works fine but its consuming much of my processor. Without running the script Without running the script While Script is running While Script is running Is there any way to minimize this consumption? Why is it consuming so much of processor? My processor: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz
tagged with: python
tagged with: psutil
has title: How To Kill Process With Minimum Processor Consumption
has comment: http://stackoverflow.com/comment/87425276
type: AnsweredQuestion
tagged with: kill-process
has answer: http://stackoverflow.com/a/50204182

http://stackoverflow.com/q/50216736
tagged with: python
tagged with: regex
score: 2
upvote count: 2
has body: Consider this input in a text file: foo bar foobar If I look in python API for the re package I understand that if I want to match the foo and not the foobar I understand that this code should do it import re code = open ('play.txt').read() print code print re.findall('^foo$',code) However the output reads Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import play foo bar foobar [] &gt;&gt;&gt; Why?
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/57761358
has answer: http://stackoverflow.com/a/50216841
favorite count: 0
type: Question
type: UnansweredQuestion
has title: matching a whole line in python regex

http://stackoverflow.com/a/50163154
has comment: http://stackoverflow.com/comment/87346973
answers question: http://stackoverflow.com/q/50162004
score: 0
has comment: http://stackoverflow.com/comment/87346696
accepted answer of: http://stackoverflow.com/q/50162004
type: Answer
has body: it looks like you have a typo in def sale_price(self): return 5000.0 * self.wheels not return 5000.0 * self_wheels in def spec(self): you are not calling the class methods, you want. def spec(self): x = self.sale_price() y = self.purchase_price() print "This car should sell at: ", x print "This car should be bought at: ", y
type: AcceptedAnswer

http://stackoverflow.com/comment/87475497
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50223639
type: AnswerComment
has text: Oh wait, in fact the dataframe I shown you is a previous print, when I do: `data[keep.astype(bool)]` `print(data)` I actually only get ` Killed: 9` but no new ataframe. I edited my comment.

http://stackoverflow.com/comment/87297195
type: AnswerComment
has text: ah, ok, never used Python 2 :)
score: 0
comment on: http://stackoverflow.com/a/50139431
type: Comment

http://stackoverflow.com/comment/87357053
has text: What is the traceback error that appears?
comment on: http://stackoverflow.com/q/50169437
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50095852
has comment: http://stackoverflow.com/comment/87208860
type: Answer
has comment: http://stackoverflow.com/comment/87208853
has comment: http://stackoverflow.com/comment/87209392
accepted answer of: http://stackoverflow.com/q/50095378
score: 0
has comment: http://stackoverflow.com/comment/87213659
answers question: http://stackoverflow.com/q/50095378
has comment: http://stackoverflow.com/comment/87208918
has body: You've correctly scraped all the rows. But, to get only the symbol and the name, you'll have to loop over the rows one by one and get them in each iteration. If you right click and inspect any symbol, you can see that the text is located inside an tag. The corresponding tags have the following format: S As you can see, the name is included in the tag with the title attribute. So, to get both, the symbol, and the name, you only have to get the tag. As it is the first tag inside a row, you can simply get it using row.find('a'). Complete code: import requests from bs4 import BeautifulSoup r = requests.get('https://finance.yahoo.com/trending-tickers') soup = BeautifulSoup(r.text, 'lxml') table = soup.find('table', class_='yfinlist-table W(100%) BdB Bdc($tableBorderGray)') for row in table.find_all('tr')[1:]: a_tag = row.find('a') symbol = a_tag.text name = a_tag['title'] print(symbol, name) Output: S Sprint Corporation TMUS T-Mobile US, Inc. AAPL Apple Inc. ^HSI HANG SENG INDEX ^N225 Nikkei 225 000001.SS SSE Composite Index WMT Walmart Inc. NKE NIKE, Inc. ^FTSE FTSE 100 ^AORD ALL ORDINARIES BTC-USD Bitcoin USD CL=F Crude Oil MCD McDonald's Corporation AUDUSD=X AUD/USD KO The Coca-Cola Company DIS The Walt Disney Company GBPUSD=X GBP/USD GERN Geron Corporation ^NSEI NIFTY 50 TSLA Tesla, Inc. VZ Verizon Communications Inc. EURUSD=X EUR/USD ^BSESN S&P BSE SENSEX GC=F Gold 0700.HK Tencent Holdings Limited ^KS11 KOSPI Composite Index
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87208996
has comment: http://stackoverflow.com/comment/87208947

http://stackoverflow.com/comment/87342752
comment on: http://stackoverflow.com/q/50162424
type: QuestionComment
has text: If you use a `numpy.array` they will already print out formatted like that, otherwise there are many ways to [pretty print a 2d list](https://stackoverflow.com/questions/13214809/pretty-print-2d-python-list)
score: 1
type: Comment

http://stackoverflow.com/comment/87182017
comment on: http://stackoverflow.com/a/50082998
has text: Could you add some more information? I can't reproduce the error with the code I have above.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/50194521
has comment: http://stackoverflow.com/comment/87413656
linked to: http://stackoverflow.com/q/8685809
has answer: http://stackoverflow.com/a/50198989
favorite count: 0
has comment: http://stackoverflow.com/comment/87406513
type: Question
has body: I've got a dictionary with multiple rows from my question before. It's generated via: import requests from bs4 import BeautifulSoup import re import csv links = ["34519-kevitsa-copper-concentrator-plant", "34520-kevitsa-copper-mine", "34356-glogow-copper-refinery"] for l in links: page = requests.get("https://www.industryabout.com/country-territories-3/2199-finland/copper-mining/"+l) soup = BeautifulSoup(page.content, 'lxml') rows = soup.select("strong") d = {} for r in rows: name, value, *rest = r.text.split(":") if not rest: d[name] = value print(d) print(d.items()) gives: dict_items([('Commodities', ' Copper, Nickel, Gold'), ('Area', ' Lappi'), ('Type', ' Copper Concentrator Plant') ]) dict_items([('Commodities', ' Copper, Nickel, Gold'), ('Area', ' Lappi'), ('Type', ' Open-pit Mine') ]) dict_items([('Commodities', ' Copper'), ('Area', ' Dolnoslaskie'), ('Type', ' Copper Refinery') ]) But when I write this to CSV with any of the solutions from "Writing a dictionary to a csv file with one line for every 'key: value'" I only get the LAST dictionary item, the others are omitted. Commodities;Copper Area;Dolnoslaskie Type;Copper Refinery How can I write a CSV with looks like this: Commodities;Area;Type Copper, Nickel, Gold;Lappi;Copper Concentrator Plant Copper, Nickel, Gold;Lappi;Open-pit mine Copper;Dolnoslaskie;Copper Refinery I've also tried to change to an array, but coulnd't find a solution for array[name] = value. This answer seems perfect, but iterkeys is Python 2 only. with open('my_data.csv', 'wb') as ofile: writer = csv.writer(ofile, delimiter='\t') writer.writerow(['ID', 'dict1', 'dict2', 'dict3']) for key in ddict.iterkeys(): writer.writerow([key] + [d[key] for d in dicts])
upvote count: 2
has answer: http://stackoverflow.com/a/50194618
has comment: http://stackoverflow.com/comment/87413747
has title: Python: Write dictionary with multiple rows to CSV
linked to: http://stackoverflow.com/q/22273970
has comment: http://stackoverflow.com/comment/87412675
downvote count: 2
accepted answer: http://stackoverflow.com/a/50198989
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87412466
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50194618
linked to: http://stackoverflow.com/q/50193802
score: 0
has comment: http://stackoverflow.com/comment/87413832
answer count: 2
has comment: http://stackoverflow.com/comment/87414380
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/50198630
type: Answer
has comment: http://stackoverflow.com/comment/87414047
score: 0
has body: itertools uses the sort order of the data. Your list is not sorted. So if you have ["gmail.com", "something.com", "gmail.com"] itertools will create three groups. This is different than the groupby in some functional languages (or Python pandas for that sake). You need to sort the dict first. import itertools students = [{'name': 'Paul', 'mail': '@gmail.com'}, {'name': 'Tom', 'mail': '@yahoo.com'}, {'name': 'Jim', 'mail': 'gmail.com'}, {'name': 'Jules', 'mail': '@something.com'}, {'name': 'Gregory', 'mail': '@gmail.com'}, {'name': 'Kathrin', 'mail': '@something.com'}] for key, group in itertools.groupby(sorted(students, key=lambda x: x["mail"]), key=lambda student: student['mail']): print(key) print(list(group)) # @gmail.com # [{'name': 'Paul', 'mail': '@gmail.com'}, {'name': 'Gregory', 'mail': '@gmail.com'}] # @something.com # [{'name': 'Jules', 'mail': '@something.com'}, {'name': 'Kathrin', 'mail': '@something.com'}] # @yahoo.com #[{'name': 'Tom', 'mail': '@yahoo.com'}] #gmail.com # [{'name': 'Jim', 'mail': 'gmail.com'}]
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50198597
has comment: http://stackoverflow.com/comment/87414033

http://stackoverflow.com/q/50108533
tagged with: loops
has body: So, I'm just trying to iterate over a Spark RDD and perform an action on each row, like so: for row in df.rdd.toLocalIterator(): print(row) But I get a weird exception: ERROR PythonRDD:91 - Error while sending iterator java.lang.IllegalArgumentException at org.apache.xbean.asm5.ClassReader.&lt;init&gt;(Unknown Source) at org.apache.xbean.asm5.ClassReader.&lt;init&gt;(Unknown Source) at org.apache.xbean.asm5.ClassReader.&lt;init&gt;(Unknown Source) at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:46) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:449) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:432) at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:230) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40) at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:103) at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732) at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:432) at org.apache.xbean.asm5.ClassReader.a(Unknown Source) at org.apache.xbean.asm5.ClassReader.b(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:262) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:261) at scala.collection.immutable.List.foreach(List.scala:381) at org.apache.spark.util.ClosureClea…
favorite count: 0
upvote count: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87271169
type: Question
score: 2
has comment: http://stackoverflow.com/comment/87372804
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/87257458
has comment: http://stackoverflow.com/comment/87239570
tagged with: pyspark
tagged with: python
has title: Spark RDD - Error while sending iterator

http://stackoverflow.com/comment/87328877
has text: @Zinki I used both ^ this and mabac's answers and it works fine now
type: AnswerComment
comment on: http://stackoverflow.com/a/50155361
score: 0
type: Comment

http://stackoverflow.com/q/50217771
has title: Adding text from row in csv with some empty cells into a list in Python
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50217900
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87452645
has comment: http://stackoverflow.com/comment/87454377
tagged with: python
has comment: http://stackoverflow.com/comment/87454564
has comment: http://stackoverflow.com/comment/87453329
has comment: http://stackoverflow.com/comment/87452909
has comment: http://stackoverflow.com/comment/87453598
score: 0
has comment: http://stackoverflow.com/comment/87452908
has body: Right now my code adds the text from the required rows from 2 different csv files into one list: import csv res = [] with open('csvexample.csv') as f, open('csvexample1.csv') as a: reader=csv.reader(f) reader1=csv.reader(a) next(reader) next(reader1) for row in zip(reader, reader1): res.extend([row[0][0], row[1][1]]) print(res) Let's say csvexample.csv looks like this: ID Text 1 'good morning' 2 'good afternoon' 3 'good evening' and csvexample1.csv looks like this: Day Month 14 'Feb' 21 'Mar' 31 'May' 10 The outcome is as follows: ['1', 'feb', '2', 'mar', '3', ''] However, I want it to print out 'May' for the csvexample1.csv file was well, and just ignore the empty cells. What do I need to change about the current code to make sure that happens?
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/87465583
comment on: http://stackoverflow.com/q/50223662
type: Comment
score: 0
type: QuestionComment
has text: I am not actually the owner of the question, just wanted to show what you asked for

http://stackoverflow.com/q/50154436
has answer: http://stackoverflow.com/a/69407955
downvote count: 0
has title: sqlalchemy how to get list of data instead of list of sqlalchemy.util._collections.result
accepted answer: http://stackoverflow.com/a/50154966
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50154966
upvote count: 2
tagged with: python
has body: I have a table of file information in my DB I am trying to query and return the file_path column of the result as list of string. My code looks like below path_found = session.query(db.file_table.path).filter([filters]).all() It returns a list of sqlalchemy.util._collections.result instead of list of string. Is there any way to get the query result as a list of string?
tagged with: flask-sqlalchemy
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/69407955
score: 2

http://stackoverflow.com/comment/87408289
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50194070
type: QuestionComment
has text: Thanks mdn, @phd for your interest, to finish answering your questions with the second ones, in the environment we get: which python is /Users/jbs/PycharmProjects/WakeUpTEST/env/bin/python . And python --version is Python 2.7.15.

http://stackoverflow.com/comment/87241802
score: 0
comment on: http://stackoverflow.com/q/50112279
type: Comment
type: QuestionComment
has text: sorting strings representing numbers can lead to unexpected results, just format your strings and convert to actual numbers before sorting...

http://stackoverflow.com/a/50115164
has comment: http://stackoverflow.com/comment/87247484
has comment: http://stackoverflow.com/comment/87247387
has comment: http://stackoverflow.com/comment/87247451
upvote count: 2
has comment: http://stackoverflow.com/comment/87247875
accepted answer of: http://stackoverflow.com/q/50115125
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50115125
score: 2
has comment: http://stackoverflow.com/comment/87247978
type: Answer
has body: filter will create new queryset object. Instead of it you can filter with Python: for document in documents: document.hello = "Hello" # Lots more happens here like carrying out more querying and appending things on to document drawings = [document for document in documents if document.type == 'd'] schedules = [document for document in documents if document.type == 's'] context = {'documents': documents, 'drawings': drawings, 'schedules': schedules} You need to add new lists to context to use them in template: {% for document in drawings %} &lt;p&gt;{{document.hello}}&lt;/p&gt; {% endfor %} UPD Or instead of it you probably want to use annotation: from django.db.models import CharField, Value documents=Document.objects.annotate(hello=Value('hello',output_field=CharField())) drawings=documents.filter(type='d') schedules=documents.filter(type='s')
has comment: http://stackoverflow.com/comment/87248146

http://stackoverflow.com/q/50124201
has comment: http://stackoverflow.com/comment/87266571
has answer: http://stackoverflow.com/a/50124256
score: 1
has comment: http://stackoverflow.com/comment/87266715
downvote count: 1
possible better answer: http://stackoverflow.com/a/50124756
favorite count: 0
has body: I have the following Python dictionary: { "cat": 1, "dog": 1, "person": 2, "bear": 2, "bird": 3 } I would like to use dictionary comprehensions to convert it to the following dictionary: { 1 : ["cat", "dog"], 2 : ["person", "bear"], 3 : ["bird"] } How can I go about doing this in a one liner?
type: Question
has answer: http://stackoverflow.com/a/50124756
has comment: http://stackoverflow.com/comment/87267068
upvote count: 2
tagged with: dictionary-comprehension
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has title: Converting Python dictionary using dictionary comprehension
answer count: 3
has comment: http://stackoverflow.com/comment/87266575
accepted answer: http://stackoverflow.com/a/50124256
has answer: http://stackoverflow.com/a/50124258

http://stackoverflow.com/q/50186129
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87389089
tagged with: python-3.x
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/87398480
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87389132
has comment: http://stackoverflow.com/comment/87389189
has comment: http://stackoverflow.com/comment/87389109
has answer: http://stackoverflow.com/a/50186206
has comment: http://stackoverflow.com/comment/87389161
score: 4
tagged with: ubuntu
downvote count: 1
has title: How can i remove python 2.7 as i already have 3.6.5 installed on ubuntu?
has body: i have both 2.7 as well as 3.6.5 installed , at first in ubuntu 18.04 the only python version available was 3.6 but after i installed numpy package, along with it 2.7 got installed as well and it turned into default. Is there any solution so as to make 3.6 the default one instead of 2.7??
has comment: http://stackoverflow.com/comment/87389139
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/67569751
linked to: http://stackoverflow.com/q/41986507

http://stackoverflow.com/comment/93108882
comment on: http://stackoverflow.com/q/50181484
score: 0
has text: Could you give more details on how you solved it? This is kind of a general problem
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87463257
type: Comment
comment on: http://stackoverflow.com/a/50222767
type: AnswerComment
score: 1
has text: Good answer, but that last bullet point is off, `re.match(r'^a.+.b+$', 'abcb')` matches fine.

javascript
tags question: http://stackoverflow.com/q/50183196
tags question: http://stackoverflow.com/q/50158267
tags question: http://stackoverflow.com/q/50124207
tags question: http://stackoverflow.com/q/50189490
tags question: http://stackoverflow.com/q/50140375
tags question: http://stackoverflow.com/q/50087492
tags question: http://stackoverflow.com/q/50220184
tags question: http://stackoverflow.com/q/50204036
tags question: http://stackoverflow.com/q/50108758
tags question: http://stackoverflow.com/q/50103361
tags question: http://stackoverflow.com/q/50100406
tags question: http://stackoverflow.com/q/50119107
tag name: javascript
tags question: http://stackoverflow.com/q/50185118
tags question: http://stackoverflow.com/q/50167203
tags question: http://stackoverflow.com/q/50127085
tags question: http://stackoverflow.com/q/50143672
tags question: http://stackoverflow.com/q/50105188
tags question: http://stackoverflow.com/q/50145145
tags question: http://stackoverflow.com/q/50198172
tags question: http://stackoverflow.com/q/50229842
tags question: http://stackoverflow.com/q/50209797
tags question: http://stackoverflow.com/q/50189486
tags question: http://stackoverflow.com/q/50108133
tags question: http://stackoverflow.com/q/50091348
tags question: http://stackoverflow.com/q/50141756
tags question: http://stackoverflow.com/q/50091265
tags question: http://stackoverflow.com/q/50163268
tags question: http://stackoverflow.com/q/50138722
type: Tag
tags question: http://stackoverflow.com/q/50086517
tags question: http://stackoverflow.com/q/50078543

http://stackoverflow.com/comment/87198605
type: Comment
type: QuestionComment
has text: Updated the imgur album with naive, it displayed the same behavior until I [updated the loss and initializers to match GoogLeNet](https://gist.github.com/Kaapp/abdb54b232eb7f07b87955d9a18df57d/revisions) However, it is also dropping the learning rate every epoch as validation is getting worse. So it seems that the updated naive will overfit on a small set but the small variation in output numbers on different images makes me think that perhaps it is too small to extract much meaningful info from the data?
comment on: http://stackoverflow.com/q/50089597
score: 0

http://stackoverflow.com/comment/87470964
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50216349
has text: i am looking for "status_message":"Email not found"

http://stackoverflow.com/q/50092357
answer count: 1
tagged with: user-interface
has answer: http://stackoverflow.com/a/50100162
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has title: Tkinter OptionMenu not displaying properly
has comment: http://stackoverflow.com/comment/87233713
tagged with: python
has comment: http://stackoverflow.com/comment/87201854
has body: I am trying to create a tkinter GUI with drop down selection menus. The dropdowns are not displaying fully and only show the full bar when something has been selected (see images below). The option menus are created with code similar to this: startmonth = StringVar() p1_PubStartMonth = OptionMenu(DateStartFrame, startmonth, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") p1_PubStartMonth.configure(width=10, bg=_active) p1_PubStartMonth.grid(row=5, column=1) Does anyone know what could be causing these widgets to show up this way?
score: 2

http://stackoverflow.com/q/50114993
has comment: http://stackoverflow.com/comment/87346613
tagged with: video-processing
type: Question
has comment: http://stackoverflow.com/comment/87506056
tagged with: ffmpeg
has body: I'm using the following code to open a video stream: import cv2 video = cv2.VideoCapture() video.open("some_m3u8_link") success, image = video.read() However, even if the code works as intended locally, on Heroku success is always false. I'm using cedar-14 stack with the following buildpacks: heroku/python https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git (I tried several buildpack options for ffmpeg) Running ffmpeg --version on heroku instance will return ffmpeg version 4.0-static https://johnvansickle.com/ffmpeg/ Is there any setting/configuration I missed in order to make it work on deployment? Thank you! Later edit: I tried several links for "some_m3u8_link" including from twitch and other streaming services (including traffic streaming li An example for reproducing: python -c "import cv2; video=cv2.VideoCapture(); video.open('https://hddn01.skylinewebcams.com/live.m3u8?a=5tm6kfqrhqbpblan9j5d4bmua4'); success, image = video.read(); print(success)" Returns True on local machine and False on Heroku. (the link is taken from here)
downvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87326333
has answer: http://stackoverflow.com/a/50262183
upvote count: 13
score: 11
tagged with: opencv
tagged with: heroku
has title: Opencv VideoCapture always returns false on Heroku
has comment: http://stackoverflow.com/comment/87515475
linked to: http://stackoverflow.com/q/47112642
answer count: 3
has comment: http://stackoverflow.com/comment/87515544
has comment: http://stackoverflow.com/comment/87326077
has comment: http://stackoverflow.com/comment/87334524
has comment: http://stackoverflow.com/comment/87425023
has comment: http://stackoverflow.com/comment/87342241
has answer: http://stackoverflow.com/a/72779095
favorite count: 0
has answer: http://stackoverflow.com/a/50267017

http://stackoverflow.com/comment/87218937
comment on: http://stackoverflow.com/q/50101108
type: Comment
type: QuestionComment
has text: Have a look at : https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user
score: 0

http://stackoverflow.com/q/50184303
upvote count: 1
tagged with: python
answer count: 6
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50184372
has answer: http://stackoverflow.com/a/50184343
score: 1
has answer: http://stackoverflow.com/a/61613068
has title: Matching similar items in a list from user input with Python?
has answer: http://stackoverflow.com/a/50184577
accepted answer: http://stackoverflow.com/a/50184334
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50184334
possible better answer: http://stackoverflow.com/a/50184332
has body: I'm very new to Python, and before anything else, I'd like to apologize if the title is not specific enough, but I don't know another way to word it. Also, apologies if this question is a duplicate. As I said, I really don't know what to look for. Anyways, here's what I want to do: I have a list like this: names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford'] I want the user to be able to input a name, so I'll use name = input('Enter name:'), and here's where I get stuck. I want the user to be able to enter a string like shak and have the program display 1. William Shakespeare 2. Shakira or maybe if the user put ford have the program show 1. Tom Ford 2. Tim Ford, and if the user gets more specific, like: shakespeare have the program show only 1. William Shakespeare. I suppose this is a Regex question, but I find Regex very confusing. I've tried watching several videos to no avail. Any type of help is appreciated. Thanks in advance!
tagged with: matching
downvote count: 0
has answer: http://stackoverflow.com/a/50184332

http://stackoverflow.com/comment/87179712
comment on: http://stackoverflow.com/a/50081594
type: Comment
score: 0
type: AnswerComment
has text: @CodingNoob also if a answer was helpful please remember to upvote or/and accept the answer. If not please provide feedback so that it is possible to impove.

http://stackoverflow.com/a/50121582
downvote count: 0
has body: print(soup.find('body').getText()[:300])
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50121519

http://stackoverflow.com/comment/87403363
comment on: http://stackoverflow.com/q/50187902
has text: I get the same segfault at home on Ubuntu 16.04. So I tend to use the matplotlib calls to display an image on that machine. At work on Windows 7, it works fine. The [first few tutorials from the official docs](https://docs.opencv.org/3.4.1/d6/d00/tutorial_py_root.html) all use imshow, but by the time you get [to this tutorial](https://docs.opencv.org/3.4.1/d3/df2/tutorial_py_basic_ops.html), they occasionally use matplotlib. For my apps, I usually display my image in pyqt, so knocking up prototypes in matplotlib is not too annoying.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50157452
type: Question
type: UnansweredQuestion
tagged with: python
has title: Restoring the tensorflow model
has body: I want to restore a tensorflow model after it's trained. I know that I can use tf.train.Saver but the problem is with the restoring because I get confused with the names for get_tensor_by_name. Can anybody help me? This is my graph: x_hat = tf.placeholder(tf.float32, shape=[None, dim_img], name='input_img') x = tf.placeholder(tf.float32, shape=[None, dim_img], name='target_img') # dropout keep_prob = tf.placeholder(tf.float32, name='keep_prob') # input for PMLR z_in = tf.placeholder(tf.float32, shape=[None, dim_z], name='latent_variable') # network architecture y, z, loss, neg_marginal_likelihood, KL_divergence = vae.autoencoder(x_hat, x, dim_img, dim_z, n_hidden, keep_prob)
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50157899
upvote count: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/50227106
downvote count: 1
has answer: http://stackoverflow.com/a/50227226
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50227401
has answer: http://stackoverflow.com/a/50240837
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/50227401
has title: python: read from .txt and judge the new string in the txt file
type: AnsweredQuestion
score: 0
answer count: 3
has body: I am trying to read/write txt file. I want to read from txt file, and then write new string to the next line if the string not existed in the original file. f = open('./video/1.txt', 'a') f.write('123' + '\n') f.close() with open('./video/1.txt') as o: lines=o.readlines() lines=set(lines) if '123' in lines: print("Existed") else:print("Not Existed") The question is : i have '123' is the 1.txt file. And the result is "Not Existed" And I tried to use for line in lines: print(line + '\n') to print out the set variable "lines", it print out 123 at one line. I am confused now. What causes the "NOT EXISTED"? Thank you. Update: I uploaded the screenshot. Still confused.
accepted answer: http://stackoverflow.com/a/50227226
upvote count: 1

http://stackoverflow.com/q/50105801
tagged with: python
type: UnansweredQuestion
answer count: 1
has title: Get a list of documents from list of IDs
tagged with: pymongo
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/4955160
has body: I have a list of _ids of objects in a Mongo database. Using pymongo, what is the best way to get a the list of documents identified by these IDs? I know that I can simply loop over the IDs and do find_one on each ID, but it seems inefficient to do one request for each ID. def get_all(ids): return [coll.find_one({'_id': id}) for id in ids]
type: Question
has answer: http://stackoverflow.com/a/50105995

http://stackoverflow.com/comment/87315560
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50129983
has text: @TheTechGuy I modified the answer adding `index = False` to `df.to_csv`. In this way you dont save the index in the csv file.
type: Comment

http://stackoverflow.com/comment/87274857
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50128490
has text: If I convert the DataFrame to pandas Series then it's all OK, but if I try to iterate on it then I get indexError: for e.g.: len(data.iloc[0]['numbers']) = 1 which can't be true, because after converting it to series it's a list with 2000 elements
type: AnswerComment

http://stackoverflow.com/comment/87348834
type: Comment
has text: I was actually referring to `totalcount` for birthday.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50163319

http://stackoverflow.com/a/50183577
has comment: http://stackoverflow.com/comment/87449729
accepted answer of: http://stackoverflow.com/q/50180227
type: Answer
answers question: http://stackoverflow.com/q/50180227
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: This code does what you want: class menu: hover = False def __init__(self, text, pos, callback): self.text = text self.pos = pos self.callback = callback # so we now what function to call self.set_rect() self.draw() # the rest of your code def quit_loop(): global running running = False select = [menu("Computer Virus", (100, 200), lambda: print("Computer Virus")), # Add a callback menu("Computer Crime", (100, 300), lambda: print("Computer Crime")), menu("QUIT", (100, 400), quit_loop)] running = True while running: for evnt in event.get(): if evnt.type == QUIT: running = False if evnt.type == MOUSEBUTTONDOWN: # if a mousebutton got pressed if evnt.button == 1: # if the first button got pressed for menu in select: if menu.rect.collidepoint(evnt.pos): # does this one collide menu.callback() # call the callback
has comment: http://stackoverflow.com/comment/87390383
has comment: http://stackoverflow.com/comment/87387239

http://stackoverflow.com/a/50075087
type: Answer
has comment: http://stackoverflow.com/comment/87171050
has body: You can use pd.DataFrame.xs with axis=1: res = ag.xs([('a', 'sum'), ('b', 'count')], axis=1) print(res) a b sum count cat a 2 2 b 3 1
accepted answer of: http://stackoverflow.com/q/50074981
has comment: http://stackoverflow.com/comment/87170866
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50074981
score: 1

http://stackoverflow.com/comment/87414785
score: 0
has text: @ DeepSpace each 22222222 should still have separate rows as they have different adsl/port
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50198820

http://stackoverflow.com/comment/87449343
comment on: http://stackoverflow.com/q/50215911
type: Comment
has text: He is asking something which can avoid duplicates before appending to the list. check my answer!
score: 0
type: QuestionComment

http://stackoverflow.com/q/50091283
has comment: http://stackoverflow.com/comment/87199746
has body: is it possible to run matplotlib from text-only console? I am using matplotlib to generate few graphs and save it using fig.savefig(). So, basically, the graphs are genrated in the background and saved on the filesystem. The error is self.fig1 = plt.figure(figsize=plt.figaspect(aspect_ratio)) File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 535, in figure **kwargs) File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager return new_figure_manager_given_figure(num, figure) File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure window = Tk.Tk() File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1818, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87206982
tagged with: python
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has title: run matplotlib from a terminal to generate and save figures
has comment: http://stackoverflow.com/comment/87206898
linked to: http://stackoverflow.com/q/37604289

http://stackoverflow.com/q/50109634
type: Question
has body: I have a dictionary where I store a tuple (x,y) as the key However, when I place the following condition it returns true even though the tuple is already in the dictionary. if (virtual_box_i, virtual_box_j) not in self.visitid_indices: break I am sure the tuple is there as I can see it in self.visitid_indices when debugging as below: What could be I am doing wrong here?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87236823
score: -3
has comment: http://stackoverflow.com/comment/87237060
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87236988
has title: Using tuple of integers as a key in python not working
has comment: http://stackoverflow.com/comment/87236651
has comment: http://stackoverflow.com/comment/87237444
has comment: http://stackoverflow.com/comment/87237124
has comment: http://stackoverflow.com/comment/87237055
has comment: http://stackoverflow.com/comment/87236641
upvote count: 0
has answer: http://stackoverflow.com/a/50110134
downvote count: 3
has comment: http://stackoverflow.com/comment/87237323
has comment: http://stackoverflow.com/comment/87237189
answer count: 1
has comment: http://stackoverflow.com/comment/87236783
has comment: http://stackoverflow.com/comment/87237334
has comment: http://stackoverflow.com/comment/87236669
favorite count: 0

http://stackoverflow.com/q/50163407
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: How do I edit a specific line in a text file with python without converting everything in the text file into a list?
has answer: http://stackoverflow.com/a/50163482
score: 0
has comment: http://stackoverflow.com/comment/87344886
type: Question
has body: Im creating a code that has six quizzes and all the results from these quizzes get stored in the users text file (code below is from a larger piece of code). This code below is from one of the quizzes and shows how the results get stored in the file (the 'Counter' variable is the results): User = str(input("please re-enter your username: ")) with open(User+'.txt', 'r') as f: line = f.readlines() line[8] = Counter with open('User+.txt', 'w') as f: f.writelines(str(line)) Depending on the quiz, one of the '-' in the user's file should change to the score for that quiz (EG: if I scored 1 on a quiz, the user's file should show this): (username) (password) (year) (firstname) (surname) - - - 1 - - However when its run, the user's file converts into this: ['(username)\n', '(password)\n', '(year)\n', '(firstname)\n', '(surname)\n', '-\n', '-\n', '-\n', 1, '-\n', '-'] What do I have to change in the code in order for my results to be shown like that?

http://stackoverflow.com/comment/87183631
score: 0
comment on: http://stackoverflow.com/a/50083921
type: AnswerComment
has text: Perfect! Thank you! I just did not like having to concatenate the strings, and knew there was a way to combine this in a list comprehension.
type: Comment

http://stackoverflow.com/a/50155627
accepted answer of: http://stackoverflow.com/q/50155552
type: Answer
answers question: http://stackoverflow.com/q/50155552
score: 2
upvote count: 2
downvote count: 0
has body: Initialise a list and then use list.append: lst = [] for m in range(12): lst.append(float(input('Enter entry for month {0}: '.format(m)))) Alternatively, you can use a list comprehension, but this is inadvisable as it is a less readable solution: lst = [float(input('Enter entry for month {0}: '.format(m))) for m in range(2)]
type: AcceptedAnswer

http://stackoverflow.com/a/50183673
has body: new_dict = {} for k, v in d.items(): new_dict[k] = max(v.values())
answers question: http://stackoverflow.com/q/50183032
type: Answer
upvote count: 2
score: 1
downvote count: 1

http://stackoverflow.com/comment/87427702
comment on: http://stackoverflow.com/q/50205251
type: Comment
type: QuestionComment
has text: General programming discussions are off topic here. Good luck!
score: 3

http://stackoverflow.com/comment/87385408
comment on: http://stackoverflow.com/q/50180086
has text: No worries, mate! You are welcome!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50164830
downvote count: 0
has comment: http://stackoverflow.com/comment/87347766
upvote count: 1
has comment: http://stackoverflow.com/comment/87348131
tagged with: string
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: Code def search(self, arg1, arg2): global ipv4_regex, type_regex if isinstance(arg2, type_regex): text = re.search(arg2, arg1) if text: p = text.group() return len(p) else: return 0 else: if arg2 in arg1: return len(arg2) else: return 0 I have a python script where, to serve one request, this function gets recomputed around 452900 times(found this value by doing profiling of code using pprofile), to give the output. Some notes about function: arg1 = string arg2 = ith string/regex Basically, arg2 is an ith instance of a long list of regex/strings that needs to be matched against arg1 (arg1 remains constant for one request) inorder to find matching length. I came up with this function, but time &amp; CPU consumption is becoming bottleneck for me. Because of many search operations, CPU goes very high soon. What ideas I thought till now Use dictionary comprehension instead of if-else as suggested here Use some kind of Tree based search, the way we do for strings. both these ideas are simple ideas as of now, I am not able to bring them into action. I have no control over regexes in arg2, so regex optimization wouldn't help here. Please suggest, I am looking for ideas as to how can i optimize this function? Thanks
tagged with: regex
linked to: http://stackoverflow.com/q/9442724
tagged with: optimization
tagged with: tree
has title: optimise python regex search
answer count: 0
score: 1

http://stackoverflow.com/a/50138092
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50137947
has body: i know that i need to use for line in f: data.append(json.loads(line))" Why on earth would you do that ??? You've already parsed the whole file, you have a list object back, all you have to do is iterate on the list. with open('output.json') as json_data: data = json.load(json_data,) for item in data: print(item)
downvote count: 0

http://stackoverflow.com/comment/87310552
type: AnswerComment
comment on: http://stackoverflow.com/a/50146114
has text: Hm,Im running into a Syntax Error: Invalid syntax on the line `if instance.__class__.__name__ == 'Profile'` And yes,Profile does have a OneToOneField to User in models :)
type: Comment
score: 0

http://stackoverflow.com/a/50666056
score: 7
type: AcceptedAnswer
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/50214773
type: Answer
has body: I had exactly the same issue and solved it this way: widgets = { 'request_date': DateTimeInput(attrs={'type': 'datetime-local'}), }
has comment: http://stackoverflow.com/comment/122869715
accepted answer of: http://stackoverflow.com/q/50214773

http://stackoverflow.com/q/50088266
has answer: http://stackoverflow.com/a/50088568
accepted answer: http://stackoverflow.com/a/50088568
tagged with: python
has comment: http://stackoverflow.com/comment/87192392
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/87192486
has comment: http://stackoverflow.com/comment/87192469
has answer: http://stackoverflow.com/a/50088345
possible better answer: http://stackoverflow.com/a/50088345
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I was writing a code that will ask you to play a guessing game. It will ask you whether you want to play or not and proceed. It was supposed to ask a number again if the entered value is not in the list but It is not working. I couldn't get it. Thx by now! import random import math import time repeat=True numbers = ["1","2","3","4","5"] gamestart=False gamecontinue=True def guess(): chosennumber=random.choice(numbers) guessnumber=raw_input("&gt;Guess the number I chose between 0 and 6:") if guessnumber==chosennumber and guessnumber in numbers: print "&gt;Congratulations, I chose %d too!" % (int(chosennumber)) print elif guessnumber!=chosennumber: print "That is not right." print "I chose %d." % (int(chosennumber)) print elif not guessnumber in numbers: while not guessnumber in numbers: guessnumber=raw_input("&gt;Please enter a number between 0 and 6:") if raw_input("&gt;Do you want to play guessing game? Y or N:") == "Y": gamestart=True else: print "Okay, I will play myself." time.sleep(2) print "Bye :(" while gamestart==True and gamecontinue==True: guess() if raw_input ("&gt;Do you want to play again? Y or N:") == "N": gamecontinue=False print "Okay, I will play myself." time.sleep(2) print "Bye :("
has answer: http://stackoverflow.com/a/50088454
has title: Python; How do I test if something is in a list?

http://stackoverflow.com/comment/87230422
comment on: http://stackoverflow.com/q/50106519
type: Comment
type: QuestionComment
score: 0
has text: Could you include a [mcve] for just the operation that is puzzling you?

http://stackoverflow.com/a/50152588
has comment: http://stackoverflow.com/comment/87323087
has comment: http://stackoverflow.com/comment/87324342
downvote count: 0
has comment: http://stackoverflow.com/comment/87323462
has comment: http://stackoverflow.com/comment/87323373
upvote count: 1
has comment: http://stackoverflow.com/comment/87323821
answers question: http://stackoverflow.com/q/50152386
score: 1
has body: I think your regex pattern is wrong here. Its of Javscript. It should be like regex1 = r'^[a-zA-Z]{3,7}$' Also I am assuming that the regex should match entire string NOT some sub-string. So if a string is like aaaaabbb cc should be discarded. If it doesn't you should use word boundary \b instead of start ^ and end $ anchors. So it should be regex1 = r'\b[a-zA-Z]{3,7}\b' Here is a working example from sklearn.feature_extraction.text import CountVectorizer regex1 = r'\b[a-zA-Z]{3,7}\b' token_dict = {123: 'horses', 345: 'ab'} vectorizer = CountVectorizer(token_pattern = regex1) vectorizer1 = vectorizer.fit_transform(token_dict.values()) print(vectorizer.get_feature_names()) Output ['horses']
type: Answer
has comment: http://stackoverflow.com/comment/87323322

http://stackoverflow.com/comment/87192608
comment on: http://stackoverflow.com/a/50087435
has text: @Daniel Each field gets stored as an instance attribute of the class. And by using `@property` you can get fields to calculate and update their values automatically. Alternatively, you can store them into a dict, using the field name as the dict key. One problem with plain dicts in old versions of Python is that dicts are unordered collections, which can be annoying if you want the fields to be in a particular order. However, there's an OrderedDict in the `collections` module, and recent versions of Python 3 _do_ retain the insertion order of dicts.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87359854
comment on: http://stackoverflow.com/a/50170356
has text: Thanks! Seems k-means works, but doesn't this code cluster the transactions rather than the users? I would like to say to which cluster each user belongs. I am not sure if it's possible, but this seems to be very close!
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/50164954
has comment: http://stackoverflow.com/comment/87349605
has body: As noted the issue is that the numpy MaskedArray.filled() method seems to try converting the fill value to the appropriate type before checking if there is actually anything to fill. Since the table in the example has an int column, this fails within numpy (and astropy.Table is just calling the filled() method on each column). This should work: In [44]: def fill_cols(tbl, fill=np.nan, kind='f'): ...: """ ...: In-place fill of ``tbl`` columns which have dtype ``kind`` ...: with ``fill`` value. ...: """ ...: for col in tbl.itercols(): ...: if col.dtype.kind == kind: ...: col[...] = col.filled(fill) ...: In [45]: t = simple_table(masked=True) In [46]: t Out[46]: &lt;Table masked=True length=3&gt; a b c int64 float64 str1 ----- ------- ---- -- 1.0 c 2 2.0 -- 3 -- e In [47]: fill_cols(t) In [48]: t Out[48]: &lt;Table masked=True length=3&gt; a b c int64 float64 str1 ----- ------- ---- -- 1.0 c 2 2.0 -- 3 nan e
downvote count: 0
has comment: http://stackoverflow.com/comment/87349532
accepted answer of: http://stackoverflow.com/q/50161173
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50161173
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/87373220
has comment: http://stackoverflow.com/comment/87349499
upvote count: 3

http://stackoverflow.com/a/50166225
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50166133
upvote count: 1
has body: The classification function you've written is an instance method, which means it should be called on an instance of the class. You can do that in two steps: bob = HumanClassification() # create the instance bob.classification(32, 6, 'male') # call the method on it But it might make more sense for the arguments to be passed directly to __init__, rather than having a separate method. You can provide default arguments if you want it to be possible to create an instance without specifying all the values up front. class HumanClassification: def __init__(self, age=0, height=0, gender=''): self.age = age self.height = height self.gender = gender Using a list as a default argument is usually a bad idea, so I used an empty string as the default for gender. Another approach would be to change classification to a classmethod, rather than a normal method. A classmethod is usually called directly on the class, as you're currently doing. Some classes are designed with alternative constructors implemented with classmethods. Here's what that might look like: class HumanClassification: def __init__(self): self.age = 0 self.height = 0 self.gender = [] @classmethod # use the classmethod decorator def classification(cls, age, height, gender): # first arg is the class, not an instance self = cls() # create a new instance by calling the class self.age = age self.height = height self.gender = gender return self # return the instance bob = HumanClassification.classification(32, 6, 'male') # this works now print (bob.age)
answers question: http://stackoverflow.com/q/50166133
has comment: http://stackoverflow.com/comment/87350878
has comment: http://stackoverflow.com/comment/87353210

http://stackoverflow.com/a/50118006
has comment: http://stackoverflow.com/comment/87256587
has comment: http://stackoverflow.com/comment/87256319
has comment: http://stackoverflow.com/comment/87255188
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87257379
has comment: http://stackoverflow.com/comment/87255374
upvote count: 1
has comment: http://stackoverflow.com/comment/87255644
has comment: http://stackoverflow.com/comment/87255779
accepted answer of: http://stackoverflow.com/q/50116513
has comment: http://stackoverflow.com/comment/87255702
has comment: http://stackoverflow.com/comment/87257176
has comment: http://stackoverflow.com/comment/87256221
has comment: http://stackoverflow.com/comment/87255496
has comment: http://stackoverflow.com/comment/87255465
has comment: http://stackoverflow.com/comment/87257456
type: Answer
has comment: http://stackoverflow.com/comment/87257405
has body: I was looking into the man page of ffmpeg and came across the loglevel option. -loglevel [repeat+]loglevel | -v [repeat+]loglevel Set the logging level used by the library. Adding "repeat+" indicates that repeated log output should not be compressed to the first line and the "Last message repeated n times" line will be omitted. "repeat" can also be used alone. If "repeat" is used alone, and with no prior loglevel set, the default loglevel will be used. If multiple loglevel parameters are given, using 'repeat' will not change the loglevel. loglevel is a string or a number containing one of the following values: verbose, 40 Same as "info", except more verbose. So here is a simple one-liner workaround to get the things working in your case - ffmpeg -i my_vid_feed -vcodec copy -map 0 -f segment -segment_time 5 -loglevel 40 -segment_format mp4 capture-%05d.mp4 2&gt;&amp;1 | grep --line-buffered -Eo "segment:.+ended" | awk -F "'" '{print $2; system("")}' | xargs -n1 python my_processor.py -p I am just parsing the output of the ffmpeg, when a new file is written completely the verbose log emits a line like this - [segment @ 0x7fc253817000] segment:'capture-00002.mp4' count:2 ended So I am just taking the filename from the line and passing it to that argparse python file. The -n1 option in the xargs tells it to only pass one arg at a time to the python file and then execute the python script with that file as an argument. Here is the output of the command in action - root$ ffmpeg -i my_vid_feed -vcodec copy -map 0 -f segment -segment_time 5 -loglevel 40 -segment_format mp4 capture-%05d.mp4 2&gt;&amp;1 | grep --line-buffered -Eo "segment:.+ended" | awk -F "'" '{print $2; system("")}' | xargs -n1 python my_processor.py -p started capture-00000.mp4 ended started capture-00001.mp4 ended started capture-00002.mp4 ended started capture-00003.mp4 ended The python file used - my_processor.py import argparse import time if __name__ == "__main__": parser = argparse.ArgumentParser() p…
has comment: http://stackoverflow.com/comment/87256038
answers question: http://stackoverflow.com/q/50116513
has comment: http://stackoverflow.com/comment/87253868
has comment: http://stackoverflow.com/comment/87254105
has comment: http://stackoverflow.com/comment/87255410

http://stackoverflow.com/comment/87409187
type: QuestionComment
comment on: http://stackoverflow.com/q/50194794
has text: @Starter See my answer. It works for arbitrary list of lists too.
score: 0
type: Comment

http://stackoverflow.com/comment/87514301
type: Comment
has text: https://bugs.python.org/issue17950 actually describes precisely this behavior. But it's closed without a fix. Oh well I will just live with it. Thanks for your insights.
type: AnswerComment
comment on: http://stackoverflow.com/a/50173178
score: 1

http://stackoverflow.com/comment/87202913
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50092443
score: 0
has text: As mentioned in the OP, the env vars work in every environment except for when I run unit tests. This post is trying to understand why.

http://stackoverflow.com/a/50188569
score: 6
accepted answer of: http://stackoverflow.com/q/50188520
has body: itertools.product() can do the job: from itertools import product l = [3,2,4] print(*product(*[range(i+1) for i in l]), sep='\n') would print: (0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 0, 3) (0, 0, 4) (0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 1, 3) (0, 1, 4) (0, 2, 0) (0, 2, 1) (0, 2, 2) (0, 2, 3) (0, 2, 4) (1, 0, 0) (1, 0, 1) (1, 0, 2) ... (3, 2, 3) (3, 2, 4)
type: Answer
answers question: http://stackoverflow.com/q/50188520
upvote count: 6
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87410026
has text: is' Client` linked to a specific instance of `User` [auth.models.User]?
score: 0
comment on: http://stackoverflow.com/q/50196294
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50113468
score: 0
has body: pandas.read_csv() can parse such CSV files properly if such strings are quoted correctly: CSV: a,b,c 1,"text which includes line breaks",100 2,another line,200 3,yet another line,300 import pd as pandas df = pd.read_csv(r'D:\temp\1.csv') result: In [21]: df Out[21]: a b c 0 1 text which includes\r\nline\r\nbreaks 100 1 2 another line 200 2 3 yet another line 300
type: Answer
answers question: http://stackoverflow.com/q/50113009
has comment: http://stackoverflow.com/comment/87246095

http://stackoverflow.com/comment/87301464
has text: Sure, happy to help! :) I know the feeling, you can get confused after a while... :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50134688
type: Comment

http://stackoverflow.com/comment/87326626
has text: If none of them work, then you are doing something wrong.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50153468
type: Comment

http://stackoverflow.com/comment/87414116
type: QuestionComment
comment on: http://stackoverflow.com/q/50197326
score: 0
has text: The MSE value of 0.70 by itself makes answering that part of your qustion difficult - for instance, if I ask the same question after modeling experimental data with units of meters or kilometers it would still be the same model. In addition to using MSE, consider using the R-squared (R2) value calculated as "R2 = 1.0 - (absolute_error_variance / dependent_data_variance)". This can be interpreted as telling you how much of the data variance is explained by the model. If R2 = 0.5, then the model explains 50 percent of the data variance. If the R2 is 0.99 then the model explains 99 percent.
type: Comment

http://stackoverflow.com/comment/87469313
type: AnswerComment
has text: thats what I have written.. see first command, you go to that directory vk and then run batch command using second command i.e. `TestBatch`
type: Comment
comment on: http://stackoverflow.com/a/50225846
score: 0

http://stackoverflow.com/comment/87292319
score: 0
has text: I think you misunderstand the difference between the two. `pytest` mainly replaces `unittest` in test collection, test execution, test signatures (functions vs classes + classmethods) and assertions. In fact, the test above was written using `pytest`; it won't be even recognized by `unittest`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50101960

http://stackoverflow.com/comment/87447677
has text: @jdv: I tried with min, max range. and I think Mohit has given one solution.
type: Comment
comment on: http://stackoverflow.com/q/50215207
score: 0
type: QuestionComment

http://stackoverflow.com/q/50214763
has title: Unable to Write to bigquery - Permission denied: Apache Beam Python - Google Dataflow
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/54231086
answer count: 3
tagged with: apache-beam
has answer: http://stackoverflow.com/a/50219893
tagged with: python
tagged with: google-cloud-dataflow
tagged with: google-bigquery
type: Question
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/50935693
type: UnansweredQuestion
has body: I have been using apache beam python sdk using google cloud dataflow service for quite some time now. I was setting dataflow up for a new project. The dataflow pipeline Reads data from google datastore Processes it Writes to Google Big-Query. I have similar pipelines running on other projects which are running perfectly fine. Today, When I started a dataflow job, the pipeline started, read data from datastore, processed it and when it was about to write it to bigquery, It resulted in apache_beam.runners.dataflow.dataflow_runner.DataflowRuntimeException: Dataflow pipeline failed. State: FAILED, Error: Workflow failed. Causes: S04:read from datastore/GroupByKey/Read+read from datastore/GroupByKey/GroupByWindow+read from datastore/Values+read from datastore/Flatten+read from datastore/Read+convert to table rows+write to bq/NativeWrite failed., BigQuery import job "dataflow_job_8287310405217525944" failed., BigQuery creation of import job for table "TableABC" in dataset "DatasetABC" in project "devel- project-abc" failed., BigQuery execution failed., Error: Message: Access Denied: Dataset devel-project-abc:DatasetABC: The user service-account-number-compute@developer.gserviceaccount.com does not have bigquery.tables.create permission for dataset devel-project- abc:DatasetABC: HTTP Code: 403 I made sure all the required API are enabled. According to me the service account has the necessary permission. My question is Where this might be going wrong? Update From what I remember on previous projects (3 different projects to be precise) I didn't give the dataflow service agent any specific permission. The compute engine service agent had permissions like dataflow admin, editor, dataflow viewer. Hence before proceeding with giving the service agent permissions related to bigquery, i would like to know why the environment is behaving differently than the previous projects. Is there any permission/policy changes/updates that went live in last few months resulting in requirement…

http://stackoverflow.com/comment/87179644
type: QuestionComment
comment on: http://stackoverflow.com/q/50081408
score: 1
has text: On decryption you must undo all the processing steps **in the reverse order** that was done upon encryption. For encryption you do these steps: pad -> encrypt -> hexlify. Therefore on decrypt you must do unhexlify -> decrypt -> unpad.
type: Comment

http://stackoverflow.com/comment/87259580
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50120806
has text: @PM2Ring thanks for the comment. i'm well aware of the benefits of adding it as a text block. ill fix is as soon as i have 5 minutes to spare.
score: 1

http://stackoverflow.com/q/50148061
score: 2
has body: In scrapy projects, we can get persistence support by defining a job directory through the JOBDIR setting for eg. scrapy crawl somespider -s JOBDIR=crawls/somespider-1 But how to do the same when running spiders using scrapy.crawler.CrawlerProcess from a python script as answered in How to run Scrapy from within a Python script?
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 2
has title: How to run and save scrapy state from a python script
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/13437402
tagged with: web-scraping
tagged with: scrapy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50148816
has answer: http://stackoverflow.com/a/50148816
tagged with: python

http://stackoverflow.com/q/50195365
has comment: http://stackoverflow.com/comment/87407760
tagged with: django
type: Question
tagged with: session
has comment: http://stackoverflow.com/comment/87408086
has title: How to add default value to Django Sessions
tagged with: python
type: UnansweredQuestion
has body: I'm making a multi-language site, and would like to have a default language set to a specific one. How would I add a default value to every new session? Namely, I would like to request.session['lang'] = 'de' to be the default value upon creation of every new session. By default, 'lang' is not stored in request.session, and attempting to call request.session['lang'] for purpose of finding out the prefered language of a user, would return Key error unless 'lang' has been set beforehand. So instead of checking for and setting default language in every view, how would I go about making &lt;'lang':'de'&gt; part of every new session?
has comment: http://stackoverflow.com/comment/87407767
score: 0
answer count: 0

http://stackoverflow.com/q/50228530
type: UnansweredQuestion
tagged with: python
answer count: 1
has title: ValueError: 'too many values to unpack' on trying access from Database
has answer: http://stackoverflow.com/a/50228617
tagged with: python-2.x
tagged with: database
has body: I'm trying to fetch data from DB and store But I'm getting an error [pqr] = abc_report.updates[0]['mno'][0]['groups'][0]['params'].iteritems() The data is something like this in the params {u'def': True, u'efg': 17, u'ijk': 127, u'xyz': True}
type: Question
has comment: http://stackoverflow.com/comment/87477615
score: 0
has comment: http://stackoverflow.com/comment/87474188

http://stackoverflow.com/comment/87229963
has text: @Prateek - I didn't think about a tools issue - thanks. I double checked and Anaconda is installed on VScode - I'm at a loss.
type: QuestionComment
comment on: http://stackoverflow.com/q/50093335
type: Comment
score: 0

http://stackoverflow.com/comment/87376854
comment on: http://stackoverflow.com/a/50179204
has text: i added __init__.py and i tried both sys.path.append(path) but also , same error apears
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87391518
has text: I think the spaces around `-` are required, not optional. Probably to allow names with `-` in them.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50187439
type: AnswerComment

http://stackoverflow.com/a/50175063
score: 0
type: Answer
has body: Your calculate_mathematical_expression function is not returning anything. Try following code: def calculate_mathematical_expression(num1,num2,operation): if operation == "+": return mathematical_sum(num1,num2) elif operation == "-": return mathematical_difference(num1,num2) elif operation == "*": return mathematical_product(num1,num2) elif operation == "/": return mathematical_division(num1,num2) else: return operation_error(operation)
answers question: http://stackoverflow.com/q/50174965

http://stackoverflow.com/q/50218190
tagged with: python-unittest
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50219605
tagged with: python
has body: I'm writing tests for my application using unittest in Python3.6. I'm creating a simple Flask app for this test, that I want to register my defined blueprints with. The issue I get is when I try to import my blueprints is this one: File "/app/test/__init__.py", line 1, in &lt;module&gt; from . import test_views File "/app/test/test_views.py", line 50, in &lt;module&gt; from api.metrics.views import stats File "/app/api/metrics/__init__.py", line 1, in &lt;module&gt; from .views import stats File "/app/api/metrics/views.py", line 13, in &lt;module&gt; def get_stats(client=None): File "/testenv/lib/python3.6/site-packages/flask/blueprints.py", line 161, in decorator endpoint = options.pop("endpoint", f.__name__) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py", line 584, in __getattr__ raise AttributeError(name) AttributeError: __name__ The error comes where I call @stats.route... in this code: stats = Blueprint('metrics', __name__) @stats.route('/metrics', methods=['POST']) @setup.require_suth def get_metrics(client=None): &lt;This code is not relevant&gt; Does anyone know how to do this correctly? I really can't figure out how to do this. This is my structure: /app /api /metrics __init__.py views.py /test test_views.py And here is the import statement in my tests: app_ = define_test_app() from api.metrics.views import stats app_.register_blueprint(stats) Would appreciate help, since I'm completely stuck at this point.
tagged with: flask
has answer: http://stackoverflow.com/a/60295286
tagged with: python-decorators
has title: Tests for Flask Blueprint gives attributeerror
answer count: 2
score: 1

http://stackoverflow.com/a/50218057
answers question: http://stackoverflow.com/q/50217971
score: 1
has body: I don't know if you're using python 3. Check this out here: https://docs.python.org/3/howto/unicode.html . Moreover, you should use UTF-8 to encode your unicode. CP1255 has only Hebrew in it https://en.wikipedia.org/wiki/Windows-1255 Your console should support unicode, which is why you see it properly there. Basically, what I'm saying is: If you use Python 3 and use no shenanigan at all, it should work by default :-) If you force an old encoding... then you'll get down the rabbit hole...
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87336599
type: Comment
type: QuestionComment
has text: I have deleted all of the data in the database by using manage.py flush and it now seems to have migrated. Further testing is required though. Can anyone advise on if it would have been the locations column causing the issue and on how to purge data from just one column? In this instance all of the data was just junk test data so it was okay for me to delete the lot.
score: 0
comment on: http://stackoverflow.com/q/50149707

join
type: Tag
tags question: http://stackoverflow.com/q/50228213
tags question: http://stackoverflow.com/q/50101772
tags question: http://stackoverflow.com/q/50084992
tags question: http://stackoverflow.com/q/50191861
tag name: join
tags question: http://stackoverflow.com/q/50184243
tags question: http://stackoverflow.com/q/50124679
tags question: http://stackoverflow.com/q/50189828

http://stackoverflow.com/q/50139596
score: 0
has title: JSONDecodeError: Expecting value: line 1 column 1 (char 0) when doing large API request
tagged with: http://stackoverflow.com/tag/json
has body: I am using a script to fill a python list with data I get from an API request. However, I am getting the following error: JSONDecodeError: Expecting value: line 1 column 1 (char 0) The rate limit of the API is 500 per request and 200 request per minute which I am not exceeding since the package I am using does this in a loop. This happens every time when reaching 49000 results. Any idea why this happens? Thanks! Output of error: JSONDecodeError Traceback (most recent call last) &lt;ipython-input-100-c4c6bcbc9cbd&gt; in &lt;module&gt;() 10 cache = [] 11 ---&gt; 12 for c in gen: 13 cache.append(c) 14 /Users/xxx/anaconda/lib/python3.5/site-packages/psaw/PushshiftAPI.py in _query(self, kind, stop_condition, **kwargs) 100 limit = 0 101 --&gt; 102 results = self._get(kind, payload) 103 if self._limited(payload): 104 yield results /Users/xxx/anaconda/lib/python3.5/site-packages/psaw/PushshiftAPI.py in _get(self, kind, payload) 81 success = response.status_code == 200 82 i+=1 ---&gt; 83 response_json = json.load(response.text) 84 outv = response_json['data'] 85 if self._limited(payload): /Users/xxx/anaconda/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 317 parse_int is None and parse_float is None and 318 parse_constant is None and object_pairs_hook is None and not kw): --&gt; 319 return _default_decoder.decode(s) 320 if cls is None: 321 cls = JSONDecoder /Users/xxx/anaconda/lib/python3.5/json/decoder.py in decode(self, s, _w) 337 338 """ --&gt; 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 340 end = _w(s, end).end() 341 if end != len(s): /Users/xxx/anaconda/lib/python3.5/json/decoder.py in raw_decode(self, s, idx) 355 obj, end = self.scan_once(s, idx) 356 except StopIteration as err: --&gt; 357 raise JSONDecodeError("Expecting value", s, err.value) from None 358 return obj, end JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is my input code: I am using this .p…
tagged with: python
has comment: http://stackoverflow.com/comment/87297905
type: Question
has comment: http://stackoverflow.com/comment/87297747
has comment: http://stackoverflow.com/comment/87298233
answer count: 0
tagged with: api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87298659
has comment: http://stackoverflow.com/comment/87298108

http://stackoverflow.com/a/50163640
has comment: http://stackoverflow.com/comment/87345389
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: For training, you're using X = np.array(df.ix[:, 2:6]) i.e., a matrix with 6 - 2 = 4 columns, meaning that the neighbors are 4-tuples. For predicting, you're using u = df['Close'].iloc[-1] which is a scalar. The nearest neighbor is undefined, and sklearn is very unhappy.
accepted answer of: http://stackoverflow.com/q/50163386
type: Answer
answers question: http://stackoverflow.com/q/50163386
has comment: http://stackoverflow.com/comment/87345885
score: 1

http://stackoverflow.com/comment/87217465
type: AnswerComment
comment on: http://stackoverflow.com/a/50100411
type: Comment
has text: `elif conition` sounds odd.
score: 0

http://stackoverflow.com/q/50169016
has title: Python, Tkinter how to give optionmenu its own windows when pressed
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: tkinter
tagged with: optionmenu
answer count: 1
has body: I have a drop down menu girded on my calculator and i have it set so that there is 3 menu items. What i want to happen is that when one of the menu items is selected it opens a toplevel window describing that item menu and each one is a different menu because they contain different things how can i code this to happen. Im stuck with setting it so that it opens different window for when a different one is slected. def change_dropdown(*args): top = Toplevel() top.title("READ") toplabel = Label(top,text= "Lmao", font = ("Helvetica", 13)) toplabel.grid() button = Button(top, text="Dismiss", relief=FLAT, font = ("Helvetica", 10, "bold"), fg = "ghostwhite", bg = "black", width = "30", height = "2", command=top.destroy) button.grid() top.focus() def popmenu(): global tkvar tkvar = StringVar(master) choices = {"About","Colour themes", "Contact",} popupMenu = OptionMenu(master, tkvar, *choices) popupMenu.grid(row = 0, column = 0, columnspan = 5, sticky=W+E+S+N) tkvar.set("About") tkvar.trace("w", change_dropdown)
has answer: http://stackoverflow.com/a/50169914
type: Question

apache-spark-sql
tags question: http://stackoverflow.com/q/50174227
tags question: http://stackoverflow.com/q/50207995
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/50187800
tags question: http://stackoverflow.com/q/50184938
tags question: http://stackoverflow.com/q/50104422
tags question: http://stackoverflow.com/q/50105631
type: Tag
tags question: http://stackoverflow.com/q/50210651
tags question: http://stackoverflow.com/q/50196447

http://stackoverflow.com/comment/87249657
has text: try `findAll` instead of `find_all`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50096918
score: 0

http://stackoverflow.com/comment/87325688
type: QuestionComment
comment on: http://stackoverflow.com/q/50154076
score: 2
type: Comment
has text: your functions don't return anything. so they return `None`

http://stackoverflow.com/a/50188375
has comment: http://stackoverflow.com/comment/87393624
answers question: http://stackoverflow.com/q/50188344
has body: Use zip to pair and replace to replace: &gt;&gt;&gt; synonymes = ['verb1', 'verb2', 'verb3'] &gt;&gt;&gt; phrases = ['blabla verb blabla', 'blibli verb blibli', 'verb bloblo bloblo'] &gt;&gt;&gt; [y.replace('verb', x) for x, y in zip(synonymes, phrases)] ['blabla verb1 blabla', 'blibli verb2 blibli', 'verb3 bloblo bloblo'] EDIT: &gt;&gt;&gt; [y.replace('verb', x) for y in phrases for x in synonymes] ['blabla verb1 blabla', 'blabla verb2 blabla', 'blabla verb3 blabla', 'blibli verb1 blibli', 'blibli verb2 blibli', 'blibli verb3 blibli', 'verb1 bloblo bloblo', 'verb2 bloblo bloblo', 'verb3 bloblo bloblo']
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50188344
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87393843
upvote count: 1

arrays
tags question: http://stackoverflow.com/q/50121980
tags question: http://stackoverflow.com/q/50182502
tags question: http://stackoverflow.com/q/50090052
tags question: http://stackoverflow.com/q/50207924
tag name: arrays
tags question: http://stackoverflow.com/q/50082186
tags question: http://stackoverflow.com/q/50215907
tags question: http://stackoverflow.com/q/50194752
tags question: http://stackoverflow.com/q/50119207
tags question: http://stackoverflow.com/q/50137367
type: Tag
tags question: http://stackoverflow.com/q/50121277
tags question: http://stackoverflow.com/q/50225801
tags question: http://stackoverflow.com/q/50078269
tags question: http://stackoverflow.com/q/50169588
tags question: http://stackoverflow.com/q/50166721
tags question: http://stackoverflow.com/q/50162727
tags question: http://stackoverflow.com/q/50088730
tags question: http://stackoverflow.com/q/50194517
tags question: http://stackoverflow.com/q/50168122
tags question: http://stackoverflow.com/q/50083492
tags question: http://stackoverflow.com/q/50083466
tags question: http://stackoverflow.com/q/50189756
tags question: http://stackoverflow.com/q/50152770
tags question: http://stackoverflow.com/q/50108740
tags question: http://stackoverflow.com/q/50158420
tags question: http://stackoverflow.com/q/50146782
tags question: http://stackoverflow.com/q/50218044
tags question: http://stackoverflow.com/q/50092701
tags question: http://stackoverflow.com/q/50125846
tags question: http://stackoverflow.com/q/50076147
tags question: http://stackoverflow.com/q/50127658
tags question: http://stackoverflow.com/q/50180958
tags question: http://stackoverflow.com/q/50154447
tags question: http://stackoverflow.com/q/50090076
tags question: http://stackoverflow.com/q/50152911
tags question: http://stackoverflow.com/q/50132042
tags question: http://stackoverflow.com/q/50079133
tags question: http://stackoverflow.com/q/50076262
tags question: http://stackoverflow.com/q/50192998
tags question: http://stackoverflow.com/q/50178530
tags question: http://stackoverflow.com/q/50210458
tags question: http://stackoverflow.com/q/50114635
tags question: http://stackoverflow.com/q/50202884
tags question: http://stackoverflow.com/q/50096645
tags question: http://stackoverflow.com/q/50122226
tags question: http://stackoverflow.com/q/50100246
tags question: http://stackoverflow.com/q/50154945
tags question: http://stackoverflow.com/q/50151417
tags question: http://stackoverflow.com/q/50177594
tags question: http://stackoverflow.com/q/50194338
tags question: http://stackoverflow.com/q/50217615
tags question: http://stackoverflow.com/q/50099100
tags question: http://stackoverflow.com/q/50095730
tags question: http://stackoverflow.com/q/50167936
tags question: http://stackoverflow.com/q/50142829
tags question: http://stackoverflow.com/q/50130759
tags question: http://stackoverflow.com/q/50123260
tags question: http://stackoverflow.com/q/50133009
tags question: http://stackoverflow.com/q/50195967
tags question: http://stackoverflow.com/q/50150055
tags question: http://stackoverflow.com/q/50130230
tags question: http://stackoverflow.com/q/50144414
tags question: http://stackoverflow.com/q/50120062
tags question: http://stackoverflow.com/q/50099427
tags question: http://stackoverflow.com/q/50129198
tags question: http://stackoverflow.com/q/50121887
tags question: http://stackoverflow.com/q/50137159
tags question: http://stackoverflow.com/q/50161915
tags question: http://stackoverflow.com/q/50228163
tags question: http://stackoverflow.com/q/50176262
tags question: http://stackoverflow.com/q/50087073
tags question: http://stackoverflow.com/q/50179457
tags question: http://stackoverflow.com/q/50159625
tags question: http://stackoverflow.com/q/50162424
tags question: http://stackoverflow.com/q/50101539
tags question: http://stackoverflow.com/q/50193335
tags question: http://stackoverflow.com/q/50170109
tags question: http://stackoverflow.com/q/50144888
tags question: http://stackoverflow.com/q/50215808

http://stackoverflow.com/q/50081211
tagged with: python-2.7
has title: Tkinter window won't open?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87178375
has body: I'm trying to make a basic calculator with Tkinter, but when I run the program the window doesn't open and there isn't any error message. Here's the code(the program is'nt finished yet). from Tkinter import * Calculette=Tk() Calculette.title("Calculette") Chiffres=StringVar B7=Button(Calculette, text="7").grid(column=0, row=1) B8=Button(Calculette, text="8").grid(column=1, row=1) B9=Button(Calculette, text="9").grid(column=2, row=1) B4=Button(Calculette, text="4").grid(column=0, row=2) B5=Button(Calculette, text="5").grid(column=1, row=2) B6=Button(Calculette, text="6").grid(column=2, row=2) B1=Button(Calculette, text="1").grid(column=0, row=3) B2=Button(Calculette, text="2").grid(column=1, row=3) B3=Button(Calculette, text="3").grid(column=2, row=3) Bfois=Button(Calculette, text="x").grid(column=3, row=3) Bmoins=Button(Calculette, text="-").grid(column=3, row=2) Bdivision=Button(Calculette, text="/").grid(column=3, row=4) Bplus=Button(Calculette, text="+").grid(column=3, row=1) Begal=Button(Calculette, text="=").grid(column=3, row=5) Affichage=Entry(Calculette, textvariable=Chiffres).grid(column=0, row=0) Calculette.mainloop
has comment: http://stackoverflow.com/comment/87178445
has comment: http://stackoverflow.com/comment/87178641
tagged with: tkinter
answer count: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/50102677
has body: Thanks everyone! I've tried a lot of things including the suggestions above. I did manage to get rid of the miscolorations but still couldn't get quite the result I wanted. However I found this https://pillow.readthedocs.io/en/3.0.x/index.html which looks like it should be able to do the trick for me. Edit: I tested the above solution and it worked fine :). See example below: from PIL import Image, ImageEnhance img = Image.open("dev/poster.png") br = ImageEnhance.Brightness(img) img = br.enhance(0.7) img.show("")
type: Answer
has comment: http://stackoverflow.com/comment/87275035
answers question: http://stackoverflow.com/q/50099347
score: 0

http://stackoverflow.com/comment/87255417
type: AnswerComment
has text: The files may be located outside of the project directory and even lie in some system dir (I actually have to maintain an obscure project that copies headers from `/usr/include/`).
comment on: http://stackoverflow.com/a/50114715
type: Comment
score: 0

http://stackoverflow.com/comment/87229075
type: Comment
comment on: http://stackoverflow.com/a/50104215
type: AnswerComment
score: 0
has text: Can you post a sample of your DF and the Mapping please?

http://stackoverflow.com/a/50088667
type: Answer
downvote count: 0
upvote count: 1
has body: I would split each wav by the areas of silence. Trim the silence from beginning and end. Then I'd run each one through a FFT for different sections. Smaller ones at the beginning of the sound. Then I'd normalise the frequencies against the fundamental. Then I'd feed the results into the NN as a 3d array of volumes, frequencies and times.
score: 1
answers question: http://stackoverflow.com/q/50087271

http://stackoverflow.com/comment/87254904
score: 0
has text: list comprehension you commented is creating new list not removing from existing one
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50118656

http://stackoverflow.com/a/50289346
has body: When I installed pytorch by creating a conda environment, it worked fine. Below are the steps that I tried out. Please try it from your side. conda create -n (env_name) python=3.5 source activate (env_name) conda install pytorch-cpu -c pytorch pip install torchvision
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50185227

http://stackoverflow.com/comment/87249328
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50114689
type: QuestionComment
has text: Thanks for the above suggestions. Will try Hercules to narrow down where the error is coming from.

http://stackoverflow.com/comment/87318196
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50134837
type: AnswerComment
has text: With "name", do you mean **reference** so you can address the button?

http://stackoverflow.com/q/50202010
linked to: http://stackoverflow.com/q/27750842
has comment: http://stackoverflow.com/comment/87420747
has title: Replace tab between names with a space
tagged with: python
has answer: http://stackoverflow.com/a/50202116
has comment: http://stackoverflow.com/comment/87420739
score: 2
linked to: http://stackoverflow.com/q/16052862
tagged with: python-2.7
answer count: 3
upvote count: 3
has body: How can I get rid of that tab with regular expressions? I also need to do it on the fly because the name will be inside a list. import re x = 'Muh kay' I want x to be x = 'Muh Kay' with only one space between them.
has answer: http://stackoverflow.com/a/76306232
tagged with: regex
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87420686
has answer: http://stackoverflow.com/a/50202087
has comment: http://stackoverflow.com/comment/87422384
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87420650

http://stackoverflow.com/q/50108831
has comment: http://stackoverflow.com/comment/87235509
has comment: http://stackoverflow.com/comment/87235545
has answer: http://stackoverflow.com/a/50109445
score: 0
answer count: 1
type: Question
has body: Assume I have two classes that use threads class foo(threading.Thread): def __init__(self): threading.Thread.__init__(self,name="foo=&gt;bar") self.var1 = {} def run(self): while True value, name = getvalue() // name is an string self.var1[name] = value bar(self) class bar(threading.Thread): def __init__(self,fooInstance): threading.Thread.__init__(self,name="bar") def run(self): while True arg = myfunction() // somefunction (not shown for simplicity) val = myOtherfunction(fooInstance.var1[arg]) //other function print(val) f = foo() f.start() The variable var1 in foo will change over time and bar needs to be aware of these changes. It makes sense to me, but I wonder if there is something fundamental here that could fail eventually. is this correct in python?
has comment: http://stackoverflow.com/comment/87235893
has comment: http://stackoverflow.com/comment/87235649
tagged with: multithreading
has comment: http://stackoverflow.com/comment/87235881
has comment: http://stackoverflow.com/comment/87235955
tagged with: python
tagged with: parameter-passing
has title: Passing variables between classes in different threads?
tagged with: class
has comment: http://stackoverflow.com/comment/87236205
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87235346
accepted answer: http://stackoverflow.com/a/50109445

http://stackoverflow.com/a/50183751
answers question: http://stackoverflow.com/q/50183521
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50183521
type: AcceptedAnswer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/87385037
has body: Since you're getting this out of BeautifulSoup, you're probably doing something like this to get the input tag: &gt;&gt;&gt; str(tr.input) '&lt;input name="submit" onclick="var srvstr=\'Friday 4th of May 2018\';someweb(srvstr);document.someemail.securitystring.value=\'\';return false;" src="images/button-submit.png" type="image"/&gt;' Instead, let BS4 parse it all the way down to the onclick attribute value: &gt;&gt;&gt; tr.input['onclick'] "var srvstr='Friday 4th of May 2018';someweb(srvstr);document.someemail.securitystring.value='';return false;" Sure, it's still messy, but it's not quite as bad—and, more to the point, we know it's Javascript code quoted to fit into HTML. So we know what can and can't be in it without escaping, so we don't have to worry about a lot of stuff that would otherwise probably never happen but you can't be sure (and therefore will definitely happen 15 minutes after you deploy and go to sleep). &gt;&gt;&gt; re.search(r"srvstr='(.*?)'", tr.input['onclick']) &lt;_sre.SRE_Match object; span=(4, 35), match="srvstr='Friday 4th of May 2018'"&gt; &gt;&gt;&gt; re.search(r"srvstr='(.*?)'", tr.input['onclick']).group(1) 'Friday 4th of May 2018' Now we don't have to reverse-engineer their date format and hope we got it right; it's just whatever string they're putting in that srvstr variable. (Although if you actually want to parse this into a datetime object or something…) Of course you can never guarantee anything for sure with parsing other people's text, but it seems very likely that if this ever stops working, it'll be because they've completely changed the way they do their onclick handler, in which case this code should fail badly with an exception rather than start producing garbage.
has comment: http://stackoverflow.com/comment/87385151
has comment: http://stackoverflow.com/comment/87385109
type: Answer

http://stackoverflow.com/a/50181045
has body: The error is telling you that child is a tuple, because that's what ('Ronny', 'Joice', '123', '27389476231') is. You want an Employee. To instantiate (i.e. make an instance of) a class, you need to use the class name: child = Employee('Ronny', 'Joice', '123', '27389476231')
type: Answer
answers question: http://stackoverflow.com/q/50180999
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/50162090
has comment: http://stackoverflow.com/comment/87349321
tagged with: pyqt4
has answer: http://stackoverflow.com/a/50166220
accepted answer: http://stackoverflow.com/a/50166220
tagged with: python
has comment: http://stackoverflow.com/comment/87349936
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/53729463
tagged with: pyqt
upvote count: 3
has comment: http://stackoverflow.com/comment/87344529
answer count: 1
downvote count: 0
has body: I created a QLabel and set it's movie to a QMovie object with an animated gif. Then in the resizeEvent of my app I resize and move the label, so that it is centered/fit to the layout. This works fine but the movie has a lot of fine lines which get totally garbled in the resize operation, it seems there is no anti-aliasing. So either I am using the wrong resize method, or I need to set anti-aliasing somewhere right? There is nothing in the QMovie or QLabel documentation to suggest how to do this. I did read that the QMovie is inherited from a QImageReader, though that too has no property for anti-aliasing that I could find. EDIT I did somewhat get this to work, but it's still not quite right. I found that QMovie has a setScaledSize method which actually scales the underlying QImageViewer. Then I just have the label adjust to it's contents, namely the movie. Using the following code I am able to resize the movie with proper anti-aliasing, however it is quite "jumpy" and "flickery" during resize so obviously I'm not doing this quite "right". Also it somehow loses it's aspect ratio sometimes. Still looking for the correct way to do this... Maybe a QLabel is the wrong way to go? Here's a working example import sys from PyQt4 import QtGui class MovieTest(QtGui.QDialog): def __init__(self): super(MovieTest, self).__init__() layout = QtGui.QVBoxLayout() self.setLayout(layout) self.loading_lbl = QtGui.QLabel() self.loading_lbl.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicyIgnored) self.loading_lbl.setScaledContents(True) layout.addWidget(self.loading_lbl) loading_movie = QtGui.QMovie("loading-radial_loop.gif") # some gif in here self.loading_lbl.setMovie(loading_movie) loading_movie.start() self.setGeometry(50,50,100,100) self.setMinimumSize(10,10) def resizeEvent(self, event): rect = self.geometry() size = min(rect.width(), rect.height()) movie = self.loading_lbl.movie() movie.setScaledSize(QtCore.QSize(size, size)) self.loading_lbl.adjustSize() def main(): app …
has comment: http://stackoverflow.com/comment/87343175
favorite count: 0
type: Question
tagged with: qlabel
has comment: http://stackoverflow.com/comment/87350009
linked to: http://stackoverflow.com/q/67261133
score: 3
has title: PyQt resize QMovie with proper anti-aliasing

http://stackoverflow.com/comment/87383159
type: Comment
comment on: http://stackoverflow.com/a/50182773
type: AnswerComment
has text: Awesome !! This works. However, it shows distributionnot found error. If setup.py has name of project as "app" and version as "1.0". It complains distribution app==1.0 is not found.Strange!!
score: 0

http://stackoverflow.com/q/50194199
accepted answer: http://stackoverflow.com/a/50203278
has title: How to transform and save dataframe to csv python
type: Question
has answer: http://stackoverflow.com/a/50203278
has comment: http://stackoverflow.com/comment/87405537
has comment: http://stackoverflow.com/comment/87405563
answer count: 1
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
tagged with: screen-scraping
has body: Is there a way to transform and then save following dataframe to a csv file like this? import requests from bs4 import BeautifulSoup url = 'https://ev-database.uk' resp = requests.get(url) soup = BeautifulSoup(resp.text, 'lxml') urls = [] cars = [] for h in soup.find_all('h2'): a = h.find('a') cars.append(a.attrs['href'][10:]) urls.append(a.attrs['href']) import requests import pandas as pd list_length = len(urls) table = pd.DataFrame() for x in range(5): page_link ='https://ev-database.uk' + urls[x] for i in range(1,3): next_table = pd.read_html(requests.get(page_link).content)[i] next_table[3] = cars[x] table = table.append(next_table, ignore_index = True) Dataframe: csv.output:

http://stackoverflow.com/q/50106163
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50107963
favorite count: 0
tagged with: numpy
type: Question
has title: Having an N element output from rejection sampling for N elements
has body: I am applying a rejection sampling for N elements given probability density function pdf. When applying this method for N elements, it is likely that you will return an array of values that has less number of elements compared to the N number you are evaluating, which is from applying the rejection method without looping for values of condition that are False. In order to reconcile this, I can try and loop the values that does not meet the condition until they are True. However, I am not sure on how to loop the condition until the number of elements in my array has the same length with the number of values N given the functions I have defined. import numpy N = 1000 # number of elements x = np.linspace(0, 200, N) pdf = pdf(x) # some pdf # Rejection Method #1 # ------------------- fx = np.random.random_sample(size=N) * x.max() # uniform random samples scaled out u = np.random.random_sample(size=N) # uniform random sample condition = np.where(u &lt;= pdf/pdf.max())[0] # Run first rejection criterion that returns bool values x_arr = fx[condition] # Here, len(x_arr) &lt; N, so I want to fix it until len(x_arr) == N while len(x_arr) &lt; N: ... if len(x_arr) == N: break After this, I am having trouble forming a method of iterating until len(x_arr) = N.
tagged with: python
has comment: http://stackoverflow.com/comment/87230737
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87229657
accepted answer: http://stackoverflow.com/a/50107963
score: 1

http://stackoverflow.com/q/50144092
tagged with: pip
has comment: http://stackoverflow.com/comment/87306655
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/87306559
has comment: http://stackoverflow.com/comment/87306806
has comment: http://stackoverflow.com/comment/87306690
has comment: http://stackoverflow.com/comment/87307965
type: Question
has title: easy_install not working on ubuntu
tagged with: python
has comment: http://stackoverflow.com/comment/87306669
has comment: http://stackoverflow.com/comment/90716934
tagged with: easy-install
has body: I've created an Ubuntu desktop on a flash drive that I've booted via my Mac laptop. I'm trying to install pip, and am having no luck. I've installed the setuptools for python, and have updated apt-get and all that stuff, but when I go to run sudo easy_install pip it's not recognizing the easy_install command. Any help would be much appreciated, (especially since I'm using Ubuntu since I was never able to install pip and pygame and numpy to run properly on my Mac because of errors between python 2 and 3).
has comment: http://stackoverflow.com/comment/87308070
has comment: http://stackoverflow.com/comment/87306583
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87306630
tagged with: apt-get

http://stackoverflow.com/comment/87443810
score: 0
type: AnswerComment
has text: Yes, but not able to display it in browser in tabular format
comment on: http://stackoverflow.com/a/50151439
type: Comment

http://stackoverflow.com/comment/87344886
comment on: http://stackoverflow.com/q/50163407
has text: Just don't convert `line` to a string. This will make the list into the one-line string you read in the file. Just do `f.writelines(line)`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87212968
score: 0
has text: please before downvoting a question, please at least give a good reason. here is someone who wants to learn but the downvotes puts them off this site.
type: Comment
comment on: http://stackoverflow.com/q/50097925
type: QuestionComment

http://stackoverflow.com/q/50108648
answer count: 0
duplicate of: http://stackoverflow.com/q/2612802
tagged with: deep-copy
type: Question
has body: I am fairly new to Python and I am trying to write a very simple piece of code. I have defined two matrices (lists of lists), A and B and a function that replaces the columns of matrix A with the columns of Matrix B based on some indicator variable called index. I have also added some print statements for debugging. A = [[5,-5,5],[7,7,7],[-6,-6,6]] B = [[2,2,-1],[-1,2,4],[0,-4,3]] index = [1,2] def Matrix_Interchange(A,B,index): print("Value of A Inputed",A) Temp = A for i in index: Temp[i-1][:]=B[i-1][:] print("Value of A in For Loop",A) return(Temp) Matrix_Interchange(A,B,index) print(A) The problem I am having is that once the code enters the for loop inside of the function, it is changing the values of the matrix A. Why would it do that if I am no longer referencing A and instead referencing the new matrix Temp? Here is the output of the print statements I included to help me debug. Am I missing something obvious here? Value of A Inputed [[5, -5, 5], [7, 7, 7], [-6, -6, 6]] Value of A in For Loop [[2, 2, -1], [7, 7, 7], [-6, -6, 6]] Value of A in For Loop [[2, 2, -1], [-1, 2, 4], [-6, -6, 6]]
has title: Function to swap lists is changing contents inside iteration
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87234630
tagged with: copy
tagged with: list
has comment: http://stackoverflow.com/comment/87234647
tagged with: matrix
score: 0
linked to: http://stackoverflow.com/q/2612802

ubuntu-16.04
tags question: http://stackoverflow.com/q/50171840
tags question: http://stackoverflow.com/q/50208859
tags question: http://stackoverflow.com/q/50179694
tags question: http://stackoverflow.com/q/50157653
tag name: ubuntu-16.04
tags question: http://stackoverflow.com/q/50224943
type: Tag
tags question: http://stackoverflow.com/q/50136943

http://stackoverflow.com/comment/87263093
type: Comment
comment on: http://stackoverflow.com/a/50119790
score: 0
type: AnswerComment
has text: Fantastic, thank you very much. I will try now to play around with additional stuff, just to see how it all works together. Cheers

http://stackoverflow.com/comment/87258271
comment on: http://stackoverflow.com/q/50120247
score: 0
has text: ive got around 14,000 rows in df and 3000 in df1, I'm basically trying to get the longitude and latitude for all the values in df however i have to compare df to df1 because the longitude and latitude reside there
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87189041
comment on: http://stackoverflow.com/q/50085847
score: 0
type: Comment
type: QuestionComment
has text: @usr2564301 but how? indexes are different in output. I don't understand :/ can you show me

http://stackoverflow.com/a/55092356
answers question: http://stackoverflow.com/q/50082846
type: Answer
upvote count: 2
score: 2
downvote count: 0
has body: I'm a little bit surprise that nobody has mentioned so far the use of pd.concat... Take a look below: df1 = pd.DataFrame({'Col1':[1,2,3,4], 'Col2':[5,6,7,8]}) df1 Col1 Col2 0 1 5 1 2 6 2 3 7 3 4 8 Now if you make: df2 = pd.concat([df1,df1]) you get: Col1 Col2 0 1 5 1 2 6 2 3 7 3 4 8 0 1 5 1 2 6 2 3 7 3 4 8 This is what you wanted, isn't?

http://stackoverflow.com/comment/87467139
type: Comment
type: QuestionComment
score: 0
has text: What does not work?
comment on: http://stackoverflow.com/q/50224771

http://stackoverflow.com/a/50229711
has body: Numpy has several components which need to be compiled, hence you need a C++ compiler such as the one from Visual Studio installed: error: Could not initialize compiler instance: do you have Visual Studio installed? It is usually easier to use the Python Extension Packages provided by Christoph Gohlke or a Python distribution such as Anaconda on Windows, which will provide the binaries for you.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50229600

http://stackoverflow.com/comment/87370563
has text: @Ben. Went back, updated same naming to be different. idxmax() is finding the correct value 2.57, seems the iterrow looks to be taking the row order as the index. Do continue to think through other ways in grabbing data-subsets and validate patterns. Thinking here would be to use loop within loop. Use the index on the dataframe, grab the surrounding data prior and after, do some functions to validate on these subsets, then go back and label each signals.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50175886

http://stackoverflow.com/comment/87433081
score: 0
comment on: http://stackoverflow.com/q/50207218
type: Comment
type: QuestionComment
has text: @BurhanKhalid, shouldn't that ampersand be a comma?

http://stackoverflow.com/q/50142357
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87302975
tagged with: python-requests
has comment: http://stackoverflow.com/comment/87676191
tagged with: python
tagged with: jupyter-notebook
has title: How to hide the Request-Response cycle information from the outputs in ipynb - Spotipy
type: Question
score: 0
has body: I am not sure if it has a common solution for any packages using web API's, but the package I am using is specifically Spotipy. While I am requesting something from the API (calling any function from the package) it gives a long output of the GET and RESP info first and then gives the desired outputs. Is there a way to hide all the informative outputs as below, when wanted? (like setting some parameters to silent for example) The output I'd like to hide is something like this; headers {' #some info here http status 200 GET https://api. ... # GET request link here RESP { ... # a lot of (sometimes undesired) output printed here Please let me know if this is an API-specific issue, then I will ask a solution from the git repository.
tagged with: spotipy

http://stackoverflow.com/comment/87189236
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50086583
has text: @Edmund It doesn't matter ragged or not, the question I mentioned was what you're looking for. It is applicable for both cases. check my answer.
score: 0

http://stackoverflow.com/comment/87331082
type: QuestionComment
comment on: http://stackoverflow.com/q/50156550
has text: Just a small note - you can just do `"a" in mydict` without having to call `mydict.keys()`
score: 1
type: Comment

http://stackoverflow.com/q/50092680
answer count: 2
has title: How to access a tuple inside a 2d list
downvote count: 0
has answer: http://stackoverflow.com/a/50092820
upvote count: 1
has comment: http://stackoverflow.com/comment/87485756
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87201593
tagged with: tuples
type: UnansweredQuestion
score: 1
tagged with: python
has body: I have a 2d list like this: [[0, (1, 2), (2, 1), (3, 3)], [(1, 4), (3, 'y'), ('x', 'y'), ('x', 'y')], [(2, 1), (1, 'y'), ('x', 'y'), ('x', 'y')], [(3, 1), ('x', 'y'), ('x', 'y'),('x', 'y')]] I want to access and work with just the first element(index 0) of each tuple. How can I do that in python?
has comment: http://stackoverflow.com/comment/87201642
tagged with: list
has answer: http://stackoverflow.com/a/50092741

http://stackoverflow.com/q/50106611
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50107152
answer count: 2
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87231431
has comment: http://stackoverflow.com/comment/87231666
linked to: http://stackoverflow.com/q/50119490
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50107438
has title: Convert list of dictionaries containing another list of dictionaries to dataframe
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/50107438
has body: I tried to look for the solution and I am unable to get 1. I have the following output from an api in python. insights = [ &lt;Insights&gt; { "account_id": "1234", "actions": [ { "action_type": "add_to_cart", "value": "8" }, { "action_type": "purchase", "value": "2" } ], "cust_id": "xyz123", "cust_name": "xyz", }, &lt;Insights&gt; { "account_id": "1234", "cust_id": "pqr123", "cust_name": "pqr", }, &lt;Insights&gt; { "account_id": "1234", "actions": [ { "action_type": "purchase", "value": "45" } ], "cust_id": "abc123", "cust_name": "abc", } ] I want the data frame something like this - account_id add_to_cart purchase cust_id cust_name - 1234 8 2 xyz123 xyz - 1234 pqr123 pqr - 1234 45 abc123 abc When I use the following &gt; insights_1 = [x for x in insights] &gt; df = pd.DataFrame(insights_1) I get the following - account_id actions cust_id cust_name - 1234 [{'value': '8', 'action_type': 'add_to_cart'},{'value': '2', 'action_type': 'purchase'}] xyz123 xyz - 1234 NaN pqr123 pqr - 1234 [{'value': '45', 'action_type': 'purchase'}] abc123 abc How do I move ahead with this?
tagged with: dataframe
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/50107152

http://stackoverflow.com/comment/87237646
comment on: http://stackoverflow.com/a/50109058
type: AnswerComment
score: 0
has text: If anyone reading this answer has difficulties understanding the meaning of the `level` (like I did), take a look an my answer to the question about levels: https://stackoverflow.com/a/50110162/672018
type: Comment

http://stackoverflow.com/comment/87389007
score: 4
has text: Using eval is not a good idea. Read about its potential threats. Instead you should use csv.DictReader
type: Comment
comment on: http://stackoverflow.com/a/50186116
type: AnswerComment

http://stackoverflow.com/comment/87326236
has text: They explicitly said they work looking for a recursive solution, this is the iterative solution to the problem
comment on: http://stackoverflow.com/a/50154260
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87196667
comment on: http://stackoverflow.com/a/50089933
type: Comment
score: 0
type: AnswerComment
has text: sorry, I did not understand. Could you please give more details.

http://stackoverflow.com/comment/87389460
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50177146
has text: `cross_val_score` uses the `score()` method of supplied estimator as default. And for regressor estimators, `score()` calculates the R_squared value. Hence `cross_val_score()` gives out this.
type: Comment

http://stackoverflow.com/comment/87300395
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50125076
has text: But don't use it for classification.
type: AnswerComment

http://stackoverflow.com/q/50187767
has comment: http://stackoverflow.com/comment/87394766
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50212714
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87421877
has answer: http://stackoverflow.com/a/50212714
has answer: http://stackoverflow.com/a/50259760
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has title: ImportError: No module named 'gdbm' occuring while using source ~/.bashrc
has body: Hey after making some changes in the bashrc I tried to use source ~/.bashrc but got the following error baaz@FireStorm:~$ source ~/.bashrc Traceback (most recent call last): File "/usr/lib/python3.5/dbm/gnu.py", line 4, in &lt;module&gt; from _gdbm import * ImportError: No module named '_gdbm' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 7, in &lt;module&gt; import dbm.gnu as gdbm File "/usr/lib/python3.5/dbm/gnu.py", line 6, in &lt;module&gt; raise ImportError(str(msg) + ', please install the python3-gdbm package') ImportError: No module named '_gdbm', please install the python3-gdbm package During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/command-not-found", line 27, in &lt;module&gt; from CommandNotFound.util import crash_guard File "/usr/lib/python3/dist-packages/CommandNotFound/__init__.py", line 3, in &lt;module&gt; from CommandNotFound.CommandNotFound import CommandNotFound File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 9, in &lt;module&gt; import gdbm ImportError: No module named 'gdbm' I tried using the install commands as mentioned in the error baaz@FireStorm:~$ sudo apt-get install python3-gdbm Reading package lists... Done Building dependency tree Reading state information... Done python3-gdbm is already the newest version (3.6.5-3~16.04.york0.2). python3-gdbm set to manually installed. 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. Also some solutions mentioned to use version specific commands, but still got no solution baaz@FireStorm:~$ sudo apt-get install python3.5-gdbm Reading package lists... Done Building dependency tree Reading state information... Done Package python3.5-gdbm is a virtual package provided by: python3-gdbm 3.5.1-1 [Not candidate version] E: Package 'python3.5-gdbm' has no installat…
answer count: 2
tagged with: bash
possible better answer: http://stackoverflow.com/a/50259760
has comment: http://stackoverflow.com/comment/87415503
has comment: http://stackoverflow.com/comment/94365291
downvote count: 0

http://stackoverflow.com/q/50196322
answer count: 1
favorite count: 0
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/50196645
tagged with: python
has answer: http://stackoverflow.com/a/50196645
tagged with: numpy
tagged with: python-2.7
has body: I want to know of it's possible to store the result of the plt.bar function into an array. Something like a=[1,2,3] b=[21321,5345,654457] height=list(b) plt.bar(a,height=height) a_b=result_of_pltbar
type: AnsweredQuestion
downvote count: 0
has title: how to store the result of plt.bar into an array
upvote count: 1
score: 1

http://stackoverflow.com/comment/87210239
type: QuestionComment
type: Comment
has text: Can you share much more details, if the questions have a pattern, we can use reg expressions to extract questions/answers
comment on: http://stackoverflow.com/q/50096962
score: 0

http://stackoverflow.com/comment/87248663
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50115718
has text: Well, I'm mostly trying to write a yaml file with python so it ***results*** in the yaml example from the docs

http://stackoverflow.com/comment/87265735
type: Comment
has text: You don't need directories inside sites-available, you just need a file. And you need to create it yourself.
comment on: http://stackoverflow.com/q/50123764
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87457196
type: QuestionComment
has text: I've run your code and I don't get the error. What line are you getting the error on? Also, I would recommend changing t to `np.linspace(1, 10, 100)` because having the last argument as 1 will draw a point instead of a line.
comment on: http://stackoverflow.com/q/50219781
score: 0
type: Comment

http://stackoverflow.com/q/50116344
has title: Python: turn JSON object to JSON array
favorite count: 0
accepted answer: http://stackoverflow.com/a/50116379
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87249893
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87249877
type: Question
has answer: http://stackoverflow.com/a/50116379
upvote count: 2
linked to: http://stackoverflow.com/q/26745519
tagged with: python
has body: I have the following dictionary in python which I'm saving into a file: d2 = { "CHARACTER": { "IDENTITY": { "FORM": { "id": "BK1", "type": "MAGE", "role": "DARK" } }, "USER": { "owner": { "id": "SABBATH13" }, "level": "16" } } } jsonfile = open('d2.json', 'w') jsonfile.write(simplejson.dumps(d2, indent=4)) jsonfile.close() However, I'm told this is a JSON object, which I need to turn into a JSON array of the form: [{ "CHARACTER": { "IDENTITY": { "FORM": { "id": "BK1", "type": "MAGE", "role": "DARK" } }, "USER": { "owner": { "id": "SABBATH13" }, "level": "16" } } }] Which is essentially adding square brackets at the beginning and end. What is the proper way to do this? Should I convert to string and add brackets, then convert back? Sorry, total JSON newbie here.

http://stackoverflow.com/q/50090821
type: AnsweredQuestion
answer count: 2
tagged with: neural-network
downvote count: 0
linked to: http://stackoverflow.com/q/49982746
favorite count: 0
has body: I have a tensor of size [150, 182, 91], the first part is just the batch size while the matrix I am interested in is the 182x91 one. I need to run a function on the 182x91 matrix for each of the 50 dimensions separately. I need to get a diagonal matrix stripe of the 182x91 matrix, and the function I am using is the following one (based on my previous question: Getting diagonal matrix stripe automatically in numpy or pytorch): def stripe(a): i, j = a.size() assert (i &gt;= j) out = torch.zeros((i - j + 1, j)) for diag in range(0, i - j + 1): out[diag] = torch.diag(a, -diag) return out The stripe function expects a matrix of size IxJ and can't deal with the 3rd dimension. So when I run this: some_matrix = x # &lt;class 'torch.autograd.variable.Variable'&gt; torch.Size([150, 182, 91]) get_diag = stripe(some_matrix) I get this Error: ValueError: too many values to unpack (expected 2) If I just try to skip the first dimension by doing x, i, j = a.size(), I get this: RuntimeError: invalid argument 1: expected a matrix or a vector at I am still on PyTorch 0.3.1. Any help is appreciated!
accepted answer: http://stackoverflow.com/a/50093900
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/50093900
tagged with: matrix
has title: How to apply a custom function to specific columns in a matrix in PyTorch
possible better answer: http://stackoverflow.com/a/50269935
tagged with: python
has answer: http://stackoverflow.com/a/50269935
score: 8
tagged with: tensor
tagged with: pytorch

http://stackoverflow.com/q/50223406
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87487382
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87486482
score: 0
has title: TypeError with quiver plots
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50235186
downvote count: 1
has body: I'm trying to make a quiver plot in Jupyter Notebook but I'm getting a TypeError the way I'm defining my u,v arrays. I have an array ug with the velocity norm (it only has x-component) so I'm doing: ug = [0.0 0.072 0.128 0.16800000000000004 0.19200000000000006 0.20000000000000007 0.19200000000000006 0.16800000000000004 0.128 0.07200000000000001 1.734723475976807e-17] xg = np.linspace(0,l,int(l/50)) yg = np.linspace(0,d,len(ug)) (Xg,Yg) = np.meshgrid(xg,yg) (Vg,Ug) = np.meshgrid(0*xg,ug) plt.quiver(Xg,Yg,Ug,Vg) The last line, the call to quiver, raises the following error: TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Why does quiver reject these arrays?
favorite count: 0

http://stackoverflow.com/comment/87521424
has text: yes ofcourse. he is Android developer by profession.
comment on: http://stackoverflow.com/q/50214614
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87224646
type: QuestionComment
has text: How did you create this dataframe? I can't reproduce your error using this with pd.read_clipboard(), which makes me suspect there's something weird earlier in your code.
comment on: http://stackoverflow.com/q/50103697
type: Comment
score: 7

http://stackoverflow.com/q/50159527
has answer: http://stackoverflow.com/a/50163059
tagged with: linux
has title: Reason for "TypeError: integer argument expected, got float" in my pygame game?
has comment: http://stackoverflow.com/comment/87337102
type: Question
has comment: http://stackoverflow.com/comment/87337642
has body: I'm trying to program a game using the pygame library but for some reason it keeps on throwing out a TypeError: integer argument expected, got float error for following lines: if surface.get_at((player["x"], player["y"] + player["height"])) == (0,0,0,255): leftOfPlayerOnPlatform = False if surface.get_at((player["x"] + player["width"], player["y"] + player["height"])) == (0,0,0,255): rightOfPlayerOnPlatform = False if leftOfPlayerOnPlatform is False and rightOfPlayerOnPlatform is False and (player["y"] + player["height"]) + player["vy"] &lt; windowHeight: player["y"] += player["vy"] The full code to my problem is: import pygame, sys, random import pygame.locals as GAME_GLOBALS import pygame.event as GAME_EVENTS import pygame.time as GAME_TIME pygame.init() clock = pygame.time.Clock() title_image = pygame.image.load("assets/title.jpg") game_over_image = pygame.image.load("assets/game_over.jpg") windowWidth = 400 windowHeight = 600 surface = pygame.display.set_mode((windowWidth, windowHeight)) pygame.display.set_caption('Drop!') leftDown = False rightDown = False gameStarted = False gameEnded = False gamePlatforms = [] platformSpeed = 3 platformDelay = 2000 lastPlatform = 0 platformsDroppedThrough = -1 dropping = False gameBeganAt = 0 timer = 0 player = { "x" : windowWidth / 2, "y" : 0, "height" : 25, "width" : 10, "vy" : 5 } def drawPlayer(): pygame.draw.rect(surface, (255,0,0), (player["x"], player["y"],player["width"], player["height"])) def movePlayer(): global platformsDroppedThrough, dropping leftOfPlayerOnPlatform = True rightOfPlayerOnPlatform = True if surface.get_at((player["x"], player["y"] + player["height"])) == (0,0,0,255): leftOfPlayerOnPlatform = False if surface.get_at((player["x"] + player["width"], player["y"] + player["height"])) == (0,0,0,255): rightOfPlayerOnPlatform = False if leftOfPlayerOnPlatform is False and rightOfPlayerOnPlatform is False and (player["y"] + player["height"]) + player["vy"] &lt; windowHeight: player["y"] += player["vy"] if …
answer count: 2
downvote count: 5
type: UnansweredQuestion
tagged with: python
tagged with: pygame
score: -2
has answer: http://stackoverflow.com/a/54030148
upvote count: 3
favorite count: 0

http://stackoverflow.com/comment/131145967
type: Comment
comment on: http://stackoverflow.com/a/50137686
has text: Basically, fastparquet gives you this lever to be explicit, where arrow decides for you. Only the arrow backend supports (or should) passing in a schema, as the docstring of to_parquet says.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87421357
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50202236
score: 0
has text: Then you need to show that template, and the view that renders it. There's no point only showing unrelated code.

http://stackoverflow.com/comment/87263995
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50122930
score: 0
has text: For plotting, I would take a look at the seaborn package. It expects data organized that way. As for the second point, `groupby` method is probably what you'll want, although I'm not exactly sure what you want.

http://stackoverflow.com/comment/87341267
comment on: http://stackoverflow.com/q/50161316
type: Comment
type: QuestionComment
score: 0
has text: @What yes its a range of seconds in the day and values that math each. When there is no value corresponding to list1 it will add a 0 instead

http://stackoverflow.com/comment/87280439
type: Comment
comment on: http://stackoverflow.com/a/50119487
type: AnswerComment
has text: You don't have to install, just download the EXE and put it in the same file as your `.py` file
score: 0

http://stackoverflow.com/comment/87456180
comment on: http://stackoverflow.com/q/50218330
type: Comment
type: QuestionComment
has text: (I am working on a version with lark) What you want will not work if there a multiple groups in a file. The toplevel element should be a list.
score: 0

http://stackoverflow.com/a/50124162
answers question: http://stackoverflow.com/q/50123845
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50123845
has body: You could get a random index and use that for both the word and the corresponding clue. index = random.randint(0, len(df1["Word"])) word = df1["Word"][index] print("Your clue is {}".format(df1["Clue"][index]))

http://stackoverflow.com/q/50096909
tagged with: python
tagged with: date
linked to: http://stackoverflow.com/q/7999935
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87210146
has title: Change time display format python 3
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87210255
has body: I am able to get the current time using the below code import datetime current_time = print(datetime.datetime.now()) Output : 2018-04-30 14:09:58.483829 I would however like to remove the decimal portion and only display 2018-04-30 14:09:58. How could I get this value. Thanks..
duplicate of: http://stackoverflow.com/q/7999935
score: 0
tagged with: datetime

http://stackoverflow.com/a/50086453
score: 7
has body: The go-to data structure to use for all kinds of grouping is the dict. The idea is to use something that uniquely identifies a group as the dict's keys, and store all values that belong to the same group under the same key. As an example, your data could be stored in a dict like this: {1: ['a', 'b'], 2: ['x']} The integer that you're using to group the values is used as the dict key, and the values are aggregated in a list. The reason why we're using a dict is because it can map keys to values in constant O(1) time. This makes the grouping process very efficient and also very easy. The general structure of the code will always be the same for all kinds of grouping tasks: You iterate over your data and gradually fill a dict with grouped values. Using a defaultdict instead of a regular dict makes the whole process even easier, because we don't have to worry about initializing the dict with empty lists. import collections groupdict = collections.defaultdict(list) for value in data: group = value[0] value = value[1] groupdict[group].append(value) # result: # {1: ['a', 'b'], # 2: ['x']} Once the data is grouped, all that's left is to convert the dict to your desired output format: result = [(key, ''.join(values)) for key, values in groupdict.items()] # result: [(1, 'ab'), (2, 'x')] The Grouping Recipe The following section will provide recipes for different kinds of inputs and outputs, and show how to group by various things. The basis for everything is the following snippet: import collections groupdict = collections.defaultdict(list) for value in data: # input group = ??? # group identifier value = ??? # value to add to the group groupdict[group].append(value) result = groupdict # output Each of the commented lines can/has to be customized depending on your use case. Input The format of your input data dictates how you iterate over it. In this section, we're customizing the for value in data: line of the recipe. A list of values More often than not, all the values are …
has comment: http://stackoverflow.com/comment/87259798
type: Answer
answers question: http://stackoverflow.com/q/50086452
has comment: http://stackoverflow.com/comment/108535958
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87189890
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50086452
has comment: http://stackoverflow.com/comment/87190011
has comment: http://stackoverflow.com/comment/87260011
upvote count: 8

http://stackoverflow.com/q/50125055
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50125110
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/50125110
has answer: http://stackoverflow.com/a/62602362
downvote count: 0
has body: I need to match data from multiple CSV files. For example, if I have three CSV files. input 1 csv PANYNJ LGA WEST 1,available, LGA West GarageFlushing PANYNJ LGA WEST 4,unavailable,LGA West Garage iPark - Tesla,unavailable,530 E 80th St input 2 csv PANYNJ LGA WEST 4,unavailable,LGA West Garage PANYNJ LGA WEST 5,available,LGA West Garage input 3 csv PANYNJ LGA WEST 5,available,LGA West Garage imPark - Tesla,unavailable,611 E 83rd St The first column is name, the second one is status, and the last one is address. I would like to merge these three documents into one csv file if they have the same name. My desire output file is like output csv PANYNJ LGA WEST 1,available, LGA West GarageFlushing PANYNJ LGA WEST 4,unavailable,LGA West Garage iPark - Tesla,unavailable,530 E 80th St PANYNJ LGA WEST 5,available,LGA West Garage imPark - Tesla,unavailable,611 E 83rd St I'm trying to fix this with pandas or CSV but I'm unsure how to go about this. Any help is greatly appreciated!
upvote count: 1
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62602362
has title: Merging multiple CSV files and dropping duplicates by field
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/50153832
has comment: http://stackoverflow.com/comment/87326967
has comment: http://stackoverflow.com/comment/87325151
score: 0
has comment: http://stackoverflow.com/comment/87326717
answer count: 1
type: Question
tagged with: for-loop
type: UnansweredQuestion
has body: I run this code in purpose to processing text before feed it in my model and got RecursionError: maximum recursion depth exceeded in comparison train_text is a python series with text stem is PorterStemmer object from nltk library train_corpus = [] for i in range(0, len(train_text)): data = re.sub("[^a-zA-Z]", ' ', train_text[i]).lower().split() data = [ps.stem(word) for word in data if not word in set(stopwords.words("english"))] data = ' '.join(data) train_corpus.append(data) RecursionError Traceback (most recent call last) &lt;ipython-input-25-4a8646f33f6f&gt; in &lt;module&gt;() 57 for i in range(0, len(train_text)): 58 data = re.sub("[^a-zA-Z]", ' ', train_text[i]).lower().split() ---&gt; 59 data = [ps.stem(word) for word in data if not word in set(stopwords.words("english"))] 60 data = ' '.join(data) 61 train_corpus.append(data) &lt;ipython-input-25-4a8646f33f6f&gt; in &lt;listcomp&gt;(.0) 57 for i in range(0, len(train_text)): 58 data = re.sub("[^a-zA-Z]", ' ', train_text[i]).lower().split() ---&gt; 59 data = [ps.stem(word) for word in data if not word in set(stopwords.words("english"))] 60 data = ' '.join(data) 61 train_corpus.append(data) ~\Anaconda3\lib\site-packages\nltk\stem\porter.py in stem(self, word) 665 stem = self._step1a(stem) 666 stem = self._step1b(stem) --&gt; 667 stem = self._step1c(stem) 668 stem = self._step2(stem) 669 stem = self._step3(stem) .... What can I do to solve this? Thanks.
has title: RecursionError using NLTK
tagged with: python
has comment: http://stackoverflow.com/comment/87326068
has comment: http://stackoverflow.com/comment/87325755
has answer: http://stackoverflow.com/a/50154031
linked to: http://stackoverflow.com/q/3323001
tagged with: recursion
has comment: http://stackoverflow.com/comment/87325684
has comment: http://stackoverflow.com/comment/87325980

http://stackoverflow.com/comment/87254262
has text: Have you looked at [`Pool.close()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.close) and [`Pool.terminate()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.terminate) (`terminate()` should be a last resort).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50118036
type: QuestionComment

http://stackoverflow.com/q/50109804
duplicate of: http://stackoverflow.com/q/3477283
duplicate of: http://stackoverflow.com/q/7604966
has title: Python scope of numerical type
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87236857
has body: I use python3.x,I want to know the scope of numerical type. For example, the float, the maximum and the minimum. I know the scope of java's float and int, but in python I can't find it now. For example,java float from 10^-38 to 10^38,so python's float?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87236912
has comment: http://stackoverflow.com/comment/87236945
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/50109826
linked to: http://stackoverflow.com/q/3477283
linked to: http://stackoverflow.com/q/7604966
answer count: 1
has comment: http://stackoverflow.com/comment/87236855

http://stackoverflow.com/comment/87217562
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50100368
has text: @Roelant Thx sir!! Wait for a second!

http://stackoverflow.com/comment/87350231
type: Comment
comment on: http://stackoverflow.com/a/50166061
score: 0
type: AnswerComment
has text: Could you post the first few rows from your dataframe in your question as an edit?

http://stackoverflow.com/a/50239574
answers question: http://stackoverflow.com/q/50183915
upvote count: 3
downvote count: 0
has body: You should use the s3a protocol when accessing S3 locally. Make sure you add your key and secret to the SparkContext first. Like this: sc = SparkContext(conf = conf) sc._jsc.hadoopConfiguration().set('fs.s3a.access.key', 'awsKey') sc._jsc.hadoopConfiguration().set('fs.s3a.secret.key', 'awsSecret') inputFile = sparkContext.textFile("s3a://somebucket/file.csv")
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/87502280
has comment: http://stackoverflow.com/comment/87502041

http://stackoverflow.com/q/50121980
has comment: http://stackoverflow.com/comment/87262142
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50122034
has body: I have the following numpy array: import numpy as np arr = np.array([[1,2,3,4,2000], [5,6,7,8,2000], [9,0,1,2,2001], [3,4,5,6,2001], [7,8,9,0,2002], [1,2,3,4,2002], [5,6,7,8,2003], [9,0,1,2,2003] ]) I understand np.sum(arr, axis=0) to provide the result: array([ 40, 28, 36, 34, 16012]) what I would like to do (without a for loop) is sum the columns based on the value of the last column so that the result provided is: array([[ 6, 8, 10, 12, 4000], [ 12, 4, 6, 8, 4002], [ 8, 10, 12, 4, 4004], [ 14, 6, 8, 10, 4006]]) I realize that it may be a stretch to do without a loop, but hoping for the best... If a for loop must be used, then how would that work? I tried np.sum(arr[:, 4]==2000, axis=0) (where I would substitute 2000 with the variable from the for loop), however it gave a result of 2
upvote count: 8
has answer: http://stackoverflow.com/a/50122468
tagged with: sum
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/87261857
has comment: http://stackoverflow.com/comment/87262590
answer count: 4
accepted answer: http://stackoverflow.com/a/50122329
has comment: http://stackoverflow.com/comment/87262238
has comment: http://stackoverflow.com/comment/87262584
linked to: http://stackoverflow.com/q/39922986
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87262164
has title: Numpy: conditional sum
has comment: http://stackoverflow.com/comment/87262959
has answer: http://stackoverflow.com/a/50122307
has answer: http://stackoverflow.com/a/50122034
has answer: http://stackoverflow.com/a/50122329
downvote count: 0
has comment: http://stackoverflow.com/comment/87261996
score: 8
favorite count: 0

http://stackoverflow.com/q/50172936
has body: I have this design # coding: utf-8 from sqlalchemy import Column, VARCHAR, ForeignKey, create_engine from sqlalchemy.dialects.mysql import INTEGER, TINYINT from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.inspection import inspect from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.associationproxy import association_proxy engine = create_engine('mysql://root:toor@localhost/test', echo=True) Model = declarative_base() Session = sessionmaker(bind=engine) session = Session() class A(Model): __tablename__ = 'A' id = Column(INTEGER(unsigned=True), primary_key=True) name = Column(VARCHAR(32), nullable=False, index=True) class AB(Model): __tablename__ = 'AB' A_id = Column(INTEGER(10, unsigned=True), ForeignKey('A.id'), nullable=False, primary_key=True) B_id = Column(INTEGER(10, unsigned=True), ForeignKey('B.id'), nullable=False, primary_key=True) type = Column(TINYINT(3, unsigned=True), nullable=False) A_rel = relationship( "A", foreign_keys=[A_id] ) B_rel = relationship( "B", foreign_keys=[B_id], ) mapper_AB = inspect(AB) class B(Model): __tablename__ = 'B' id = Column(INTEGER(10, unsigned=True), primary_key=True) As = relationship("A", secondary=mapper_AB.local_table, uselist=False) ABs = relationship("AB") type = association_proxy('ABs', 'type') Model.metadata.create_all(engine) a = A( name="test", ) session.add(a) session.commit() b = B( As=a, type=2 ) print(b.type) session.add(b) session.commit() This obviously fails, but I am trying to simplify the design by adding the AB extra information (type) via one (B) of the related classes constructor. I have gone through tons of SQLAlchemy documentation, and even lost myself inside the source code but to no avail. The 3 table design of the database cannot be modified, as is part of a bigger system and belongs to another project. My goal is to map those table into a more simplified design for further development where this models will be used. Is this possible using SQLAlchemy mec…
tagged with: orm
upvote count: 4
tagged with: sqlalchemy
favorite count: 0
tagged with: associations
type: Question
has title: SQLAlchemy association data via related class constructor
type: UnansweredQuestion
tagged with: python
score: 4
answer count: 0
downvote count: 0

dart
tags question: http://stackoverflow.com/q/50176811
tag name: dart
type: Tag

http://stackoverflow.com/comment/87315995
type: AnswerComment
type: Comment
has text: Sure, if B is a substring of `A*(q+1)` it is also a substring of `A*(q+n)`, but the question you gave asks for the "minimum number of times A has to be repeated", and that is either `q` or `q+1`, so checking these two is sufficient. If B is not a substring of `A*(q+1)`, it is never a substring.
comment on: http://stackoverflow.com/a/50148252
score: 0

http://stackoverflow.com/comment/87511005
comment on: http://stackoverflow.com/a/50224288
type: AnswerComment
score: 0
type: Comment
has text: Many thanks for your help. I understand your solution. unfortunately I still have an issue when I run this code: print('Start average for col3: {:.2f}, col4: {:.2f}, col5: {:.2f}'.format(sum(start_values['col3'])/len(start_values['col3']), sum(start_values['col4'])/len(start_values['col4']), sum(start_values['col5'])/len(start_values['col5']))) ZeroDivisionError: division by zero I'll try to look closer tomorrow.

http://stackoverflow.com/a/50143168
has comment: http://stackoverflow.com/comment/87304537
upvote count: 3
has comment: http://stackoverflow.com/comment/87304833
has comment: http://stackoverflow.com/comment/87304606
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87362284
accepted answer of: http://stackoverflow.com/q/50143138
type: Answer
answers question: http://stackoverflow.com/q/50143138
score: 3
has body: you need to use broadcasting: a[None, :] * d[:, None] In [2]: a = np.arange(5) In [3]: d = np.arange(3) In [4]: a[None, :] * d[:, None] Out[4]: array([[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) You can use np.newaxis instead of None, it does the same (np.newaxis is just an alias, with a more explicit name). What it does it to add an additional axis to a or d: In [5]: a[None, :].shape Out[5]: (1, 5) Broadcasting is a very efficient tool to perform operations on arrays in numpy, read more about it in the doc. As a remark, a * d[:, None] would also work, but I find the first formulation to be more explicit.

http://stackoverflow.com/comment/87296795
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50137536
score: 0
has text: @Alasdair The silly thing is, I had those in the __init__ to begin with, and I can't remember why I had decided to pull them out!!!

http://stackoverflow.com/q/50104264
type: Question
has comment: http://stackoverflow.com/comment/87225796
accepted answer: http://stackoverflow.com/a/50104330
has body: I have the following code. I would like to know how I can create an as many attribute for the object labyrinth that I have robot. I have two doubts, how to create the attribute and how to call the function. Anyone ? :) class Robot: """Class that represents a robot.""" def __init__(self, name, x, y): self.name = name self.x = x self.y = y class Labyrinth: """Class that represents a labyrinth.""" def __init__(self, obstacles, *args): self.grid = {} for robot in args: # First doubt self.robot.name = [robot.x, robot.y] # First doubt robot_1 = Robot(robot_1, 5, 6) robot_2 = Robot(robot_2, 8, 9) ... ... ... # unkown number of robots... labyrinth = Labyrinth(obstacles, ......) # Second doubt
has comment: http://stackoverflow.com/comment/87225705
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50104330
score: 0
has comment: http://stackoverflow.com/comment/87226145
has comment: http://stackoverflow.com/comment/87225922
answer count: 1
has comment: http://stackoverflow.com/comment/87225780
has title: Python Create unknown number of attribute in a class

http://stackoverflow.com/q/50121976
type: UnansweredQuestion
has body: The result I want: List Result List 1 1 1 2 2 1 2 2 2 3 3 1 4 1 Now I use for loop, how can I use numpy way to come true it?
duplicate of: http://stackoverflow.com/q/23435270
has comment: http://stackoverflow.com/comment/87261967
score: 0
has comment: http://stackoverflow.com/comment/87262036
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/87261915
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/23435270
answer count: 0
has title: how to sum frequency respectively by numpy

http://stackoverflow.com/a/50142695
has body: Why fuss over read_csv? Use np.loadtxt: pd.DataFrame(np.loadtxt(file, dtype=int)) 0 1 2 3 4 5 6 7 8 9 10 11 12 0 0 0 1 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 0 1 2 0 0 1 1 0 0 1 1 1 0 1 1 1 3 0 1 1 1 1 1 1 1 1 1 1 1 2 4 0 1 1 1 0 1 1 1 1 1 1 1 1 5 0 0 0 1 1 1 0 1 0 0 0 1 1 6 0 0 0 0 1 1 0 0 1 0 1 0 2 7 0 1 1 0 1 1 1 1 0 1 1 1 1 8 0 0 1 0 0 0 0 0 0 1 1 0 1 9 0 1 1 1 0 1 1 0 0 0 0 1 1 The default delimiter is whitespace, and no headers/indexes are read in by default. Column types are also not inferred, since the dtype is specified to be int. All in all, this is a very succinct and powerful alternative.
upvote count: 4
score: 3
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50142569
answers question: http://stackoverflow.com/q/50142569
type: Answer

http://stackoverflow.com/a/50200792
type: Answer
has comment: http://stackoverflow.com/comment/87418324
has comment: http://stackoverflow.com/comment/87419520
has comment: http://stackoverflow.com/comment/87418381
has comment: http://stackoverflow.com/comment/87418414
has comment: http://stackoverflow.com/comment/87419578
has comment: http://stackoverflow.com/comment/87419607
downvote count: 0
upvote count: 1
has body: np.zeros is a function that takes shape tuple and return matrix of zeros. Following your logic, it would be Gz=np.zeros(G.shape). In addition to that, I would prefer to generated 4-tile matrix and assigns G to 2 of them. # G = np.random.random((2, 2)) m, n = G.shape GG = np.zeros((m * 2, n * 2)) # 4 tiles GG[m:, n:] = G # assign left-top GG[:m, :n] = G # assign right-bottom print(GG) # [[0.16518374 0.83519636 0. 0. ] # [0.76530177 0.21199601 0. 0. ] # [0. 0. 0.16518374 0.83519636] # [0. 0. 0.76530177 0.21199601]]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87418487
accepted answer of: http://stackoverflow.com/q/50200747
has comment: http://stackoverflow.com/comment/87418669
has comment: http://stackoverflow.com/comment/87419300
answers question: http://stackoverflow.com/q/50200747
has comment: http://stackoverflow.com/comment/87419406
has comment: http://stackoverflow.com/comment/87418510
score: 1
has comment: http://stackoverflow.com/comment/87418672
has comment: http://stackoverflow.com/comment/87418590

http://stackoverflow.com/comment/87390313
type: QuestionComment
comment on: http://stackoverflow.com/q/50186384
has text: How is it not working? Is it raising an exception? If so, copy and paste the exception (the whole thing, with traceback) here. Also: can you open that URL in a browser, or download it with curl? If not, then `urllib` isn't going to do any better. Also, is there a reason you're using `urllib` instead of `urllib2` (or `requests`)?
score: 0
type: Comment

http://stackoverflow.com/comment/87341370
score: 1
type: Comment
has text: True! I edited my answer to address that second concern, but stripping it and getting rid of the unnecessary things in the original dataframe as you did is probably smarter to end up with a cleaner dict
comment on: http://stackoverflow.com/a/50161685
type: AnswerComment

http://stackoverflow.com/comment/87428860
has text: You don't need the `continue` in the `except` block if you're going to put an `else` afterwards (you only need one of those things, not both). And you don't need the continue at the end of the inner `else` at all, since the end of the loop happens immediately afterwards already.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50205659
type: AnswerComment

http://stackoverflow.com/q/50170961
has title: Django tests manage.py
downvote count: 1
favorite count: 0
type: Question
tagged with: testing
type: UnansweredQuestion
has body: To run my Django's tests, I was using the manage.py file. But I decided to create my own file runtests.py. As specified in the Django's doc, the manage.py file will execute all methods whose name is starting like "test" and whose class inherits TestCase ! My aim is to use this searching method to display all possible tests (not running them). So do you know where I could get this "searching method" ? Thank you !
tagged with: python
tagged with: manage.py
has comment: http://stackoverflow.com/comment/100626343
score: 0
has answer: http://stackoverflow.com/a/50171497
answer count: 1
tagged with: django
upvote count: 1

http://stackoverflow.com/a/50144529
type: Answer
has body: It's just a constant. The Python tkinter library is a wrapper around tk, so you'll want to reference the source documentation, which can be found at: http://www.tkdocs.com/tutorial/text.html#basics. For your question, see the section on Retrieving the Text. In their Python example, they don't even use the constant: thetext = text.get('1.0', 'end')
upvote count: 2
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/50144388

http://stackoverflow.com/comment/87208932
comment on: http://stackoverflow.com/q/50096286
score: 0
type: QuestionComment
has text: You could use the `requests` library. Not Qt, but it works.
type: Comment

http://stackoverflow.com/q/50155039
tagged with: local-variables
has comment: http://stackoverflow.com/comment/87328038
has comment: http://stackoverflow.com/comment/87327748
has comment: http://stackoverflow.com/comment/87327644
favorite count: 0
accepted answer: http://stackoverflow.com/a/50155111
type: Question
score: 3
has answer: http://stackoverflow.com/a/50155111
possible better answer: http://stackoverflow.com/a/50155264
answer count: 3
has comment: http://stackoverflow.com/comment/87327715
tagged with: python
has comment: http://stackoverflow.com/comment/87327780
has comment: http://stackoverflow.com/comment/87328275
has answer: http://stackoverflow.com/a/50155235
has comment: http://stackoverflow.com/comment/87327573
has body: This works: def foo(): locals().update({'bar': 12}) print(locals()['bar']) # 12 This fails: def foo(): locals().update({'bar': 12}) bar = locals()['bar'] # KeyError: 'bar' print(bar)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87327968
has title: How to assign a value from locals() to a local variable with the same name?
has comment: http://stackoverflow.com/comment/87327660
upvote count: 3
has answer: http://stackoverflow.com/a/50155264
has comment: http://stackoverflow.com/comment/87328313
has comment: http://stackoverflow.com/comment/87328160
downvote count: 0

http://stackoverflow.com/comment/87381822
comment on: http://stackoverflow.com/q/50182148
type: Comment
type: QuestionComment
has text: Actually trying it for indexing 0 for first index. but obviously it doesnot work
score: 0

http://stackoverflow.com/comment/87362738
comment on: http://stackoverflow.com/q/50172412
score: 0
has text: Do you want to parse an input file or do you want to use a Pandas DataFrame or what else? Having more info would help.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50159859
has body: i confused to how to input two size pictures and it also can't use resize and crop.I have seen this question but it is also not resolved.this is my code but i get follow error: StopIteration: 'NoneType' object cannot be interpreted as an integer i hope you can give me some advice model = Sequential() model.add(Conv2D(filters=6,kernel_size=(5,5),padding='same',input_shape=(None,None,3))) model.add(Activation('tanh')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Conv2D(filters=16,kernel_size=(5,5),padding='same')) model.add(Activation('tanh')) model.add(GlobalAveragePooling2D()) model.add(Dense(1)) model.add(Activation('sigmoid')) #sgd = optimizers.RMSprop(lr=0.01, clipvalue=0.5) model.compile(loss='binary_crossentropy',#'binary_crossentropy'categorical_crossentropy, optimizer='sgd', metrics=['accuracy'], ) train_datagen = ImageDataGenerator(rescale=1./255, vertical_flip=True, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary')#'binary'categorical) validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary')#'binary') early_stopping = EarlyStopping(monitor='val_acc',patience=10,mode='max') model.fit_generator(train_generator, steps_per_epoch=nb_train_samples//batch_size, epochs=nb_epoch, validation_data=validation_generator, validation_steps=nb_validation_samples, callbacks=[early_stopping, TensorBoard(log_dir='C:\\Users\\ccri\\Desktop\\new\\iou30\\426\\lenet\\log', write_images=True), ModelCheckpoint(filepath='C:\\Users\\ccri\\Desktop\\new\\iou30\\426\\lenet\\canshu\\weights.{epoch:02d}-{val_loss:.2f}.h5', monitor='val_acc', save_best_only=True, mode='auto')] )
type: Question
has answer: http://stackoverflow.com/a/50160298
tagged with: spp
has title: How to give different size images to cnn model in keras/tensorflow
answer count: 2
linked to: http://stackoverflow.com/q/47795697
upvote count: 0
downvote count: 2
tagged with: keras
possible better answer: http://stackoverflow.com/a/50160298
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
score: -2
accepted answer: http://stackoverflow.com/a/50160749
tagged with: python
has comment: http://stackoverflow.com/comment/87337720
has answer: http://stackoverflow.com/a/50160749

http://stackoverflow.com/a/50212150
accepted answer of: http://stackoverflow.com/q/50211485
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50211485
downvote count: 0
has body: You can do it so: df = pd.DataFrame([(k1, k2, k3, v) for k1, k23v in dict.items() for k2, k3v in k23v.items() for k3, v in k3v.items() ]) df.columns = ['Col1', 'Col2', 'Col3', 'Col4'] Output: Col1 Col2 Col3 Col4 0 Main1 A1 a1 0 1 Main1 A3 a3 22 2 Main1 A2 a2 15 3 Main1 A4 a4 130 4 Main2 B1 b1 150 5 Main2 B2 b2 30 6 Main2 B3 b3 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87231555
comment on: http://stackoverflow.com/a/50106882
score: 0
type: AnswerComment
has text: Each sample will be associated with either the class `0.` or `1.` and `it.class_indices` will be `{'image_set_X': 0., 'image_set_Y': 1.}`. So you can use these two properties to reconstruct the sample-class name relationship.
type: Comment

http://stackoverflow.com/q/50107548
accepted answer: http://stackoverflow.com/a/50107606
has answer: http://stackoverflow.com/a/50107607
has answer: http://stackoverflow.com/a/50107606
type: Question
has answer: http://stackoverflow.com/a/50107717
upvote count: 2
has title: for loop inclusive or exclusive in python
has comment: http://stackoverflow.com/comment/87232407
downvote count: 0
has body: When I run the following code, it prints. However, I expected only one 1 rather than two. for i in (1,1): print(i) Output 1 1
tagged with: python
has comment: http://stackoverflow.com/comment/87232486
has comment: http://stackoverflow.com/comment/87389527
favorite count: 0
score: 2
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/50107607

http://stackoverflow.com/q/50122098
has answer: http://stackoverflow.com/a/50122215
tagged with: python
has title: Creating a new matrix from an existing one while only storing the first two columns in python
has comment: http://stackoverflow.com/comment/87262077
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/50122132
tagged with: matrix
has comment: http://stackoverflow.com/comment/87262387
has body: I have an existing matrix: matrix = [[3,5,7,9], [6,8,12,14], [2,1,0,5], [7,8,9,10]] I am trying to extract just the first two columns from any matrix and store them in another matrix. For example, I'm hoping the new matrix would look like: new_matrix = [[3,5], [6,8], [2,1], [7,8]] Any help is much appreciated.
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87262132

http://stackoverflow.com/a/50137422
score: 0
type: AcceptedAnswer
has body: In repl which internal time is UTC the result is the same: https://repl.it/repls/IndolentBurlywoodAddons On my local machine (UTC+2) two values differ exactly for two hours. So looks like the explanation is the timezone.
answers question: http://stackoverflow.com/q/50137069
type: Answer
accepted answer of: http://stackoverflow.com/q/50137069

http://stackoverflow.com/a/50122581
answers question: http://stackoverflow.com/q/50122543
score: 0
upvote count: 1
downvote count: 1
has body: Use strptime() to convert the string into a datetime object and then use strftime() to format that object into the string you desire. See https://docs.python.org/3.6/library/datetime.html#strftime-and-strptime-behavior Openpyxl can be used to read and write *.xlsx files.
type: Answer

http://stackoverflow.com/q/50116523
has answer: http://stackoverflow.com/a/50116626
tagged with: django-forms
tagged with: stripe-payments
type: Question
answer count: 2
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/50116744
has body: I'm working with Pinax-Stripe library, and I want to create a custom account for the logged in user. I'm trying to rewrite the CreateCustomAccountView() as a function based view. The reason for that, is that I don't understand where CreateBankAccountView comes from and it's nowhere to be seen in the GitHub code. So for simplicity, I have the following form: class Form(DynamicForm): # some form fields def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") views.py def view(request): if request.method == 'POST': form = Form(request.POST) else: form = Form() return render(request, 'dashboard/template.html', {'form': form}) I do have request in my template processor. I'm not sure why this happens and how it's possible to instantiate an empty form?
has answer: http://stackoverflow.com/a/50116744
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50116626
score: 0
has title: Django Key Error: KeyError at 'template.html' request when initiating a form

http://stackoverflow.com/comment/87426801
comment on: http://stackoverflow.com/q/50202455
has text: Thank you all for your comments. I will try these and write back.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87239245
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50110774
has text: And we all agree that 67 is an odd number, right?
score: 1

http://stackoverflow.com/a/50119487
has comment: http://stackoverflow.com/comment/87257479
has comment: http://stackoverflow.com/comment/87280439
score: 1
downvote count: 0
upvote count: 1
has body: Do you have ffmpeg installed? AFAIK that is a requirement. You can download ffmpeg from here: http://ffmpeg.org Put this in your script directory and everything should then work fine.
type: Answer
answers question: http://stackoverflow.com/q/50119444

http://stackoverflow.com/q/50132257
type: AnsweredQuestion
tagged with: xpath
score: 0
has comment: http://stackoverflow.com/comment/87282450
answer count: 3
has answer: http://stackoverflow.com/a/50132427
upvote count: 1
accepted answer: http://stackoverflow.com/a/50132427
downvote count: 1
possible better answer: http://stackoverflow.com/a/50134401
tagged with: selenium
has title: How to uniquely identify xpath for multiple tags and multiple values
tagged with: webdriver
favorite count: 0
has answer: http://stackoverflow.com/a/50132425
type: Question
has comment: http://stackoverflow.com/comment/87733555
tagged with: python
has answer: http://stackoverflow.com/a/50134401
has body: I have following html: Interface Name ==$0 Neighbor Id ==$0 I need to send text to the text box with label: Interface Name. Is there a way to uniquely write the xpath to send the text to the textbox. Note that the only way to identify uniquely is wrt the label. The other fields in the tag is same for both. I tried using AND operator. No luck. Please help me out here.
tagged with: selenium-webdriver

http://stackoverflow.com/q/50177359
type: Question
possible better answer: http://stackoverflow.com/a/50178612
has answer: http://stackoverflow.com/a/50177470
accepted answer: http://stackoverflow.com/a/50177470
has title: Rename variously formatted column headers in pandas
has answer: http://stackoverflow.com/a/50177452
type: AnsweredQuestion
has body: I'm working on a small tool that does some calculations on a dataframe, let's say something like this: df['column_c'] = df['column_a'] + df['column_b'] for this to work the dataframe need to have the columns 'column_a' and 'column_b'. I would like this code to work if the columns are named slightly different named in the import file (csv or xlsx). For example 'columnA', 'Col_a', ect). The easiest way would be renaming the columns inside the imported file, but let's assume this is not possible. Therefore I would like to do some think like this: if column name is in list ['columnA', 'Col_A', 'col_a', 'a'... ] rename it to 'column_a' I was thinking about having a dictionary with possible column names, when a column name would be in this dictionary it will be renamed to 'column_a'. An additional complication would be the fact that the columns can be in arbitrary order. How would one solve this problem?
downvote count: 0
has answer: http://stackoverflow.com/a/50177549
tagged with: pandas
has answer: http://stackoverflow.com/a/50178612
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87372135
tagged with: dataframe
tagged with: python
answer count: 4
favorite count: 0

http://stackoverflow.com/comment/87339716
score: 0
has text: ....But it's only 1% of every possible value...
comment on: http://stackoverflow.com/q/50160678
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50185280
has body: I want to get &lt; from a string that contains the character. So what I want to do is: magic_function('&lt;') = &lt; in order to make. For example: 1 magic_function('&lt;') 3 I expect, of course, that the program returns True
accepted answer: http://stackoverflow.com/a/50185297
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50185297
has comment: http://stackoverflow.com/comment/87387741
has comment: http://stackoverflow.com/comment/87387779
has comment: http://stackoverflow.com/comment/87387774
has comment: http://stackoverflow.com/comment/87387799
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87387733
has comment: http://stackoverflow.com/comment/87387822
downvote count: 2
answer count: 1
upvote count: 1
has title: Convert < > from string
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87387763

http://stackoverflow.com/q/50178499
has answer: http://stackoverflow.com/a/50181867
type: Question
answer count: 2
downvote count: 0
upvote count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/50179264
tagged with: conv-neural-network
type: AnsweredQuestion
has title: Specify some untrainable filters for Keras convolutional network
has body: I would like to develop a convolutional network architecture where in the first layer (Conv1D in this case), I would like to prespecify some portion of untrainable fixed filters, while also having several trainable filters that the model can learn. Is this possible and how would this be done? My intuition is that I can make two separate Conv1D layers - one trainable and one untrainable - and then somehow concatenate them, but I'm not sure what this would look like in code. Also, for the untrainable filters, how do I prespecify the weights?
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/50181867
favorite count: 0
possible better answer: http://stackoverflow.com/a/50179264

http://stackoverflow.com/comment/115668512
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50221512
type: Comment
has text: @KPM would you mind to finally click & accept the best answer proided? That is how StackOverflow used to work since ever & its fair, isn't it?

http://stackoverflow.com/q/50186714
has comment: http://stackoverflow.com/comment/87401249
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87391275
tagged with: jenkins
has comment: http://stackoverflow.com/comment/87390337
has comment: http://stackoverflow.com/comment/87390190
answer count: 1
accepted answer: http://stackoverflow.com/a/50187535
tagged with: jenkins-pipeline
has body: I can able to install below packages using python script in my scp(Python version 2.7). But in jenkins i am getting syntax error . PYTHON CODE: VIRT_DIR = "home/user/vitual_dir/" subprocess.call("pip install --user virtualenv", shell=True) subprocess.call("python -m virtualenv " + VIRT_DIR, shell=True) activate_this = (VIRT_DIR + "/bin/activate_this.py") execfile(activate_this, dict(__file__= activate_this)) subprocess.call("pip install pylint", shell=True) subprocess.call("pip install coverage", shell=True) subprocess.call("pip install pytest", shell=True) Error message in jenkins:(python version 2.6.6) Traceback (most recent call last): File "/home/jenkins/vapor/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/home/jenkins/vapor/lib/python2.6/site- packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/home/jenkins/vapor/lib/python2.6/site- packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/home/jenkins/vapor/lib/python2.6/site-packages/pip/_internal/index.py", line 526 {str(c.version) for c in all_candidates}, ^ SyntaxError: invalid syntax Please help me to solve this.
has answer: http://stackoverflow.com/a/50187535
type: Question
tagged with: python-2.6
has comment: http://stackoverflow.com/comment/87390371
has comment: http://stackoverflow.com/comment/87390397
has title: Syntax Error while installing packages in jenkins

http://stackoverflow.com/q/50197712
tagged with: python-2.7
tagged with: colors
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87412414
tagged with: python
has body: I want to change the colors of my histogram plot to vary by its height as this example: My code for histogram plot is from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') nbins = 1000 mean_list = [366, 657, 594, 1200] scale_list = [15,50,19,7] height_list = [1200, 300, 900, 600] n = 0 for z in [30, 15, 10, 0]: ys = np.random.normal(loc=mean_list[n], scale=scale_list[n], size=height_list[n]) # loc is mean hist, bins = np.histogram(ys, bins=int(nbins/10)) xs = (bins[:-1] + bins[1:])/2 ax.bar(xs, hist, zs=z, zdir='y', alpha=0.8) n += 1 plt.show()
has title: How to color 3D histogram matplotlib plot like heatmap color
type: Question
downvote count: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
favorite count: 0

http://stackoverflow.com/a/50849513
type: Answer
answers question: http://stackoverflow.com/q/50082849
has body: If you load only the input part (red square in your question) as df, and if the column 'Host name' is merged, it would look like this (df) Host name IP address LAX_R 192.168.1.1 NaN 192.168.1.2 NaN 192.168.1.3 By the way, you can check if the column 'Host name' is initially merged by checking if it contains NaN value (Note: I'm assuming there should not be NaN values if it is not initially merged): if sum(df['Host name'].isnull()) &gt; 0: And then, by forward filling NaN, df.ffill(inplace=True) we get Host name IP address LAX_R 192.168.1.1 LAX_R 192.168.1.2 LAX_R 192.168.1.3 After that, IP address of the same Host name are aggregated to the same cell as a list df = pd.DataFrame(df.groupby('Host name')['IP address'].apply(list)) At this point, df looks like this IP address Host name LAX_R [192.168.1.1, 192.168.1.2, 192.168.1.3] The next step is to remove some unnecessary characters df.columns = ['IP address'] for ch in ["[", "]", ",", "'"]: df['IP address'] = df['IP address'].apply(lambda x: str(x).replace(ch, "")) (Optional) For "Apache Open Office", displaying each IP address in new line is done by df['IP address'] = df['IP address'].apply(lambda x: x.replace(" ", "\n")) Finally save it. df.to_excel("yourfile.xlsx", index=True) (Appendix) For "Microsoft Office", displaying each IP address in new line is done by Skip (Optional) part above Choose column "IP address" Choose Home --> Wrap Text as the following red square It's a bit lengthy, but it should do the task. Hope it helps.
score: 1
accepted answer of: http://stackoverflow.com/q/50082849
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50109536
has comment: http://stackoverflow.com/comment/87267375
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50125829
has comment: http://stackoverflow.com/comment/87267928
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/87267643
score: 2
has body: I have a Python Script which uses the pyodbc library to run some queries which I have task scheduler running on a set schedule. The script had been working fine without issue all of last week and it suddenly encountered the error: DatabaseError: Execution failed on sql 'select * from #output ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name '#output'. (208) (SQLExecDirectW)") This error arises when I try to extract that data from the query using pd.read_sql. The very odd part is that no modifications were made to the script at all. It had been working just fine up until today. I researched similar problems on stackoverflow and attempted using the same solutions (creating a global temp table instead of a local one) and the issue persists. Strangely, the query includes two temp tables, #data and #output and I'm able to access to contents of #data using pd.read_sql with no problem, but for whatever reason, attempting to use the same method on the other temp table results in the error above. The code itself might be a bit long to include on here, but this is what it resembles for the most part (I'll be happy to share the entire thing if it's not an issue): connection = pyodbc.connect(...) cursor = connection.cursor() query = """create table #data (...) ... #some other commands here in the middle create table #output (...) ... #two more lines of SQL commands and that's it """ cursor.execute(query) totals = pd.read_sql("""select * from #output"""), connection) The line cursor.execute(query) doesn't appear to generate an error as I get &lt;pyodbc.Cursor at 0xef2eea0&gt; if I run up to that line only. I appreciate the assistance. EDIT: I suspect the error message is due to the fact that there is a while loop portion before the create table #output statement and it is somehow preventing the next commands from executing properly. I've included a bit more detail using my example code from above: connection = pyodbc.connect(...) cursor…
upvote count: 2
tagged with: sql
has title: Pyodbc execution failed on temp table
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87236981
has comment: http://stackoverflow.com/comment/87263441

http://stackoverflow.com/comment/87335957
comment on: http://stackoverflow.com/a/50159008
has text: I am also intrigged why I am using `notnull()` and you are using `null()`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87391911
comment on: http://stackoverflow.com/q/50187537
has text: I would have a look here https://stackoverflow.com/questions/32400867/pandas-read-csv-from-url this will put your data in a useful structure, so you can do something with it
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87213819
comment on: http://stackoverflow.com/a/50098552
type: Comment
score: 0
type: AnswerComment
has text: Thank you that has solved the problem! I did a lot of research and never came across the enumerate function.

http://stackoverflow.com/q/50079585
tagged with: conv-neural-network
has title: CNN with keras, accuracy not improving
downvote count: 0
possible better answer: http://stackoverflow.com/a/52727016
tagged with: keras
has answer: http://stackoverflow.com/a/52727016
favorite count: 0
has body: I have started with Machine Learning recently, I am learning CNN, I planned to write an application for Car Damage severity detection, with the help of this Keras blog and this github repo. This is how car data-set looks like: F:\WORKSPACE\ML\CAR_DAMAGE_DETECTOR\DATASET\DATA3A ├───training (979 Images for all 3 categories of training set) │ ├───01-minor │ ├───02-moderate │ └───03-severe └───validation (171 Images for all 3 categories of validation set) ├───01-minor ├───02-moderate └───03-severe Following code gives me only 32% of accuracy. from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import backend as K # dimensions of our images. img_width, img_height = 150, 150 train_data_dir = 'dataset/data3a/training' validation_data_dir = 'dataset/data3a/validation' nb_train_samples = 979 nb_validation_samples = 171 epochs = 10 batch_size = 16 if K.image_data_format() == 'channels_first': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3) model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # this is the augmentation configuration we will use for training train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # this is the augmentation configuration we will use for testing: # only rescaling test_datagen…
score: 9
type: Question
answer count: 2
upvote count: 9
tagged with: theano
has comment: http://stackoverflow.com/comment/87179800
accepted answer: http://stackoverflow.com/a/50083565
tagged with: python
has answer: http://stackoverflow.com/a/50083565
has comment: http://stackoverflow.com/comment/87180869
type: AnsweredQuestion

http://stackoverflow.com/q/50212165
has comment: http://stackoverflow.com/comment/87441611
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87441970
tagged with: c++
score: 0
has title: querying mongodb collection in c++ using mongocxx driver and returning the resultset to python which called the c++ program
has comment: http://stackoverflow.com/comment/87441489
answer count: 0
has comment: http://stackoverflow.com/comment/87442094
has body: I'm trying to call c++ program from python, that connects to mongo using mongocxx , queries some data and returns the resultset to python. Here's my c++ program. contents of c++ program file #include &lt;bsoncxx/builder/stream/document.hpp&gt; #include &lt;bsoncxx/json.hpp&gt; #include &lt;mongocxx/client.hpp&gt; #include &lt;mongocxx/instance.hpp&gt; #include &lt;iostream&gt; extern "C" std::vector&lt;std::string&gt; data(){ std::vector&lt;std::string&gt; arr; mongocxx::instance inst{}; mongocxx::client conn{mongocxx::uri{}}; bsoncxx::builder::stream::document document{}; auto collection = conn["watchman"]["testcol"]; auto cursor = collection.find({}); for (auto&amp;&amp; doc : cursor) { std::cout &lt;&lt; bsoncxx::to_json(doc) &lt;&lt; std::endl; arr.push_back(bsoncxx::to_json(doc)); } return arr; } To compile the C++ file i am using: g++ --std=c++11 -c -fPIC program.cpp -o program.o $(pkg-config --cflags --libs libmongocxx) -Wl,-rpath,/usr/local/lib g++ -shared -Wl,-soname,library.so -o library.so program.o contents of python program that calls c++ program. import ctypes from numpy.ctypeslib import ndpointer lib = ctypes.CDLL('./library.so') lib.function.restype = ndpointer(dtype=ctypes.c_int, shape=(10,)) res = lib.data() print res error that i get Traceback (most recent call last): File "d.py", line 4, in &lt;module&gt; lib = ctypes.CDLL('./library.so') File "/usr/lib64/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: ./library.so: undefined symbol: _ZN8mongocxx7v_noabi3uri13k_default_uriE Any help would be appreciated.
tagged with: mongo-cxx-driver
type: Question
tagged with: mongodb
tagged with: ctypes
has comment: http://stackoverflow.com/comment/87442284

http://stackoverflow.com/q/50131358
tagged with: pip
tagged with: python
accepted answer: http://stackoverflow.com/a/50131397
has comment: http://stackoverflow.com/comment/87281934
type: AnsweredQuestion
has title: Pip not installing anything
score: 1
tagged with: macos
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/49748063
favorite count: 0
has answer: http://stackoverflow.com/a/50131397
has comment: http://stackoverflow.com/comment/87281980
type: Question
upvote count: 2
has body: When I do pip install Flask or pip install click or pretty much pip install &lt;anything&gt; returns the same error : Could not find a version that satisfies the requirement Flask (from versions: ) No matching distribution found for Flask Same error for any virtual environment I may have created. I'm on Mac OS, using Python 3.4.

http://stackoverflow.com/comment/87406214
type: QuestionComment
score: 0
has text: The operator `is` tests object identity, not value identity.
comment on: http://stackoverflow.com/q/50194532
type: Comment

http://stackoverflow.com/q/50172324
accepted answer: http://stackoverflow.com/a/50720710
has comment: http://stackoverflow.com/comment/87372808
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50720710
has comment: http://stackoverflow.com/comment/87433275
has comment: http://stackoverflow.com/comment/87433117
score: 1
downvote count: 0
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/87367761
upvote count: 1
has comment: http://stackoverflow.com/comment/87422091
favorite count: 0
type: Question
tagged with: robotframework
has comment: http://stackoverflow.com/comment/87364897
has comment: http://stackoverflow.com/comment/87367146
has comment: http://stackoverflow.com/comment/87363400
has comment: http://stackoverflow.com/comment/87474525
tagged with: python
has title: how to use wait for condition in RIDE python robot frame work
has body: enter image description hereCan someone help how to use wait for condition in RIDE Robot Framework PYTHON? I get this error everytime, but it stops at this point. I want it to proceed to next command. Country Code Creation 2 | FAIL | Element '//*[@id="mainBody"]/div[7]/p' not visible after 3 seconds. Project1.TestSuite1 | FAIL | 2 critical tests, 1 passed, 1 failed 2 tests total, 1 passed, 1 failed Project1 | FAIL | 2 critical tests, 1 passed, 1 failed 2 tests total, 1 passed, 1 failed

http://stackoverflow.com/a/50217785
has comment: http://stackoverflow.com/comment/87455271
score: 0
answers question: http://stackoverflow.com/q/50216816
has comment: http://stackoverflow.com/comment/87454513
accepted answer of: http://stackoverflow.com/q/50216816
type: Answer
has body: First of all, you're using all 77 points of your dataset in your classifier and in your plot. The variable you created with 54 points in it is not used either to fit the classifier or to produce the resulting plot. You should check the Variable Explorer in Anaconda after running the script to see the sizes of the different variables you're using. As to the plot you're generating, if you look at the way the data is distributed you will see why you see only 22 points: If you look at the original dataset, there are several points that share duplicate values in these two columns (fat and calories). As a result, several points are stacked on top of one another on the plot, so although you are plotting 77 points, you only "see" 22 of them on your plot. You might want to pick some other attribute if you want to see them all separated nicely.
type: AcceptedAnswer

http://stackoverflow.com/a/50113246
has comment: http://stackoverflow.com/comment/87246085
has comment: http://stackoverflow.com/comment/111832157
has comment: http://stackoverflow.com/comment/111831705
upvote count: 2
has comment: http://stackoverflow.com/comment/87247074
downvote count: 0
type: Answer
has body: Re. 1, it seems you already found out that message_id is left untouched when an item is moved. I can't find any hard documentation from EWS regarding this fact, so make sure to do extensive testing. Re. 2, it's true that you can only use account.fetch with item_id values. However, there are some things to note: When you call item.move(), item.item_id and item.changekey attributes are updated to the new location, which you could store for a future bulk operation. See https://github.com/ecederstrand/exchangelib/blob/3a1def29951d26c8a1b7021c7582c3d118181140/exchangelib/items.py#L365 You can still fetch in bulk by message_id by first translating the message_id to an item_id. This does a FindItem call and then a GetItem call: item_ids = account.inbox.filter(message_id__in=&lt;your_message_ids&gt;) \ .values_list('item_id', 'changekey') bulk_items = account.fetch(item_ids) You probably want to chunk &lt;your_message_ids&gt; items so the __in filter does not get extremely large.
answers question: http://stackoverflow.com/q/50103169
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50103169

http://stackoverflow.com/comment/87293525
has text: That's something for another question.... as your edit shows, your data is being properly preprocessed.
comment on: http://stackoverflow.com/a/50136397
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87352288
comment on: http://stackoverflow.com/q/50165614
score: 0
type: Comment
type: QuestionComment
has text: @ScottBoston: No, that's the solution I'm trying to figure out. In R I would generate a random vector say [1,2,01] and then use a map function to select that index per function. Not sure how to do it quickly in python.

http://stackoverflow.com/a/50100716
answers question: http://stackoverflow.com/q/50095445
type: Answer
has comment: http://stackoverflow.com/comment/87219839
score: 0
has body: Git submodule to manage common proto could solve your problem. When you define a submodule you are sure that this portion of code is common to all the repo pointing to this module. Also your submodule are in reality pointing to a commit. So if there are update on your module (proto model), you will have to pull manually the update into your buisness code. On the other hand, if you are delivering a bug, if you don't update the submodule, you will not redeliver the proto.

http://stackoverflow.com/comment/87405746
score: 0
has text: that's nice if you solved it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50189032

http://stackoverflow.com/q/50199666
score: 1
tagged with: benfords-law
has comment: http://stackoverflow.com/comment/87416154
tagged with: python-3.x
answer count: 0
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87416160
favorite count: 0
has comment: http://stackoverflow.com/comment/87415962
type: Question
has title: Benford's Law count leading digits from csv file
has body: I am new to python and am writing a program that reads values from a .csv file, then displays a graph that shows the test results compared to the expected output for Benford's Law. The .csv file has loan values which I need to read in the 1st column like below: Values Leading Digit Number of occurances 170 1 88 900 9 62 250 2 44 450 4 51 125 1 19 ..... The main file, app.py: ... filename = filedialog.askopenfilename(filetypes=( ("Excel files", "*.csv"), ("All files", "*.*"))) print(filename) try: with open(filename, 'rt') as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader, None) # skip the headers for row in reader: minutePriceCloses.append(row[0]) # calculate the percentage distribution of leading digits benford_test_data_dist = calc.getBenfordDist(minutePriceChanges) .... in calc.py: import numpy as np def getBenfordDist(data): # set initial dist to zero dist = [0, 0, 0, 0, 0, 0, 0, 0, 0] # for each figure, check what the first non-zero digit is, hacky multiply # by 1000000 to handle small values for d in data: # sneaky multiply by 1000000 to ensure that the leading digit is unlikely to be zero # since benfords law is assumed to relate somehow to scale invariance, this *SHOULDN'T* make a difference # but it might, so this might all be wrong :-) s = str(np.abs(d) * 1000000) for i in range(0, 8): if(s.startswith(str(i + 1))): dist[i] = dist[i] + 1 break # return fractions of the total for each digit percentDist = [] # convert to % - todo, start using numpy vectors that allow scalar mult/div for count in dist: percentDist.append(float(count) / len(data)) # print(float(count)) return percentDist Now the problem I am having is that the graph output is not correctly displaying the percentage results for the value column count divided by the total number of rows with values i.e for the values with leading digit of 1, the percentage on graph should be 0.25 and so on. There are 352 rows. Please help. Thanks

http://stackoverflow.com/comment/87205717
score: 4
comment on: http://stackoverflow.com/q/50094765
has text: [`bytearray.decode`](https://docs.python.org/3/library/stdtypes.html#bytearray.decode)
type: QuestionComment
type: Comment

pickle
tags question: http://stackoverflow.com/q/50170079
tags question: http://stackoverflow.com/q/50159760
tags question: http://stackoverflow.com/q/50114709
tags question: http://stackoverflow.com/q/50109404
tags question: http://stackoverflow.com/q/50102426
type: Tag
tags question: http://stackoverflow.com/q/50192386
tags question: http://stackoverflow.com/q/50108601
tags question: http://stackoverflow.com/q/50156118
tags question: http://stackoverflow.com/q/50165242
tags question: http://stackoverflow.com/q/50213578
tag name: pickle

http://stackoverflow.com/comment/87341099
has text: there is no need to write the string names to a file, you can just add them to a `list` (`myList=[]`)
score: 0
comment on: http://stackoverflow.com/q/50161299
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50157962
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50158068
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50158136
score: 1
accepted answer: http://stackoverflow.com/a/50158176
has body: I have my data stored in json format. And by using json:load() I am reading the data. What I am trying to do is based on argument passed , I am trying to extract specific part of Key:Value from the list and storing them into a new list for later processing. Code selected_env='mydev2' server_list=[{'mydev': ['192.168.56.102', '192.168.56.102', '192.168.56.102']}, {'mydev2': ['192.168.56.102', '192.168.56.102', '192.168.56.102']}] for item in server_list : host_list=[item for item in server_list[selected_env] if selected_env in server_list] print(host_list) And I am getting error as TypeError: list indices must be integers or slices, not str Note: I have achieved already one way of extraction as below for item in server_list: for element in item : if element == selected_env : host_list=item[selected_env] even though its working, I thought of optimizing it and went to read some articles on list extraction and kind of stuck with above error. Any help, greatly appreciated.
has title: Python3: TypeError: list indices must be integers or slices, not str
downvote count: 0
has answer: http://stackoverflow.com/a/50158176
upvote count: 1
has answer: http://stackoverflow.com/a/76644212
possible better answer: http://stackoverflow.com/a/50158068
favorite count: 0

http://stackoverflow.com/comment/87441007
has text: I've scattered the values of the OSEBX, plt.scatter(t, x, s=1), But the trend is missing.
score: 0
comment on: http://stackoverflow.com/q/50209037
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50220099
score: 0
has body: You're basically describing something like SQLite. You may say that it's inflexible, but to an old DB fart like me it can more rightly be accused of not being stringent enough, e.g. about types. But for the sort of application you describe, that's not going to be an issue. The sort of flexibility you're looking for means you're looking for a document database of some sort; no RDBMS is going to fit your use case much better than SQLite. You can search for a good fit as well as I can, and a few good keywords would be document database, nosql and embedded, the latter setting it apart from a DB that runs as a separate service. Let us know what you find.
type: Answer
answers question: http://stackoverflow.com/q/50213596

http://stackoverflow.com/comment/87452313
type: AnswerComment
comment on: http://stackoverflow.com/a/50215854
score: 2
has text: A clean towel and a fresh steak.
type: Comment

http://stackoverflow.com/q/50182878
tagged with: python
has title: Baffled by solution to Vimscript recursion error
tagged with: org-mode
tagged with: vim
type: AnsweredQuestion
score: 2
has body: I want to use gf to open hyperlinked filenames in .org files (I use the vim plugin vim-orgmode): I type gf and the file should open. To avoid having to move past the first two [[, I created the following script to do the job: function! GFOrg() python &lt;&lt; EOF import vim try: filename=vim.eval("@%") if filename.endswith(".org"): line = vim.current.line linkstart=line.find("[[") if linkstart != -1: row, start = vim.current.window.cursor vim.current.window.cursor = row, linkstart+2 vim.command("normal gf") except Exception as e: print("Error: {}".format(e)) EOF endfunction Now if I map it to override gf: nnoremap gf :call GFOrg()&lt;CR&gt; I get a recursion error: But if I quit and reopen Vim (MacVim actually), and use gfgf as my mapping, I can just type gf (once) and it works fine: nnoremap gfgf :call GFOrg()&lt;CR&gt; Can anyone explain why I don't need to type gf twice to get mapped to the call, and why it stops the recursion error?
upvote count: 2
has comment: http://stackoverflow.com/comment/87384256
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50183101
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50183101
has comment: http://stackoverflow.com/comment/87384387

http://stackoverflow.com/q/50140316
score: 0
tagged with: gimpfu
answer count: 1
tagged with: gimp
type: Question
has answer: http://stackoverflow.com/a/50158022
tagged with: python
type: UnansweredQuestion
tagged with: script-fu
has title: Gimp python-fu: selecting two layers
has body: I would like to create a python-fu script for gimp where the user could select two layers. register( (....) [ (PF_IMAGE, "image", "Input image", None), (PF_DRAWABLE, "layermask", "MASK:", None), (PF_LAYER, "drawinglayer", "DRAWING:", None), (PF_INT, "treshold", "TRESHOLD:", 1) ], (...) whenever I try this, my form contains only one choice (I suppose it uses the default layer ?) . How can I get two 'select' controls ? I've tried to change PF_DRAWABLE to PF_LAYER but I still get the same result.

http://stackoverflow.com/comment/87401982
comment on: http://stackoverflow.com/q/50191729
score: 0
type: Comment
has text: DecisionTreeRegressor supports both numerical and categorical variables. Are you getting an error?
type: QuestionComment

http://stackoverflow.com/comment/87231809
score: 0
type: Comment
has text: Thanks for chiming in. The accepted answer below solved this issue.
type: QuestionComment
comment on: http://stackoverflow.com/q/50105545

http://stackoverflow.com/a/50209393
has comment: http://stackoverflow.com/comment/87435720
has comment: http://stackoverflow.com/comment/87436132
type: Answer
has comment: http://stackoverflow.com/comment/87435761
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50209287
has body: In f-strings expressions are parsed with the equivalent of: ast.parse('(' + expression + ')', '&lt;fstring&gt;', 'eval') see https://docs.python.org/3/library/ast.html#ast.parse But variables will be replaced with their actual value. What are you looking for is sort of a nested evaluation which is not supported by f-strings. Instead as a safe approach you can first split with '**' then covert to int and finally use power: In [9]: s = "2**4" In [10]: print(f"{pow(*map(int, s.split('**')))}") 16
downvote count: 0
has comment: http://stackoverflow.com/comment/87435906
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50209287
has comment: http://stackoverflow.com/comment/87436249
score: 3

http://stackoverflow.com/comment/87457024
comment on: http://stackoverflow.com/a/50215239
type: AnswerComment
has text: Just remove `\*\*` at the end and beginning. I think it's pretty self explanatory
score: 0
type: Comment

http://stackoverflow.com/a/50153879
score: 0
has body: Change this line: data_T0_random=data_T0.loc[np.random.choice(data_T0.index, 10000)] to: data_T0_random=random.sample(data_T0,10000) More info: random.choices(population, weights=None, *, cum_weights=None, k=1) Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError. random.sample(population, k) Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
type: Answer
answers question: http://stackoverflow.com/q/50153816

http://stackoverflow.com/comment/87268219
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50122930
has text: It is unlikely you will get an answer unless you include an excerpt of your data frame (3-5 rows).

http://stackoverflow.com/q/50155552
has body: if you are inputing 12 values like the months of the year via a for loop to reduce repetition how to get all of the numbers assigned to a list in order of entry, also say you have the list how do you add up all the items within a list [1,2,3] total would be: 6 for month in range(12): whatever = float(input("enter whatever in 12 months: ")) syntax to put above 12 values into a list
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to store values in a list that were inputed through the input command
has comment: http://stackoverflow.com/comment/87328759
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87329544
tagged with: input
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50155627
accepted answer: http://stackoverflow.com/a/50155627
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87328756
answer count: 1

http://stackoverflow.com/q/50182498
has body: I use pyenv to install and manage both different versions of python and virtual environments for various projects on my system. But pipenv is the recommended tool for managing virtual environments now, and I like a lot of its features. Everything works for the most part, but pipenv seems to have a leak or something when it comes to Jupyter notebook. Here are the steps which replicate the problem on my machine. Install pipenv using brew install pipenv. Install a new version of Python using, say, pyenv install 3.6.3, and activate it via pyenv global 3.6.3. Install Jupyter notebook and another package, e.g. pip install jupyter requests. Create a new directory and navigate into it; create a pipenv project using pipenv install Activate the pipenv virtual environment using pipenv shell. Do not install any packages, and confirm that none are installed in the current virtualenv using pip list. (I only get pip, setuptools, and wheel.) Run jupyter notebook. My expectation: the console errors out with jupyter: command not found. Actual: the notebook server and browser UI launch as normal. Create a new notebook and import the auxiliary package from step 3: import requests. My expectation: a ModuleNotFoundError is thrown. Actual: the package is imported and can be used as normal. If I try to import the auxiliary package in the pipenv virtual environment but outside Jupyter notebook (in the repl or in a Python script) , I get a ModuleNotFoundError as expected. So somehow the problem is with jupyter specifically. Note that if I try to recreate this problem using a pyenv virtual environment instead of a pipenv virtual environment then the expected behavior occurs: jupyter notebook produces a jupyter: command not found error in the console. My question is: am I using pipenv in a way that was not intended, or is there an alternative way to use pipenv that avoids this problem? Thanks in advance!
downvote count: 0
has comment: http://stackoverflow.com/comment/87382590
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50183177
tagged with: pipenv
type: Question
has answer: http://stackoverflow.com/a/50183177
tagged with: pyenv
tagged with: python
tagged with: jupyter-notebook
score: 4
upvote count: 4
has title: pipenv + pyenv + jupyter
type: AnsweredQuestion

http://stackoverflow.com/comment/87326401
type: Comment
has text: welcome to stackoverflow! please take the [tour](http://stackoverflow.com/tour), read up on [how to ask a question](https://stackoverflow.com/help/asking).
comment on: http://stackoverflow.com/q/50154447
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87350606
comment on: http://stackoverflow.com/a/50166377
has text: I have a batch of JSON files actually. They are long documents scraped from the web and many have 700 plus characters in them. Now the challenge is, the error does not indicate which of the 100,000 files in the folder that I am trying to deal with has the faulty JSON. So, this is another challenge.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87189129
type: AnswerComment
has text: Thanks for pointing that out - it's a bit unfortunate that the link in the bokeh page was wrong, as even with a correct link the error appears - I posetd a more detailled sdescription of my problem in the question section
comment on: http://stackoverflow.com/a/50086586
type: Comment
score: 0

http://stackoverflow.com/a/50157297
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50157251
downvote count: 0
has comment: http://stackoverflow.com/comment/87332900
has comment: http://stackoverflow.com/comment/87332746
has comment: http://stackoverflow.com/comment/87334339
has comment: http://stackoverflow.com/comment/87334863
type: Answer
has comment: http://stackoverflow.com/comment/87334286
score: 4
has body: Use transform of max values per groups with same size as original DataFrame, compare by column pident and last filter by boolean indexing: data_grpd = data.groupby(['cluster']) result = data.loc[data_grpd['pident'].transform('max') == data['pident']] print (result) cluster seq 1 seq2 pident whatever 0 1 A B 89 47 1 1 A B 89 68 4 2 G H 89 45 Detail: print (data_grpd['pident'].transform('max')) 0 89 1 89 2 89 3 89 4 89 Name: pident, dtype: int64 EDIT: One possible solution is sorting first: data_wo_eqSpec'seq1','seq2' = np.sort(data_wo_eqSpec'seq1','seq2', axis=1) data_grpd = data_wo_eqSpec.groupby(['cluster_name']) result = data_wo_eqSpec.loc[data_grpd['pident'].transform('max') == data_wo_eqSpec['pident']] print(result)
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50157251
has comment: http://stackoverflow.com/comment/87333261
has comment: http://stackoverflow.com/comment/87333347

http://stackoverflow.com/comment/87472141
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50210935
has text: Based on suggestions I have decided not to use "exec". The input file is a bit unusual and I had no privilege to modify that. Thank you for your reply.
type: Comment

http://stackoverflow.com/comment/87203853
type: Comment
type: AnswerComment
has text: This solution looks simpler but it adds some days that didn't exist in the daily DataFrame. For example: 2017-10-30 and 2017-11-20.
comment on: http://stackoverflow.com/a/50093425
score: 1

http://stackoverflow.com/q/50128159
has body: I was trying to implement a DQN to solve the CartPole-v0 task in the OpenAI Gym. Unfortunately, my implementation's performance does not seem to be improving. Currently, as the training occurs, the episode reward actually decreases whereas the goal is to find better policies that increase this value. I am using experience replay and a separate target network to back up my q values. I tried adding/deleting layers and neurons in the agent; this did not work. I altered the schedule for decaying the exploration rate; this did not work either. I've grown increasingly convinced that something's wrong with my loss function, but I'm not sure how I could change it to improve performance. Here's my code for the loss function: with tf.variable_scope('loss'): one_hot_mask = self.one_hot_actions eval = tf.reduce_max(self.q * one_hot_mask, axis=1) print(eval) trg = tf.reduce_max(self.q_targ, axis = 1) * self.gamma print(trg) label = trg + self.rewards self.loss = tf.reduce_mean(tf.square(label - eval)) Where one_hot_actions is a placeholder defined as: self.one_hot_actions = tf.placeholder(tf.float32, [None, self.env.action_space.n], 'one_hot_actions') Here's my full code: import tensorflow as tf import numpy as np import gym import sys import random import math import matplotlib.pyplot as plt class Experience(object): """Experience buffer for experience replay""" def __init__(self, size): super(Experience, self).__init__() self.size = size self.memory = [] def add(self, sample): self.memory.append(sample) if len(self.memory) > self.size: self.memory.pop(0) class Agent(object): def __init__(self, env, ep_max, ep_len, gamma, lr, batch, epochs, s_dim, minibatch_size): super(Agent, self).__init__() self.ep_max = ep_max self.ep_len = ep_len self.gamma = gamma self.experience = Experience(100) self.lr = lr self.batch = batch self.minibatch_size = minibatch_size self.epochs = epochs self.s_dim = s_dim self.sess = tf.Session() self.env = gym.make(env).unwrapped self.state_0s = tf.placeh…
tagged with: reinforcement-learning
has answer: http://stackoverflow.com/a/50296472
has title: Deep Q Network not Solving OpenAI CartPole
tagged with: openai-gym
answer count: 1
downvote count: 1
tagged with: tensorflow
score: -1
favorite count: 0
type: Question
upvote count: 0
tagged with: machine-learning
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87412685

http://stackoverflow.com/q/50170587
has comment: http://stackoverflow.com/comment/87358592
has comment: http://stackoverflow.com/comment/87358476
score: 0
has comment: http://stackoverflow.com/comment/87358589
type: Question
answer count: 0
has body: Hy guys. I'm working with face-emotion recognition program and need to convert this code from python to c#. This is a nueral network with which help we could recognize emotions. The network outputs a list of softmax scores for the seven classes. The emotion with maximum score is displayed. Here is code: Python class EMR: def __init__(self): self.target_classes = ['angry', 'disgusted', 'fearful', 'happy', 'sad', 'surprised', 'neutral'] def build_network(self): """ Build the convnet. Input is 48x48 3072 nodes in fully connected layer """ print("\n---&gt; Starting Neural Network \n") self.network = input_data(shape = [None, 48, 48, 1]) print("Input data",self.network.shape[1:]) self.network = conv_2d(self.network, 64, 5, activation = 'relu') print("Conv1",self.network.shape[1:]) self.network = max_pool_2d(self.network, 3, strides = 2) print("Maxpool",self.network.shape[1:]) self.network = conv_2d(self.network, 64, 5, activation = 'relu') print("Conv2",self.network.shape[1:]) self.network = max_pool_2d(self.network, 3, strides = 2) print("Maxpool2",self.network.shape[1:]) self.network = conv_2d(self.network, 128, 4, activation = 'relu') print("Conv3",self.network.shape[1:]) self.network = dropout(self.network, 0.3) print("Dropout",self.network.shape[1:]) self.network = fully_connected(self.network, 3072, activation = 'relu') print("Fully connected",self.network.shape[1:]) self.network = fully_connected(self.network, len(self.target_classes), activation = 'softmax') print("Output",self.network.shape[1:]) print('\n') self.network = regression(self.network,optimizer = 'momentum',metric = 'accuracy',loss = 'categorical_crossentropy') self.model = tflearn.DNN(self.network,checkpoint_path = 'model_1_nimish',max_checkpoints = 1,tensorboard_verbose = 2) self.load_model() def predict(self, image): """ Image is resized to 48x48 model.predict() is an inbuilt function in tflearn. """ if image is None: return None image = image.reshape([-1, 48, 48, 1]) return self.model.predict(imag…
has title: Convert python to c# neural network
type: UnansweredQuestion
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/87358490

http://stackoverflow.com/comment/87384640
has text: If you run softmax separately per batch, this option could work
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50183530
type: Comment

http://stackoverflow.com/comment/87297911
score: 0
type: Comment
has text: @BluHaz You should avoid using regular expressions whenever you can. They might get long, overly complicated, hard to understand and maintain.
type: AnswerComment
comment on: http://stackoverflow.com/a/50138987

http://stackoverflow.com/comment/87458101
has text: Ooh..... the optimizer is an object with a minimization function. I have not seen that I can initialize the optimizer without calling its minimization function directly.... I think it's time to take a break. Thank you very much, your comment was helpful.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50219773
score: 0

http://stackoverflow.com/a/50172393
answers question: http://stackoverflow.com/q/50172287
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50172287
downvote count: 0
type: AcceptedAnswer
has body: Ex: import csv columns = defaultdict(list) res = [] with open(filename) as f, open(filename2) as a: reader=csv.reader(f, delimiter=' ') reader1=csv.reader(a, delimiter=' ') next(reader) next(reader1) for row in zip(reader, reader1): res.extend([row[0][0], row[1][1].replace("'", "")]) print(res) Output: ['1', 'Feb', '2', 'Mar', '3', 'May']
has comment: http://stackoverflow.com/comment/87362702
has comment: http://stackoverflow.com/comment/87362460

blas
tags question: http://stackoverflow.com/q/50166194
tag name: blas
type: Tag

http://stackoverflow.com/comment/87271131
comment on: http://stackoverflow.com/q/50126523
type: Comment
score: 0
has text: how do i check the docker logs... @Shadow
type: QuestionComment

http://stackoverflow.com/comment/87367859
has text: @CristiFati I'm from .NET and we have Serializable attribute there, to mark classes as serializable. Hoped that there are some easy ways here too, historically XML serialization was very popular before JSON. And what kind of functions I have to define?
type: QuestionComment
comment on: http://stackoverflow.com/q/50174855
score: 0
type: Comment

http://stackoverflow.com/q/50206585
tagged with: python
score: 3
tagged with: python-2.7
has body: Versions are: PyCharm 2018.1.2 (Professional Edition) Python 2.7 Python 3.6 test.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import sys print(sys.getdefaultencoding()) d = {'中文': '中文'} print(d) When you run python test.py, the output is ascii {u'\u4e2d\u6587': u'\u4e2d\u6587'} But will raise UnicodeEncodeError when watching it in debugger with Python2.7. But it's normal when debuging it in Pycharm with Python3.6:
has title: Pycharm debugger watch UnicodeEncodeError
answer count: 0
has comment: http://stackoverflow.com/comment/89468393
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: encode
type: UnansweredQuestion

http://stackoverflow.com/q/50075877
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50076060
tagged with: python
has title: Scipy.io savemat / loadmat with list of lists
type: AnsweredQuestion
tagged with: list
score: 1
has body: I'm trying to create a list of lists and add it to a dictionary key and then save the dictionary as a .mat file. My code looks like this: from scipy.io import loadmat dic = {"X": [[1,2,3],[1,2,4],[6,7,8,9],[1]]} savemat('Test.mat', mdict=dic) When I load the .mat file with loadmat and print dic['X']; the output should be [[1,2,3],[1,2,4],[6,7,8,9],[1]]. Instead I'm getting this: [[array([[1, 2, 3]]) array([[1, 2, 4]]) array([[6, 7, 8, 9]]) array([[1]])]] My code snippet for loading and restoring dic: X = loadmat("Test.mat") print(X['X']) How do I store the original list into .mat file?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87172811
upvote count: 1
tagged with: scipy
accepted answer: http://stackoverflow.com/a/50076060
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/q/50158588
has answer: http://stackoverflow.com/a/50158733
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87335531
tagged with: datetime
has title: Convert year-week to date condition to date where the week has max days for that month
has comment: http://stackoverflow.com/comment/87335987
tagged with: python
has comment: http://stackoverflow.com/comment/87336259
has comment: http://stackoverflow.com/comment/87335192
has comment: http://stackoverflow.com/comment/87335325
has comment: http://stackoverflow.com/comment/87335406
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50159923
has comment: http://stackoverflow.com/comment/87337087
has comment: http://stackoverflow.com/comment/87335110
type: Question
has body: Let me explain, I'm trying to convert the 5th week of 2017; 201705 to a date that belongs to February because that belongs to 5th week of the year. So far I've been able to convert the custom date format to a date as follows: import datetime d = '201705' dt = datetime.datetime.strptime(d+'1', '%Y%W%w') Which then output, 2017-01-30 00:00:00 But is there a way I can convert the date to February and similarly all week numbers that belong to a month gets converted to that month EDIT: What I'm after is if the week number is 5 then its February, ,if its 9 then its March - sort of week-month mapping but I've not found any way of doing that besides changing the year-week to dateformat
has comment: http://stackoverflow.com/comment/87336893

http://stackoverflow.com/comment/87449711
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50213563
type: Comment
has text: /root/abhithak Already exists --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-202-dead83ea1f54> in <module>() 9 10 ---> 11 os.system("uname -a" > path/'uname') # I want to redirect o/p of shell commands to file using varibale "path" but it is not working 12 os.system("df -hP"> path/'df') TypeError: unsupported operand type(s) for /: 'str' and 'str'

http://stackoverflow.com/a/50112365
type: Answer
answers question: http://stackoverflow.com/q/50112332
has comment: http://stackoverflow.com/comment/87242826
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87242037
has body: If what you want here is to combine two queries with the SQL UNION operation, Django supports that as a QuerySet method. But it's not clear why you want to try to force this into a single query; more information about your use case would help in coming up with suggestions.

http://stackoverflow.com/comment/87376861
type: Comment
has text: First of all thank you, I want to know exactly what the cause is. dtype?
comment on: http://stackoverflow.com/a/50172001
score: 0
type: AnswerComment

http://stackoverflow.com/a/50089933
type: Answer
score: -2
has comment: http://stackoverflow.com/comment/87196644
has body: Why don't you use time: import time time.time() trime.ctime()
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/87196667
answers question: http://stackoverflow.com/q/50089849

http://stackoverflow.com/a/60632483
type: Answer
answers question: http://stackoverflow.com/q/50083682
has body: from your code if request.method == 'POST': formset = forms.InviteesFormSet(request.POST) if formset.is_valid(): formset.save(commit = False) return redirect('/invitees/') else: formset = forms.InviteesFormSet(request.POST) do not use request.POST if it is a GET request just do formset = forms.InviteesFormSet(queryset=Invitees.objects.all()) (you can remove the else clause altogether)
score: 0

http://stackoverflow.com/comment/87342909
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50161995
has text: My pleasure - see if the updated version doesn't work for you.
type: Comment

http://stackoverflow.com/comment/87376339
comment on: http://stackoverflow.com/q/50179154
has text: The way your model is built, you could ensure uniqueness by checking that the pair `(parent, suffix)` is unique, but it would probably be more expensive than what you're doing. It would not require double calculation of the `number_as_char` but I don't think you'd win much, if anything. This is a super common headache with django...
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87376803
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50179713
has text: @GianlucaMicchi, I'd like it to iterate through all of the letters list, so ```ZBCDEFGHIJKLMNOPQRSTUVWXYZ``` is also an expected output.

http://stackoverflow.com/a/50175710
score: 4
has comment: http://stackoverflow.com/comment/87432808
accepted answer of: http://stackoverflow.com/q/50175555
has body: There are only a few changes necessary to do that with threading. First create a function start_tryout: def start_tryout(): Thread(target=tryout, daemon=True).start() # deamon=True is important so that you can close the program correctly Then create the button with the new command: butTest = Button(master, text='test', command=start_tryout) Then it should no longer freeze the gui and you should be able to see the label change.
type: Answer
answers question: http://stackoverflow.com/q/50175555
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87431954
downvote count: 0

http://stackoverflow.com/comment/87167451
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50075566
type: AnswerComment
has text: Share you rtf.txt file

http://stackoverflow.com/comment/87280736
comment on: http://stackoverflow.com/q/50131449
type: Comment
has text: Your question is unclear: do you want to replace the 'u' because it is a 'u' or because it is in 4th position?
score: 2
type: QuestionComment

http://stackoverflow.com/comment/87205586
type: QuestionComment
has text: Oh, I see. Anywhere that's roughly in the center of the cell would be okay.
score: 0
comment on: http://stackoverflow.com/q/50093507
type: Comment

http://stackoverflow.com/q/50111745
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50111814
accepted answer: http://stackoverflow.com/a/50111827
has comment: http://stackoverflow.com/comment/87240836
type: AnsweredQuestion
score: 0
has body: Let's say that I have csv format string a='1,2,3\r4,5,6\r7,8,9\r' in python. How can I get "3 rows x 3 columns" of DataFrame [[1,2,3],[4,5,6],[7,8,9]] from variable a? Thanks.
answer count: 3
has answer: http://stackoverflow.com/a/50111827
tagged with: pandas
has answer: http://stackoverflow.com/a/50111915
possible better answer: http://stackoverflow.com/a/50111814
type: Question
tagged with: python-3.x
has title: How to get DataFrame format from csv format string in python
tagged with: http://stackoverflow.com/tag/csv

siblings
type: Tag
tag name: siblings
tags question: http://stackoverflow.com/q/50091000

http://stackoverflow.com/a/50118292
accepted answer of: http://stackoverflow.com/q/50118240
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50118240
type: Answer
has body: col_list = ['a','b','c'] df = pd.concat( [df, df[col_list].div(df['X'] ** 2, axis=0).add_prefix('new_')], axis=1 ) df X a b c new_a new_b new_c 0 5 3 4 5 0.120000 0.160000 0.200000 1 7 2 4 2 0.040816 0.081633 0.040816 Pandas performs index-aligned division on each column, just concatenate the result afterwards.

http://stackoverflow.com/comment/87269728
has text: Do you have example input?
score: 0
comment on: http://stackoverflow.com/q/50125658
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50142997
has comment: http://stackoverflow.com/comment/87314919
has comment: http://stackoverflow.com/comment/87634979
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87304371
tagged with: crash
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87656211
linked to: http://stackoverflow.com/q/39293731
tagged with: python
tagged with: large-data
score: 4
has title: Python: Proper way to read large dataset without crashing memory
linked to: http://stackoverflow.com/q/24825522
has comment: http://stackoverflow.com/comment/87304809
upvote count: 4
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87309320
tagged with: memory-management
has body: I read a TDMS binary dataset generated by LabView using this code. The file is about 500 MB, so it's not so big as commented in another posted questions as Q1 and Q2. My computer has a quadcore i7 processor and 8GB RAM memory, uses ubuntu 16.04 and run IPython Notebook (Python 2.7). I noticed, in the monitor system, everytime that I read the file (~500 MB), it is apparently stored in RAM memory. Data has 8 arrays of 3.3e7 points. When I tried to plot (using matplotlib) only one array, the memory consumption increase to about 1 GB more. So, imagine when I tried to plot the 8 arrays in one plot. I have to restart the kernel to clear from the RAM memory. But what if I need to plot every array? I experimented this before when read multiples astronomical images. I tried to found the answer for these looking in questions Q1 and Q2 but these answer are not resolved. So, the question is: How can I manage the memory for large datasets using python? Code Example: %matplotlib nbagg import matplotlib.pyplot as plt import numpy as np from nptdms import TdmsFile tdms_file = TdmsFile("20180320_190351_060_PXI-5105.tdms") root_object = tdms_file.object() # Iterate over all items in the properties dictionary and print them for name, value in root_object.properties.items(): print("{0}: {1}".format(name, value)) Timestamp: 2018-03-20 19:03:51.060532343 Digitizer: PXI-5105 SamplingRate: 30000000 PreTrigger: 0.05 PostTrigger: 1.05 TriggerSource: 4 TriggerHigh: 0.95 TriggerLow: -0.95 Offset: 447.0 Longitude: -46.7273776 Latitude: -23.4832443 GPS-Status: self survey not completed tdms_groups = tdms_file.groups() print tdms_groups [u'PXI-5105-Ch0', u'PXI-5105-Ch1', u'PXI-5105-Ch2', u'PXI-5105-Ch3', u'PXI-5105-Ch4', u'PXI-5105-Ch5', u'PXI-5105-Ch6'] dms_Variables_0 = tdms_file.group_channels("PXI-5105-Ch0") dms_Variables_1 = tdms_file.group_channels("PXI-5105-Ch1") dms_Variables_2 = tdms_file.group_channels("PXI-5105-Ch2") dms_Variables_3 = tdms_file.group_channels("PXI-5105-Ch3") dms_Variab…
answer count: 0
linked to: http://stackoverflow.com/q/44796977
downvote count: 0
has comment: http://stackoverflow.com/comment/87304638

http://stackoverflow.com/a/50100244
upvote count: 1
answers question: http://stackoverflow.com/q/50100199
has body: I've been using this library and it has been working great.
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/87217256
downvote count: 0

eval
tag name: eval
type: Tag
tags question: http://stackoverflow.com/q/50074956

http://stackoverflow.com/comment/87437039
type: AnswerComment
has text: @Robert Columbia: Done!
comment on: http://stackoverflow.com/a/50190114
score: 0
type: Comment

http://stackoverflow.com/q/50079247
favorite count: 0
type: Question
has title: How Can I Make this Code More Efficient i.e. to one or two lines?
has comment: http://stackoverflow.com/comment/87174552
upvote count: 1
tagged with: dataframe
tagged with: python
score: -1
has body: census_df = census_df.loc[((census_df['REGION'] &gt;= 1) &amp; (census_df['REGION'] &lt;=2))] census_df = census_df[census_df['CTYNAME'].str.match('Washington')] census_df = census_df[census_df['POPESTIMATE2015'] &gt; census_df['POPESTIMATE2014']] census_df = census_df'STNAME', 'CTYNAME' census_df I know that there must be a way that I can condense this to one line of code using . Would I just use the "&amp;" symbol to connect the first three lines?
accepted answer: http://stackoverflow.com/a/50079662
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50079662
tagged with: pandas
downvote count: 2
has comment: http://stackoverflow.com/comment/87174560
answer count: 1

http://stackoverflow.com/q/50184720
type: Question
has answer: http://stackoverflow.com/a/50185056
tagged with: swig
has title: TypeError: in method '...', argument 1 of type 'unsigned char const *' when using swig module
tagged with: python
linked to: http://stackoverflow.com/q/50212416
has body: Consider this little swig mcve: example.h void init(int width, int height); void dump(const unsigned char *buffer,int pitch); example.c #include &lt;stdio.h&gt; void init(int width, int height) { printf("Initializing width=%d height=%d", width, height); } void dump(const unsigned char *buffer,int pitch) { for(int i=0;i&lt;pitch;i++) { printf("%d\n", buffer[i]); } } example.i %module example %{ #include "example.h" %} %include "example.h" setup.py from distutils.core import setup, Extension example_module = Extension('_example', sources=['example.i', 'example_wrap.c', 'example.c'], swig_opts = [], include_dirs = ["."], ) setup(name='example', version='0.1', author="BPL", description="""Mcve stackoverflow""", ext_modules=[example_module], py_modules=["example"] ) test.py import struct import example as swig_thing count = 256 width = 8 height = 4 swig_thing.init(width, height) for frame in range(count): print(f"frame {frame}") data = [] for y in range(height): for x in range(width): data.append(0x00FF0000) _buffer = struct.pack(f'{len(data)}L', *data) swig_thing.dump(_buffer, width*4) If I run python setup.py build_ext --inplace and then I try to run test.py I'll get the following error: TypeError: in method 'dump', argument 1 of type 'unsigned char const *' Question, how to avoid the above error?
accepted answer: http://stackoverflow.com/a/50185056
score: 2
type: AnsweredQuestion
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/87309471
has text: Sure! It's the same as the birthday problem, which is very well documented: https://en.wikipedia.org/wiki/Birthday_problem
type: AnswerComment
comment on: http://stackoverflow.com/a/50145004
score: 1
type: Comment

http://stackoverflow.com/q/50189365
tagged with: nginx
has answer: http://stackoverflow.com/a/59266441
has body: I have deployed a flask web application using uWSGI and NGINX as the reverse proxy. The application response time is about 9ms on average but after a batch of requests my workers crashed and I got this log on my uWSGI log: [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 24488] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 4059] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 46764] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 9951] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 9449] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 51355] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 39565] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 63142] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 7861] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 10165] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 10917] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] [uwsgi-http key: backend client_addr: 172.17.0.1 client_port: 20392] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 647] The uWSGI config: [uwsgi] http = 0.0.0.0:…
tagged with: python
has comment: http://stackoverflow.com/comment/100328285
upvote count: 13
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: uwsgi
favorite count: 0
score: 13
has title: uWSGI error hr_instance_read(): Connection reset by peer
type: Question

http://stackoverflow.com/comment/87198155
type: QuestionComment
has text: ive got it to work guys thanks, ive accidentally added an extra try statement that was not needed
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50090793

http://stackoverflow.com/q/50161427
has title: YAML-serialized data for multiple config files with Jinja2
has body: I've already been able to load data from a YAML document into a configuration file. YAML: id: 1 x: key1 y: key2 Python script: #Import necessary functions from Jinja2 module from jinja2 import Environment, FileSystemLoader #Import YAML module import yaml import sys ALLOWED_ARGS = set(['template', 'data']) def print_usage(): print('Wrong arguments: Usage: configplate.py --template=&lt;template.jinja&gt; --data=&lt;data.yaml&gt;') def load_args(args): out = {} for arg in args: if arg == __file__: #ignore the filename argument continue args_splited = arg.split('=') out[args_splited[0].lstrip('-')] = args_splited[1] if set(out.keys()) != set(ALLOWED_ARGS): print_usage() raise ValueError('Required argument not present.') return out def make(template, data): #Load data from YAML into Python dictionary config_data = yaml.load(open(data)) #Load Jinja2 templates env = Environment(loader = FileSystemLoader('.'), trim_blocks=True, lstrip_blocks=True) template = env.get_template(template) #Render the template with data and print the output return template.render(config_data) if __name__ == '__main__': if len(sys.argv) != 3: print_usage() else: args = load_args(sys.argv) res = make(args['template'], args['data']) print(res) Config file: &lt;add name="Cloud" connectionString="{{ x }}" /&gt; The issue I'm facing now is that I can't load the same YAML to multiple config files. I have a second config file that I would like to fill at the same time. Config file 2: &lt;add name="Cloud" connectionString="{{ y }}" /&gt; How can I add this in the same python script? I also do not need to set the config files on the console, I can simply put their path into the script.
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50167669
score: 1
has answer: http://stackoverflow.com/a/50167669
tagged with: yaml
downvote count: 0
answer count: 1
tagged with: jinja2
tagged with: pyyaml
favorite count: 0
type: Question

http://stackoverflow.com/comment/87252294
type: Comment
type: QuestionComment
has text: @RiaRenold I think, you should: set execution permission of the current user and chromedriver.exe. In your path, I sow "C:\\Users\\Admin\\"
comment on: http://stackoverflow.com/q/50115238
score: 0

http://stackoverflow.com/q/50229634
linked to: http://stackoverflow.com/q/1951742
tagged with: command-line
has answer: http://stackoverflow.com/a/50230064
score: 0
tagged with: bash
answer count: 2
has answer: http://stackoverflow.com/a/50268086
upvote count: 1
linked to: http://stackoverflow.com/q/1522564
downvote count: 1
tagged with: shell
has body: I have been looking into bash and shell and have been trying to figure out how Git is able to run its C script in any directory. I have recently fiddled with environment variables, although this just redirects you to run a script in the location of that file, plus you have the $. How is Git able to integrate its scripts into the terminal? How would I be able to do the same with an arbitrary script in python? It is really hard to find any information without knowing the correct terminology although here's my attempt of mimicking such a command line system as git. I start with a command file in a folder in my home directory something.command Which on the inside directs me to a python script. e.g cd cd python_script_location python3 script.py Then I make this an environment variable through editing the .bash_profile. export pyinit=/Users/Charlkie/vcscmd/pyinit.command This although will just run a script in another directory. How can I make a terminal command that runs a python script in the current directory? Any help would be greatly appreciated :)
has comment: http://stackoverflow.com/comment/87476896
has title: How to run a python script through command line?
linked to: http://stackoverflow.com/q/50243373
tagged with: git
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87476568
duplicate of: http://stackoverflow.com/q/50243373
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50128665
possible better answer: http://stackoverflow.com/a/50157732
has body: I was working in azure ml for the past few days. I came up with a dataset which consists of date in the below format mm/dd/yyyy hh:mm:ss I want to extract month and year from it by writing python code in azure ml. I am trying the following code: def azureml_main(dataframe1 = None, dataframe2 = None): import pandas as pd dates = pd.to_datetime(dataframe1['Order Date']) dates = dates.apply(lambda x: x.strftime('%m-%d-%Y')) dataframe1['Order Date'] = dates # Execution logic goes here print('Input pandas.DataFrame #1:\r\n\r\n{0}'.format(dataframe1)) But I am getting an error saying that NTType there is no attribute with the name strftime. Can anyone tell me what's the issue here and how to solve it.
has answer: http://stackoverflow.com/a/50157732
type: Question
has title: How to extract month and year from given date in python in azure ml
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50128691
accepted answer: http://stackoverflow.com/a/50128691
score: 0
answer count: 2
tagged with: azure

http://stackoverflow.com/comment/87410530
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50196699
type: QuestionComment
has text: What is the problem? What is the expected output?

http://stackoverflow.com/q/50122873
has body: I'm running a Keras-based neural net on Windows. A lot of my parameters are large, and it causes issues with RAM and swapping. It'll cause my computer to slow down so much it's unusable, and won't finish running. Thing is, I don't care how long the program takes to run, I just want to run it once. I know resources works in Linux, but I don't know the equivalent in Windows.
favorite count: 0
type: Question
tagged with: anaconda
tagged with: windows
tagged with: ram
tagged with: python
has title: Limiting keras/ Anaconda's resources on Windows?
score: -1
has answer: http://stackoverflow.com/a/50130035
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: keras
downvote count: 1

http://stackoverflow.com/q/50183994
has comment: http://stackoverflow.com/comment/87385739
has answer: http://stackoverflow.com/a/50184218
accepted answer: http://stackoverflow.com/a/50184218
tagged with: python
has comment: http://stackoverflow.com/comment/87385670
tagged with: discord
has comment: http://stackoverflow.com/comment/87385475
type: AnsweredQuestion
has title: on_message won't detect any message
score: 1
has body: I am writing a discord bot with discord.py. I wrote an initial version but I decided it all needed reorganizing so I moved code to different files. The code is all the same as it was before but now when I boot up the bot, the bot detects no messages being sent in any server unless the message came from the bot itself. The main code that handles the client is: import discord import time from command_list import * from resource_functions import grab_setting_from_category print("Main initialized") client = discord.Client() token = "BOT TOKEN" prefix = "!" @client.event async def on_ready(): print("*** BOT IS READY ***") async def server_count_loop(): while True: servers = client.servers await client.change_presence( game=discord.Game(name=" in {0} Servers".format(str(len(servers))))) time.sleep(10) for server in client.servers: for channel in server.channels: if channel.name == "general": await client.send_message(channel, content="Bot Online") await server_count_loop() @client.event async def on_message(message): print("Message detected from {0} as '{1}'".format(message.author, message.content)) if not message.author.bot: global prefix prefix = grab_setting_from_category(message.server.id, "server", "prefix") if message.content.startswith(prefix): for i in range(0,len(commands)): key = list(commands.keys())[i] table = list(commands.values())[i] if message.content.startswith(prefix+key): table["function"](message, commands) client.run(token) In the code there's the print(...) at the start of the on_message function which I am using as a basic way to let me know if the bot is detecting messages. The print statement prints whenever the bot sends a message in on_ready but no messages from other users on Discord are triggering the function.
answer count: 1
has comment: http://stackoverflow.com/comment/87385543
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87385501
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87385516
has comment: http://stackoverflow.com/comment/87385771
tagged with: discord.py

http://stackoverflow.com/a/50145720
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87309548
has comment: http://stackoverflow.com/comment/87309589
score: 9
has body: You should adding np.inf bins =[-np.inf,1, 5, 10, 25, 50, 100, np.inf] df['Bins'] = pd.cut(df['Numbers'], bins,include_lowest =True) df Out[580]: Numbers Bins 0 0 (-inf, 1.0] 1 1 (-inf, 1.0] 2 2 (1.0, 5.0] 3 7 (5.0, 10.0] 4 11 (10.0, 25.0] 5 16 (10.0, 25.0] 6 45 (25.0, 50.0] 7 200 (100.0, inf]
upvote count: 9
answers question: http://stackoverflow.com/q/50145702
type: Answer
has comment: http://stackoverflow.com/comment/87309523
accepted answer of: http://stackoverflow.com/q/50145702
has comment: http://stackoverflow.com/comment/87309538
has comment: http://stackoverflow.com/comment/87309553

http://stackoverflow.com/comment/87406437
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50194604
has text: Please give the complete traceback, and also print out what `line` is when the error happens. And, even more importantly, provide some sample input that actually raises this exception, because yours doesn't. One obvious possibility is that your file has an empty line at the end, or something else without an `Rs.` in it, in which case you need to write code to handle that case.
score: 0

http://stackoverflow.com/q/50210634
has title: Calculating each row variance from csv file
upvote count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 5
has answer: http://stackoverflow.com/a/50210808
score: -5
answer count: 1
has body: I have file like that x 1 2 3 y 6 7 9 z 9 0 0 ı want to read that csv files then calculate the each row of variance with np.var() using with python then ı want to rank them. T Could you help me?
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87438252

http://stackoverflow.com/q/50229030
answer count: 0
has title: OpenCV in Fullscreen mode changes video aspect ratio
has comment: http://stackoverflow.com/comment/87477031
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87481151
tagged with: opencv
score: 3
has comment: http://stackoverflow.com/comment/87477846
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100111956
has comment: http://stackoverflow.com/comment/87480565
tagged with: python
upvote count: 4
tagged with: c++
has body: My video aspect ratio is 16:9 and my monitor is 16:10. I wrote this code for playing video in full screen mode but the problem is it causes my video to stretch. I want to keep its aspect ratio and have black bars on top and bottom (just like playing videos in KMPlayer) Is there any solution? Thanks import cv2 import numpy as np vid = cv2.VideoCapture('video.mp4') cv2.namedWindow('My Window',cv2.WINDOW_KEEPRATIO) cv2.setWindowProperty('My Window',cv2.WND_PROP_ASPECT_RATIO,cv2.WINDOW_KEEPRATIO) cv2.setWindowProperty('My Window',cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN) while vid.isOpened(): ret,frame = vid.read() cv2.imshow('My Window',frame) if cv2.waitKey(1) == ord('q'): break vid.release() cv2.destroyAllWindows()

http://stackoverflow.com/comment/130577209
comment on: http://stackoverflow.com/a/55943881
score: 0
type: Comment
type: AnswerComment
has text: OP should accept this answer as this is the actual correct one. The others are unnecessary work arounds.

http://stackoverflow.com/q/50107749
tagged with: python
has answer: http://stackoverflow.com/a/50108019
accepted answer: http://stackoverflow.com/a/50108019
has title: Keep prompting user for correct directory to file, store input in variable
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50107901
has comment: http://stackoverflow.com/comment/87233096
has comment: http://stackoverflow.com/comment/87232949
has comment: http://stackoverflow.com/comment/87233012
has comment: http://stackoverflow.com/comment/87232948
linked to: http://stackoverflow.com/q/9319317
has body: This is the beginning of my code that takes a dataset and plots it using matplotlib. However, I want to create a while loop that prompts the user to provide the correct path or directory to the file (e.g. /Users/Hello/Desktop/file.txt). While the user does not inputs a correct path, the loop should keep prompting for a directory. If there is indeed a file in that path, it should store this input in the variable path, which is later used to display the data. If there is no file, it should ask it again. It seems that my while loop is stuck at the first print statement.. import pandas as pd import matplotlib.pyplot as plt import numpy as np import itertools import os # This is the correct directory: os.path.isfile('/Users/Hello/Desktop/file.txt') """ Prompt the user for the right directory to the file. If the file is not there, ask again. If the path is correct, store it in the variable Path. """ correct = os.path.isfile(directory) directory = input("Please provide the correct directory to the dataset ") while os.path.isfile == False: if os.path.isfile(Directory) != True: directory = ath print('Thank you') elif os.path.isfile(Directory) == True: print("This directory does not exist, please try again.") #this variable inserts the users input and displays the data in the file dframe = pd.read_table(path, delim_whitespace=True, names=('X','Y'), dtype={'X': np.float64, 'Y':np.float64}) dframe.head(10) # show the first 10 rows of the data
type: Question
has comment: http://stackoverflow.com/comment/87232967
linked to: http://stackoverflow.com/q/23294658
possible better answer: http://stackoverflow.com/a/50107901
has comment: http://stackoverflow.com/comment/87242882

http://stackoverflow.com/comment/87296860
type: QuestionComment
comment on: http://stackoverflow.com/q/50139186
has text: Do `values()` and `values_list()` methods fit your requirements? Check doc here: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values
score: 1
type: Comment

http://stackoverflow.com/comment/87194615
type: Comment
comment on: http://stackoverflow.com/q/50089328
score: 2
type: QuestionComment
has text: You will probably get answers around splitting the string `'[ city is beautiful ]'` if that is all you show. Probably best to show a little more surrounding context so that potential answerers understand what kind of text needs to be matched vs. what is to be skipped.

http://stackoverflow.com/comment/87299889
score: 0
comment on: http://stackoverflow.com/a/50139123
type: Comment
type: AnswerComment
has text: Perhaps it's also due to the fact that there are a few NaN values in the columns 4 and 5.

http://stackoverflow.com/a/50184190
type: Answer
upvote count: 0
has body: You are resetting the value of done everytime you run the loop. Not only that - you're trying to change the value a global variable, but is instead changing the value of a simple parameter, so lol(done) isn't actually doing anything. If you want to keep it in a function, you should use the keyword global to indicate you're using the global variables: def lol(): global done global really_done done += 1 really_done = done == 10 really_done = False done = 0 while not really_done: lol() This should work, but it's bad code - you shouldn't use global if it's not a real need. Not changing much of your code, you could use return to keep your code cleaner: def lol(done, really_done): done += 1 really_done = done == 10 return done, really_done really_done = False done = 0 while not really_done: done, really_done = lol(done, really_done) That makes it a bit better. Yet, we could solve everything by simply looping a range with a for: done = 0 for n in range(10): done += 1 print(done)
downvote count: 2
score: -2
answers question: http://stackoverflow.com/q/50184053

http://stackoverflow.com/a/50136516
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50136290
upvote count: 2
downvote count: 0
has body: In python, a function that has no return statement always returns None. I guess what you are trying to do is calling the mys function, and not printing it. Note that you should remove x parameter, because it is asked inside of the function. def mys(): x = input("Enter a number: ") for i in range(2,x): r = x % i if r == 0: print(i) mys() It would be better not to include user input and printing in your function. It would make it easier to test and to reuse: def mys(x): result = [] for i in range(2,x): r = x % i if r == 0: result.append(i) return result x = input("Enter a number: ") print(mys(x))

http://stackoverflow.com/comment/87406750
comment on: http://stackoverflow.com/q/50194821
type: Comment
type: QuestionComment
score: 0
has text: Did you check that df.dtypes returns numerical type for the columns that create the issue? I know you say they are but it is worth double checking..

http://stackoverflow.com/a/50202890
has body: Just use product method from itertools package. a=[1,2,3] b=[4,5,6] c = list(itertools.product(a,b)) print(c) Output [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
has comment: http://stackoverflow.com/comment/87422721
has comment: http://stackoverflow.com/comment/87422628
type: Answer
accepted answer of: http://stackoverflow.com/q/50202870
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50202870
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50199606
has comment: http://stackoverflow.com/comment/87416006
type: Question
has comment: http://stackoverflow.com/comment/87415995
has comment: http://stackoverflow.com/comment/87415957
has comment: http://stackoverflow.com/comment/87415982
has title: how to solve sequence item 0: expected str instance, tuple found
has comment: http://stackoverflow.com/comment/87416168
tagged with: python
has body: Im trying to do some POS_Tagging using nltk (code below) and im running into the above issue when i try to write to a new file. if i run #fout.write("\n".join(tagged))this then it says the above error and totry and solve that when i run #fout.write(str.join(tagged)) this it says 'join' requires a 'str' object but received a 'list' The text file is locally stored and is relatively large from pathlib import Path from nltk.tokenize import word_tokenize as wt import nltk import pprint output_dir = Path ("\\Path\\") output_file = (output_dir / "Token2290newsML.txt") news_dir = Path("\\Path\\") news_file = (news_dir / "2290newsML.txt") tagged_dir = Path("\\Path\\") tagged_file = (tagged_dir / "tagged2290newsML.txt") file = open(news_file, "r") data = file.readlines() f = open(tagged_file, "w") def process_content(): try: for i in data: words = wt(i) pprint.pprint(words) tagged = nltk.pos_tag(words) pprint.pprint(tagged) #f.write("\n".join(tagged)) f.write(str.join(tagged)) except Exception as e: print(str(e)) process_content() file.close() Any help will be appreciated thanks :)
tagged with: nlp
accepted answer: http://stackoverflow.com/a/50199907
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50199907
has comment: http://stackoverflow.com/comment/87416033
has comment: http://stackoverflow.com/comment/87416993
answer count: 1
has comment: http://stackoverflow.com/comment/87415958

http://stackoverflow.com/q/50160827
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87340283
has body: I want to make GUI app that draws the graph when a button is pressed. I want to have an empty graph on tkinter window, and when you press the button named "Draw", the program should draw the graph. I made a window that shows the empty graph, and button for drawing, but when button is pressed, nothing happens, and I do not get any error. Can you help me with this? This is the code: from tkinter import * from tkinter import ttk import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.backend_bases import key_press_handler from matplotlib.figure import Figure myApp = Tk() myApp.title("Cost Analysis") myApp.geometry("1900x1000") X=[1,4,6,8,9] Y=[3,5,7,8,10] fprojektiTroskovi=Figure(figsize=(7, 4.5),dpi=83) GrafikProjektiTroskovi=fprojektiTroskovi.add_subplot(111) CanvasProjectsTroskovi=FigureCanvasTkAgg(fprojektiTroskovi, master=myApp) CanvasProjectsTroskovi.show() CanvasProjectsTroskovi.get_tk_widget().grid(row=30,column=0,sticky="wn",padx=5) toolbar_FrameProjektiTroskovi=Frame(myApp) toolbar_FrameProjektiTroskovi.grid(row=1,column=0,sticky="wn",padx=5) ToolbarProjectsTroskovi = NavigationToolbar2TkAgg(CanvasProjectsTroskovi,toolbar_FrameProjektiTroskovi) ToolbarProjectsTroskovi.update() CanvasProjectsTroskovi._tkcanvas.grid(row=0,column=0,sticky="wn",padx=5,pady=5) GrafikProjektiTroskovi.set_xlabel("Size") GrafikProjektiTroskovi.set_ylabel("Costs") GrafikProjektiTroskovi.set_title("All Projects (Size - Costs)") GrafikProjektiTroskovi.grid() def draw_graph(): GrafikProjektiTroskovi.plot(X, Y, color="blue",marker="o", linewidth=1, label="Planned Costs") GrafikProjektiTroskovi.legend() button=Button(myApp, text="Draw", command=draw_graph) button.grid(row=0,column=1) myApp.mainloop()
tagged with: matplotlib
score: 1
has title: Showing empty graph in tkinter until you click the button
favorite count: 0
has comment: http://stackoverflow.com/comment/87346853
type: Question
has comment: http://stackoverflow.com/comment/87340199
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87341154
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50194261
has answer: http://stackoverflow.com/a/50207260
downvote count: 0
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50194478
has answer: http://stackoverflow.com/a/50194319
tagged with: dictionary
answer count: 4
type: AnsweredQuestion
score: 15
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50194319
accepted answer: http://stackoverflow.com/a/50194296
has body: I have this dictionary: d = {'val_1': [1,2,3,4,5], 'val_2': 4} And I want to create a pandas DataFrame from this with only one row. When I do: import pandas as pd df = pd.DataFrame(d) print(df) I get 5 rows: val_1 val_2 0 1 4 1 2 4 2 3 4 3 4 4 4 5 4 However, when I append it to the existing dataframe, I get the behavior I want. import pandas as pd df = pd.DataFrame(d) df = df.append(d, ignore_index=True) print(df) val_1 val_2 0 1 4 1 2 4 2 3 4 3 4 4 4 5 4 5 [1, 2, 3, 4, 5] 4 How can I create the dataframe from the dict, and get only one row as in the append case? val_1 val_2 0 [1, 2, 3, 4, 5] 4
favorite count: 0
has answer: http://stackoverflow.com/a/50194296
has title: Pandas - Create dataframe with only one row from dictionary containing lists
type: Question
upvote count: 15

http://stackoverflow.com/comment/87249125
type: AnswerComment
has text: I tried your input. chromedriver.exe is already downloaded. and i have added the path in the environment variable . But still it did not work
score: 1
comment on: http://stackoverflow.com/a/50113663
type: Comment

http://stackoverflow.com/comment/87404540
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50193364
has text: @AntonvBR, yes it does matter. That's interesting, your solution seems to be approx. 2x faster compared to mine (for larger DFs)...
score: 0

http://stackoverflow.com/comment/87414199
has text: @kviatek It is about ordering the *list* of dictionaries, not the dictionaries themselves.
type: Comment
comment on: http://stackoverflow.com/a/50198641
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87279485
type: AnswerComment
score: 1
type: Comment
has text: Thanks Eyllanesc. In my case, I made the following change : self.ui.show()
comment on: http://stackoverflow.com/a/50128663

http://stackoverflow.com/comment/87261015
type: Comment
type: QuestionComment
score: 0
has text: I'm using Python 3.6.5. My hostname contains non-ASCII character. I've changed it. It works. Thanks.
comment on: http://stackoverflow.com/q/50121124

http://stackoverflow.com/comment/87398495
has text: @AlexHall - can you create an answer please.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50190682

http://stackoverflow.com/q/50100498
has body: I want to inspect a Tornado coroutine to see if it has certain keywords. Normally I would do this with the inspect module, and in particular inspect.signature, which works great. However in Python 2 (I have to support both) signature doesn't exist, so I'm looking for an alternative. The standard inspect.getargspec doesn't work as desired. In [1]: import inspect In [2]: import tornado.gen In [3]: class Foo(object): ...: def a(self, x, y=None): ...: pass ...: ...: @tornado.gen.coroutine ...: def b(self, x, y=None): ...: pass ...: In [4]: foo = Foo() In [5]: inspect.getargspec(foo.a) Out[5]: ArgSpec(args=['self', 'x', 'y'], varargs=None, keywords=None, defaults=(None,)) In [6]: inspect.getargspec(foo.b) Out[6]: ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None) In [7]: import sys; sys.version_info Out[7]: sys.version_info(major=2, minor=7, micro=14, releaselevel='final', serial=0) Is there a way, in Python 2, to answer questions like "does foo.b have a parameter named y?"
has comment: http://stackoverflow.com/comment/87331146
answer count: 1
accepted answer: http://stackoverflow.com/a/50183642
type: Question
has title: Determine keywords of a tornado coroutine
tagged with: python
linked to: http://stackoverflow.com/q/43506378
tagged with: tornado
tagged with: inspect
has answer: http://stackoverflow.com/a/50183642
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87215576
comment on: http://stackoverflow.com/q/50099365
score: 0
has text: MySQL follows these general date formats yyyy-mm-dd or yyyy/mm/dd not mm/dd/yyyy assuming the Date column is date datatype.. little demo http://sqlfiddle.com/#!9/96e79f
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87393817
comment on: http://stackoverflow.com/a/50171889
score: 0
has text: I am experimenting another problem, but very rarely: interpolation = interp1d(Xnew, Y, kind='quadratic') ValueError: Expect x to be a 1-D sorted array_like. I do not know why but it happens very rarely, but the Xnew are dates generated by appending new datetimes that are for sure ordered
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/124377901
has text: okay, it is well known but line termination doesn't matter with xml files.
type: AnswerComment
comment on: http://stackoverflow.com/a/50203787
score: 0
type: Comment

http://stackoverflow.com/q/50121952
type: Question
has title: Why do I get two windows when using wxPython?
has comment: http://stackoverflow.com/comment/87267484
type: UnansweredQuestion
has body: I wrote a hello world wxpython application but I notice when I run it I get two windows rendering. See the screenshot with the window and the code. Why is this happening?
has comment: http://stackoverflow.com/comment/87277085
tagged with: python
has answer: http://stackoverflow.com/a/55592448
downvote count: 0
answer count: 1
tagged with: wxpython
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87261902
has comment: http://stackoverflow.com/comment/87305961
favorite count: 0

http://stackoverflow.com/comment/87342788
comment on: http://stackoverflow.com/q/50162459
score: 1
type: Comment
type: QuestionComment
has text: What is `time`?

http://stackoverflow.com/a/50137464
score: 0
has body: This error message... selenium.common.exceptions.ElementNotVisibleException: Message: element not visible ...implies that the Locator Strategy you have adapted doesn't identifies any unique WebElement on the webpage. However there are a couple of issues including the version compatibility between the binaries you are using as follows : You are using chromedriver=2.35 Release Notes of chromedriver=2.35 clearly mentions the following : Supports Chrome v62-64 You are using chrome=66.0 Release Notes of ChromeDriver v2.38 clearly mentions the following : Supports Chrome v65-67 So there is a clear mismatch between the ChromeDriver version (v2.35) and the Chrome Browser version (v66.0) Solution Upgrade Selenium to current levels Version 3.11.0. Upgrade ChromeDriver to current ChromeDriver v2.38 level. Keep Chrome version at Chrome v66.x levels. (as per ChromeDriver v2.38 release notes) Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only. Use CCleaner tool to wipe off all the OS chores before and after the execution of your test Suite. If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client. Take a System Reboot. As you are seeing ElementNotVisibleException you need to induce WebDriverWait for the WebElement to be clickable as follows : from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC # other code WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//form[@data-abide='ajax']//input[@ng-model='UserPhoneNew']"))).send_keys("08100000000") Execute your @Test. Note : Here you will find a detailed discussion on ElementNotVisibleException : Selenium Python
type: Answer
answers question: http://stackoverflow.com/q/50135960

http://stackoverflow.com/a/50092697
has body: The issue is that firstly you strip the lines and throw away the stripped value. strings are immutable, that means they cant be changed. So i.strip('\n') is useless. It should be assigned to a variable. i2 = i.strip('\n') Also you are not using your the lists you built in the zip function call, you are zipping the files lines. These still have newline characters. Changed code. def user1(): file = open('password.txt') passwords = file.readlines() g=[] for i in passwords: g.append(i.strip('\n')) rfile = open('user.txt') users = rfile.readlines() r = [] for i in users: r.append(i.strip('\n')) dictionaries = dict(zip(g, r)) print(dictionaries) user1() The key things are that , we stash the stripped strings in the lists r.append(i.strip('\n')) and also use the lists in the zip dictionaries = dict(zip(g, r)) You should also watch that you have not closed your files. To this use with, instead of manually calling close later. This is safer as an exception, in the intervening code would mean the close was not called. As far as an example of this. with open('password.txt') as file: passwords = file.readlines() Note that the lifetime of the file is controlled by the scope of the with, any code within that block has access to an open file. After the block it is closed. If you wish to have each entry print on a separate line, don't try to rely on the newlines already in the file. Iterate over the dict and print each entry on a new line. for name, pwd in dictionaries.items(): print('{}: {}'.format(name, pwd)) Of course, you can express this in much less code and without copying the lines to intermediate lists. with open('user.txt') as fuser, open('password.txt') as fpass: def stripped(f): return map(str.strip, f) d = dict(zip(stripped(fuser), stripped(fpass))) for name, pwd in d.items(): print('{}: {}'.format(name, pwd))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50092618

http://stackoverflow.com/comment/87470947
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50226654
score: 1
has text: Thanks for the reply. But converting the sparse to numpy ndarray will give MemoryError, I guess the size is simply too big (the case I'm testing atm is 185600x185600, and it could be larger).

http://stackoverflow.com/q/50226701
type: Question
has comment: http://stackoverflow.com/comment/87470961
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/87470926
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87471103
accepted answer: http://stackoverflow.com/a/50227041
tagged with: valueerror
has answer: http://stackoverflow.com/a/50227041
has body: I have a function, that parses string and takes values by using indexes. When I try to take the exact variable and convert it into integer, it gives me a ValueError. The exact code part is: y = special_string[y_start:y_end] print(y) y = int(y) Traceback for it: 14 Traceback (most recent call last): File "levelBuilder.py", line 255, in &lt;module&gt; newLevel, rows, columns = importLevel(levelName) File "levelBuilder.py", line 124, in importLevel y = int(y) ValueError: invalid literal for int() with base 10: '' The question is - what can cause this error? As you see, y is integer (14). When I use the same method for another variable (x), it works correctly
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87470806
answer count: 1
has comment: http://stackoverflow.com/comment/87470728
has title: Function returns invalid literal for int() with base 10: ''
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/50207740
upvote count: 1
answers question: http://stackoverflow.com/q/50207640
downvote count: 0
type: Answer
score: 1
has body: You are printing the class object, not return value of the method (see last line here). Possible indentation issue for __str__() method fixed, too. class Person: age = 0 name = '' def __init__(self,personAge,personName): self.age = personAge self.name= personName def __str__(self): return self.name d = Person(24,'ram') print(d.__str__()) See also PEP 8 for naming conventions.

http://stackoverflow.com/comment/87279295
score: 1
type: Comment
has text: Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables)
type: QuestionComment
comment on: http://stackoverflow.com/q/50130759

http://stackoverflow.com/comment/87300631
type: QuestionComment
type: Comment
has text: However, if `Fibonacii` is *outputing* each number, rather than returning a list, you don't need to print the (irrelevant) return value.
comment on: http://stackoverflow.com/q/50141123
score: 0

http://stackoverflow.com/q/50208943
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50214583
tagged with: numpy
answer count: 2
score: 1
tagged with: html5lib
downvote count: 0
has comment: http://stackoverflow.com/comment/87434903
upvote count: 1
tagged with: tensorflow
has body: tensorflow 1.7.0 has requirement numpy&gt;=1.13.3, but you'll have numpy 1.11.0 which is incompatible. tensorboard 1.7.0 has requirement html5lib==0.9999999, but you'll have html5lib 0.999 which is incompatible. tensorboard 1.7.0 has requirement numpy&gt;=1.12.0, but you'll have numpy 1.11.0 which is incompatible. Please refer to this screenshot Why are these messages showing up...even though I have the proper versions installed??I have upgraded and reinstalled them over and over. I also reinstalled pip and also tried easy install for pip. But the problem persists. Could something be wrong with my OS installation? (Ubuntu 16.4) These are some results I got by running pip freeze tensorboard==1.8.0 tensorflow==1.8.0 numpy==1.14.3 html5lib==0.9999999 httplib2==0.9.1
has answer: http://stackoverflow.com/a/50454218
favorite count: 0
type: Question
has title: incompatible numpy and html5lib for tensorflow

http://stackoverflow.com/comment/87224941
has text: I also left out the distinct and tried to let it running without, the error remains the same, I get an ObjectNotExecutableError. I tried to get it printed, but `print(str(stmt))` returns another error: ` 'str' object has no attribute '_compiler_dispatch'`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50103662

http://stackoverflow.com/q/50138219
has comment: http://stackoverflow.com/comment/87303699
type: Question
has comment: http://stackoverflow.com/comment/87296266
answer count: 2
tagged with: mocking
possible better answer: http://stackoverflow.com/a/50147402
upvote count: 3
has comment: http://stackoverflow.com/comment/87296330
has answer: http://stackoverflow.com/a/50147402
downvote count: 0
tagged with: python
tagged with: unit-testing
favorite count: 0
has title: Mock Class with original spec Python
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/50145136
tagged with: python-unittest
has answer: http://stackoverflow.com/a/50145136
has comment: http://stackoverflow.com/comment/87294825
has body: I am trying to mock a class in Python using the Mock package, specifically, using the patch decorator in the test class. from unittest import TestCase from unittest.mock import Mock, patch @patch("mypackage.subpackage.mymodule", autospec=True) class MyClassTest(TestCase): def setUp(self): [...] def test_with_boundary_creates_job_flow_task(self): returned_value = self.some_class.return_something_from_my_module() self.assertIsInstance(returned_value, expected_value_class) I would like my mock to have the original behavior of the class being mocked, i.e. unless I specifically mock an attribute/method, it should behave as in the provided class (with its logic &amp; return value). Thus, when testing a not mocked method but existing method in the original class, test should run successfully rather than failing with following (specific) error: AssertionError: &lt;class 'unittest.mock.MagicMock'&gt; is not an instance of &lt;class 'airflow.contrib.operators.emr_create_job_flow_operator.EmrCreateJobFlowOperator'&gt; Any ideas about how to achieve this?
has comment: http://stackoverflow.com/comment/87295080

http://stackoverflow.com/q/50192386
has comment: http://stackoverflow.com/comment/87401719
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/87404848
has comment: http://stackoverflow.com/comment/87401813
answer count: 0
score: 1
has title: KeyError: 1744843431 when loading a pickle file
downvote count: 0
upvote count: 1
has body: so I was trying to load the pickled file like I used to do using set_x = pickle.load(open('retaindata/h50_cl2_all.visits.train', 'rb'), encoding='bytes') But somehow it gives me an error that I couldn't find a solution to on google: error msg Can someone help and let me know what went wrong?
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/50090369
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50090356
has comment: http://stackoverflow.com/comment/87197224
has comment: http://stackoverflow.com/comment/87197283
has body: You probably want to print leng not len. len is the builtin function. def infolist(alist): maxi=max(alist) mini=min(alist) leng=len(alist) print(maxi,mini,leng) thelist=(23,33,1,7) print(thelist) infolist(thelist) print(thelist)
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87197253
has comment: http://stackoverflow.com/comment/87197323
score: 1
answers question: http://stackoverflow.com/q/50090356
type: AcceptedAnswer

http://stackoverflow.com/a/50152869
upvote count: 13
has comment: http://stackoverflow.com/comment/87325702
type: AcceptedAnswer
downvote count: 0
score: 13
has body: You have to adapt the fixture scope to cache its results for all tests in test run (scope='session'), all tests in module (scope='module'), all tests in class (old unittest-style tests only, scope='class'), or for a single test (scope='function'; this the default one). Examples: fixture function @pytest.fixture(scope='session') def token(): return token_helper.get_api_access_token() class Tests(object): def test_one(self, token): ... def test_two(self, token): ... class OtherTests(object): def test_one(self, token): ... The token will be calculated once when first requested and kept in cache throughout the whole test run, so all three tests Tests::test_one, Tests::test_two and OtherTests::test_one will share the same token value. fixture class method If you intend to write old-style test classes instead of test functions and want the fixture to be a class method (like it is in your code), note that you can only use the class scope, so that the fixture value is shared only between the tests in the class: class TestStuff(object): @pytest.fixture(scope='class') def token(self): return token_helper.get_api_access_token() def test_one(self, token): ... def test_two(self, token): ... Stuff aside: pytest.yield_fixture is deprecated and replaced by pytest.fixture; you don't need to set autouse=True because you explicitly request the fixture in the test parameters. It will be called anyway.
accepted answer of: http://stackoverflow.com/q/50151189
answers question: http://stackoverflow.com/q/50151189
type: Answer

http://stackoverflow.com/comment/87193426
comment on: http://stackoverflow.com/q/50088734
type: QuestionComment
type: Comment
score: 0
has text: What is it that your dictionary is representing? This isn't going to be fast, so if you can use another data structure that might help. You could also look into using a database instead.

http://stackoverflow.com/q/50114689
tagged with: sockets
downvote count: 0
tagged with: python
answer count: 0
score: 1
has title: Socket connection using Python is getting "actively refused"
has comment: http://stackoverflow.com/comment/87248630
has comment: http://stackoverflow.com/comment/87249208
upvote count: 1
has body: I am trying to utilize Socket connections to send data from my python script (Python 3.6.3) in PyCharm to my C# script in Unity3D. Something very similar to: https://www.youtube.com/watch?v=eI3YRluluR4 Following the documentation, the below script should work well Python script: import socket host, port = "127.0.0.1", 25001 data = "hello" # SOCK_STREAM means a TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Connect to server and send data sock.connect((host, port)) sock.sendall(data.encode("utf-8")) data = sock.recv(1024).decode("utf-8") print(data) finally: sock.close() C# script: using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using UnityEngine; using System.Threading; public class networkCon : MonoBehaviour { Thread mThread; public string connectionIP = "127.0.0.1"; public int connectionPort = 25001; IPAddress localAdd; TcpListener listener; TcpClient client; Vector3 pos = Vector3.zero; bool running; private void Start() { ThreadStart ts = new ThreadStart(GetInfo); mThread = new Thread(ts); mThread.Start(); } public static string GetLocalIPAddress() { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); } } throw new System.Exception("No network adapters with an IPv4 address in the system!"); } void GetInfo() { localAdd = IPAddress.Parse(connectionIP); listener = new TcpListener(IPAddress.Any, connectionPort); listener.Start(); client = listener.AcceptTcpClient(); running = true; while (running) { Connection(); } listener.Stop(); } void Connection() { NetworkStream nwStream = client.GetStream(); byte[] buffer = new byte[client.ReceiveBufferSize]; int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead); if (dataReceived != null) { if (dataReceived == "stop") { running = false; …
favorite count: 0
type: Question
tagged with: unity-game-engine
has comment: http://stackoverflow.com/comment/87248432
has comment: http://stackoverflow.com/comment/87248820
tagged with: c#
has comment: http://stackoverflow.com/comment/87248688
linked to: http://stackoverflow.com/q/28346177
has comment: http://stackoverflow.com/comment/87249328
has comment: http://stackoverflow.com/comment/87248662
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87249267
has comment: http://stackoverflow.com/comment/87249130

http://stackoverflow.com/comment/87309523
comment on: http://stackoverflow.com/a/50145720
type: AnswerComment
has text: Hmm, seems like the question is a dupe. Best thing to do would be to delete the answer, what do you think?
score: 0
type: Comment

http://stackoverflow.com/q/50095640
upvote count: 1
favorite count: 0
score: 1
tagged with: python
tagged with: gitlab
has body: I have been working with python-gitlab package and I have a problem to create submodules. Does anyone knows a way to create a submodule which connects to another project or alternative way to make a link inside a git tree which reference to another project? Thanks.
has title: python-gitlab create submodule
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/87219260
type: QuestionComment
comment on: http://stackoverflow.com/q/50101119
score: 0
type: Comment
has text: You want to align the tandem repeats?

http://stackoverflow.com/a/50140915
has comment: http://stackoverflow.com/comment/87345372
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87345673
has body: I rewrote your code trying to solve your problem because i did not understand the need for limit_denominator. This is the result: from fractions import * x = Fraction(1, 2) for i in range(1000): y = 1 + Fraction(x) print 'Y', y x = 1 / (2 + x) print 'X', x The problem is that computers don't really understand numbers, instead they work with an abstract representation of numbers in memory called floating point (the origin of float i assume). This representation has a given precision (limit) which depends on the amount of memory reserved for the data type. That is why int32 has fewer accepted values than int64 for example. However, python has a smart and efficient way of calculating large numbers. Besides, the fractions library provides you with a way of representing numbers (fractions) that escape (not really, after all it is a computer) the floating point numbers constraint. If you want to dive more into floating point arithmetic I recommend the all-mighty Numerical Analysis by Burden &amp; Faires and Numerical Methods by Dr David Ham.
answers question: http://stackoverflow.com/q/50140323
has comment: http://stackoverflow.com/comment/87300487
has comment: http://stackoverflow.com/comment/87345258
score: 1
type: Answer

http://stackoverflow.com/a/50222006
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Let ser = test.loc[1]. You can convert this series to a dictionary with .to_dict(), Then convert the dictionary into a list of key/value tuples with .items(), Then merge the tuples into one list with itertools.chain, and finally Join the list items with periods with .join(). Python code: from itertools import chain '.'.join(chain.from_iterable(ser.to_dict().items())) #'outlook.sunny.temperature.mild.humidity.normal....yes'
type: Answer
accepted answer of: http://stackoverflow.com/q/50221920
answers question: http://stackoverflow.com/q/50221920

http://stackoverflow.com/a/50406755
score: 0
has body: There is a pickle file in the dataset i.e a dictionary containing the url for the dataset images. I am able to view it using pandas by using this code. import pickle as pkl import pandas as pd if __name__ == '__main__': pkl.HIGHEST_PROTOCOL = 2 df = pd.read_pickle(r"/home/samuel/dataset/eye-closed/dataset_B_FacialImages/train.pkl") print(df) Which gives the following output 1896 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1897 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 1 1898 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1899 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 1 1900 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1901 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1902 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1903 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1904 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 1 1905 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 1 1906 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1907 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 1908 /home/mtk/dataset/eye-closed/dataset_B_FacialI... 0 [1909 rows x 2 columns] i want to change this pickle file so that the name /home/mtk/... is changed to /home/samuel/... What should I do?
type: Answer
answers question: http://stackoverflow.com/q/50113684

http://stackoverflow.com/comment/87441638
type: QuestionComment
score: 0
has text: It prints `True` because 'hello' is in your list. It will likely read `False` because `row` is a list.
type: Comment
comment on: http://stackoverflow.com/q/50212253

http://stackoverflow.com/a/50218501
has body: threading.enumerate gives you the list of all running threads including the main one, so you could do this: main_thread = threading.main_thread() while True: L = threading.enumerate() L.remove(main_thread) # or avoid it in the for loop for t in L: t.join() The while True is needed in case your library creates new threads while you wait for the current ones to finish. Assuming that no threads are created while enumerate is running, you can check if L has only one element (the main thread) and if so, break the loop. This combined with Tadhg McDonald-Jensen's suggestion of using iter with a sentinel, results in: main_thread = threading.main_thread() main_threads = [main_thread, ] # WARN: can't have more than one thread here for threads in iter(threading.enumerate, main_threads): for t in threads: if t == main_thread: continue t.join() enumerate returns a list in undefined order, so if you have more than one "main" thread, order starts to matter. A solution would be to use sets, i.e. main_threads = {main_thread, } and iter(lambda : set(threading.enumerate()), main_threads). If you prefer the EAFP approach of asking for forgiveness instead of permission and all your threads are started when you reach the end of your script, you can also do this: for thread in threading.enumerate(): try: thread.join() except RuntimeError: # trying to join the main thread, which would create a deadlock (see https://docs.python.org/3/library/threading.html#threading.Thread.join for details) pass
has comment: http://stackoverflow.com/comment/135590750
accepted answer of: http://stackoverflow.com/q/50216918
downvote count: 0
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/87488444
upvote count: 6
answers question: http://stackoverflow.com/q/50216918
has comment: http://stackoverflow.com/comment/87498746
has comment: http://stackoverflow.com/comment/87495887
type: AcceptedAnswer

http://stackoverflow.com/comment/87211025
type: AnswerComment
has text: That explains it very nicely! Thank you! Do you also have an idea how I could achieve my expected behavior? Just do a subset (slice) before I use `np.gradient`? Like `np.gradient(x[1:-1])` and then put that back into the original array? But that will not work for the interior points...
comment on: http://stackoverflow.com/a/50090421
score: 1
type: Comment

http://stackoverflow.com/a/50184334
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50184303
has body: Regex would be overkill in my opinion. You can use a for loop to iterate through the list. Then using the in operator you can check if an entered string is within the string (called a substring). I'll give a simple example. names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford'] substring = input('Enter a substring: ') for name in names: if (substring in name): print(name) Since you say you are new to python I refrained from using list comprehensions or anything complicated.
answers question: http://stackoverflow.com/q/50184303
upvote count: 2
type: Answer
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/50166308
has comment: http://stackoverflow.com/comment/87350663
has answer: http://stackoverflow.com/a/50166377
answer count: 2
downvote count: 0
has title: Python JSON data load perplexing "expecting , delimiter" error
has comment: http://stackoverflow.com/comment/87350616
has answer: http://stackoverflow.com/a/50166419
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87350621
has comment: http://stackoverflow.com/comment/87350590
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/87350580
tagged with: delimiter
has body: Trying to implement this code and keep getting the following error. I have searched and tried everything and nothing gets me past it. import json import sys import re import os reload(sys) sys.setdefaultencoding('utf8') path = '/Users/.../' #(The actual path is in my code) textfiles = [] for root, dirs, files in os.walk(r'/Users/.../'): for file in files: if file.endswith(".txt"): textfiles.append(file) for filename in textfiles: with open(path + filename) as json_data: data = json.load(json_data) opinion = data['plain_text'] f = open(path + filename, 'w') f.write(opinion) f.close() Then, I keep getting this error: ValueError: Expecting , delimiter: line 17 column 3 (char 765)

http://stackoverflow.com/comment/101922381
has text: I found out that I had to run that software through Docker, then it worked. The setup is still invalid in my case, but otherwise the problem reported here is not happening.
comment on: http://stackoverflow.com/a/50117550
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87231210
type: AnswerComment
comment on: http://stackoverflow.com/a/50106927
score: 0
type: Comment
has text: ah i see, i wonder where i made the mistake of making django generate the mismatching code between versions, i would think the default generated code would be correct

http://stackoverflow.com/a/50078402
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50078374
upvote count: 2
downvote count: 0
type: Answer
has body: Using Regex: Ex: import re import ast big_str = "[41.386263640000003, -81.494450689999994] 6 2011-08-28 19:02:28 yay. little league world series!\n[42.531041999999999, -82.90854831] 6 2011-08-28 19:02:29 i'm at holiday inn express suites &amp; hotel roseville mi (31900 little mack ave., at masonic blvd., roseville)\n[39.992309570000003, -75.131119729999995] 6 2011-08-28 19:02:29 @_tweetthis what dorm r you in?\n[54.104106119999997, 28.336019929999999] 6 2011-08-28 19:02:29 @andykozik круто !!!\n[25.787949600000001, -80.132949600000003] 5 2011-09-03 05:40:14 pizza rustica #ftw" res = [] for i in re.findall(r'\[.*?\]', big_str): res.extend(ast.literal_eval(i)) print(res) Output: [41.38626364, -81.49445069, 42.531042, -82.90854831, 39.99230957, -75.13111973, 54.10410612, 28.33601993, 25.7879496, -80.1329496]
has comment: http://stackoverflow.com/comment/87173462
score: 2
accepted answer of: http://stackoverflow.com/q/50078374
has comment: http://stackoverflow.com/comment/87172879

http://stackoverflow.com/a/50103743
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50103295
has body: Unless I'm mistaken, I think you're over complicating this a bit, you should just need to take the diff: df = pd.read_fwf(StringIO( '''timestamp price 2018-04-29 13:14:43.026 6394.0 2018-04-29 13:16:53.714 6378.0 2018-04-29 13:17:01.324 6378.0 2018-04-29 13:17:02.246 6378.0 2018-04-29 13:17:07.413 6384.0 2018-04-29 13:17:08.331 6380.0 2018-04-29 13:17:11.437 6380.0 2018-04-29 13:17:11.895 6377.0 2018-04-29 13:17:13.449 6377.0 2018-04-29 13:17:13.452 6379.0''' ), colspecs=[(0,23), (25, 31)], dtype={ 'timestamp': 'datetime64[ns]', 'price': 'float' }) diff = df.diff() selection = (diff['timestamp'].dt.seconds &lt;=1) &amp; (diff['price'] == 0) selection = selection | selection.shift(periods=-1) print(df[selection]) Output timestamp price 2 2018-04-29 13:17:01.324 6378.0 3 2018-04-29 13:17:02.246 6378.0 7 2018-04-29 13:17:11.895 6377.0 8 2018-04-29 13:17:13.449 6377.0
has comment: http://stackoverflow.com/comment/87225895
type: Answer

http://stackoverflow.com/comment/87346026
has text: Mmmh I'm not too sure, in the timing process, do you take the time needed to pass data from python to C/C++ and back ? Could you maybe share the code ?
type: Comment
comment on: http://stackoverflow.com/a/50098112
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87225135
has text: Can you provide test data ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50103656

export
tags question: http://stackoverflow.com/q/50202415
type: Tag
tag name: export

http://stackoverflow.com/q/50222689
upvote count: 2
has answer: http://stackoverflow.com/a/50222997
accepted answer: http://stackoverflow.com/a/50222997
answer count: 1
downvote count: 0
tagged with: scroll
has title: Scroll content of a TreeView in PyGObject without scrolling the headers
has body: I want to scroll the content of a Gtk.TreeView. This means the rows but not the header. So using a Gtk.ScrolledWindow will not help here because this would scroll the complete widget. I found Gtk.Adjustment but don't know how to use it. This is what I tried so far #!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class TreeView(Gtk.TreeView): def __init__(self): # model self.model = Gtk.ListStore.new([int]) for i in range(30): self.model.append([i]) # view Gtk.TreeView.__init__(self, self.model) col_a = Gtk.TreeViewColumn('int', Gtk.CellRendererText(), text=0) self.append_column(col_a) # "adjustment" ??? self.adj = Gtk.Adjustment() self.set_vadjustment(self.adj) class Window(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title='Mein Gtk-Fenster') self.set_default_size(100, 120) self.view = TreeView() # layout self.layout = Gtk.Grid() self.add(self.layout) self.layout.attach(self.view, 0, 1, 1, 1) self.connect('destroy', Gtk.main_quit) self.show_all() if __name__ == '__main__': win = Window() Gtk.main()
type: AnsweredQuestion
tagged with: pygobject
tagged with: python
favorite count: 0
type: Question
score: 2
tagged with: python-3.x

http://stackoverflow.com/comment/87395584
score: 0
type: AnswerComment
has text: It ooks nice :) But.. I am getting a error in this line new['true_move'] = [i for i in range(-max_move, max_move + 1)]
comment on: http://stackoverflow.com/a/50189123
type: Comment

http://stackoverflow.com/q/50189248
score: 0
has comment: http://stackoverflow.com/comment/87543805
has body: I have a dictionary named "enron_data". In the dictionary, each key has a variable named "poi". I would like to count how many of the keys have poi=1. Like enron_data[person_name]["poi"]==1. Dictionary keys are some names and there are 146 names. I want to count how many of them have poi variable equal to one. Thank a lot.
linked to: http://stackoverflow.com/q/3294889
has comment: http://stackoverflow.com/comment/87395385
has comment: http://stackoverflow.com/comment/87395393
accepted answer: http://stackoverflow.com/a/50189304
type: Question
has title: How to count how many times a dictionary element takes a specific value
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50189304
type: AnsweredQuestion

http://stackoverflow.com/q/50218050
tagged with: nuke
type: UnansweredQuestion
downvote count: 0
upvote count: 1
score: 1
has body: I would like to assign a shortcut to a function for nuke menu in The Foundry NUKE. So far I'm doing it like this: nuke.menu('Nuke').addCommand('customTools/do_this', 'do_This.doThis()', 'alt+u') I would like to skip all the nuke.menu part and just assign alt+u shortcut to do_This.doThis(). Thanks a lot for the help.
answer count: 1
has title: Assign a shortcut to a function without creating a menu item
tagged with: python
has answer: http://stackoverflow.com/a/50272859
favorite count: 0
type: Question

http://stackoverflow.com/comment/87329709
has text: does your cassandra work as a systemd service?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50133234

http://stackoverflow.com/q/50191062
upvote count: 2
has title: Pandas Comparing hourly multiple year data in one plot
answer count: 1
has body: So I have a pandas dataframe, called year, on this form: discharge (m^3/s) date 2016-01-01 00:00:00 17.6930 2016-01-01 01:00:00 17.3247 2016-01-01 02:00:00 17.2436 2016-01-01 03:00:00 17.5696 2016-01-01 04:00:00 16.4074 2016-01-01 05:00:00 17.5696 2016-01-01 06:00:00 17.0420 .... 2017-12-31 20:00:00 10.5911 2017-12-31 21:00:00 10.5620 2017-12-31 22:00:00 10.7374 2017-12-31 23:00:00 10.5620 The dataset contains discharge data for several years and I want to do a plot comparing f.ex. the month of january for the years 2016 and 2017. My attempts thus far has been to extract the wanted months and just plotting them on top of each other. But this does not work as you can see in this picture: Attempt plot 1 My code for this was: # Comparison full months def plotmonthdischarge(month, years, number_of_years): df = pd.read_csv('resources\FinVannføringEidsfjordvatn.csv', encoding = 'ISO-8859-1',sep=';') df['date'] = pd.to_datetime(df['date'],dayfirst=True) df = df.set_index(df['date']) df['Day Of Year'] = df['date'].dt.dayofyear df = df.drop(['date'], axis = 1) df = df.replace(to_replace='-9999', value = np.NaN) fig, ax = plt.subplots() # For a starting year 2016 and a 1 following year # Call example: # plotmonthdischarge(1,[2016],2) if len(years) == 1: start_year = years[0] for i in range(number_of_years): year = df['{0}-{1}-01 00:00:00'.format(start_year+i,month):'{0}-{1}-31 23:59:59'.format(start_year+i,month)] ax.plot(year['discharge (m^3/s)'], label = 'Year {}'.format(start_year+i)) # Just for plotting(ignore) formatted_list = ['{:&gt;3}' for i in range(number_of_years)] string_of_years = ', '.join(formatted_list).format(*[start_year+i for i in range(number_of_years)]) plt.title('Comparison plot of years {}'.format(string_of_years)) # Specific years 2006 and 2017 # Call example: # plotmonthdischarge(1,[2006,2017],1) if len(years) &gt; 1: number_of_years = 1 for item in years: year = df['{0}-{1}-01 00:00:00'.format(item,month):'{0}-{1}-31 23:59:59'.format(item,month)] ax.…
downvote count: 0
type: AnsweredQuestion
score: 2
tagged with: pandas
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/50191330
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50191330

http://stackoverflow.com/comment/87202750
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50093297
has text: Is the script running or PyCharm loses library path? Is "Preferences>Python Interpreter" the one you desire? You may force PyCharm to reindex libraries by switching interpreter version.
score: 0

http://stackoverflow.com/q/50160676
answer count: 2
accepted answer: http://stackoverflow.com/a/50165412
score: 1
possible better answer: http://stackoverflow.com/a/50161995
has answer: http://stackoverflow.com/a/50165412
has comment: http://stackoverflow.com/comment/87342286
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50161995
favorite count: 0
type: Question
has body: I have 400 folders. Within each folder, there are 3 additional folders I have to drill into and then in the last folder I have 22 different files. Each of these 400 folders have the same named files. Ultimately, I want to create 22 folders, one for each file name and within each of the 22 folders I want only files that have the same name. Since a folder cannot have two files with the same name, adding the final 6 characters of the file path to the file name solves the issue. Using the image below as an example of the files: I need an ACO folder with 400 files all of which are labeled i.e., "ACO050168", "ACO150074", "ACO150128" I need an BDUAL folder with 400 files all of which are labeled BDUAL i.e., "BDUAL050168", "BDUAL150074", "BDUAL150128" etc.. Here are file paths for example, notice that the final folder and the 4th from the last folder are unique 'C:\\Users\\MBobak\\Documents\\Loop\\Raw Claims Data 050168\\D#CJR\\Y2018M02\\P050168', 'C:\\Users\\MBobak\\Documents\\Loop\\Raw Claims Data 150074\\D#CJR\\Y2018M02\\P150074', 'C:\\Users\\MBobak\\Documents\\Loop\\Raw Claims Data 150128\\D#CJR\\Y2018M02\\P150128' The 22 files within each folder are structured as .csv but do not have the .csv extension. They are just files. I attached an image to show what it looks like. I know there are ways to do this in the command-line, but I can't find a specific example of this question since there are drills downs from each initial folder. I attempted to do this in python, and I wrote a small script in python to find the final directories that hold the 22 files: all_files_dir = r'C:\Users\MBobak\Documents\Loop' folders = os.listdir(all_files_dir) ccn_list = [x[-6:] for x in folders] ccn_file_dir = [r'C:\Users\MBobak\Documents\Loop\Raw Claims Data ' + x + '\D#CJR\Y2018M02\P' + x for x in ccn_list] But now I am having trouble copying/moving these into new folders.
has comment: http://stackoverflow.com/comment/87342236
tagged with: python
tagged with: copy
has title: How to combine similar named files from multiple folders into one folder for each file name
tagged with: command-line
type: AnsweredQuestion

docker
tags question: http://stackoverflow.com/q/50114065
tags question: http://stackoverflow.com/q/50134704
tags question: http://stackoverflow.com/q/50171834
tags question: http://stackoverflow.com/q/50126523
tag name: docker
type: Tag
tags question: http://stackoverflow.com/q/50227736
tags question: http://stackoverflow.com/q/50130234
tags question: http://stackoverflow.com/q/50184873
tags question: http://stackoverflow.com/q/50106240
tags question: http://stackoverflow.com/q/50190676
tags question: http://stackoverflow.com/q/50077958
tags question: http://stackoverflow.com/q/50087103
tags question: http://stackoverflow.com/q/50179326
tags question: http://stackoverflow.com/q/50229873
tags question: http://stackoverflow.com/q/50127140
tags question: http://stackoverflow.com/q/50088685
tags question: http://stackoverflow.com/q/50084539
tags question: http://stackoverflow.com/q/50203849
tags question: http://stackoverflow.com/q/50203275
tags question: http://stackoverflow.com/q/50191768
tags question: http://stackoverflow.com/q/50176905
tags question: http://stackoverflow.com/q/50082719
tags question: http://stackoverflow.com/q/50207974
tags question: http://stackoverflow.com/q/50136318
tags question: http://stackoverflow.com/q/50091895
tags question: http://stackoverflow.com/q/50177182

http://stackoverflow.com/comment/87322665
type: QuestionComment
comment on: http://stackoverflow.com/q/50143656
score: 0
has text: Here's the issue you're facing: https://github.com/PyMySQL/mysqlclient-python/issues/70, though there's not much of a solution there. If you were [using a raw connection and cursor](http://docs.sqlalchemy.org/en/latest/core/connections.html#multiple-result-sets), you could then call `cur.nextset()` to inspect the actual error that happened before executing `SHOW WARNINGS`.
type: Comment

http://stackoverflow.com/q/50095618
has answer: http://stackoverflow.com/a/50096417
tagged with: python
type: Question
upvote count: 4
tagged with: fuzzy-logic
has title: How to map a value to a fuzzy term in python
type: UnansweredQuestion
answer count: 1
downvote count: 0
score: 4
favorite count: 0
has body: Following the tip example from scikit-fuzzy, I have used the following code to create an input/output to a fuzzy control system: quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality') service = ctrl.Antecedent(np.arange(0, 11, 1), 'service') tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip') quality.automf(3) service.automf(3) tip.automf(3) In the "Fuzzy rules" section of the example, the rules are manually written. I would like to generate them from training examples. Suppose I have a set of (quality, service, tip) tuples, where quality and service range from 0 to 10 and tip ranges from 0 to 25. I would like to be able to generate automatically a rule from each training tuple. In order to do so, I need to map the values of quality and service (respectively tip) to a term (a.k.a linguistic value): either 'poor', 'average', or 'good' (respectively 'low', 'medium', or 'high'). How can I do that with scikit-fuzzy ?

http://stackoverflow.com/comment/87220542
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50101695
type: Comment
has text: Btw I removed the `INFO:niftynet: Optional Python module yaml not found, please install yaml and retry if the application fails.` message with `pip install pyyaml`. Not sure this is in the docs.

http://stackoverflow.com/comment/87432379
type: Comment
has text: Possible duplicate of [WebDriverException: 'geckodriver' executable needs to be in PATH even though it is](https://stackoverflow.com/questions/49947694/webdriverexception-geckodriver-executable-needs-to-be-in-path-even-though-it)
type: QuestionComment
comment on: http://stackoverflow.com/q/50206758
score: 0

http://stackoverflow.com/comment/87294504
comment on: http://stackoverflow.com/a/50137955
type: AnswerComment
has text: I think @sharp only wants to remove those specific characters & combinations he/she mentioned
score: 0
type: Comment

http://stackoverflow.com/a/50204182
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50204124
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87452114
answers question: http://stackoverflow.com/q/50204124
has body: import time and throw a time.sleep(some small time frame) in your loop. Doing while True with no break is going to thrash your cpu.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87299247
comment on: http://stackoverflow.com/a/50137968
has text: Based on lishu's suggestion, the problem was with calling the foo function not the graph.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87316815
has text: Try `df = pd.Dataframe(doc)` Not sure if you can convert the cursor into a dataframe directly or not. But you can convert the documents inside the cursor to dataframe
type: AnswerComment
comment on: http://stackoverflow.com/a/50149344
score: 0
type: Comment

http://stackoverflow.com/q/50228213
upvote count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50228855
tagged with: python-3.x
has title: Joining pandas dataframes of identical columns and getting ONLY the items in table B not present in A
linked to: http://stackoverflow.com/q/20225110
tagged with: python
has answer: http://stackoverflow.com/a/50228359
score: 4
possible better answer: http://stackoverflow.com/a/50228359
has answer: http://stackoverflow.com/a/50228335
accepted answer: http://stackoverflow.com/a/50228335
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: pandas
tagged with: join
has body: I have two dataframes, dfA and dfB of identical columns. I'm looking to get only the records from dataframe dfB that are not present in dataframe dfA. to be clear, I do not want to get the records in dfA that are not in dfB. I managed to hack something together that works using this, but the code is not easy to understand and by extension not very pythonic. I'm looking for a more elegant solution, perhaps using pandas join/merge/append but wasn't able to make it work. Example of what I want: dfA: Date Category Price 1 2013-11-24 Coat 22.1 2 2013-11-24 Shirt 8.7 3 2013-11-01 Socks 9 &lt;&lt;&lt; Only present in this df dfB: Date Category Price 1 2013-11-24 Coat 22.1 2 2013-11-24 Shirt 8.7 3 2013-11-24 Helmet 2.1 &lt;&lt;&lt; Only present in this df 4 2013-11-24 Pants 10.7 &lt;&lt;&lt; Only present in this df Result: Date Category Price 1 2013-11-24 Helmet 2.1 2 2013-11-24 Pants 10.7
tagged with: dataframe

http://stackoverflow.com/a/50118899
has body: The variable form in the else has not been assigned any value: else: return render (request, 'edit_view.html',{'form':form}) The variable form was only assigned in the if. Python has specific scoping rules, and if those rules are broken, Python throws an exception. Python won't execute your code because your variable is unassigned in the event that the else is executed. This question is answered in detail here: https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
score: 1
has comment: http://stackoverflow.com/comment/87255157
has comment: http://stackoverflow.com/comment/87463046
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50118542

http://stackoverflow.com/q/50092665
tagged with: arrays
has comment: http://stackoverflow.com/comment/87203306
tagged with: python
has comment: http://stackoverflow.com/comment/87201804
has comment: http://stackoverflow.com/comment/87202112
has comment: http://stackoverflow.com/comment/87203151
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50093546
tagged with: list
has comment: http://stackoverflow.com/comment/87201594
answer count: 3
has answer: http://stackoverflow.com/a/50093546
score: 1
has comment: http://stackoverflow.com/comment/87201870
has comment: http://stackoverflow.com/comment/87201570
possible better answer: http://stackoverflow.com/a/50092793
downvote count: 1
has body: EDIT: I have changed np.array to np.arange to better explain what my problem is. Being new to Python, I still struggle a lot with data structures. This seems like it should be a very obvious (and obviously duplicate) question, yet I can't understand enough of other explanations to make it work. I need to create a list of lists (and / or arrays, I'll explain this in a minute), all with different lengths and ranges. I set up my initial arrays in the following way, but I still don't understand how to create the 'partotal' array. I know the syntax is wrong but still don't understand why. import numpy as np par1 = np.arange([10,80,1]) par2 = np.arange([50,120,1]) par3 = np.arange([0,40,1]) par4 = np.arange([0,30,1]) partotal = np.array([par1][par2][par3][par4]) The second problem, as you may have guessed, is that I have no idea whether I should be using numpy arrays, list of lists, pandas, or something else entirely. Since all my arrays are of different lengths, I find it hard to understand how to put things together or remove them again. EDIT: The purpose of partotal is to create a set of starting positions for another function (see below) inputnumber = 200 def positions(partotal, inputnumber): return np.random.uniform(partotal, size=(inputnumber, len(partotal))) I know this must sound very basic but as a beginner I find it confusing and difficult. Most answers focus on syntax and don't help develop true insight. If someone can take some time to explain the very obvious I would appreciate it. FINAL EDIT: The answer was very simple when I understood my own problem. I won't delete the rest of the post, for the sake of others who might need to follow my thought process. par = 3 par1 = np.random.uniform(10,80,size=par) par2 = np.random.uniform(5,120,size=par) par3 = np.random.uniform(0,40,size=par) allpar = np.array([par1,par2,par3])
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50092793
has answer: http://stackoverflow.com/a/50105788
upvote count: 2
has title: numpy array vs list of lists?

http://stackoverflow.com/a/50176691
downvote count: 0
has body: On your Kafka broker server.properties you need to set advertised.listeners to the external IP so that clients can correctly connect to it. Otherwise they'll try to connect to the internal IP (since advertised.listeners will default to listeners unless explicitly set) Ref: https://kafka.apache.org/documentation/#brokerconfigs See also https://www.confluent.io/blog/kafka-client-cannot-connect-to-broker-on-aws-on-docker-etc/
score: 6
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/115276102
answers question: http://stackoverflow.com/q/50173481

http://stackoverflow.com/a/50182094
has comment: http://stackoverflow.com/comment/87381546
accepted answer of: http://stackoverflow.com/q/50181895
has comment: http://stackoverflow.com/comment/87383329
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50181895
score: 0
has body: How are you opening the CSV to see the data in it? If you're opening in Excel it might be converting the actual CSV data of (1-4) to (4-Jan). Have you tried opening in a text editor?

http://stackoverflow.com/comment/87417046
has text: Elvez - as @jdv has stated, there is a dedicated thread on how to ask questions on SO : https://stackoverflow.com/questions/how-to-ask Not complying with this standard will probably result in downvotes from other SO users. This is not personal, but rather an enforcement of a protocol which helps individuals from multiple nationalities communicate with one another. Best of luck buddy.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50199500
score: 0

http://stackoverflow.com/q/50165733
type: Question
accepted answer: http://stackoverflow.com/a/50166271
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50166271
has body: seq = 'abcdefghijklmn' for i in itertools.islice(enumerate(seq), 2, 5): print(i) #(2, 'c') #(3, 'd') #(4, 'e') for i in itertools.islice(enumerate(seq), 3, 4): print(i) #(3, 'd') but the expected result from the second for loop should be: #(8, 'i') Why the enumerate(seq) was not advanced after the first loop?
has comment: http://stackoverflow.com/comment/87350143
tagged with: python
has comment: http://stackoverflow.com/comment/87349823
has title: itertools.islice does not advance iterator in python3
tagged with: python-3.x
score: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87349763
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50209920
has title: OpenCV Python Windows : ImportError: DLL load failed: The specified module could not be found
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87437245
score: 0
answer count: 0
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: opencv
type: Question
has comment: http://stackoverflow.com/comment/87437602
tagged with: windows
has body: I'm trying to run openCV with python in windows. However I'm getting the following error when I'm trying to import openCV in python. I also installed the unofficial python .whl package from https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv for openCV. However I'm still getting this error stating : &gt;&gt;&gt; import cv2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: DLL load failed: The specified module could not be found. My Python version is : Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Can someone help me with this?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87437308

http://stackoverflow.com/q/50218856
type: Question
has answer: http://stackoverflow.com/a/50219246
tagged with: python-asyncio
tagged with: python
score: 2
type: AnsweredQuestion
has title: How can I get to run `loop.run_until_complete()` itself asynchronously on asyncio?
upvote count: 2
downvote count: 0
answer count: 1
has body: In the following code: loop = asyncio.get_event_loop() l_x = map(async_func, data_x) l_y = map(async_func, data_y) l_z = map(async_func, data_z) x = loop.run_until_complete(asyncio.gather(*l_x)) y = loop.run_until_complete(asyncio.gather(*l_y)) z = loop.run_until_complete(asyncio.gather(*l_z)) The async_func includes the I/O task and takes a bit longer, so I'm going to use the asyncio to run it concurrently. However, the problem is that I found it is blocking the execution after the first loop.run_until_complete(), and only after all the execution on l_x are done, it then goes into the execution of the second loop.run_until_complete(). But I rather want to run all of them simultaneously, and also don't like to merge the three results as all of them are irrelevant. In this case, can I still run all of them concurrently?
accepted answer: http://stackoverflow.com/a/50219246
favorite count: 0

http://stackoverflow.com/comment/87397095
type: Comment
has text: I did. See above.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50189936

http://stackoverflow.com/comment/87282702
type: Comment
comment on: http://stackoverflow.com/a/50132375
score: 0
type: AnswerComment
has text: what does the if statement mean? @Reblochon

http://stackoverflow.com/comment/87397936
comment on: http://stackoverflow.com/q/50190508
type: Comment
score: 1
has text: j looks like it is incremented in the wrong place. Also, if this is a 3 part quicksort, shouldn't the recursive main part of the function call itself 3 times? Your missing `randomized_quick_sort(a, m1 + 1, m2 - 1);`
type: QuestionComment

http://stackoverflow.com/comment/87257724
type: QuestionComment
has text: Looks like django-filer does not work under django 1.10 or greater :/
comment on: http://stackoverflow.com/q/50119370
score: 0
type: Comment

http://stackoverflow.com/comment/87233141
type: QuestionComment
comment on: http://stackoverflow.com/q/50107512
score: 1
type: Comment
has text: @chepner iterating a memoryview should give you into, at least in Python 3

http://stackoverflow.com/q/50136046
has title: Spliting the text with regex in python
answer count: 2
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/50136189
has comment: http://stackoverflow.com/comment/87290948
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87291224
has answer: http://stackoverflow.com/a/50137353
has comment: http://stackoverflow.com/comment/87290242
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: regex
has body: I have a sample from a text: The whole text is here: pastebin Dr. Trischler (FDP): Meine Damen und Herren! Ich möchte von vornherein als einer der Flücht- lingsvertreter in diesem Hause meiner Freude darüber Ausdruck verleihen, daß die Anträge zur Linderung der Not der Flüchtlinge aus allen Par- teien kommen, daß sich hier Regierung und Oppo- sition anscheinend einig in der Auffassung sind, daß dieses Problem ein allgemeines ist, daß wir alle gemeinsam zusammenarbeiten müssen. Weil ich weiß, daß hier das nötige Verständnis vor- handen ist, will ich mich auch aller Ausführungen enthalten, die irgendwie allgemeiner Natur sind. Ich will nicht über die Notwendigkeit der Linde- rung der Not usw. sprechen, sondern ich will zu einzelnen Fragen, die in diesen verschiedenen An- trägen angeschnitten sind, kurz Stellung nehmen. Die Frage des gerechten Ausgleichs. Auch meine Fraktion ist hier selbstverständlich für einen ge- rechten, gleichmäßigen Ausgleich über alle Länder hinweg. Auch wir lehnen wie die Mehrheit in diesem Hause es ab, daß man unter den Flücht- lingen irgendwelche Gruppierungen macht und daß für die einzelnen Gegenden die oder jene be- vorzugt behandelt werden sollen Zur Frage der Freiwilligkeit: Ich habe das Ge- fühl, daß mein Vorredner von zweierlei Frei- willigkeit gesprochen hat. Einmal sehe ich die Frage der Freiwilligkeit vom Standpunkt der Hei- matvertriebenen aus. In dieser Frage sind wir der Meinung, daß keinerlei Zwang angewendet werden darf. Wir kennen aus der Vergangenheit auch ver- schiedenen „freiwilligen" Zwang; auch dies würden wir ablehnen. Wir können es den Menschen nicht zumuten, daß sie noch einmal gezwungen werden, von dort wieder wegzugehen, wo sie bereits o einigermaßen eine neue Heimstätte gefunden ha- ben. — Die zweite Freiwilligkeit ist die Frage der Freiwilligkeit der Länder, wieweit sie diesen Aus- gleich für sich wollen oder nicht. Hier können wir nun vorerst ruhig abwarten, wie weit die eigene Bereitwilligkeit gehen wird und wiewe…

http://stackoverflow.com/a/50164545
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87349273
accepted answer of: http://stackoverflow.com/q/50164511
downvote count: 0
has comment: http://stackoverflow.com/comment/87347144
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50164511
has body: The reason why you ended up with the Divide-By-Zero error is because in this case, the item['goalsAgainst'] in Line 55, item['shotsAgainst']/item['goalsAgainst'] equals zero. Also you need to watch out for item['goalsFor']/item['shotsFor'], in row. Since the exception happened inside one giant expression assigned to row, create a function that calculates these ratios, and catches ZeroDivisionErrors. If a ZeroDivisionError is caught, return sentinel value -1. Calculating item['shotsAgainst']/item['goalsAgainst']+item['shotsAgainst'] (which caused that error) def save_ratio(shotsAgainst, goalsAgainst): try: return shotsAgainst/goalsAgainst + shotsAgainst except ZeroDivisionError: return -1 ... #replace item['shotsAgainst']/item['goalsAgainst']+item['shotsAgainst'] with save_ratio(item['shotsAgainst'], item['goalsAgainst']), Calculating item['goalsFor']/item['shotsFor'],: def for_ratio(goalsFor, shotsFor): try: return goalsFor/shotsFor except ZeroDivisionError: return -1 # Sentinel value, since goalsFor/shotsFor &gt;= 0 otherwise ... #replace item['goalsFor']/item['shotsFor'] with for_ratio(item['goalsFor'],item['shotsFor']),

http://stackoverflow.com/q/50194382
has body: I am trying to rewrite a formula by counting how many parenthesis are there in a formula.Starting with s=0 and increase s whenever finding a "(" and decrease it when finding a ")" but leaving "(" and ")" corresponding to their original indices in the new string. This sounds very simple, and probably it should be so, but I am failing to find the solution . This is what I coded: def parenthesis(text): s=0 result="" for character in text : if character=="(": s+= 1 if s&gt;0 : result+= str(s) if s==0 : result+=str(0) elif character==")": s-=1 return result For this input: print parenthesis("(asss)+(aa(12))") I get 111111011122221 And I am having problem in assigning "(" and ")" to the the numbers that correspond to the original indices. like: (1111)0(11(22)) I was trying for many times now to implement something similar to this: for i in range(len(result)): if result[i-1]&lt;result[i]: result[i] = "(" if result[i-1]&gt;result[i]: result[i] = ")" But of course this is a string assignment and it won't work like this, so my question is how can I go around this or if there is a simpler way am all ears, grateful for any help.
has answer: http://stackoverflow.com/a/50194705
has comment: http://stackoverflow.com/comment/87406068
tagged with: python
has title: Ways to go around assigning an item to a string?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87406048
has comment: http://stackoverflow.com/comment/87405989
has comment: http://stackoverflow.com/comment/87406549
answer count: 1
accepted answer: http://stackoverflow.com/a/50194705
tagged with: python-2.x
tagged with: string
has comment: http://stackoverflow.com/comment/87405972
type: Question

http://stackoverflow.com/q/50086517
tagged with: javascript
has comment: http://stackoverflow.com/comment/87188781
has body: Please have a look at the page: https://docs.bokeh.org/en/latest/docs/reference/models/widgets.tables.html#bokeh.models.widgets.tables.HTMLTemplateFormatter I have been trying to use that formatter for a datatable of mine, but am having a problem : the location of the table file is appended before the actual link. How create a url link with the formatter that correctly redirect to the target page? EDIT: Here is the code I am using: (this is the bokeh package from python): from bokeh.io import output_file, show from bokeh.layouts import widgetbox from bokeh.models import ColumnDataSource from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, HTMLTemplateFormatter from datetime import datetime from pandas import Timestamp start, end = datetime(2018,4,18), datetime(2018,4,18,23,59) input = { 'datetime': [Timestamp('2018-04-18 00:34:16')], 'event': ['Barbara Bush, former US First Lady, 1925-2018'], 'url': ['https://www.ft.com/content/336e7f52-4189-11e8-93cf-67ac3a6482fd']} output_file("data_table.html") source = ColumnDataSource(input) columns = [ TableColumn( field="datetime", title="Datetime", width = 50, formatter = DateFormatter(format = '%Y-%m-%d %H:%M')), TableColumn( field='event', title='Event', width = 150, formatter = HTMLTemplateFormatter(template = '&lt;a href=”&lt;%= url %&gt;”&gt;&lt;%= value %&gt;&lt;/a&gt;'))] data_table = DataTable(source=source, columns=columns, width=1000, height=1000) show(widgetbox(data_table)) This create the following table: You can see in the inspect pane that the link is correct. However, when clicking on it, it redirect to the page:
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50086586
has answer: http://stackoverflow.com/a/50086586
tagged with: python
tagged with: bokeh
has title: Bokeh HTML template formatter not working
score: 2
type: AnsweredQuestion
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50107820
answers question: http://stackoverflow.com/q/50097431
type: Answer
score: 0
has body: This code answers my question: import pandas as pd a = df1['Sentence'] b = df2['First2'] def func(r): for i in b: if i in r: q = r[r.index(i):] return q return '' df['Segments'] = a.apply(func) It was pointed out by Daming Lu here: How to select sub-strings based on the presence of word pairs? Python Hope this helps others.

http://stackoverflow.com/comment/87250147
type: QuestionComment
has text: python 3.. I also guessed that But having a hard time solving the issue
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50116405

http://stackoverflow.com/a/50134667
answers question: http://stackoverflow.com/q/50134468
has comment: http://stackoverflow.com/comment/87289089
has comment: http://stackoverflow.com/comment/87288664
has body: Update This bug has now been solved in Pillow==6.2.0. The link to the issue on GitHub is here. If you cannot update to the new version of Pillow, please see below. PIL's Image.fromarray function has a bug with mode '1' images. This Gist demonstrates the bug, and shows a few workarounds. Here are the best two workarounds: import numpy as np from PIL import Image # The standard work-around: first convert to greyscale def img_grey(data): return Image.fromarray(data * 255, mode='L').convert('1') # Use .frombytes instead of .fromarray. # This is &gt;2x faster than img_grey def img_frombytes(data): size = data.shape[::-1] databytes = np.packbits(data, axis=1) return Image.frombytes(mode='1', size=size, data=databytes) Also see Error Converting PIL B&amp;W images to Numpy Arrays.
has comment: http://stackoverflow.com/comment/103395092
type: Answer
has comment: http://stackoverflow.com/comment/87288145
has comment: http://stackoverflow.com/comment/87288250
upvote count: 13
accepted answer of: http://stackoverflow.com/q/50134468
type: AcceptedAnswer
downvote count: 0
score: 13

http://stackoverflow.com/a/78810203
answers question: http://stackoverflow.com/q/50151157
has body: One line solution: model.layers.index(model.get_layer(layer_name))
score: 0
type: Answer

http://stackoverflow.com/comment/87359310
comment on: http://stackoverflow.com/a/50163814
type: Comment
type: AnswerComment
score: 1
has text: What do you mean by it didn’t work? Could you post the error message? Also, could you you precise that in your initial post?

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/50218325

http://stackoverflow.com/comment/87449729
has text: one last question: How would I make it so that lambda doesn't print something, but goes to the next screen? Kinda like a menu, where when you click on the button, it would go the next part of it. I tried adding a function and making lambda return the function, but the screen would refresh too fast and nothing would show up. The problem I'm having is that the screen would refresh to the original before showing me the new screen.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50183577

http://stackoverflow.com/comment/87214209
score: 0
has text: @StasDeep [Here is the link](http://www.genesiscinemas.com/portharcourt.php)
type: QuestionComment
comment on: http://stackoverflow.com/q/50097551
type: Comment

http://stackoverflow.com/comment/87422541
has text: There is no local Hadoop installation in this case - just Spark installed in the virtualenv via pip.
comment on: http://stackoverflow.com/q/50183915
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/50208182
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: jquery
has comment: http://stackoverflow.com/comment/87433728
tagged with: flask
tagged with: ajax
has comment: http://stackoverflow.com/comment/106012327
has comment: http://stackoverflow.com/comment/87455152
has comment: http://stackoverflow.com/comment/87435803
answer count: 0
has comment: http://stackoverflow.com/comment/87434791
score: 1
upvote count: 1
has body: In flask I'm using a GET request to first render a template and get data the user has selected. @app.route('/surveys', methods=['POST', 'GET']) def register_form(): if request.method == 'GET': return render_template('survey_table.html') else: example = request.json return json.dumps(example) This data (which is the #ids of checkboxes selected in a table) is then posted back to FLASK using an ajax Post request. Since the data was initially an array I have used JSON.stringify $(document).ready(function() { $('#submit').click(function() { var list = []; var checkBoxes = $('#surveyDetails').find("input[type='checkbox']:checked"); checkBoxes.each(function() { var currentRow = this.parentNode.parentNode; list.push(currentRow.getElementsByTagName("td")[0].innerText); }); // now names contains all of the names of checked checkboxes $.ajax({ contentType: "application/json", url: '/surveys', type: 'POST', data: JSON.stringify({'Hello': list}), success: function (result) { alert(result); }, error: function (result) { alert("error!"); } }); //end ajax }); }); The Problem: I can see that the ajax post is executed successfully since I am able to see the selected ids as an alert once I click the submit button. However, in flask when I return this JSON object, I always get a null response. I have already tried get_json(force=True). Still the same result.
type: Question
favorite count: 0
has title: Flask request returns None; but Ajax Post is successful
has comment: http://stackoverflow.com/comment/87451401
has comment: http://stackoverflow.com/comment/87433574
has comment: http://stackoverflow.com/comment/87437605

http://stackoverflow.com/q/50156908
has body: I have a string s which contains two dates in it and I am trying to extract these two dates in order to subtract them from each other to count the number of days in between. In the end I am aiming to get a string like this: s = "o4_24d_20170708_20170801" At the company I work we can't install additional packages so I am looking for a solution using native python. Below is what I have so far by using the datetime package which only extracts one date: How can I get both dates out of the string? import re, datetime s = "o4_20170708_20170801" match = re.search('\d{4}\d{2}\d{2}', s) date = datetime.datetime.strptime(match.group(), '%Y%m%d').date() print date
has comment: http://stackoverflow.com/comment/87331714
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87331661
has comment: http://stackoverflow.com/comment/87331694
has comment: http://stackoverflow.com/comment/87331815
has answer: http://stackoverflow.com/a/50157056
possible better answer: http://stackoverflow.com/a/50157056
tagged with: python
has comment: http://stackoverflow.com/comment/87331751
tagged with: regex
has answer: http://stackoverflow.com/a/50157240
accepted answer: http://stackoverflow.com/a/50157240
has comment: http://stackoverflow.com/comment/87331826
type: Question
has title: Python: Extract two dates from string
answer count: 2
tagged with: string

http://stackoverflow.com/a/50141973
score: 1
has comment: http://stackoverflow.com/comment/87304502
accepted answer of: http://stackoverflow.com/q/50138511
downvote count: 0
has body: As @Preston Hager mentioned, the format of your file suggests that you should use the csv module. However, another approach without using csv and reading from a .txt file would be this: with open("examples.txt", "r") as inFile: #Read all data from file. data = inFile.read() #Split each set to examples and samples. examples = data.split("#")[1].split(":\n")[1].split("\n") samples = data.split("#")[2].split(":\n")[1].split("\n") #Create sublists of every example or sample record and dispose the last record which is empty. examples = [example.split(";") for example in examples][:-1] samples = [sample.split(";") for sample in samples][:-1] #Print results. print("Examples: ") for example in examples: print(example) print("Samples: ") for sample in samples: print(sample) Output: Examples: ['ff44578jhT', ' marsBug', ' 2', ' 7', ' 3', ' 5', ' 2', ' 1', ' 71', ' 235', ' 312'] ['ff11443asT', ' momu', ' 4', ' 2', ' 1', ' 4', ' 6', ' 3', ' 1', ' 11', ' 23'] ['ff1123dasT', ' nomu', ' 1', ' 3', ' 1', ' 2', ' 3', ' 2', ' 1', ' 1', ' 3'] ['ff44578jhT', ' jupiterBug', ' 2', ' 7', ' 3', ' 5', ' 2', ' 1', ' 71', ' 235', ' 312'] ['ff44578jhT', ' uranusBug', ' 2', ' 7', ' 3', ' 5', ' 2', ' 1', ' 71', ' 235', ' 312'] ['k123vv31', ' bibug', ' 4', ' 8', ' 9', ' 3', ' 4', ' 2', ' 200', ' 4000', ' 0'] Samples: ['k345fv78', ' littleMonster', ' 2', ' 4', ' 3', ' 0', ' 2', ' 1', ' 89', ' 2345', ' 0'] ['k434fv78', ' bigMonster', ' 1', ' 3', ' 3', ' 0', ' 2', ' 1', ' 89', ' 2345', ' 0'] ['k623fv78', ' hugeMonster', ' 2', ' 4', ' 3', ' 0', ' 2', ' 1', ' 89', ' 2345', ' 0'] ['k13ued31', ' edu', ' 3', ' 2', ' 1', ' 8', ' 0', ' 1', ' 20', ' 4', ' 0']
type: AcceptedAnswer
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50138511

http://stackoverflow.com/q/50158808
has comment: http://stackoverflow.com/comment/87336450
has body: I've run into some weird behavior and and I am not exactly sure how to address this issue. Overview: I have a Linux/Ubuntu server with a API that receives thousands of records an hour. These records are stored in a table in my database, we'll call it a staging table, where the records are processed at a later time. I run a cron every minute to grab x records from this staging table and process them with a simple python script. Problem: Lets say this script can process x records per minute. Then each process finishes before the next one begins. However, if I increase the number of records I'm trying to process to 2x then the cron that fired at time 0 has not finished processing it's batch of records when the next cron that fires at time 1 starts. So now we have two running processes, the cron that fired at time 0 which is almost done and the cron which fired at time 1 which just started. This is where something unexpected happens. I have a simple function in the script to process and save processed results to another table. When there are two scripts that are overlapping (as described above), these records each get saved twice to the database. If only one process is running it only gets saved once. I'm scratching my head and not sure how this is possible since each script should be independent. I didn't think it would be useful to include code since it's literally just a cron firing a script to 1. pull records from staging table. 2. make changes to those records 3. save those changed records to new table. If you think it's helpful, I would be glad to upload code to the question. Can anyone point me in the right direction? Thanks
downvote count: 0
tagged with: cron
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50158979
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87335801
has comment: http://stackoverflow.com/comment/87335478
has comment: http://stackoverflow.com/comment/87336165
tagged with: python
has comment: http://stackoverflow.com/comment/87336556
has comment: http://stackoverflow.com/comment/87336105
accepted answer: http://stackoverflow.com/a/50158979
has title: Python overlapping processes?
has comment: http://stackoverflow.com/comment/87335630
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87335689

http://stackoverflow.com/q/50187703
tagged with: django-views
upvote count: 3
has comment: http://stackoverflow.com/comment/87392951
linked to: http://stackoverflow.com/q/40520797
has body: I made image gallery with grid view, but I don't like the way that rows look like - vertical photos disrupt everything. As I don't want to manually change images order I'm looking for a way to sort them automaticaly by image height or just image orientation, so vertical photos go to the bottom in one row. Thats how my model in Django looks like: class Photo(models.Model): title = models.CharField(max_length=150) image = models.ImageField() description = models.TextField(blank=True) category = models.IntegerField(choices=CATEGORIES) published = models.DateTimeField(default=timezone.now) def __str__(self): return self.title Here is my grid_view: def photos_grid(request): global cat_list photos = Photo.objects.order_by('published') output = {'photos': photos, 'categories': cat_list,} return render(request, 'photos/photos_grid.html', output) I tried that (how to find height and width of image for FileField Django) way of getting image dimensions but I got ValueError: invalid literal for int() with base 10: 'height' every way I try to put it in my code. Other idea (by getting manually dimensions in views.py) works, but I can't put it together with my photos on the list so it get sorted.
has comment: http://stackoverflow.com/comment/87393093
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50188502
has title: Sorting images by height/orientation
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87393248
score: 3

http://stackoverflow.com/q/50127690
has comment: http://stackoverflow.com/comment/87324740
has body: I have built a script to read my Gmail inbox for a new email, if found store it for posting and mark the email as "read". Everything has been working fine there. I have since been trying to fuse Tweepy into this to post said stored email to twitter. Except it looks like tweepy doesn't like my variable "part.get_payload()" api.update_status("Test") ....works fine and posts to twitter TweetMsg = part.get_payload() api.update_status(TweetMsg) ....doesnt post anything to twitter Looking through Tweepy documentation I couldnt find any info on using variables with Status Updates. Any Advice?
tagged with: gmail
type: Question
answer count: 0
has title: using tweepy to post email to twitter
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87301873
has comment: http://stackoverflow.com/comment/87287649
tagged with: python
tagged with: twitter
tagged with: tweepy

http://stackoverflow.com/a/50204206
accepted answer of: http://stackoverflow.com/q/50204011
has comment: http://stackoverflow.com/comment/87445182
has comment: http://stackoverflow.com/comment/87458119
type: Answer
has comment: http://stackoverflow.com/comment/87447376
score: 0
type: AcceptedAnswer
has body: The way you set up this field done = models.ForeignKey('reports', on_delete=models.CASCADE) means that this field can't remain empty nor null. When you createe a makereport object, this field must have a report instance, if not IntegrityError: Not Null will raise In case of creating makereport object without a report instance. the following can do it done = models.ForeignKey('reports', on_delete=models.SET_NULL,null=True,blank=True) in your views, try this: ''' codes ''' repo.done = None repo.save()
answers question: http://stackoverflow.com/q/50204011
has comment: http://stackoverflow.com/comment/87449612
has comment: http://stackoverflow.com/comment/87449823
has comment: http://stackoverflow.com/comment/87449528

http://stackoverflow.com/q/50111275
has comment: http://stackoverflow.com/comment/87239774
score: 0
has title: send email in Python and list items as email content not as attachment
answer count: 1
tagged with: smtp
has body: I am trying to send an email containing list of URLs along with message stating these are urls for example: BADURL = ['abc.123.com','xyz.456.com','rtf.892.com'] Requiring output Following are BAD URLs abc.123.com xyz.456.com rtf.892.com I am writing following code but I am getting message as email body and urls as an attachment. I don't want to send URLs as attachment instead I just want them to be listed in the email. Following is my code: message = multipart.MIMEMultipart('mixed') message['Subject'] = 'Policy.txt file update' message['From'] = sender message['To'] = ','.join(destination) message['Date'] = formatdate(localtime=True) message.attach(text.MIMEText('Following are BAD URLs')) message.attach(text.MIMEText('\n'.join(y),'plain')) print('sending message')enter code here print (message.as_string()) try: z = smtplib.SMTP('localhost') z.sendmail(sender, destination, message.as_string()) z.quit() except(smtplib.SMTPException, IOError) as e: z.quit() print(str(e))
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50111404
tagged with: python

http://stackoverflow.com/comment/87293548
comment on: http://stackoverflow.com/q/50137536
score: 1
has text: Please show `DataTable`, or say which package it comes from.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50163988
upvote count: 1
tagged with: properties
duplicate of: http://stackoverflow.com/q/17330160
duplicate of: http://stackoverflow.com/q/6193556
score: 1
has comment: http://stackoverflow.com/comment/87346055
tagged with: python
has comment: http://stackoverflow.com/comment/87346170
has title: Why does the property builtin work in conjunction with classes but not outside of them?
has body: I can do class Foo(object): x = property(lambda _: 123) f = Foo() f.x to get 123 However, if I try p = property(lambda : 123) p I get &lt;property object at 0x108f2f3b8&gt; Now I understand that an member of a class instance is not the same thing as a regular variable but I'm not sure what exactly makes this behavior different. Does the fact that you instantiate a class somehow do extra binding on property objects? Is it a special case or is it a behavior I can take advantage in other situations and extend? Related - are property objects useful outside of a class declaration? Or is it just for this specific case?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87345973
tagged with: built-in
answer count: 0
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/6193556

http://stackoverflow.com/comment/87384793
type: AnswerComment
comment on: http://stackoverflow.com/a/50183530
score: 0
type: Comment
has text: I see, maybe I didn't understand your question then. If so, sorry! Hope you find a good answer.

http://stackoverflow.com/comment/87421207
has text: The error is caused by the `url` template tag. Can you check whether you have `{% url 'appointments' %}` in your template? You need to pass an id in your `url` tag for appointments.
comment on: http://stackoverflow.com/q/50202236
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50165398
upvote count: 7
favorite count: 0
tagged with: series
accepted answer: http://stackoverflow.com/a/50165531
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50165531
has body: The HDF5 format apparently does not support categoricals with format="fixed". The following example s = pd.Series(['a','b','a','b'],dtype='category') s.to_hdf('s.h5','s') Returns the error: NotImplementedError: Cannot store a category dtype in a HDF5 dataset that uses format="fixed". Use format="table". How do I construct the categorical series with format='table'?
tagged with: pandas
score: 7
has title: In a Pandas categorical, what is format="table"?
tagged with: hdf5
tagged with: pytables
type: Question
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/a/50085774
answers question: http://stackoverflow.com/q/50084539
has comment: http://stackoverflow.com/comment/127233679
type: Answer
accepted answer of: http://stackoverflow.com/q/50084539
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/134975007
downvote count: 0
has body: UPDATE After a lot of fiddling around I got it to work. As @Iarwa1n suggested, you map one db as such "5432:5432" and the other as such "5433:5432". The error I encountered was due to how I was calling postgres from the application itself. It is important to realize the postgres host is not localhost anymore, but whatever name you gave your database service in docker-compose.yaml. In my case; db for backend and login_db for the login service. Additionally, I had to change my driver from postgresql to postgres – not sure why this is... As such, my db_url ended up looking like this from within my python backend app: postgres://ludo:password@db:5432/main_db And defined in this way: DATABASE_CONFIG = { 'driver': 'postgres', 'host': 'db', 'user': 'ludo', 'password': 'password', 'port': 5432, 'dbname': main_db } db_url = '{driver}://{user}:{password}@{host}:{port}/{dbname}'.format(database_config) Two things to note: 1) Regardless of how you mapped your ports, you always have to connect to postgres default port 5432 from within your app 2) If you're using the requests python library (as was I) then make sure to change the url appropriately as well. For example I had a ppt service I was calling via the requests library and I had to change the url to: 'http://ppt:6060/api/getPpt' instead of 'http://localhost:6060/api/getPpt'
type: AcceptedAnswer

http://stackoverflow.com/comment/87453694
score: 0
has text: Make sure to read the programmers guide to understand the Tensorflow Dataset preprocessing pipeline. What you want to do is wrap `to_local_iterator()` with a Python generator functions. Then you pass that generator to `tf.data.Dataset.from_generator()`. You will create a tensorflow iterator from the Dataset which will produce tensors that you can use just like a placeholder or any other tensor.
type: Comment
comment on: http://stackoverflow.com/a/50181132
type: AnswerComment

http://stackoverflow.com/comment/87334945
type: QuestionComment
comment on: http://stackoverflow.com/q/50158333
type: Comment
has text: @TwistedSim Just tried it and that doesn't seem to work, but it does help to show the problem, so I've included it in the code and chart.
score: 0

http://stackoverflow.com/a/54030148
has body: I placed int() around every argument in the function call to surface.get_at(). This resolved my problem. I am using Python3 and the same tutorial. Example: From (with error) if surface.get_at(( player["x"] , player["y"] + player["height"] )) == (0,0,0,255): leftOfPlayerOnPlatform = False To (no error) if surface.get_at((int(player["x"]), int(player["y"] + player["height"]))) == (0,0,0,255): leftOfPlayerOnPlatform = False There were three instances where I changed the code. Once I did so, then I was able to execute drop.py from Thonny.
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/50159527
type: Answer
score: -1

http://stackoverflow.com/a/50183773
has comment: http://stackoverflow.com/comment/87385511
has body: You're over-complicating it. Just use else:, like this: class Avatar: """Returns members avatar.""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) @commands.cooldown(5, 60, commands.BucketType.user) async def avatar(self, context, member: discord.Member): """Returns members avatar.""" role = discord.utils.get(member.server.roles, name="Private Avatar") author = context.message.author.mention mention = member.mention if role in member.roles: pa = "This members avatar is private" await self.bot.say(pa) else: avatar = "{0} here is {1}'s avatar" u = member.avatar_url url = process_avatar(u) embed = discord.Embed(description=avatar.format(author, mention), colour=discord.Colour.blue()) embed.set_image(url=u) await self.bot.say(embed=embed) P.S.: In theory, your code should work. Unless there's something I'm not seeing wrong, that is. I must also note that just because the bot won't fetch it, doesn't mean the client can't. Avatars are public.
accepted answer of: http://stackoverflow.com/q/50183721
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50183721
has comment: http://stackoverflow.com/comment/87385369
has comment: http://stackoverflow.com/comment/87402252
has comment: http://stackoverflow.com/comment/87385063
score: 0

http://stackoverflow.com/comment/87416730
comment on: http://stackoverflow.com/q/50200023
score: 0
type: Comment
has text: and on server you also have 1.10?
type: QuestionComment

http://stackoverflow.com/a/50107729
has comment: http://stackoverflow.com/comment/87250846
answers question: http://stackoverflow.com/q/50107615
has comment: http://stackoverflow.com/comment/87263430
has body: The issue might be from sqlalchemy side which believes that there is an index as message of deletion of tables was not notified to the sqlalchemy. There is a sqlalchemy way of deleting the tables table.declarative_base.metadata.drop_all(engine) This should keep Sqlalchemy informed about the deletions.
upvote count: 0
has comment: http://stackoverflow.com/comment/87248708
has comment: http://stackoverflow.com/comment/87258373
downvote count: 1
has comment: http://stackoverflow.com/comment/87258672
type: Answer
score: -1

http://stackoverflow.com/comment/130210650
comment on: http://stackoverflow.com/q/50117278
type: QuestionComment
has text: I have same problem now. [502 Bad Gateway in GAE with Django, & Log say "libBLT.2.5.so.8.6 No such file or directory"](https://stackoverflow.com/questions/73729042/502-bad-gateway-in-gae-with-django-log-say-libblt-2-5-so-8-6-no-such-file-or) Did you solve it? Thank you.
type: Comment
score: 0

http://stackoverflow.com/comment/87431191
type: AnswerComment
has text: I figured out the reason, I missed the package: from mpl_toolkits.mplot3d import Axes3D
type: Comment
comment on: http://stackoverflow.com/a/50204991
score: 0

http://stackoverflow.com/a/50224471
score: 1
has comment: http://stackoverflow.com/comment/87492075
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87491996
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50224441
has comment: http://stackoverflow.com/comment/87500297
has comment: http://stackoverflow.com/comment/87500256
has comment: http://stackoverflow.com/comment/87500054
has comment: http://stackoverflow.com/comment/87500243
downvote count: 0
has comment: http://stackoverflow.com/comment/87499834
type: Answer
has comment: http://stackoverflow.com/comment/87491779
has body: I think this is just a simple Boolean filter . df.loc[(df.hour==0)|(df.minute==0)] To fix your code def clean_start_data (df): l=[] for index, row in df.iterrows(): if row['hour'] &gt; 0 or row['minute'] &gt; 0: l.append(index) else: break return df.drop(l, inplace=True)
answers question: http://stackoverflow.com/q/50224441

http://stackoverflow.com/q/50082882
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87263190
has title: Test data predictions yield random results when making predictions from a saved model
possible better answer: http://stackoverflow.com/a/50111738
has body: I am classifying aerial imagery that is tiled into 256x256 tiles using Keras and TensorFlow. The model splits the training data (i.e. the 256x256 image tiles making up the study area) into 70% training data and 30% validation data. A sequential model is used followed by an image data generator. Lastly, a fit generator is used to fit the model to the data. The model is then saved to h5 format to be used to predict classes with other imagery in different study areas. When I run the model using the 70%/30% training/validation split, the predictions on the validation images work great with increasingly higher accuracies and steadily decreasing loss per epoch. Additionally, when I visualize the predictions (i.e. probability arrays) by joining the probability arrays to vector polygons representing the tile boundaries, the classified results look very good. My problem is when I use the saved h5 model to make predictions on new imagery--the results are nonsensical and appear random for each tile. It is as if the probability arrays are being shuffled randomly such that when I join the results to the vector image boundary tiles, the results look totally random. How can I resolve this issue? Here is relevant portions of the code used to train the model: base_model = applications.VGG16(weights='imagenet', include_top=False, input_shape=(img_rows, img_cols, img_channel)) add_model = Sequential() add_model.add(Flatten(input_shape=base_model.output_shape[1:])) add_model.add(Dense(256, activation='relu')) add_model.add(Dense(n_classes, activation='sigmoid')) # n classes model = Model(inputs=base_model.input, outputs=add_model(base_model.output)) model.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9), metrics=['accuracy']) ###################### batch_size = 32 epochs = 50 print('Running the image data generator...') train_datagen = ImageDataGenerator( rotation_range=30, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True) train_dat…
has comment: http://stackoverflow.com/comment/87183777
score: 7
has answer: http://stackoverflow.com/a/50111738
has comment: http://stackoverflow.com/comment/87261908
tagged with: python
accepted answer: http://stackoverflow.com/a/50195395
has answer: http://stackoverflow.com/a/50195395
has comment: http://stackoverflow.com/comment/87187592
answer count: 2
tagged with: deep-learning
downvote count: 0
tagged with: machine-learning
upvote count: 7
tagged with: keras
tagged with: tensorflow

http://stackoverflow.com/q/50090614
linked to: http://stackoverflow.com/q/39048229
type: AnsweredQuestion
tagged with: apache-spark
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/50090820
upvote count: 1
has answer: http://stackoverflow.com/a/50090820
favorite count: 0
type: Question
has body: I don't have much experience in PySpark I need to check in Spark Dataframe how many values are greater then certain threshold(absolute) in a row. I tried this and it doesn't work n = lit(len(df.columns)) rank= (reduce(add, (1 for x in df.columns[1:] if abs(col(x)) &gt; threshold))).alias(rank)
downvote count: 0
tagged with: python
has title: Spark dataframe need to check values row wise

http://stackoverflow.com/comment/122906140
comment on: http://stackoverflow.com/a/50242085
score: 0
type: Comment
type: AnswerComment
has text: it's no longer available

http://stackoverflow.com/a/50104041
has comment: http://stackoverflow.com/comment/87226220
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50103957
has body: Have you tried using matplotlib with the notebook backend in your Jupyter notebook? You can do this by adding %matplotlib notebook magic command in a cell at the beginning of your notebook (e.g. right after importing matplotlib) More info here: http://ipython.readthedocs.io/en/stable/interactive/plotting.html

http://stackoverflow.com/comment/87308228
has text: The simplest answer is to reorganize your code so that instead of doing three separate xpath queries and trying to zip the results together, you do one top-level query to get the groups, and then, for each group, xpath the three subfields from the group.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50144983

http://stackoverflow.com/comment/87243001
comment on: http://stackoverflow.com/q/50112706
type: Comment
type: QuestionComment
has text: One example: `class NotEditableException(Exception): pass`
score: 0

http://stackoverflow.com/q/50201139
tagged with: string
has answer: http://stackoverflow.com/a/50201467
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87420001
linked to: http://stackoverflow.com/q/22604564
score: 1
has body: My string is like below Module Available Used Remaining (Watts) (Watts) (Watts) ------ --------- -------- --------- 1 485.0 0.0 485.0 I need to extract value under Used. I was trying to split the string. Is there any better way to get the value?
tagged with: python
has title: Extracting value under particular column in a string
tagged with: python-3.x
linked to: http://stackoverflow.com/q/27964942
answer count: 2
has answer: http://stackoverflow.com/a/50201169
type: UnansweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50202199
answer count: 1
upvote count: 1
tagged with: scikit-learn
tagged with: keras
favorite count: 0
type: Question
has body: how to calculate confusion matrix for this training model? model = Model([encoder_inputs, decoder_inputs], decoder_outputs) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit([encoder_input_data, decoder_input_data], decoder_target_data, batch_size=batch_size, epochs=epochs, validation_split=0.2, verbose=1) model.summary()
has title: How to calculate confusion matrix for a training model ? (from this code)
accepted answer: http://stackoverflow.com/a/50216673
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50216673
type: AnsweredQuestion
tagged with: chatbot
downvote count: 2

http://stackoverflow.com/a/50184887
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50183789
score: 3
answers question: http://stackoverflow.com/q/50183789
has body: With a list and dict comprehension, you can do that like: Code: [{'date': x['date'], 'details': {k: v for k, v in x.items() if k != 'date'}} for x in df.to_dict('records')] Test Code: df = pd.DataFrame([['2016-04-30T20:02:25.693Z', 'vmPowerOn', 'vmName'], ['2016-04-07T22:35:41.145Z', 'vmPowerOff', 'hostName']], columns=['date', 'event', 'object']) print([{'date': x['date'], 'details': {k: v for k, v in x.items() if k != 'date'}} for x in df.to_dict('records')]) Results: [{'date': '2016-04-30T20:02:25.693Z', 'details': {'event': 'vmPowerOn', 'object': 'vmName'}}, {'date': '2016-04-07T22:35:41.145Z', 'details': {'event': 'vmPowerOff', 'object': 'hostName'}} ]
type: Answer
upvote count: 3

http://stackoverflow.com/q/50127494
linked to: http://stackoverflow.com/q/13332268
accepted answer: http://stackoverflow.com/a/50130669
tagged with: subprocess
score: 1
has answer: http://stackoverflow.com/a/50130669
tagged with: email
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87278986
tagged with: shell
upvote count: 1
has body: Shell code: msg="body of the mail" echo "$msg" | mailx -s "ERROR" udhai Python Code: msg="body of the mail" subprocess.call(msg + " | mailx -s 'ERROR:' udhai",shell=True) When I execute my shell script, I am receiving email to the udhai account with both the message (body of the mail) and the subject("ERROR:"). But in my python code, I am receiving email only with the subject. How can I receive the email with the subject and message.
has comment: http://stackoverflow.com/comment/87279051
favorite count: 0
has comment: http://stackoverflow.com/comment/87280598
type: Question
has title: Different results when sending an email using the shell and through subprocess.call
tagged with: python
has comment: http://stackoverflow.com/comment/87278723
has comment: http://stackoverflow.com/comment/87274202
type: AnsweredQuestion
tagged with: python-2.7

smtp
tags question: http://stackoverflow.com/q/50111275
tag name: smtp
type: Tag

http://stackoverflow.com/q/50078170
has answer: http://stackoverflow.com/a/50078671
has comment: http://stackoverflow.com/comment/87173994
has comment: http://stackoverflow.com/comment/87172539
has comment: http://stackoverflow.com/comment/87173917
type: Question
has comment: http://stackoverflow.com/comment/87172329
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87174096
has comment: http://stackoverflow.com/comment/87236888
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87173863
tagged with: python
has comment: http://stackoverflow.com/comment/87173782
has comment: http://stackoverflow.com/comment/87173420
score: 0
has comment: http://stackoverflow.com/comment/87173137
has comment: http://stackoverflow.com/comment/87173734
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87173901
has body: I have a frame I want to use as a sidebar navigation menu. I want the menu to be resize-able with the mouse. I have code that sizes the frame but it doesn't resize until you resize the toplevel window. I know about PanedWindows and that will not work for me. from tkinter import * def dragbar_on_click(event): event.widget.mouse_x = event.x def dragbar_on_release(event): event.widget.mouse_x = 0 def dragbar_on_motion(event): if event.widget.mouse_x != 0: width = event.widget.parent.winfo_width() + event.x - event.widget.mouse_x event.widget.parent.config(width=width) class DragBar(Frame): def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.parent = parent class SideMenu(Frame): def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.config(bg='red', width=300) self.rowconfigure(0, weight=1) self.grid(sticky='NSEW') self.grid_propagate(0) self.frame = Frame(self, bg='purple') self.columnconfigure(0, weight=1) self.frame.grid(row=0, column=0, sticky='NSEW') self.dragbar = DragBar(self, bg='green', width=10) self.dragbar.mouse_x = 0 self.dragbar.grid(row=0, column=1, sticky='NSW') self.dragbar.bind("&lt;Motion&gt;", dragbar_on_motion) self.dragbar.bind("&lt;Button-1&gt;", dragbar_on_click) self.dragbar.bind("&lt;ButtonRelease-1&gt;", dragbar_on_release) root = Tk() root.rowconfigure(0, weight=1) root.columnconfigure(1, weight=1) f = SideMenu(root) Label(f.frame, text='This is a test line.').grid(sticky='NW') root.mainloop()
answer count: 1
has title: How do you size a tkinter frame dynamically

gateway
type: Tag
tags question: http://stackoverflow.com/q/50103156
tag name: gateway

http://stackoverflow.com/comment/87252426
type: Comment
score: 0
type: QuestionComment
has text: Possible duplicate of [Modifying global variables in Python unittest framework](https://stackoverflow.com/questions/6268278/modifying-global-variables-in-python-unittest-framework)
comment on: http://stackoverflow.com/q/50116836

http://stackoverflow.com/a/50211021
score: 0
accepted answer of: http://stackoverflow.com/q/50210802
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50210802
has comment: http://stackoverflow.com/comment/87507060
has body: Try a simple regular expression: import re e = r'^__(.*?)=(.*?)$' with open('data.txt') as f: print(dict(re.findall(e, f.read(), re.M))) This will print: {'A': ' 2.3', 'b': ' 3.26', 'ctx': ' 4.2', 'itermax': ' 100', 'errmax': ' 1e-07'}
type: Answer

http://stackoverflow.com/comment/87454468
comment on: http://stackoverflow.com/q/50179024
has text: No need to add "solved" in a title: instead, mark an answer as accepted using the green checkmark. Or post your own answer.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87267967
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50124914
score: 0
has text: You need `soup.findAll`

http://stackoverflow.com/comment/87423079
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50166592
has text: I did, but unfortunately I don’t have enough rep for it to show up.

http://stackoverflow.com/comment/87203518
comment on: http://stackoverflow.com/q/50093613
type: Comment
has text: Not deque specific but `functools.reduce(operator.getitem, deq, d)` is a nice way. [Related (possible duplicate) question](https://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys).
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87410366
comment on: http://stackoverflow.com/q/50196608
has text: Maybe problem is torch version, try to check your torch version with doc you using.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87332175
type: QuestionComment
comment on: http://stackoverflow.com/q/50156665
has text: you're passing the entire dataframe as your argument for `y`. What is the column of data you want to plot called?
score: 0
type: Comment

http://stackoverflow.com/comment/87239804
comment on: http://stackoverflow.com/q/50111287
has text: how do you compute beam forming with a single source? this seems like a pretty domain-specific question with out a lot of context. are you having a specific problem with the pyaudio API or are you having trouble implementing a numerical algorithm?
score: 0
type: Comment
type: QuestionComment

file-io
tags question: http://stackoverflow.com/q/50220573
tags question: http://stackoverflow.com/q/50165162
tags question: http://stackoverflow.com/q/50091972
tags question: http://stackoverflow.com/q/50123027
type: Tag
tag name: file-io
tags question: http://stackoverflow.com/q/50204783
tags question: http://stackoverflow.com/q/50224867

http://stackoverflow.com/a/50224363
downvote count: 0
has comment: http://stackoverflow.com/comment/87466596
answers question: http://stackoverflow.com/q/50224316
type: Answer
has comment: http://stackoverflow.com/comment/87466586
has body: With a loop and zip() you can do that like: Code: def split_data(some_data): results = OrderedDict() for datum in some_data: split = datum.strip().split(';') if split[0] in results: for val, dest in zip(split[1:], results[split[0]]): if val != '0': dest.append(int(val)) else: results[split[0]] = [[int(s)] for s in split[1:]] return results Test Code: from collections import OrderedDict data = """ 2018-01-31;1;2;4 2018-01-31;0;3;0 2018-02-01;5;6;7 2018-02-02;8;9;10 """.split('\n')[1:-1] print(split_data(data)) Results: OrderedDict([ ('2018-01-31', [[1], [2, 3], [4]]), ('2018-02-01', [[5], [6], [7]]), ('2018-02-02', [[8], [9], [10]]) ])
score: 2
upvote count: 2

http://stackoverflow.com/comment/87402483
comment on: http://stackoverflow.com/q/50191395
type: Comment
type: QuestionComment
score: 0
has text: @zvone it gives me respectively :`<module 'foo.bar' from '/home/nathan/Documents/workspace/omme/foo/bar.py'>` and `Reloaded modules: foo.bar ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'barClass']`

http://stackoverflow.com/a/50178885
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50177804
accepted answer of: http://stackoverflow.com/q/50177804
score: 1
has body: The problem is that your function "b" is not capable of working with series of values, it can only process single value. In order to fix it, you can either use DataFrame.apply, e.g. df['OC_Return_Bin'] = df["OC_Return_%"].apply(b) or make it capable of working with series.
type: AcceptedAnswer

http://stackoverflow.com/comment/87350364
type: QuestionComment
has text: https://repl.it/ disagrees with your assertion that simply changing the arg from "name" to "i" doesn't work the same. Is there some other detail you are leaving out? Also, you have tagged this with unused tags.
score: 0
comment on: http://stackoverflow.com/q/50164867
type: Comment

http://stackoverflow.com/comment/87190034
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50086725
has text: Despite learning Python 2, I really consider learning 3 is better. But I want to learn Javascript just after python and it seems Python 2 is more likely to the Javascript.

http://stackoverflow.com/comment/87370831
score: 2
has text: We don't write code, we only debug it. Seeing as there is nothing to debug here we can't answer your question.
comment on: http://stackoverflow.com/q/50176817
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50187087
downvote count: 0
has body: I have this exercise: You have a tree graph as input, and you need to remove its leaves. So you need to remove the empty lists from a list of lists. For example this: [[[[], []], [[], []]], [[], [], []]] becomes this: [[[], []], []] I tried to use pop and del, but the teacher said to use recursion. Also it gives None as an output. But I can't figure out how to. Can you explain it how to or can you help to solve this question? def tree_cut(tree): for i in range(len(tree)): if tree[i]=="": tree.pop(i) return tree for k in tree[i]=="": if k=="": tree.remove(k) return tree
upvote count: 1
score: 1
tagged with: tree
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50187148
has comment: http://stackoverflow.com/comment/87390888
tagged with: python
has title: How to remove something from a list with recursion? Python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50187148
answer count: 1

http://stackoverflow.com/comment/87430080
comment on: http://stackoverflow.com/q/50205977
has text: The simplest fix is presented in my answer
score: 0
type: Comment
type: QuestionComment

exception
tags question: http://stackoverflow.com/q/50085462
tags question: http://stackoverflow.com/q/50096123
tags question: http://stackoverflow.com/q/50103460
tags question: http://stackoverflow.com/q/50112706
tags question: http://stackoverflow.com/q/50093634
tags question: http://stackoverflow.com/q/50129644
tags question: http://stackoverflow.com/q/50104507
tag name: exception
tags question: http://stackoverflow.com/q/50164368
tags question: http://stackoverflow.com/q/50192870
tags question: http://stackoverflow.com/q/50106838
type: Tag
tags question: http://stackoverflow.com/q/50136746
tags question: http://stackoverflow.com/q/50216464

http://stackoverflow.com/q/50109047
has comment: http://stackoverflow.com/comment/87235754
type: UnansweredQuestion
has body: I'm trying to write a code that traverses a general tree height by height from the root of the tree. What I'm trying to write is something that prints a list where the root is at index[0] followed by the children of the root and then their children. I'm trying to write it so it repeats this process for each subtree until it reaches the bottom of the tree. This is the design code that I have but I can't figure out how to write it in python. def traversal(tree): if tree is empty: print("No tree to traverse") else: starting at the root print a list containing the root at [0], its children, and its grand children recursively call function set new root to child of root traverse each subtree until bottom of tree
tagged with: python
linked to: http://stackoverflow.com/q/2358045
tagged with: tree
tagged with: recursion
upvote count: 2
has comment: http://stackoverflow.com/comment/87235572
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87236137
downvote count: 1
has title: Traversing a general tree by height
favorite count: 0
type: Question

http://stackoverflow.com/comment/87466024
type: QuestionComment
comment on: http://stackoverflow.com/q/50224226
has text: "_I don't know how to do a swap_": Learning how to do this is a good starting point. Consult your Python book or tutor.
score: 1
type: Comment

http://stackoverflow.com/comment/87407532
score: 1
type: Comment
type: QuestionComment
has text: Just noticed something: you’re appending a slice of the presumably giant numpy array to fields. That’s not a copy, it’s a view into the parent array. Which is why slicing with numpy is so fast and space efficient, but it also means a slice view keeps that parent alive for as long as it’s alive (which is forever, in your case). If removing the append makes the problem go away, try changing to `append(x[:,start:end].copy())`. If that works, that’s your solution.
comment on: http://stackoverflow.com/q/50195197

http://stackoverflow.com/q/50193562
score: 0
has body: I have written a function in python views.py, urls.py and models.py but it doesn't seem to store stuff in the database. Need help in order to store it back into database. I have provided the html, views.py, urls.py and models.py code views.py: @login_required def job_status_update(request): status = request.GET['status'] job_id = request.GET['Jobid'] if status == 'Active': flag = True else: flag = False job = Job.objects.get(pk=job_id) try: job.active = flag job.save() return HttpResponse(status) except Exception as e: return JsonResponse(status) urls.py: url(r'^job/status_update/?status=active&jobid=\d+', views.job_status_update), models.py: active = models.BooleanField(default = True) html: Status: {% if job.active %} Active {% else %} Deactive {% endif %} Activate Deactivate
has comment: http://stackoverflow.com/comment/87404443
has title: Python function not storing in django database
has comment: http://stackoverflow.com/comment/87404796
has comment: http://stackoverflow.com/comment/87404814
has comment: http://stackoverflow.com/comment/87404384
has comment: http://stackoverflow.com/comment/87404477
has comment: http://stackoverflow.com/comment/87404589
has comment: http://stackoverflow.com/comment/87404518
possible better answer: http://stackoverflow.com/a/50194038
has comment: http://stackoverflow.com/comment/87404539
type: Question
has comment: http://stackoverflow.com/comment/87404955
has comment: http://stackoverflow.com/comment/87405079
accepted answer: http://stackoverflow.com/a/50194031
has answer: http://stackoverflow.com/a/50194038
has comment: http://stackoverflow.com/comment/87405040
answer count: 2
has answer: http://stackoverflow.com/a/50194031
has comment: http://stackoverflow.com/comment/87404756
tagged with: django
has comment: http://stackoverflow.com/comment/87405013
tagged with: python
has comment: http://stackoverflow.com/comment/87404345
has comment: http://stackoverflow.com/comment/87404468
has comment: http://stackoverflow.com/comment/87404348
has comment: http://stackoverflow.com/comment/87404728
has comment: http://stackoverflow.com/comment/87404988
has comment: http://stackoverflow.com/comment/87405110
type: AnsweredQuestion

http://stackoverflow.com/q/50142626
type: Question
has answer: http://stackoverflow.com/a/50142728
accepted answer: http://stackoverflow.com/a/50142728
tagged with: amazon-ec2
tagged with: python
has body: I'm trying to leave a script running on an EC2 instance after I close the SSH client. The script is running on an activated tensorflow_p36 virtual anaconda environment. I have tried to use screen and tmux but to no avail ( I issue these commands when the venv is active). I get a ModuleNotFoundError: No module named 'tensorflow' even though when I try conda env list I see that I'm using the tensorflow_p36 environment. Do you have any ideas?
type: AnsweredQuestion
score: 0
has title: Leave a tensorflow (anaconda venv) script running on EC2 instance
tagged with: anaconda
tagged with: ssh
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/a/50164242
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50138024
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50138024
downvote count: 0
has body: pipenv shell appears to take additional arguments that are sent as an initial command to the shell that it starts. A simulated session follows: $ cat tmp.sh echo hi $ pipenv shell . tmp.sh Spawning environment shell (/bin/bash). Use 'exit' to leave. . .../bin/activate . . tmp.sh $ . .../bin/activate $ . tmp.sh hi $ Since pipenv shell just starts an interactive session of the shell named by the SHELL environment variable, you can add code to your usual .bashrc file to source a special local file on start-up, if it exists: if -f .pipenvshrc ; then . .pipenvshrc fi You can also play around with the idea of using the value of $VIRTUAL_ENV that pipenv shell adds to the environment to choose a file to source.

http://stackoverflow.com/a/50216841
has body: You need to add re.MULTILINE to your flags. s = '''foo bar foobar''' re.findall('^foo$', s, flags=re.MULTILINE) Out[14]: ['foo']
score: 8
upvote count: 8
downvote count: 0
answers question: http://stackoverflow.com/q/50216736
type: Answer

http://stackoverflow.com/comment/87416809
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50200023
has text: @CDoc have a look at the link above and check you've followed the instructions there

http://stackoverflow.com/a/50162295
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50162212
has comment: http://stackoverflow.com/comment/87342450
type: AcceptedAnswer
downvote count: 0
score: 6
has body: This is precisely because Δ2 yt = yt - 2 yt - 1 + yt - 2 ≠ yt - yt - 2. The left hand side is df.diff().diff(), whereas the right hand side is df.diff(2). For the difference in difference, you want the left hand side.
accepted answer of: http://stackoverflow.com/q/50162212

http://stackoverflow.com/q/50213761
score: 34
favorite count: 0
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/56959013
has answer: http://stackoverflow.com/a/56959013
tagged with: plotly
has answer: http://stackoverflow.com/a/50417291
tagged with: python
has title: Changing visibility of a Dash Component by updating other Component
upvote count: 34
answer count: 2
tagged with: plotly-dash
accepted answer: http://stackoverflow.com/a/50417291
tagged with: dashboard
downvote count: 0
has body: I need to hide some Components, for example by clicking on a checkbox (for example, a graph or a table). However, the documentation did not provide a suitable section for this purpose. Thanks in advance!

http://stackoverflow.com/comment/87463462
comment on: http://stackoverflow.com/a/50222874
type: Comment
type: AnswerComment
has text: @revo, ah didn't get you. So, you mean you want `^a.*b[^b]+b`. Let me clarify that statement, I meant to say two `b` that not necessary must be together but this is good to add it
score: 0

http://stackoverflow.com/a/50200817
accepted answer of: http://stackoverflow.com/q/50199828
type: Answer
has comment: http://stackoverflow.com/comment/87418682
has comment: http://stackoverflow.com/comment/87418597
downvote count: 0
upvote count: 1
score: 1
has body: Something like this (test code)? jsn = { "type": "..", "box": "[..]", "features": [{ "type": "Feature", "geometry": { "type": "MultiPolygon", "coordinates": "[..]" }, "properties": { "p_30_34_yrs": 421, "p_tot": 3210, "year": "2014", "p_75_79_yrs": 30, "p_40_44_yrs": 259, "p_55_59_yrs": 174, "p_65_69_yrs": 96 }, "id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb1" }, { "type": "Feature", "geometry": { "type": "MultiPolygon" }, "properties": { "p_30_34_yrs": 2316, "p_tot": 22690, "year": "2014", "p_75_79_yrs": 461, "p_40_44_yrs": 1211, "p_55_59_yrs": 1031, "p_65_69_yrs": 1071 }, "id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb0" } ] } data = jsn["features"] props = {"p_30_34_yrs": 0, "p_tot": 0, "p_75_79_yrs": 0, "p_40_44_yrs": 0, "p_55_59_yrs": 0, "p_65_69_yrs": 0} for feat in data: if "properties" in feat: if "p_30_34_yrs" in feat["properties"]: props["p_30_34_yrs"] += feat["properties"]["p_30_34_yrs"] if "p_tot" in feat["properties"]: props["p_tot"] += feat["properties"]["p_tot"] if "p_75_79_yrs" in feat["properties"]: props["p_75_79_yrs"] += feat["properties"]["p_75_79_yrs"] if "p_40_44_yrs" in feat["properties"]: props["p_40_44_yrs"] += feat["properties"]["p_40_44_yrs"] if "p_55_59_yrs" in feat["properties"]: props["p_55_59_yrs"] += feat["properties"]["p_55_59_yrs"] if "p_65_69_yrs" in feat["properties"]: props["p_65_69_yrs"] += feat["properties"]["p_65_69_yrs"] print(props)
answers question: http://stackoverflow.com/q/50199828
type: AcceptedAnswer

http://stackoverflow.com/q/50109413
tagged with: api
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87236254
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87236219
has answer: http://stackoverflow.com/a/50109615
possible better answer: http://stackoverflow.com/a/50109615
accepted answer: http://stackoverflow.com/a/50109578
has comment: http://stackoverflow.com/comment/87236184
has comment: http://stackoverflow.com/comment/87236289
has title: Populate for loop with user input with JSON
tagged with: python
has body: I am still new to Python and I am still trying a lot of new things in this aspect. I am working with an API that contains JSON data that looks as follow: products: [ { id: 66057248, createdAt: "2018-02-28T14:55:22+01:00", updatedAt: "2018-04-26T20:44:12+02:00", isVisible: true, visibility: "visible", hasMatrix: false, data01: "", data02: "", data03: "", url: "product-name", title: "product name", fulltitle: "product name", etc... What I am trying to do now is to let the user give input on the values in the JSON file that he wants to compare with each other. I tried a couple of things but so far without a result. I am probably doing something stupid, but I don't know what. As you can see in my code below, I ask the user two times for the input, and these values are the values that I want to add to the for loop below. My question now is, what am I doing wrong and how can I insert the input data in the for loop? import requests import json response = requests.get('http://inserturlhere.com') data =response.text parsed=json.loads(data) first_value = input ('Name of first value: ') second_value = input ('Name of second value: ') first_test = ['first_value'] second_test = ['second_value'] for product in parsed['products']: if product[first_test] == product[second_test] : print(product['id'])
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87236269
has answer: http://stackoverflow.com/a/50109578
answer count: 2
has comment: http://stackoverflow.com/comment/87236314

http://stackoverflow.com/a/50150928
has body: Ignoring your function issue that others have mentioned in the comments, unindenting/untabbing many lines of code can be done in PyCharm by highlighting the text and pressing shift + tab. For interest, highlighting and pressing tab alone, adds a tab/indent.
upvote count: 23
score: 23
type: Answer
accepted answer of: http://stackoverflow.com/q/50150627
answers question: http://stackoverflow.com/q/50150627
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50201797
has comment: http://stackoverflow.com/comment/87420377
has comment: http://stackoverflow.com/comment/87420291
type: Answer
has comment: http://stackoverflow.com/comment/87420315
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50201745
has body: Use attribute key to get the required value. Ex: from bs4 import BeautifulSoup s = """&lt;a href="/go/wydarzenia/rozrywka/35826-majowka-w-twierdzy-klodzko? termin=265036" class="link with-img"&gt; &lt;img src="/go/resources/main/img//download/img- 14ab4e372df7bd0826c90f429f0e5933/twierdza-przewodnik-jpg.jpg" alt="Majówka w Twierdzy Kłodzko" class=""/&gt;""" soup = BeautifulSoup(s, "html.parser") print(soup.a.img["alt"]) #or print(soup.a.img.attrs["alt"]) Output: Majówka w Twierdzy Kłodzko
has comment: http://stackoverflow.com/comment/87420679
has comment: http://stackoverflow.com/comment/87420272

http://stackoverflow.com/q/50113130
tagged with: dictionary
favorite count: 0
has comment: http://stackoverflow.com/comment/87244162
answer count: 0
has title: Python: Passing variables into imported function vs keeping within the same module for loops and dictionaries
score: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/87244638
type: Question
has body: I'm sure there is a doc answering this exact question somewhere but I'm not sure what to google exactly Scenario: I have a decision tree that I need to iterate over a large dictionary and based on certain conditions needs to fetch variables from various input dictionaries. I know if I keep all these in the same module I can access the global variable in my function but if I split these into separate modules I'd have to pass in all the input dictionaries. Question 1) In the second case does this duplicate memory or are the passed in variables just a pointer to a position in memory. Question 2) For editing and creating new keys within a dictionary is there a way to amend a dictionary without having to reassign it. Many thanks Current Situation: input_dict = {'A': 1, 'B': 2} large_dictionary= {1 : { 'Name': 'John', 'Age': 30}, .... 1000 : { 'Name': 'Sam', 'Age': 20}} def function_1(): data['variable_to_create'] = input_dict['A'] for key,data in large_dictionary.items(): ... Some large decision tree ... function_1() Proposed Situation: Module def function_1(data, input_dict): data['variable_to_create'] = input_dict['A'] return data Code from new_module import function_1 input_dict = {'A': 1, 'B': 2} large_dictionary= {1 : { 'Name': 'John', 'Age': 30}, .... 1000 : { 'Name': 'Sam', 'Age': 20}} for key,data in large_dictionary.items(): ... Some large decision tree ... data = function_1(data, input_dict)
tagged with: python-3.x
tagged with: memory-management
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87244568
upvote count: 1
tagged with: python

http://stackoverflow.com/q/50143656
tagged with: mysql
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87312107
tagged with: sqlalchemy
favorite count: 0
type: Question
has title: Execute DDL/SQL files with SqlAlchemy and get good error messages
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87311642
tagged with: python
has comment: http://stackoverflow.com/comment/87620043
has comment: http://stackoverflow.com/comment/87322665
answer count: 0
has comment: http://stackoverflow.com/comment/87318931
tagged with: mysql-python
downvote count: 0
has body: Consider a simple SQL file like this: dummy.sql: DROP TABLE IF EXISTS blah; CREATE TABLE blah AS SELECT * FROM blahblah2; I can run it from the command line and get a nice error message: $ mysql -u ... -h ... ... &lt; /tmp/dummy.sql ERROR 1146 (42S02) at line 3: Table 'yourdb.blahblah2' doesn't exist Or I can run it from SQL Alchemy like this: import sqlalchemy ddl_sql = open("/tmp/dummy.sql").read() connect_string = "mysql+mysqldb://.../" engine = sqlalchemy.create_engine(connect_string) engine.execute(ddl_sql) When I run it from SQL Alchemy I get a giant stack trace with the following underlying error: "Commands out of sync; you can't run this command now" How can I get the "real error" out of SQL Alchemy? (someone asked for the traceback, so here it is) File "lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context context) File "lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 507, in do_execute cursor.execute(statement, parameters) File "lib/python3.6/site-packages/MySQLdb/cursors.py", line 252, in execute self._warning_check() File "lib/python3.6/site-packages/MySQLdb/cursors.py", line 148, in _warning_check warnings = db.show_warnings() File "lib/python3.6/site-packages/MySQLdb/connections.py", line 381, in show_warnings self.query("SHOW WARNINGS") File "lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/tmp/foo.py", line 8, in &lt;module&gt; engine.execute(ddl_sql) File "lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 2075, in execute return connection.execute(statement, *multiparams, **params) File "lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 942, in execute return self._execute_text(object, multiparams, params) File "li…
has comment: http://stackoverflow.com/comment/87319004
has comment: http://stackoverflow.com/comment/87319015

http://stackoverflow.com/q/50177330
has title: How to deal with: ImportError: /usr/lib/x86_64-linux-gnu/libatk-1.0.so.0: undefined symbol: g_log_structured_standard
tagged with: opencv
score: 15
answer count: 3
downvote count: 0
tagged with: error-handling
has answer: http://stackoverflow.com/a/50620062
has answer: http://stackoverflow.com/a/51490976
has body: I have a MacBook Pro on which I installed VirtualBox, installed Anaconda (from https://www.continuum.io), and installed OpenCV (conda install -c menpo opencv) Executed Python: python Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42) [GCC 7.2.0] on linux2 and tried to import OpenCV: &gt;&gt;&gt; import cv2 Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ImportError: /usr/lib/x86_64-linux-gnu/libatk-1.0.so.0: undefined symbol: g_log_structured_standard I Googled the error, but there are not many entries about that, and the ones I found were unsolved. I do not understand even what is the error about, so no clue how to solve it. I have installed Anaconda and OpenCV many times on other systems without problems. How can I solve this error?
favorite count: 0
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/87383772
has answer: http://stackoverflow.com/a/68161158
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/87678782
has text: Thanks. Then what should I do if I want to see the tree to the entire model?
type: Comment
comment on: http://stackoverflow.com/a/50256576
score: 0
type: AnswerComment

http://stackoverflow.com/q/50129898
linked to: http://stackoverflow.com/q/35678883
tagged with: tensorflow
has title: tensorflow restore only some variables from checkpoint
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: deep-learning
has body: After inspecting a checkpoint (let's call it model 1) I obtained the following list of variable names in it (shortened for simplicity): var_list = ["ex1_model/fc2/b", "ex1_model/fc2/b/Adam", "ex1_model/fc2/b/Adam_1", "ex1_model/fc2/w", "ex1_model/fc2/w/Adam"] Suppose I have a much bigger model 2 and want to initialize parts of it with the values from model 1. Obtain variables from names as described here (because I didn't find an easy way to do it): def get_vars_by_name(names): return [v for v in tf.global_variables() if v.name in names] Build model 2 and a saver to restore: logits = build_model(inputs) saver = tf.train.Saver(var_list=get_vars_by_name(var_list)) At saver.restore(sess, tf.train.latest_checkpoint(checkpoints_dir)) I receive the error: "ex1_model/fc2/w/Adam" [...] raise ValueError("No variables to save") Please help me find the mistake I made. I'd also be grateful for a simpler way because this is terrible. Thank you.
has answer: http://stackoverflow.com/a/50130274
answer count: 1

http://stackoverflow.com/comment/87226908
type: QuestionComment
comment on: http://stackoverflow.com/q/50104782
has text: Can you copy-paste the error message verbatim in the question?
score: 0
type: Comment

http://stackoverflow.com/comment/87229190
comment on: http://stackoverflow.com/q/50105931
has text: This question is pretty broad - try to implement something then come back and ask more specific questions other than `"how do I do this?"` You cannot [dynamically create variable names](https://stackoverflow.com/q/1373164/2823755), the most prevalent solution seems to be keeping everything in a dictionary with the keys being dynamically created. [`DataFrame.groupby('col1')`](https://pandas.pydata.org/pandas-docs/stable/groupby.html) may be what you are looking for.
type: QuestionComment
score: 3
type: Comment

http://stackoverflow.com/q/50131099
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/60377551
score: 0
accepted answer: http://stackoverflow.com/a/60377551
tagged with: python
has answer: http://stackoverflow.com/a/50133929
tagged with: interpolation
has body: I would like to create a python function to linearly interpolate within a partly empty grid and get a nearest extrapolation out of bounds. Let's say I have the following data stored in pandas DataFrame: In [1]: import numpy as np In [2]: import pandas as pd In [3]: x = [0,1,2,3,4] In [4]: y = [0.5,1.5,2.5,3.5,4.5,5.5] In [5]: z = np.array([[np.nan,np.nan,1.5,2.0,5.5,3.5],[np.nan,1.0,4.0,2.5,4.5,3.0],[2.0,0.5,6.0,1.5,3.5,np.nan],[np.nan,1.5,4.0,2.0,np.nan,np.nan],[np.nan,np.nan,2.0,np.nan,np.nan,np.nan]]) In [6]: df = pd.DataFrame(z,index=x,columns=y) In [7]: df Out[7]: 0.5 1.5 2.5 3.5 4.5 5.5 0 NaN NaN 1.5 2.0 5.5 3.5 1 NaN 1.0 4.0 2.5 4.5 3.0 2 2.0 0.5 6.0 1.5 3.5 NaN 3 NaN 1.5 4.0 2.0 NaN NaN 4 NaN NaN 2.0 NaN NaN NaN I would like to get function myInterp that returns a linear interpolation within data boundaries (i.e. not NaN values) and get a nearest extrapolation outside bounds (i.e. NaN or no values) such as: In [1]: myInterp([1.5,2.5]) #linear interpolation Out[1]: 5.0 In [2]: myInterp([1.5,4.0]) #bi-linear interpolation Out[2]: 3.0 In [3]: myInterp([0.0,2.0]) #nearest extrapolation (inside grid) Out[3]: 1.5 In [4]: myInterp([5.0,2.5]) #nearest extrapolation (outside grid) Out[4]: 2.0 I tried many combination of scipy.interpolate package with no success, does anyone have a suggestion how to do it ?
type: AnsweredQuestion
answer count: 2
has title: How to interpolate/extrapolate within partly empty regular grid?
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/50133929
tagged with: scipy

http://stackoverflow.com/a/50079973
has body: It's because when you kill the tkinter window, the canvas object is also destroyed, being a child of the tkinter window (in this instance the canvas is reported as an object number .4318456072). But the while loop is still running -- even though the tkinter window is gone. But the canvas object doesn't exist, which generates the error. Correcting can include putting a try/expect block around the canvas.move statement and cause the while loop to break when this exception occurs. In particular, anything to do with tkinter within the while loop should be caught. Very trivial error checking here could be: try: canvas.move(ball, xspeed, yspeed) Tk.update(window1) except: break
answers question: http://stackoverflow.com/q/50079363
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/50079363
type: Answer

http://stackoverflow.com/q/50147113
has body: I am creating a virtual environment and installing packages. In shell script, i can able to install all the packages. But in my python code, getting Permission denied error message while installing pytest, pytest-cov, etc. Shell Code VIRT_DIR=virt_folder pip install --user virtualenv virtualenv $VIRT_DIR . $VIRT_DIR/bin/activate pip install pylint pip install coverage pip install pytest pip install pytest-cov pip install virtualenvwrapper Python Code (Version 2.7) VIRT_DIR = "virt_folder" subprocess.call("pip install --user virtualenv", shell=True) subprocess.call("virtualenv " + VIRT_DIR, shell=True) subprocess.call(". " + VIRT_DIR + "/bin/activate", shell=True) subprocess.call("pip install pylint", shell=True) subprocess.call("pip install coverage", shell=True) subprocess.call("pip install pytest", shell=True) subprocess.call("pip install pytest-cov", shell=True) Error message: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/lib/python2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/lib/python2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/lib/python2.7/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python2.7/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/usr/lib/python2.7/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib64/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/lib/python2.7/site-packages/py' You are using pip version …
favorite count: 0
has comment: http://stackoverflow.com/comment/87312444
type: Question
has comment: http://stackoverflow.com/comment/87312403
has comment: http://stackoverflow.com/comment/87312468
has comment: http://stackoverflow.com/comment/87468705
type: UnansweredQuestion
has title: Installing Packages using python in Virtual Environment in Linux(Bash to Python )
tagged with: pip
tagged with: python
linked to: http://stackoverflow.com/q/49040017
has comment: http://stackoverflow.com/comment/87312530
tagged with: python-2.7
tagged with: bash
answer count: 0
has comment: http://stackoverflow.com/comment/87312528
score: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/49040017
has comment: http://stackoverflow.com/comment/87312429
upvote count: 1
tagged with: virtualenv

http://stackoverflow.com/comment/87318523
comment on: http://stackoverflow.com/q/50149279
score: 0
has text: I've edited my code, to give you an example of my application. Thank you
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87397953
score: 0
has text: That's due to no typemap defined in SWIG for `unsigned char *`.
type: AnswerComment
comment on: http://stackoverflow.com/a/50185056
type: Comment

http://stackoverflow.com/q/50092954
answer count: 2
has comment: http://stackoverflow.com/comment/87202108
downvote count: 2
tagged with: pip
accepted answer: http://stackoverflow.com/a/50093247
favorite count: 0
type: Question
tagged with: opencv
has title: import opencv vs import cv2
has body: I recently installed opencv-python-3.4.0.12 via pip install on Mac OS. When I run the Python interpreter, import cv2 works fine whereas import opencv raises ModuleNotFoundError. However, when I run the Python3 Interpreter, import opencv works fine whereas import cv2 raises ModuleNotFoundError. What is the reason behind this difference and on a related note, should I use import opencv or import cv2? Does cv2 refer to OpenCV version 2?
tagged with: python
score: 17
tagged with: macos
possible better answer: http://stackoverflow.com/a/73680606
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/50093247
has answer: http://stackoverflow.com/a/73680606

http://stackoverflow.com/comment/87202985
type: Comment
has text: @Anon every time you call a function in a recursive call it adds a level to the call stack, if that stack gets too large you get a stack overflow, even if using a loop is slower ( which it may it may not be) at least you wouldn't get a call stack overflow error
type: QuestionComment
comment on: http://stackoverflow.com/q/50093215
score: 0

http://stackoverflow.com/comment/87317419
has text: Correct me if I'm wrong, but can't you just parse it as XML, get all descendants of `owl:equivalentClass` and group their attributes. Then match all attributes that start with `http://purl.obolibrary.org/` and get the last path-item of the string?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50137442

http://stackoverflow.com/comment/87298916
has text: A merge is overkill here.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50140213
type: Comment

string-to-datetime
tag name: string-to-datetime
tags question: http://stackoverflow.com/q/50182568
type: Tag

http://stackoverflow.com/q/50087695
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50088790
has comment: http://stackoverflow.com/comment/87191295
type: UnansweredQuestion
tagged with: python
has title: Class Inheritance with parameters
tagged with: inheritance
has answer: http://stackoverflow.com/a/50087755
tagged with: class
answer count: 2
has body: I have a parent class and several subclasses. Every subclass accepts different parameters, but all subclasses have some common parameters. I don't want to write the "common parameters" for every subclass. How can I do this? class Parent: def __init__(self, name): self.name = name class Subclass(Parent): def __init__(self, age): self.age = age def do_something(self): print(self.name) instance = Subclass(name="Test", age=42) instance.do_something() # 42

http://stackoverflow.com/q/50161316
has comment: http://stackoverflow.com/comment/87341267
answer count: 4
type: Question
has title: Fill in missing values in lists
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50161586
favorite count: 0
has comment: http://stackoverflow.com/comment/87340768
score: 3
has answer: http://stackoverflow.com/a/50162494
has body: Lets say I have 2 lists of data related to a time stamp and a number so: list1 = ['00:00:02', '00:00:05', '00:00:06'] list2 = [2,3,4] I want to essentially fill in the missing time stamps to the rest of the day and have a '0' for any time there is not a coreseponding number to the time stamp, assuming the times match the number sin list1 and list2. So we get: list1 = ['00:00:02', '00:00:05', '00:00:06'] list2 = [2,3,4] list3 = ['00:00:00', '00:00:01', '00:00:02', '00:00:03', '00:00:04', '00:00:05', '00:00:06'] list4 = [0,0,2,0,0,3,4] Been trying to conceptualize how to do this any can't think of anything logical.
has answer: http://stackoverflow.com/a/50161687
has answer: http://stackoverflow.com/a/50161547

http://stackoverflow.com/q/50202418
has title: How to Run Anaconda pompt in Ubuntu
tagged with: ubuntu
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/54220095
possible better answer: http://stackoverflow.com/a/54220095
tagged with: python
has body: I'm using Anaconda with Python 2.7.14 and spyder 3.2.6 On Ubuntu 14.Can you please suggest me how do I access anaconda promt from Ubuntu? By Anaconda prompt I meant this
answer count: 2
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/50202631
accepted answer: http://stackoverflow.com/a/50202631

http://stackoverflow.com/a/50142271
type: AcceptedAnswer
has body: if names in f: isn't going to work as f is a filename, not a list. Maybe you want if f in names: But you don't need to scan a whole directory for this, just loop on the files you're targetting, it they exist: for f in ['cb10.txt','cb11.txt']: if os.path.exists(f): shutil.move(f,dest) If you have a lot of cbxxx.txt files, maybe an alternative would be to compute the intersection of this list with the result of os.listdir using a set (for faster lookup than a list, worth if there are a lot of elements): for f in {'cb10.txt','cb11.txt'}.intersection(os.listdir(".")): shutil.move(f,dest) On Linux, with a lot of "cb" files, this would be faster because listdir doesn't perform a fstat, whereas os.path.exists does. EDIT: if the files have the same prefix/suffix, you can build the lookup set with a set comprehension to avoid tedious copy/paste: s = {'cb{}.txt'.format(i) for i in ('10','11')} for f in s.intersection(os.listdir(".")): or for the first alternative: for p in ['10','11']: f = "cb{}.txt".format(p) if os.path.exists(f): shutil.move(f,dest) EDIT: if all cb*.txt files must be moved, then you can use glob.glob("cb*.txt"). I won't elaborate, the linked "duplicate target" answer explains it better.
answers question: http://stackoverflow.com/q/50142125
has comment: http://stackoverflow.com/comment/87303256
accepted answer of: http://stackoverflow.com/q/50142125
has comment: http://stackoverflow.com/comment/87303706
type: Answer
has comment: http://stackoverflow.com/comment/87304028
score: 0
has comment: http://stackoverflow.com/comment/87304112

http://stackoverflow.com/q/50205214
has answer: http://stackoverflow.com/a/50205315
downvote count: 2
answer count: 2
upvote count: 1
has title: how to match python list item with regular expression
favorite count: 0
type: Question
has body: import re def popular_words(text, words): """(str, array) -&gt; dictionary returns dictionary search words are the keys and values are the number of times when those words are occurring in a given text """ word_dictionary = {} for word in words: list = re.findall(word, text, re.IGNORECASE) word_dictionary.update({word : len(list) }) return word_dictionary popular_words(''' When I was One I had just begun When I was Two I was nearly new ''', ['i', 'was', 'three', 'near']) How do I ignore 'near' in the text string and not match to 'nearly' I've tried using \bword\b to define the word boundary and the error was: "unexpected character after line continuation character"
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: regex
has answer: http://stackoverflow.com/a/50205267

http://stackoverflow.com/comment/87242036
type: AnswerComment
has text: Thanks, your version is even simpler than mine.
comment on: http://stackoverflow.com/a/50112227
type: Comment
score: 0

http://stackoverflow.com/q/50164738
tagged with: python
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87365576
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: tk-toolkit
has title: Frames don't load in Tk. (Tk-Gui-Python)
type: Question
has body: I'm new to Python programming and I am doing this project for learning. My problem is, when I start the app, MainScreen is shown but after that other frames are not loading. These functions work seperately. Animate and texting functions work when executed on their own. I'm trying to put them together in a single app. import matplotlib.pyplot as plt import matplotlib.animation as animation import time from time import sleep import serial from Tkinter import * FO = open("SensorValues.txt", "w+") ser = serial.Serial() ser.baudrate = 9600 ser.port = '/dev/ttyUSB0' ser.open() data = ser.readline(5) FO.write(data + '\n') FO.flush() def organizer(frame): frame.tkraise() root = Tk() MainScreen = Frame(root) LiveGraph = Frame(root) LiveLabel = Frame(root) for frame in (MainScreen,LiveGraph,LiveLabel): frame.grid(row=0,column=0,sticky='news') Label(MainScreen,text = 'Choose what do you want').pack() def animate(i): fig = plt.figure() ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) sleep(1) dataArray = FO.split('\n') xar = [] yar = [] for eachLine in dataArray: if len(eachLine)&gt;1: x,y = eachLine.split(',') xar.append(int(x)) yar.append(int(y)) ax1.clear() ax2.clear() ax1.plot(xar) ax2.plot(yar) ani = animation.FuncAnimation(fig, animate, interval=1000) plt.show() def texting(): LiveLabel.config(text=data) root.after(1, texting) organizer(MainScreen) Button(MainScreen, text = 'Press for starting live graph!', width = 30, command = lambda:organizer(LiveGraph)).pack() Button(MainScreen, text = 'Press for starting live label!', width = 30, command = lambda:organizer(LiveLabel)).pack() Label(LiveGraph,text = '1st Table Temperature - 2nd Table Humidity').pack() Button(LiveGraph,text = 'Stop',width = 10, command = root.destroy ).pack() Button(LiveLabel,text = 'Stop',width = 10, command = root.destroy ).pack() plt.show() FO.close() ser.close() root.mainloop() Screenshots :
has comment: http://stackoverflow.com/comment/87348024
has comment: http://stackoverflow.com/comment/87347816

http://stackoverflow.com/q/50150429
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/87338453
has comment: http://stackoverflow.com/comment/87324538
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87338274
has comment: http://stackoverflow.com/comment/87333667
score: 0
has body: Is there any way to list all AWS security groups using boto3 ? With this code i can get only 5 groups (out of 25 in region) client = boto3.client('ec2') response=client.describe_security_groups( ) print response I have 4 VPC's so i tried to get groups for each VPC, added this as filter: Filters=[ { 'Name': 'vpc-id', 'Values': [ 'vpc-d60ee9b1', ] }, ], But as results i got this: {u'SecurityGroups': [], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '44f39633-4f21-4c4f-b3f4-82fbce538c5f', 'HTTPHeaders': {'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'server': 'AmazonEC2', 'content-type': 'text/xml;charset=UTF-8', 'date': 'Thu, 03 May 2018 08:25:03 GMT'}}} Tried to filter by region and got:The filter 'region' is invalid However, with AWS CLI it works: aws ec2 describe-security-groups --region $REGION Does it means i need to stick with AWS CLI or boto3 has syntax to list ALL security groups for AWS account ?
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87333151
accepted answer: http://stackoverflow.com/a/50161577
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87338526
has comment: http://stackoverflow.com/comment/87330941
has comment: http://stackoverflow.com/comment/87355204
has answer: http://stackoverflow.com/a/50161577
has title: boto3 list all security groups for AWS account
has comment: http://stackoverflow.com/comment/87340856

http://stackoverflow.com/a/54315798
score: 3
answers question: http://stackoverflow.com/q/50125472
type: Answer
upvote count: 3
downvote count: 0
has body: I had the same problem on Windows 10-64 bit and intuitively installed the 64-bit version of miniconda. However, it results in exactly the same error above. Installing 32 bit conda installer has resolved the issue

http://stackoverflow.com/comment/87497568
score: 0
type: AnswerComment
has text: @Graham Dumpleton, Thanks for the help guys. Please see EDIT 3.
comment on: http://stackoverflow.com/a/50206139
type: Comment

http://stackoverflow.com/a/50108351
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50108280
score: 2
has body: try using df_train['TRDATETIME'] = pd.to_datetime(df_train['TRDATETIME'], format='%d%b%y:%H:%M:%S') %b == Month as locale’s abbreviated name.Ex: Jan, Feb %y == Year without century as a zero-padded decimal number.Ex: 17, 18
answers question: http://stackoverflow.com/q/50108280
type: Answer
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87413710
comment on: http://stackoverflow.com/a/50198446
type: Comment
score: 0
type: AnswerComment
has text: @JörgWMittag: I don't think so: the "real" part of the list would be accessed in O(1) like a regular Python `list`, and the "virtual" part would be accessed in O(1) by simply returning the "empty" value. There is no need to materialize the virtual part.

http://stackoverflow.com/comment/107585069
type: AnswerComment
score: 1
has text: Worked for `Mysql 8.0.19` and `Windows 10`.
comment on: http://stackoverflow.com/a/54969623
type: Comment

http://stackoverflow.com/comment/87455950
comment on: http://stackoverflow.com/a/50219493
score: 0
type: AnswerComment
has text: I validated this works in python3 in my shell. Enjoy!
type: Comment

http://stackoverflow.com/a/50132279
upvote count: 4
has comment: http://stackoverflow.com/comment/87284339
has comment: http://stackoverflow.com/comment/87283994
accepted answer of: http://stackoverflow.com/q/50131823
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/50131823
has comment: http://stackoverflow.com/comment/87282705
has body: Did you try to_sql function from pandas module? from sqlalchemy import create_engine engine = create_engine('oracle://[user]:[pass]@[host]:[port]/[schema]', echo=False) dataset.to_sql(name='target_table',con=engine ,if_exists = 'append', index=False)
score: 3
has comment: http://stackoverflow.com/comment/87282963
type: Answer

http://stackoverflow.com/a/50138180
has body: If you just want to remove the bad characters from the beginning of your strings, you can use pandas.Series.str.replace: In [26]: df Out[26]: col1 0 , Matt R, Carl A 1 _ Hello, World_ 2 ). My Name is ). 'Amy' 3 . My name is 'Matt' 4 ., My name is 'Clark' In [27]: df['col1'] = df['col1'].str.replace(r'^[^a-zA-Z]+', '') In [28]: df Out[28]: col1 0 Matt R, Carl A 1 Hello, World_ 2 My Name is ). 'Amy' 3 My name is 'Matt' 4 My name is 'Clark'
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50137670
score: 2
accepted answer of: http://stackoverflow.com/q/50137670
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87310714
has text: `def ban_users(self, request, queryset): print(queryset) #select an instance from queryset` Output is still : if instance.__class__.__name__ == 'Profile' ^ SyntaxError: invalid syntax Unfortunately
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50146114

http://stackoverflow.com/q/50145969
type: Question
has answer: http://stackoverflow.com/a/50146230
has body: I'm struggling for a moment with the instance variables in Tornado. My code below: def initialize(self): self.needed_file = [] def put(self): try: if something: self.needed_file.append('Ninja file') self.needed_file.append(dico_data[0][1].decode('utf-8')) print(self.needed_file) except IndexError: pass def get(self): try: print('//' + str(self.needed_file) + '//') except AttributeError: print('{}'.format(ServerHandler.needed_file)) I don't manage to print the value of self.needed_file from put(self) to get(self), interpreter give me this traceback. ['Ninja file', '/Users/corpo/DistributedBuild/]` &lt;----------- print() from put [I 180503 10:01:59 web:2106] 200 PUT / (::1) 11.87ms //[]// &lt;--------- print() from get [E 180503 10:01:59 web:1621] Uncaught exception GET / (192.168.1.189) And of course the uncaught expression is an Index Error Exception, because I'm asking get to give me a value in a list that it doesn't have. Thanks !
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87318737
tagged with: python
tagged with: variables
tagged with: tornado
score: 0
tagged with: instance
has title: Python Tornado : Instance variable are not saved from a method to another
answer count: 1
has comment: http://stackoverflow.com/comment/87321960
tagged with: reference
has comment: http://stackoverflow.com/comment/87320269

http://stackoverflow.com/comment/87352289
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50166824
type: Comment
has text: Also see: https://stackoverflow.com/questions/12501956/randomly-select-x-number-of-items-from-class-list-in-python

http://stackoverflow.com/comment/101751380
score: 1
has text: https://airflow.apache.org/howto/operator/python.html?highlight=op_kwargs#passing-in-arguments New link
comment on: http://stackoverflow.com/a/50095130
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/117629438
type: AnswerComment
comment on: http://stackoverflow.com/a/50098557
type: Comment
score: 0
has text: This also worked perfectly for what I was trying to do. Thank you!

http://stackoverflow.com/comment/87216032
type: Comment
comment on: http://stackoverflow.com/q/50099717
score: 0
has text: please do not post pictures of errors. Edit the post and post the error and the code causing it. See [this](http://idownvotedbecau.se/imageofanexception/) for more information.
type: QuestionComment

http://stackoverflow.com/comment/129629343
has text: Isn't the recommendation here leads to multiple installations of `Jupyter` itself? This is probably not desired; there should be a single global `Jupyter` that uses kernels that are installed in the different environments (using `pipenv`). At least this is what I understand. I'm struggling with the global installation of Jupyter (and other tools as well; e.g. `black`).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50183177

http://stackoverflow.com/comment/87418799
type: Comment
comment on: http://stackoverflow.com/a/50196415
score: 0
type: AnswerComment
has text: the above code throws `(1048, "Column 'client_id' cannot be null")`. I did notice that I can use the .get() method and it "works" - but I get a `(1048, "Column 'client_id' cannot be null")` error. Which lead to the update posted above. The request type is a POST. I do now see that I'm not exactly sure what object I'm getting the `form.instance` from as both keys produce `null` values.

http://stackoverflow.com/q/50178383
has answer: http://stackoverflow.com/a/50181338
type: AnsweredQuestion
score: 0
has title: Manipulating raw packets to have NAT functionality
has comment: http://stackoverflow.com/comment/87375319
accepted answer: http://stackoverflow.com/a/50181338
type: Question
has comment: http://stackoverflow.com/comment/87374338
has body: I want to implement a custom NAT in python, in terms of doing that I want to receive all client packets and modify them. Then forward them to another device. I found scapy that can manipulate and send packets easily. But could not find a way to receive packets. So is it possible to receive packets then edit them like editing source IP and destination IP and read UDP headers and forward them and later forward the response packets?
tagged with: scapy
answer count: 1
tagged with: python

http://stackoverflow.com/q/50198539
answer count: 1
has title: Wagtail Custom Inline PageChooser
tagged with: django
favorite count: 0
type: Question
has body: Currently i face a strange problem, using wagtail. I modified a Snippet from the Documentation. But it seems like i miss something. This is my Code... The Goal is to allow selecting multible Pages using PageChooser (and maybe later show links in template) class BlogPage(Page): content_panels = Page.content_panels + [ MultiFieldPanel([ InlinePanel('related_pages', label="Related Pages"), ]) ] class BlogPageRelated(Orderable): page = ParentalKey('home.BlogPage', on_delete=models.CASCADE, related_name='related_pages') relpages = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', blank=True, null=True ) panels = [ PageChooserPanel('relpages', 'home.BlogPage'), ] The Database is filled with data. It seems like no data are delivered to the template. The template variable {{ page.related_pages }} outputs "home.BlogPageRelated.None". {{ page.related_pages }} = home.BlogPageRelated.None For better understanding this is the snipped i adopted - (!) and it works well! class BlogPageImage(Orderable): page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) panels = [ ImageChooserPanel('image'), ]
type: AnsweredQuestion
score: 1
tagged with: database
tagged with: python
has answer: http://stackoverflow.com/a/50203362
accepted answer: http://stackoverflow.com/a/50203362
downvote count: 0
upvote count: 1
tagged with: wagtail

3dr
tag name: 3dr
type: Tag
tags question: http://stackoverflow.com/q/50204883

http://stackoverflow.com/a/50205315
has body: You can definitely use string formatting and \b. That error you got may have been because you didn't use a raw string like this (always use raw strings with re if you're using backslashes, it makes life easier.): import re def popular_words(text, words): """(str, array) -&gt; dictionary returns dictionary search words are the keys and values are the number of times when those words are occurring in a given text """ word_dictionary = {} for word in words: list = re.findall(r'\b{0}\b'.format(word), text, re.IGNORECASE) word_dictionary.update({word : len(list) }) return word_dictionary print(popular_words(''' When I was One I had just begun When I was Two I was nearly new ''', ['i', 'was', 'three', 'near'])) output: {'i': 4, 'near': 0, 'was': 3, 'three': 0} EDIT: for the sake of completeness. This is what you'd have to use to not use a raw string. You have to escape backslashes by doubling them. list = re.findall('\\b{0}\\b'.format(word), text, re.IGNORECASE)
answers question: http://stackoverflow.com/q/50205214
type: Answer
score: 0

http://stackoverflow.com/comment/87240207
type: Comment
comment on: http://stackoverflow.com/q/50111322
score: 2
type: QuestionComment
has text: Please see https://stackoverflow.com/help/mcve

http://stackoverflow.com/a/50134199
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50134178
has comment: http://stackoverflow.com/comment/87290046
upvote count: 2
score: 2
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50134178
has body: You just have to make the first + not greedy: [re.sub(".+?\_(.+)","\g&lt;1&gt;",gg) for gg in test] # note the ? returns: ['ILL_BE_BACK', 'HASTA_LA_VISTA_BABY', 'SARAH', 'CONNOR'] The ? after the + makes the + none-greedy, so it consum only as much as needed: re.match('.*',"abcdefgh") # finds 'abcdefgh' (the entire string) re.match('.*?',"abcdefgh") # finds '' (an empty string) re.match('.+',"abcdefgh") # finds 'abcdefgh' (the entire string) re.match('.+?',"abcdefgh") # finds 'a' (only the first character) re.match('.+?f',"abcdefgh") # finds 'abcdef' (all characters till f) This means your regex .+\_(.+) consumes everything till he gets just enough to match the rest _(.+) which is only the last part. If you change the regex to .+?\_(.+), it will only consume till the first _ and then stop.

http://stackoverflow.com/comment/87279051
has text: hmmm strange! Yeah let me know if you are still stuck normally it should work.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50127494
type: QuestionComment

http://stackoverflow.com/q/50111462
linked to: http://stackoverflow.com/q/33511544
has comment: http://stackoverflow.com/comment/87240261
tagged with: http://stackoverflow.com/tag/xml
score: 0
has comment: http://stackoverflow.com/comment/87240520
answer count: 0
has comment: http://stackoverflow.com/comment/87240427
has title: How to extract the contents from an xml section based on a field value using python
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87240210
type: UnansweredQuestion
has body: I want to extract the contents from an xml file based on the value of a field type. Basically, it was a json file, which I converted to xml. The file has fields, 'body','id', 'type' and snippets. I want to extract the contents of all these fields if the 'type='summary'. The code I have done is given: def load_extract(data): path="" soup = BeautifulSoup(open(path),"html.parser") q1=[] qtype=[] snippets=[] for q in soup.findAll('body'): q=q.text q1.append(q) for types in soup.findAll('type'): type1=types.text qtype.append(type1) snippets=soup.findAll('snippets') summary_ids=[] summary_dict=[] for i in range (0, len(qtype)): print "extracting the summary type question" if qtype[i]=='summary': summary_ids.append(i) for j in summary_ids: summary_dict.append({q1[j]:snippets[j]}) return summary_dict The code works fine on a small set that I run, but with large set, the len(q1) is not equal to len(snippets). This creates a problem. I don't know whether the training data actually does not have snippets for some of the body. But this creates problem in mapping and hence extractions. I was thinking whether I could just extract the the body, id and snippets of type='summary'. Request your kind help!
tagged with: python
has comment: http://stackoverflow.com/comment/87240297

http://stackoverflow.com/comment/90618068
type: AnswerComment
comment on: http://stackoverflow.com/a/50509853
has text: python -m pip install --upgrade pip
type: Comment
score: 0

python-requests-html
tags question: http://stackoverflow.com/q/50154804
tags question: http://stackoverflow.com/q/50165281
type: Tag
tag name: python-requests-html

http://stackoverflow.com/q/50208954
linked to: http://stackoverflow.com/q/6367014
tagged with: django
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/87435607
score: 1
has body: I'm trying to send email with django. Here's my settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'mailpassword' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'mymail@gmail.com' I've also enabled access to less secure apps in the gmail settings. On the production server whenever I try to send an email, it's raising an error in the command line upstream prematurely closed connection while reading response header from upstream. On webpage it's showing 502 Bad Gateway error. How can we solve this issue? Thank You . . .
has comment: http://stackoverflow.com/comment/87436100
has comment: http://stackoverflow.com/comment/87435628
has title: Sending Email with Django
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87435780
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/87435520
type: UnansweredQuestion

http://stackoverflow.com/a/50114715
upvote count: 7
has comment: http://stackoverflow.com/comment/116980624
has body: How can I use python3 setup.py install to install the header files? Unfortunately, you can't as long as you're using setuptools. What happens under the hood when you call setuptools.setup()? An egg installer is being built (bdist_egg command) and installed (via easy_install), and neither bdist_egg nor easy_install support including/installing headers. Although the distribution object carries the headers info, it is never requested during the install command. This is an old well-known problem that was never resolved because apparently, installation of header files doesn't fit into the egg build/install procedure. You thus have three options (or at least three options I know of). Two of them (both inducing a switch to distutils) are not recommended and are provided for completeness sake only: Bare distutils install (not recommended) $ sed 's/from setuptools import setup/from distutils.core import setup/' setup.py This way, the good ol' distutils will take care of the installation when doing python setup.py install, no egg installer will be built and install_headers will be invoked. However, this also includes giving up all the features of setuptools including additional keyword args in setup() and all the other good stuff, needless to say that packages installed via distutils can't be uninstalled with pip. old-and-unmanageable install (not recommended) Run the installation with $ python setup.py install --old-and-unmanageable This is a switch setuptools provides if you explicitly wish to run the distutils install. The egg installer is not built, instead, the distutils.command.install.install is invoked. Thus, the installation is the same as with bare distutils install. Drawbacks of this approach: same as with bare distutils install plus: setuptools condemns usage of the switch; if you forget to provide it, you end with installing eggs and have to redo the installation. Replace python setup.py install with pip install (recommended) pip is capable of installing packages…
has comment: http://stackoverflow.com/comment/87256422
has comment: http://stackoverflow.com/comment/87256527
has comment: http://stackoverflow.com/comment/87246600
downvote count: 0
has comment: http://stackoverflow.com/comment/87255446
type: Answer
accepted answer of: http://stackoverflow.com/q/50101740
has comment: http://stackoverflow.com/comment/116953370
has comment: http://stackoverflow.com/comment/87257548
answers question: http://stackoverflow.com/q/50101740
has comment: http://stackoverflow.com/comment/87256125
has comment: http://stackoverflow.com/comment/116974631
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87254876
has comment: http://stackoverflow.com/comment/87255603
has comment: http://stackoverflow.com/comment/87255417

http://stackoverflow.com/q/50229388
tagged with: numpy
has comment: http://stackoverflow.com/comment/87481593
downvote count: 0
has answer: http://stackoverflow.com/a/50229596
has title: Iterative formula in Pandas/Numpy
tagged with: pandas
upvote count: 1
type: UnansweredQuestion
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87475966
score: 1
tagged with: python
has body: Is it possible to perform an iterative/recursive calculation using Pandas and Numpy? That is, consuming data from a DataFrame and applying the formula efficiently using Numpy functions, instead of doing the calculation step-by-step in using a Python for loop. For example, how would the Fibonacci sequence look?
type: Question

http://stackoverflow.com/a/50183546
has body: There is no way to auto-generate a Page Token, but you can use an Extended Page Token - it is valid forever. More information: https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension http://www.devils-heaven.com/facebook-access-tokens/ Token debugger: https://developers.facebook.com/tools/debug/accesstoken/
has comment: http://stackoverflow.com/comment/87402290
type: Answer
has comment: http://stackoverflow.com/comment/87403081
answers question: http://stackoverflow.com/q/50183503
score: 0

http://stackoverflow.com/comment/98830670
comment on: http://stackoverflow.com/q/50128336
type: QuestionComment
has text: Delete `print(vs2.name)`, try `print(vs2.__enter__().name)` instead.
type: Comment
score: 0

http://stackoverflow.com/comment/87445024
has text: But to answer the original question, you'll have to train different models using your desired input data. It's possible to write up code using pandas that does a "for this sample, drop all NaN, and pick a model" but sklearn doesn't have that feature
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50214040
type: QuestionComment

http://stackoverflow.com/comment/97395791
type: Comment
comment on: http://stackoverflow.com/a/50095130
type: AnswerComment
has text: @Newskooler This seems to be a new question. Regardless, this might help you: https://stackoverflow.com/questions/54894418/how-to-pass-parameter-to-pythonoperator-in-airflow
score: 0

http://stackoverflow.com/q/50102932
has title: Illogical parameters returned by scipy.curve_fit
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/87222876
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50105086
has comment: http://stackoverflow.com/comment/87234357
has body: I'm modelling a ball falling through fluid in Python and fitting the model function to a set of data points using the damping coefficients (a and b) and the density of the fluid, but the fitted value for the fluid density is coming back negative and I have no idea what is wrong in the code. My code is below: import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint from scipy.optimize import curve_fit ##%%Parameters and constants m = 0.1 #mass of object in kg g = 9.81 #acceleration due to gravity in m/s**2 rho = 700 #density of object in kg/m**3 v0 = 0 #velocity at t=0 y0 = 0 #position at t=0 V = m / rho #volume in cubic meters r = ((3/4)*(V/np.pi))**(1/3) #radius of the sphere asample = 0.0001 #sample value for a bsample = 0.0001 #sample value for b #%%Defining integrating function ##fuction =&gt; y'' = g*(1-(rhof/rho))-((a/m)y'+(b/m)y'**2) ## y' = v ## v' = g*(1-rhof/rho)-((a/m)v+(b/m)v**2) def sinkingball(Y, time, a, b, rhof): return [Y[1],(1/m)*(V*g*(rho-rhof)-a*Y[1]-b*(Y[1]**2))] def balldepth(time, a, b, rhof): solutions = odeint(sinkingball, [y0,v0], time, args=(a, b, rhof)) return solutions[:,0] time = np.linspace(0,15,151) # imported some experimental values and named the array data a, b, rhof = curve_fit(balldepth, time, data, p0=(asample, bsample, 100))[0] print(a,b,rhof)
downvote count: 2
answer count: 1
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/50125720
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/87349785
has comment: http://stackoverflow.com/comment/87286871
answer count: 0
type: UnansweredQuestion
tagged with: django
has body: I am new to Django so please forgive any silly mistakes in my code. I have made a post with multiple images using FBV. it works perfectly fine and does its job of adding multiple images to a post. Now I am working on editing the Post however I am having issues with editing the post I get the below error. AttributeError at /gangsters/edit/Scarface-the-story-of-Al-Capone/ 'tuple' object has no attribute '_committed' Request Method: POST Request URL: http://127.0.0.1:8000/gangsters/edit/Scarface-the-story-of-Al-Capone Django Version: 1.11 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute '_committed' A brief description of my models Lets say I am trying to make this web-app that allows users to write about Gangsters (more like the post model)from around the world and from different time periods. There are 2 models. Gangsters and GangMembers. GangMember has a foreign_key to Gangster my models are as below class Gangster(models.Model): user = models.ForeignKey(User, related_name='posts') gangster_name = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) history = models.TextField() gangster_image = models.ImageField() # there are more attributes like "Post-like but ignoring them as they are not relevant here" def save(self, *args, **kwargs): self.slug = slugify(self.title) #for SEO on google searches super().save(*args, **kwargs) class Gangmember(models.Model): gangster = models.ForeignKey(Gangster, on_delete=models.CASCADE, related_name="ganglord") gangmember_image= models.ImageField(upload_to='images/', blank=True, null=True, default='') gangmember_name = models.CharField(max_length=100, default='') brief_description = models.CharField(max_length=1000, default='') below is my gangster_edit views.py @login_required def gangster_edit(request, slug): gangster = get_object_or_404(Gangster, slug=slug) ImageFormSet = modelformset_factory(Gangmember, fields=('gangmember_image', 'gangmember_name'…
tagged with: django-views
has comment: http://stackoverflow.com/comment/87310458
has title: Updating and deleting multiple images using Formset in Django
has comment: http://stackoverflow.com/comment/87317290
tagged with: python
tagged with: django-forms
type: Question

http://stackoverflow.com/comment/87287872
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50134880
has text: This is working with your test case. It keep only string with at least one letter. I don't understand what is wrong for you ?

http://stackoverflow.com/a/52584853
downvote count: 0
answers question: http://stackoverflow.com/q/50091591
upvote count: 9
has body: import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import pandas as pd import numpy as np import matplotlib.image as mpimg file = "./iris.csv" df = pd.read_csv(file) import seaborn as sns map_img = mpimg.imread('1538287373.02485_image.png') # Custom it with the same argument as 1D density plot hmax = sns.kdeplot(df.sepal_width, df.sepal_length, cmap="Reds", shade=True, bw=.15) hmax.collections[0].set_alpha(0) plt.imshow(map_img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0]) plt.show()
score: 9
type: Answer

http://stackoverflow.com/comment/87194369
score: 0
has text: time temp windchill dewpoint humidity pressure visibility \ 0 12:53 AM 21.0 °F - 19.0 °F 92% 30.47 in 10.0 mi 1 1:53 AM 21.9 °F - 19.9 °F 92% 30.48 in 10.0 mi 2 2:53 AM 21.9 °F - 19.0 °F 89% 30.50 in 10.0 mi wind_direction wind_speed gust_speed precip events conditions 0 Calm Calm - NaN NaN Clear 1 Calm Calm - NaN NaN Clear 2 Calm Calm - NaN NaN Clear ---- see above @AshishAcharya
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50089074

http://stackoverflow.com/q/50082938
has answer: http://stackoverflow.com/a/50094062
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87181737
has comment: http://stackoverflow.com/comment/87182716
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87181713
tagged with: inheritance
tagged with: class
has comment: http://stackoverflow.com/comment/87204169
tagged with: derived
has body: In this situation class A is a parent of classes B and C. The goal is to share state between the instances b and c. It's not about adding or overriding functions, but about the state value a. class A(): def __init__(self): self.a ='a' print('@a') class B(A): def __init__(self): A.__init__(self) self.x = 'b' class C(A): def __init__(self): A.__init__(self) self.x = 'c' b = B() c = C() print(b.a, b.x) print(c.a, c.x) The output is @a @a a b a c I understand why this is happening; __init__() in A is being called twice. I could put a test in so it only sets the initial value once, but that does not seem to be a very elegant solution. Additionally it only allows one instance of A to be shared. If I want another instance of A to be shared between two other instance of B and C it can't be done. The same goes for making a global inside the module and getting rid of class A entirely. Is there a good Pythonic way to solve this provlem?
has title: Sharing a base class between two derived classes in Python
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50175109
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50175695
has answer: http://stackoverflow.com/a/50175231
score: 0
has body: I'm trying to insert dummy data into a mysql database. The database structure looks like: database name: messaround database table name: test table structure: id (Primary key, auto increment) path (varchar(254)) UPDATED 2 method below, and error. I have a method to try to insert via: def insert_into_db(dbcursor, table, *cols, **vals): try: query = "INSERT INTO {} ({}) VALUES ('{}')".format(table, ",".join(cols), "'),('".join(vals)) print(query) dbcursor.execute(query) dbcursor.commit() print("inserted!") except pymysql.Error as exc: print("error inserting...\n {}".format(exc)) connection=conn_db() insertstmt=insert_into_db(connection, table='test', cols=['path'], vals=['test.com/test2']) However, this is failing saying: INSERT INTO test () VALUES ('vals'),('cols') error inserting... (1136, "Column count doesn't match value count at row 1") Can you please assist? Thank you.
tagged with: mysql
has answer: http://stackoverflow.com/a/50175844
has comment: http://stackoverflow.com/comment/87367449
answer count: 4
has title: insert into mysql database with pymysql failing to insert
has comment: http://stackoverflow.com/comment/87367533
type: Question
has answer: http://stackoverflow.com/a/50175168
tagged with: pymysql

http://stackoverflow.com/q/50106138
possible better answer: http://stackoverflow.com/a/50106228
has title: How to apply style to a Django form?
score: 1
has answer: http://stackoverflow.com/a/50106940
has answer: http://stackoverflow.com/a/50106232
downvote count: 0
has answer: http://stackoverflow.com/a/50106228
upvote count: 1
tagged with: django-forms
has body: It is possible to change the style of form in the view? I found in documentation this code: {{ form.non_field_errors }} {{ form.subject.errors }} Email subject: {{ form.subject }} {{ form.message.errors }} Your message: {{ form.message }} {{ form.sender.errors }} Your email address: {{ form.sender }} {{ form.cc_myself.errors }} CC yourself? {{ form.cc_myself }} But it just put a ugly input. I want to apply a class, or a css in this input. Is it possible? This is my form: class LoginView(NextUrlMixin, RequestFormAttachMixin, FormView): form_class = LoginForm success_url = '/' template_name = 'accounts/login.html' default_next = '/' class LoginForm(forms.Form): email = forms.EmailField(label='Email') password = forms.CharField(widget=forms.PasswordInput)
has answer: http://stackoverflow.com/a/50106326
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50106232
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87229685
answer count: 4
type: AnsweredQuestion
tagged with: django-templates
has comment: http://stackoverflow.com/comment/87229567

http://stackoverflow.com/comment/87423170
score: 1
comment on: http://stackoverflow.com/q/50203106
type: Comment
type: QuestionComment
has text: They are from python import `from sklearn.metrics import roc_curve, auc, f1_score, recall_score, precision_score`

http://stackoverflow.com/a/50109333
has comment: http://stackoverflow.com/comment/87236148
type: Answer
has comment: http://stackoverflow.com/comment/87237570
score: 1
answers question: http://stackoverflow.com/q/50109289
downvote count: 0
upvote count: 1
has body: You'll need to flatten. &gt;&gt;&gt; counts = [len(b) for a in x.values() for b in a] [1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1] &gt;&gt;&gt; max(counts) 3 Or for optimal performance, use a generator: max(len(b) for a in x.values() for b in a)

http://stackoverflow.com/comment/135335807
type: Comment
score: 0
type: AnswerComment
has text: @Tim, I expect this to be more efficient than a regular expression. But would always test with your data set and consider alternatives, e.g. a list comprehension is often quicker than `pd.Series.str` methods.
comment on: http://stackoverflow.com/a/50191703

http://stackoverflow.com/q/50170814
type: Question
has body: I have a dataframe with 4 columns. 3 of these columns contain string values (people's names) and the 4th one has an int value (salary for a job done). The string values are not unique either, the same string will show up several times in each column, but never more than once per row. data = { 'worker1': ['Sam', 'Jack', 'Matt', 'Paul', 'Tim'], 'worker2': ['Alex', 'Amy', 'Sam', 'Alice', 'Amanda'], 'worker3': ['Alice', 'Aaron', 'Tony', 'Jack', 'Sam'], 'earnings': [4564552, 4573547, 3567567, 6357653, 7648576]} df = pd.DataFrame(data, columns = ['worker1', 'worker2', 'worker3', 'earnings']) print(df) worker1 worker2 worker3 earnings 'Sam' 'Alex' 'Alice' 4564552 'Jack' 'Amy' 'Aaron' 4573547 'Matt' 'Sam' 'Tony' 3567567 'Paul' 'Alice' 'Jack' 6357653 'Tim' 'Amanda' 'Sam' 7648576 So what I need is to sum all the earnings associated to the specific name, regardless if it shows on column1, 2 or 3. I'm not sure if I should use a groupby function for this, build a dictionary or go another route. This would be what I'm trying to accomplish: workers total_earnings Sam 16080695 Alex 4564552 Alice 10922205 Jack 10931200 Amy 4573547 Aaron 4573547 Matt 3567567 Tony 3567567 Paul 6357653 Tim 7648576 Amanda 7648576 I'm quite new to pandas so I'm at a place where I'm not familiar with which functions I can use for something like this. I've mostly tried to use a groupby function but that was a disaster. Any help would be highly appreciated.
downvote count: 0
tagged with: pandas
has title: Sum values in a column based on strings from multiple columns in pandas/python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50184546
favorite count: 0
has answer: http://stackoverflow.com/a/50203060
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/87359174
has answer: http://stackoverflow.com/a/50184472
tagged with: python
has comment: http://stackoverflow.com/comment/87379502
has answer: http://stackoverflow.com/a/50195675
answer count: 4

http://stackoverflow.com/comment/87387958
type: Comment
comment on: http://stackoverflow.com/q/50184153
type: QuestionComment
has text: Could you post crawl log? You can do this via `scrapy crawl spider --logfile output.log` or `scrapy crawl spider 2>1 | tee output.log` commands (the later puts output to screen and file).
score: 0

http://stackoverflow.com/q/50163386
type: AnsweredQuestion
score: 2
has body: So, I have code that works for knn.predict() if I have data that has 1 feature to predict the next outcome. To put this into context, I have stock data (Open, High, Low, Close) where I use "Open" as "X" data and "Close" as "Y" data and knn.predict will predict the next value of Y. When I try to use "Open, High, Low" columns (3 features) for my X data, I get the following error: File "sklearn\neighbors\binary_tree.pxi", line 1294, in sklearn.neighbors.kd_tree.BinaryTree.query ValueError: query data dimension must match training data dimension I believe it's because of my X.shape and Y.shape where X is not the same size as Y but I don't understand how to fix it. How do you use KNN for multifeature analysis if X and Y must be the same size? Some of the Code: df = df'Date','Time', 'Open', 'High', 'Low', 'Close' df.head() # Predictor Variables df['Open'] = df.Open df['High'] = df.High df['Low'] = df.Low df['Close'] = df.Close df = df.dropna() #Data = np.delete(arr = df, obj=0, axis = 0) X = np.array(df.ix[:, 2:6]) #X.head() print X.shape # Target Variable Y = np.where(df['Close'].shift(-1)&gt;df['Close'],1,-1) #print (Y) #Predict u = df['Close'].iloc[-1] #print u new_prediction = knn.predict(u) print new_prediction
has title: multivariate KNN prediction
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0
tagged with: machine-learning
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50163640
favorite count: 0
tagged with: knn
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50163640

http://stackoverflow.com/comment/87319573
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50150722
type: QuestionComment
has text: Ok, could you provide a [MCVE] so that we can run the code and reproduce your issue?

http://stackoverflow.com/comment/87225142
type: QuestionComment
has text: first, use `os.rename`. Then why do you need renaming? doesn't the code works with original non-xml extension?
comment on: http://stackoverflow.com/q/50103966
score: 0
type: Comment

http://stackoverflow.com/q/50110837
tagged with: python
has comment: http://stackoverflow.com/comment/87239008
has comment: http://stackoverflow.com/comment/87239064
has comment: http://stackoverflow.com/comment/87239044
answer count: 2
has body: I am trying to randomly generate a bunch of points for a graph in python to test k-means clustering algorithm with. Here's my code. N = 100 random_x0 = np.random.randn(N) + (np.random.randint(0,100) * np.random.randint(1,4)) random_x1 = np.random.randn(N) + (np.random.randint(0,100) * np.random.randint(1,4)) random_x2 = np.random.randn(N) + (np.random.randint(0,100) * np.random.randint(1,4)) random_y0 = np.random.randn(N) + (np.random.randint(0,100) * np.random.randint(1,4)) random_y1 = np.random.randn(N) + (np.random.randint(0,100) * np.random.randint(1,4)) random_y2 = np.random.randn(N) + (np.random.randint(0,100) * np.random.randint(1,4)) As you might imagine, each set of random_x[index] coordinates is matched with it's y counterpart. (random_x0, random_y0), (random_x1, random_y1), (random_x2, random_y2) Since I am testing a clustering algorithm, I want my data points to be SOMEWHAT clustered...but this seems like too much. I tried to add a random number from 1-100, then multiple that by a random number from 1-4....what am I doing wrong to get such consistent random results?
tagged with: random
upvote count: 3
has answer: http://stackoverflow.com/a/54450200
tagged with: k-means
downvote count: 0
tagged with: cluster-analysis
has comment: http://stackoverflow.com/comment/87345152
linked to: http://stackoverflow.com/q/47265844
tagged with: coordinates
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54449641
score: 3
has title: Generate random (x,y) points for K-means clustering
type: UnansweredQuestion

http://stackoverflow.com/comment/87346475
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50162808
type: Comment
has text: also, it doesn't actually seem to fill with nans. This was the first thing I tried too.

http://stackoverflow.com/q/50128136
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/50129433
answer count: 3
has comment: http://stackoverflow.com/comment/87277106
score: 1
has answer: http://stackoverflow.com/a/50133346
downvote count: 0
tagged with: selenium
upvote count: 1
favorite count: 0
type: Question
tagged with: xpath
has body: Actually i want construct an XPATH to click on all emails one by one. I see that there is an attribute "date-time" in all email divs. How i can find the XPATH of elements with attribute "date-time" given that all values are different for this attribute. of one email : <div class="_lvv_M1 ms-bgc-ts all other identifiers look very dynamic which changes frequently as page is refreshed. Can you please help find XPATH of "date-time" to select all emails. Here is what i have trying so far - elements = driver.find_elements_by_xpath(//*[text()[contains(.,'data-time')]])
has title: XPATH to select all elements with same attribute name but different values
has answer: http://stackoverflow.com/a/50128593
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87279568
tagged with: python

http://stackoverflow.com/comment/87177710
score: 0
type: Comment
type: QuestionComment
has text: Note that hexadecimal is a representation or [tag:encoding] of a binary value (byte array) in text. "Raw hex" is therefore a contradiction of terms; you have raw binary or an encoded value representing that raw binary.
comment on: http://stackoverflow.com/q/50078091

http://stackoverflow.com/comment/87348454
type: Comment
type: QuestionComment
score: 1
has text: printing the dataframe before and after using `unstack()` should illustrate quite clearly what `unstack` does with your dataframe. Especially if all the possible dataframes you might wanna feed to unstack look similar.
comment on: http://stackoverflow.com/q/50165258

http://stackoverflow.com/a/50129859
upvote count: 1
answers question: http://stackoverflow.com/q/50129848
score: 1
type: Answer
has body: Just use join method by passing a list as parameter. str = ''.join(['H','e','l','l','o',' ','W','o','r','l','d'])
downvote count: 0

http://stackoverflow.com/comment/87409428
comment on: http://stackoverflow.com/q/50196216
score: 0
type: Comment
has text: thanks for reply, but for this, I need to know complete hierarchy like Pandas>Series then searched module, do we have anything which can directly search
type: QuestionComment

http://stackoverflow.com/q/50109324
has body: I have a csv file with rows of classifications/labels followed by the data associated with them: cat, 0, 1, 45, 23, ... dog, 1, 5, 75, 23, ... cat, 3, 4, 63, 24, ... cat, 0, 1, 44, 23, ... dog, 7, 3, 25, 4, ... How can I load the csv file into sklearn? Edit: or do I need to replace the labels with number equivalents? I.e. dog = 1, cat = 2, etc.
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/50109756
has title: Loading labels and data from csv into sklearn
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: scikit-learn
tagged with: python

http://stackoverflow.com/a/66264090
has body: use the sample way with lambda like this: test_button = Button(text="your_text_button", command=lambda:[placeX(),placeO()])
type: Answer
answers question: http://stackoverflow.com/q/50078791
score: 0

http://stackoverflow.com/a/50222280
has body: I know that I didn't post minimal example for this, but for anyone who understood my problem and faces the same one here is how I managed to fix it: Just subclass QSortFilterProxyModel and override sort() method: class MySortModel(QSortFilterProxyModel): def sort(self, *args, **kwargs): # check that there is no data to sort, if so - do not sort if self.sourceModel().rowCount(QModelIndex()) &gt; 0: super().sort(*args, **kwargs) The idea is to disable sorting if there are no items in model
has comment: http://stackoverflow.com/comment/87462447
has comment: http://stackoverflow.com/comment/87462864
accepted answer of: http://stackoverflow.com/q/50221046
type: Answer
has comment: http://stackoverflow.com/comment/87462167
answers question: http://stackoverflow.com/q/50221046
has comment: http://stackoverflow.com/comment/87462325
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87462738
has comment: http://stackoverflow.com/comment/87462406

http://stackoverflow.com/q/50192674
upvote count: 1
has title: Why there is no regex match in the output of this wget command?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87403625
has comment: http://stackoverflow.com/comment/87402384
has comment: http://stackoverflow.com/comment/87403502
score: 1
tagged with: stderr
tagged with: python
has body: I download a file from internet with wget and I want to record the name of the actual downloaded file (it changes in case the file already exists). I know that wget output goes to stderr, that is why I try to search for a regex match in it. There should be one but my "match" is None (because I get the error that 'NoneType' object has no attribute 'group'. cmd = "wget " + url + " -P " + directory args = shlex.split(cmd) res = subprocess.run(args, check=True, stderr=subprocess.PIPE) pattern = re.compile("\'(.+)\'", re.MULTILINE) match = re.search(pattern, res.stderr.decode("utf-8")) filename = match.group(1) # filename is None But when I check the value of stderr, it looks like this: ... connected.HTTP request sent, awaiting response... 200 OKLength: 46Saving to: '/home/student/Downloads/helloworld' 0K I have tried to pass the command as a string to subprocess.run with shell=True, the regex with re.MULTILINE and without, and other things, to no avail.
has comment: http://stackoverflow.com/comment/87404478
has comment: http://stackoverflow.com/comment/87402704
tagged with: python-3.x
answer count: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/87404723
has comment: http://stackoverflow.com/comment/87403827
type: UnansweredQuestion
tagged with: wget
downvote count: 0

http://stackoverflow.com/comment/87186406
has text: @DevinLee:- welcome!!
score: 0
comment on: http://stackoverflow.com/a/50085272
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50194562
tagged with: python
has answer: http://stackoverflow.com/a/50194906
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: Using Django 2.0.2 class Rischi(models.Model): RISCHIO = ( ('Nullo', 'Nullo'), ('Irrilevante', 'Irrilevante'), ('Basso', 'Basso'), ('Medio', 'Medio'), ('Alto', 'Alto'), ) azienda = models.ForeignKey( 'azienda.Azienda', on_delete=models.CASCADE, ) foto = models.ImageField(upload_to='rischi', blank=True) attivita = models.ForeignKey( Attivita, blank=True, null=True, on_delete=models.CASCADE, ) luogo = models.ForeignKey( Luoghi, blank=True, null=True, on_delete=models.CASCADE, ) macchina = models.ForeignKey( Macchine, blank=True, null=True, on_delete=models.CASCADE, ) sostanza = models.ForeignKey( Sostanze, blank=True, null=True, on_delete=models.CASCADE, ) fonte_rischio = models.ForeignKey( Fonte_rischio, on_delete=models.CASCADE ) pericolo = models.CharField(max_length=200) mansione = models.ManyToManyField( 'mansione.Mansione' ) livello_rischio = models.CharField(max_length=200) rischio = models.CharField(max_length=200, choices=RISCHIO) allegato = models.ManyToManyField( Allegati, blank=True, ) note = models.TextField(blank=True) data_di_creazione = models.DateField(auto_now_add=True) data_di_modifica = models.DateField(auto_now=True) def __str__(self): return self.fonte_rischio.nome + ", id: "+ str(self.pk) and this is the related form class RischiForm(ModelForm): class Meta: model = Rischi exclude = ['azienda'] when I execute runserver this is the message i receive AttributeError: 'str' object has no attribute '_default_manager' but when I set the form excluding mansione class RischiForm(ModelForm): class Meta: model = Rischi exclude = ['azienda', 'mansione'] everything is ok I tried to read the manual and I googled this message but I did not find any answer to this problem...
favorite count: 0
type: Question
tagged with: python-3.x
has title: Django 2.0.2 Problems with modelform creation: AttributeError: 'str' object has no attribute '_default_manager'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87406471
tagged with: django

http://stackoverflow.com/q/50077553
score: 3
has body: I recently have been using the click package to build command line interfaces which has worked perfectly, so far. Now I got into some trouble when using chained commands in combination with the context object. The problem is that I somehow get an error when I want to call the function of another command from within another command. It is probably somehow related to the usage of decorators within click but I don't see the error right now. This is a minimal example of my code: import click @click.group(chain=True) @click.option('--some_common_option', type=float, default=1e-10) @click.pass_context def cli(ctx, some_common_option): # save shared params within context object for different commands for k, v in locals().items(): if 'ctx' not in k: ctx.obj[k] = v return True @cli.command() @click.argument('some_argument', type=str) @click.pass_context def say_something(ctx, some_argument): print(some_argument) return True @cli.command() @click.argument('some_other_argument', type=str) @click.pass_context def say_more(ctx, some_other_argument): ctx.obj['text'] = some_other_argument say_something(ctx, ctx.obj['text']) return True if __name__ == '__main__': cli(obj={}) And this is the error that is provided on the terminal: $ python test.py say_something 'Hello!' Hello! $ python test.py say_more 'How are you?' Traceback (most recent call last): File "test.py", line 36, in &lt;module&gt; cli(obj={}) File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 1092, in invoke rv.append(sub_ctx.command.invoke(sub_ctx)) File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", l…
tagged with: python
has title: Click: Use another function in chained commands with context object
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50117720
tagged with: python-click
upvote count: 3
has answer: http://stackoverflow.com/a/50117720
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/48619517
favorite count: 0
type: Question

http://stackoverflow.com/q/50198633
tagged with: admin
has title: Django admin Login page giving error "incorrect username password" although I am using correct
type: Question
has comment: http://stackoverflow.com/comment/87414915
answer count: 0
has body: This is my model class from django.db import models # Create your models here. from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Helps Djamgo work with our custom user model""" def create_user(self,email,name,password=None): if not email: raise ValueError('users must have an email address') #normalizing the email address convert it to the lowercase email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,password): user = self.create_user(email,name,password) user.is_superuser =True user.is_staff = True class UserProfile(AbstractBaseUser,PermissionsMixin): email = models.EmailField(max_length=255,unique = True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) related_name = "+" object = UserProfileManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ['name'] #helper funtionality def full_name(self): """Use to get full name of the user""" return self.name def short_name(self): """Use to get short name name of the user""" return self.name def __str__(self): `enter code here`return self.email My setting.py contains everything and my db is sync and I have already created a superuser. When I am trying to access my admin from admin login page it gives an error "please login with correct email password " But I have already ensured 5 times that I am using correct email password!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87415212
tagged with: django
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/87414303
tagged with: django-models
tagged with: authentication

http://stackoverflow.com/q/50099449
tagged with: python-3.x
tagged with: pika
has comment: http://stackoverflow.com/comment/87215773
has title: Change RabbitMQ Consumer Callback to Invoke with 1 Argument (body) Instead of 4 Arguments
has body: Normally, by pika driver, when we set a consumer, we should pass a callback as parameter. On new message, pika will invoke the callback with 4 arguments: ch, method, property, body. I need my callback to get just one argument: body. I mean: def my_callback(body): pass Instead of: def my_callback(ch, method, property, body): pass How can I implement it?
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50267569
tagged with: rabbitmq
downvote count: 1
has answer: http://stackoverflow.com/a/50267569
has comment: http://stackoverflow.com/comment/87215406
type: AnsweredQuestion
score: 0
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50211352
has answer: http://stackoverflow.com/a/50212674
has answer: http://stackoverflow.com/a/50212067
has body: I got a huge list of object: (about 500k elts). class Signal: def __init__(self, fq, t0, tf): self.fq = fq self.t0 = t0 self.tf = tf def __eq__(self, s): """ == comparison method.""" return self.fq == s.fq def __ne__(self, s): """ != comparison method.""" return not self.__eq__(self, s) t0, tf = 0, 200 signals = [[S(f1, t0, tf), S(f2, t0, tf), S(f3, t0, tf), S(f4, t0, tf), S(f5, t0, tf), S(f6, t0, tf)] for f1 in frequencies for f2 in frequencies for f3 in frequencies for f4 in frequencies for f5 in frequencies for f6 in frequencies] My program maps the list and generates .pkl files with a specific name for each element of the list. def file_namer(signals): frequencies = tuple([s.fq for s in signals]) return "F{}.pkl".format(frequencies) Some of the elements from the list were already computed, OR, a permutation of this element was computed, thus I would like to delete them before mapping. import itertools import os folder = "folder_of_the_pkl" files = os.listdir(folder) def is_computed(files, s): possibilities = list() for elt in itertools.permutations(s): possibilities.append(file_namer(s)) if any([name in files for name in possibilities]): return True else: return False s_to_remove = list() for s in signals: if is_computed(files, s): s_to_remove.append(s) for elt in s_to_remove: signals.remove(elt) That is what I come up with. It is fairly not efficient, and I'd be glad to see your proposition to improve this! Thanks! N.B: This is a fairly simplified version of my program. The objects are far heavier (10+ parameters).
type: Question
accepted answer: http://stackoverflow.com/a/50212674
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
has title: Removing efficiently elements from a list
possible better answer: http://stackoverflow.com/a/50212067

http://stackoverflow.com/a/50230215
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50229513
has body: I am not familar with the builtin SimpleHTTPServer, but it's for teaching purposes. I'd recommand you use the well known micro-framework named Flask, maybe this is what you want: from flask import Flask, request app = Flask(__name__) @app.route('/') def index(): return '''&lt;form action="" method="post"&gt; &lt;center&gt;&lt;input type="radio" name="radio" value="left"&gt; &lt;input type="radio" name="radio" value="middle"&gt; &lt;input type="radio" name="radio" value="right"&gt;&lt;/center&gt; &lt;center&gt;&lt;p&gt;&lt;input type="submit" name="submit" value="Submit Decision"/&gt;&lt;/p&gt;&lt;/center&gt; &lt;/form&gt;''' @app.route('/', methods=['POST']) def post_abc(): return 'radio: "%s", submit: "%s"' % (request.form['radio'], request.form['submit']) if __name__ == '__main__': app.run(debug=True) Visit http://localhost:5000 with your browser to test it. You can install Flask via pip install flask.
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50229513
score: 1
upvote count: 1

http://stackoverflow.com/q/50158598
tagged with: pymysql
tagged with: python
score: 0
linked to: http://stackoverflow.com/q/35148964
has comment: http://stackoverflow.com/comment/87335147
has answer: http://stackoverflow.com/a/50174304
has title: Dynamically create MySQL table with python?
answer count: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/87335209
has body: So I have an array of 200+ columns. How would I loop through this and create a table using pymysql? Currently am connected like: import pymysql connection = pymysql.connect( host='my_host_name', user='my_username', password='my_password', port= 0000, database='my_db') columns = ['firstname', 'lastname', 'email', .... ] cursor = connection.cursor() sql = 'CREATE TABLE my_table ( # For each column in columns )' cursor.execute(sql) Edit: I will loop through the columns first and append their appropriate data type
has comment: http://stackoverflow.com/comment/87335607
type: Question
has comment: http://stackoverflow.com/comment/87335408
has comment: http://stackoverflow.com/comment/87335141
has comment: http://stackoverflow.com/comment/87335339
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87335094
has comment: http://stackoverflow.com/comment/87335570

http://stackoverflow.com/comment/107668298
has text: True variable renaming can be down with jupyterlab and the [jupyterlab-lsp](https://github.com/krassowski/jupyterlab-lsp) extension.
score: 2
comment on: http://stackoverflow.com/q/50177616
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50102075
accepted answer of: http://stackoverflow.com/q/50099942
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50099942
type: AcceptedAnswer
has body: I'm not entirely sure what you're asking for, but here are some things you can extract from the fit result out or func (which is sort of a weird name to give the fit result, but OK): ModelResult has: params: an ordered dictionary of the best-fit parameters. Keys are the parameter names, and values are lmfit.Parameter objects that have attributes of value, stderr, max, min, correl, etc. best_values: a simple dictionary with parameter names as keys and best-fit values as values. best_fit: the ndarray of the best-fit model. More attributes of the result are described at http://lmfit.github.io/lmfit-py/model.html#modelresult-attributes So, probably what you want is something like: for parname, param in out.params.items(): print("%s = %f +/- %f " % (parname, param.value, param.stderr)) which is basically what the fit_report method does.

http://stackoverflow.com/comment/87275104
has text: So what return `print (len(data.iloc[0]['numbers']))` ?
comment on: http://stackoverflow.com/a/50128490
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/57283640
score: 50
downvote count: 1
answers question: http://stackoverflow.com/q/50146520
has body: For python3 I have used from urllib.parse import urlparse instead of from urlparse import parse_qsl, urlparse and it works recommended doc : https://docs.python.org/3/library/urllib.parse.html
upvote count: 51
type: Answer
has comment: http://stackoverflow.com/comment/101062912

http://stackoverflow.com/q/50168018
has body: I have pyspark dataframe, in which data column is there, which has weekend dates as well. I just want to change these dates to previous or next working days. from pyspark.sql.session import SparkSession spark = SparkSession.builder.getOrCreate() columns = ['Date', 'id', 'dogs', 'cats'] vals = [('04-05-2018',1, 2, 0), ('05-05-2018',2, 0, 1), ('06-05-2018',2, 0, 1)] df = spark.createDataFrame(vals, columns) df.show() DataFrame look like: +----------+---+----+----+ | Date| id|dogs|cats| +----------+---+----+----+ |04-05-2018| 1| 2| 0| |05-05-2018| 2| 0| 1| |06-05-2018| 2| 0| 1| +----------+---+----+----+ Now, i'm able to identify the weekday, as in separate column df = df.withColumn('Date', unix_timestamp(df['Date'].cast("string"), 'dd-MM-yyyy').cast("double").cast('timestamp').cast('date')) df = df.select('Date', date_format('Date', 'u').alias('dow_number'), 'id', 'dogs', 'cats') temp = df temp.show() +----------+----------+---+----+----+ | Date|dow_number| id|dogs|cats| +----------+----------+---+----+----+ |2018-05-04| 5| 1| 2| 0| |2018-05-05| 6| 2| 0| 1| |2018-05-06| 7| 2| 0| 1| +----------+----------+---+----+----+ Now i just want to shift the data to last working day or next working day if it is on weekend, means i want my dataframe to be like this: +----------+----------+---+----+----+ | Date|dow_number| id|dogs|cats| +----------+----------+---+----+----+ |2018-05-04| 5| 1| 2| 0| |2018-05-04| 5| 2| 0| 1| |2018-05-04| 5| 2| 0| 1| +----------+----------+---+----+----+ Thanks in advance.
type: Question
accepted answer: http://stackoverflow.com/a/50168360
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50168360
upvote count: 1
has comment: http://stackoverflow.com/comment/114629430
favorite count: 0
type: AnsweredQuestion
tagged with: apache-spark
score: 1
has title: Shift weekend dates to last weekday in pyspark dataframe
tagged with: pyspark
tagged with: python

http://stackoverflow.com/a/72092574
has body: I know I'm pretty late to the draw on this one, but I'm leaving the solution I came up with in case anyone else wanders across this as I have. Firstly, the linked question has a pretty nice and dynamic solution that seems to work well even for high column counts. I came across that after I made my solution, haha. Check it out here. Another answer on this thread utilizes the csv library to read and use the column names from that, as it doesn't seem to modify duplicates like Pandas does. That should work fine, but I just wanted to avoid using any extra libraries, especially considering I was originally using csv and then upgrade to Pandas for better functionality. Now here's my solution. I'm sure it could be done more nicely but this does the job for what I needed and is pretty dynamic, from what I can tell. It basically goes through the columns, checks if it can split the string based on the rightmost "." (that's the rpartition), then does a few more checks from there. It checks: Is this string in the colMap? The colMap keeps track of all of the column names, duplicate or not. If this comes back true, then that means it's a duplicate of another column that came before it. Is the string after the rightmost "." a number? All of the columns are strings, so this just makes sure that whatever it is can be converted into a number to prevent grabbing some other random column that meets previous criteria but isn't actually a dupe from Pandas. eg. "DupeCol" and "DupeCol.Stuff" wouldn't get picked up, but "DupeCol" and "DupeCol.1" would. Does the number that comes after the rightmost "." match up to the current count of duplicates in the colMap? Seeing as the colMap contains all of the names of the columns, duplicates or not, this will ensure that we're not grabbing a user-named column that managed to overlap with the ".number" convention that Pandas uses. Eg. if a user had named two columns "DupeCol" and "DupeCol.6", it wouldn't get picked up unless there were 6 "DupeCol"s pr…
score: 1
answers question: http://stackoverflow.com/q/50083583
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/50215824
has answer: http://stackoverflow.com/a/66659345
upvote count: 19
has answer: http://stackoverflow.com/a/50215974
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50215974
has answer: http://stackoverflow.com/a/50216494
downvote count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/50216494
score: 19
favorite count: 0
type: Question
tagged with: python-asyncio
has body: I want to scrape data from a website concurrently, but I found that the following program is NOT executed concurrently. async def return_soup(url): r = requests.get(url) r.encoding = "utf-8" soup = BeautifulSoup(r.text, "html.parser") future = asyncio.Future() future.set_result(soup) return future async def parseURL_async(url): print("Started to download {0}".format(url)) soup = await return_soup(url) print("Finished downloading {0}".format(url)) return soup loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) t = [parseURL_async(url_1), parseURL_async(url_2)] loop.run_until_complete(asyncio.gather(*t)) However, this program starts to download the second content only after the first one finishes. If my understanding is correct, the await keyword on the await return_soup(url) awaits for the function to be complete, and while waiting for the completion, it returns back the control to the event loop, which enables the loop to start the second download. And once the function finally finishes the execution, the future instance within it gets the result value. But why does this not work concurrently? What am I missing here?
has title: The tasks from asyncio.gather does not work concurrently
tagged with: python

http://stackoverflow.com/comment/87393779
type: QuestionComment
has text: @Kasramvd I need to generate every list possible where each element of the list is positive and is not greater than the number given at the relevant index.
comment on: http://stackoverflow.com/q/50188520
score: 0
type: Comment

http://stackoverflow.com/comment/87457035
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50219904
has text: did u try use `.distinct('link_target_id`)`?
score: 0

http://stackoverflow.com/a/50079051
accepted answer of: http://stackoverflow.com/q/50075175
downvote count: 0
type: Answer
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50075175
has body: I think this should work # First input input1=Input(shape=(300,3)) x=LSTM(50, return_sequences=True)(input1) x=GlobalMaxPool1D(x) x=Dense(n)(x) # Second Input input2=Input(shape=(106)) y=Dense(n)(input2) # Merge merged=Concatenate([x,y]) merged=Dense(1)(merged) # Define model with two inputs model=Model(inputs=[input1,input2],outputs=merged) Both the models should have same output space before merging. Then, you can pass a list of inputs and Keras will pass it at the appropriate places model.fit([X1,X2],....)
upvote count: 2

http://stackoverflow.com/comment/89684740
type: AnswerComment
has text: Hi Billal. Please comment on the code above. Does it work for you?
score: 0
comment on: http://stackoverflow.com/a/50221098
type: Comment

http://stackoverflow.com/q/50142629
tagged with: python
has answer: http://stackoverflow.com/a/50186618
tagged with: sqlalchemy
type: AnsweredQuestion
has body: I have two sql tables. Table 1 (id, name) and Table 2 with (id, name, table1_id) sql = text('SELECT t1.*, t2.* FROM table1 t1 ' 'LEFT JOIN table2 t2 ON t1.id=t2.table1_id ') query = db.session.query(Table1, Table2).from_statement(sql).params() table1_table2_tuple_list = query.all() If the result of the sql query is 67, 'some name', 1, 'some name in table 2', 67 Then everything is OK and I have [(&lt;Table1&gt;, &lt;Table2&gt;)] for table1_table2_tuple_list But If the result of the sql query is: (also all other code is for this result) 67, 'some name', Null, Null, Null Then instead of receiving [(&lt;Table1&gt;, None)] I receive [(None, None)] If I change my code a little bit: sql = text('SELECT t1.*, t2.id, t2.name,t1.id FROM table1 t1 ' 'LEFT JOIN table2 t2 ON t1.id=t2.table1_id ') query = db.session.query(Table1, Table2, Table1.id).from_statement(sql).params() table1_table2_tuple_list = query.all() Then I receive: [&lt;Table1&gt;, &lt;Table2&gt;, 1] But in this case I'm not even sure if this is correct because I match two columns from the sql to model Table2 that has three columns. Not sure at all why this is working, but everything seems on place. Still is not what I want, because I don't want to return to this query and to specify again and again new columns if there are such for Table2 What I need is a way to select from two tables with pure sql , and to match the result to my models. Also I want to have result even in the cases when one of the tables doesn't have value in it's result columns. Hope I am clear. My goal is to receive [(&lt;Table1&gt;, None)] when the query is for all colums (SELECT t1.*, t2.*) and there is LEFT JOIN with null added.
score: 7
answer count: 1
downvote count: 0
upvote count: 7
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
has title: SQLAlchemy select from two tables with null LEFT JOIN returns empty result
accepted answer: http://stackoverflow.com/a/50186618

http://stackoverflow.com/a/50176274
has comment: http://stackoverflow.com/comment/87375128
type: Answer
has comment: http://stackoverflow.com/comment/87369834
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87370479
has comment: http://stackoverflow.com/comment/87370866
answers question: http://stackoverflow.com/q/50176037
has body: I think the best way to achieve this would be to use color Masks but in HSV so that it stays focused on the color and not on the brightness/contrast. Keep in mind that OpenCV encodes HSV with those ranges: H: 0 - 180 S: 0 - 255 V: 0 - 255 Here is how I would do it: # Convert your image to HSV imgHsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV); # Define lower/upper color lower = np.array([0, 0, 180]) upper = np.array([180, 20, 255]) # Check the region of the image actually with a color in the range defined below # inRange returns a matrix in black and white bw = cv2.inRange(imgHsv, lower, upper)

http://stackoverflow.com/q/50112785
has body: meetis is my src, class CodeEditor(QPlainTextEdit, QLineEdit): def __init__(self, parent=None): QPlainTextEdit.__init__(self, parent) QLineEdit.__init__(self, parent) self.lineNumberArea = LineNumberArea(self) self.blockCountChanged.connect(self.updateLineNumberAreaWidth) self.updateRequest.connect(self.updateLineNumberArea) self.cursorPositionChanged.connect(self.highlightCurrentLine) self.returnPressed.connect(self.IndentCall) self.updateLineNumberAreaWidth(0) @pyqtSlot(str, QPlainTextEdit) def IndentCall(self): if self.ui.textEdit.toPlainText().endswith(':\n'): self.ui.textEdit.insertPlainText(' ') Error that i get is, File "D:\Python-Projects\CodeEditor\codeeditor.py", line 26, in __init__ self.returnPressed.connect(self.IndentCall) TypeError: decorated slot has no signature compatible with returnPressed() I don't want to create a event handler, all i want is to simply inherit a function into another Widget. Fellow programmer please help me with this error, if possible provide and example. !! Thanks In Advance !!
tagged with: pyqt
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87259099
has title: How to inherit returnPressed() from QLineEdit to QPlainTextEdit
tagged with: python
has comment: http://stackoverflow.com/comment/87259051
duplicate of: http://stackoverflow.com/q/27475940
score: 0
has comment: http://stackoverflow.com/comment/87259143
duplicate of: http://stackoverflow.com/q/20420072
has comment: http://stackoverflow.com/comment/87256082
tagged with: pyqt5
linked to: http://stackoverflow.com/q/50016989
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/27475940
answer count: 0

http://stackoverflow.com/comment/87402094
comment on: http://stackoverflow.com/a/50190203
has text: @M.Mehranian Your welcome! So you can approve the answer ;) thanks to you!
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50210227
has body: I have a huge dataframe that looks like this: gemeente Partij Perioden Bevolking/Bevolkingssamenstelling op 1 januari/Totale bevolking (aantal) Bevolking/Bevolkingssamenstelling op 1 januari/Geslacht/Mannen (aantal) Bevolking/Bevolkingssamenstelling op 1 januari/Geslacht/Vrouwen (aantal) Bevolking/Bevolkingssamenstelling op 1 januari/Leeftijd/Leeftijdsgroepen/Jonger dan 5 jaar (aantal) Bevolking/Bevolkingssamenstelling op 1 januari/Leeftijd/Leeftijdsgroepen/5 tot 10 jaar (aantal) Bevolking/Bevolkingssamenstelling op 1 januari/Leeftijd/Leeftijdsgroepen/10 tot 15 jaar (aantal) Bevolking/Bevolkingssamenstelling op 1 januari/Leeftijd/Leeftijdsgroepen/15 tot 20 jaar (aantal) 0 's-Hertogenbosch VVD 2007 135648.0 66669.0 68979.0 7986.0 7809.0 7514.0 7612.0 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1 's-Hertogenbosch VVD 2008 136481.0 67047.0 69434.0 7885.0 7853.0 7517.0 7680.0 ... 5.8 8.6 41.3 5.2 4.0 20.0 4.0 5.0 25.0 3.0 2 's-Hertogenbosch VVD 2009 137775.0 67715.0 70060.0 7915.0 7890.0 7497.0 7628.0 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 3 's-Hertogenbosch VVD 2010 139607.0 68628.0 70979.0 8127.0 7852.0 7527.0 7752.0 ... 5.6 8.4 40.7 5.4 4.0 20.0 3.0 5.0 24.0 3.0 4 Aa en Hunze PVDA 2007 25563.0 12653.0 12910.0 Partij consists of 6 possible labels and I have 270 columns. I want to compute the correlation and/or similarity between those 6 labels in Partij with the data from those 270 columns. I tried pd.groupby but that only give me correlations between columns and not parties. I tried to make a pd.pivot_table but and make the Partij as column names but then I still had all those normal column names and couldn't access the Partij names and compute correlation.
has title: computing correlation between values of one column
tagged with: python
accepted answer: http://stackoverflow.com/a/50211543
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50211543
type: Question
tagged with: correlation

http://stackoverflow.com/comment/87312171
comment on: http://stackoverflow.com/q/50146993
type: QuestionComment
has text: Show us how you tried adding the result to a global list. It's likely that you did something wrong, but that's close to working, and we can show you how to fix it—but if we can't see it, nobody can fix it for you.
score: 0
type: Comment

http://stackoverflow.com/a/50158994
has body: There are indexing issues (on the column name). Convert the mask to a numpy array, and you're good to go: df'A_1', 'A_2' = df.filter(like='A').mask( df.filter(like='B').isnull().values, 999 ) df A_1 A_2 B_1 B_2 0 1 4 y n 1 2 999 n NaN 2 999 999 NaN NaN Alternatively, keep this in numpy space: df'A_1', 'A_2' = np.where( df.filter(like='B').isnull(), 999, df.filter(like='A') ) df A_1 A_2 B_1 B_2 0 1 4 y n 1 2 999 n NaN 2 999 999 NaN NaN
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87336508
has comment: http://stackoverflow.com/comment/87335944
answers question: http://stackoverflow.com/q/50158941
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87335868
accepted answer of: http://stackoverflow.com/q/50158941

http://stackoverflow.com/q/50224872
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50224887
downvote count: 0
has title: Format string from variable length list
duplicate of: http://stackoverflow.com/q/22556449
score: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50224887
has body: I have a list containing a variable number of items, list_example = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...] and I'd like to format it into a string as follows: 0 1 2 3 4 5 6 7 8 9 ... Currently, I'm doing this using a simple for loop: string = "" for i in range(len(list_example) - 1): string += str(list_example[i]) + " " string += str(list_example[-1]) It works well, but I feel like it must be a better (more compact) way of achieving that. If anybody knows how to do it, please, let me know!
linked to: http://stackoverflow.com/q/22556449

http://stackoverflow.com/q/50220638
type: Question
possible better answer: http://stackoverflow.com/a/50222125
score: 3
has comment: http://stackoverflow.com/comment/87458813
has title: A long term puzzle, how to optimize multi-level loops in python?
has comment: http://stackoverflow.com/comment/87459720
has comment: http://stackoverflow.com/comment/87459504
has comment: http://stackoverflow.com/comment/87458948
accepted answer: http://stackoverflow.com/a/50224982
has comment: http://stackoverflow.com/comment/87459425
has body: I have written a function in python to calculate Delta function in Gauss broadening, which involves 4-level loops. However, the efficiency is very low, about 10 times slower than using Fortran in a similar way. def Delta_Gaussf(Nw, N_bd, N_kp, hw, eigv): Delta_Gauss = np.zeros((Nw,N_kp,N_bd,N_bd),dtype=float) for w1 in range(Nw): for k1 in range(N_kp): for i1 in range(N_bd): for j1 in range(N_bd): if ( j1 &gt;= i1 ): Delta_Gauss[w1][k1][i1][j1] = np.exp(pow((eigv[k1][j1]-eigv[k1][i1]-hw[w1])/width,2)) return Delta_Gauss I have removed some constants to make it looks simpler. Could any one help me to optimize this script to increase efficiency?
has answer: http://stackoverflow.com/a/50224982
has comment: http://stackoverflow.com/comment/87458841
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87458999
answer count: 2
has answer: http://stackoverflow.com/a/50222125
has comment: http://stackoverflow.com/comment/87458483
upvote count: 3
has comment: http://stackoverflow.com/comment/87459080
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87459347
favorite count: 0

http://stackoverflow.com/comment/87461722
score: 1
type: QuestionComment
has text: Invert/negate the image (pixel=255-pixel) and choose cyan pixels using `inRange()`
type: Comment
comment on: http://stackoverflow.com/q/50221851

http://stackoverflow.com/q/50180511
has body: I'm trying to create a regex that will only return true if certain words don't show up before a phrase. For example, I want it to return True for this sentence "stop emailing me" and false for "Message me if you have that in stock. If not, stop emailing me". This is as close as I could get and it doesn't work ^(?=(^(?:(?!(\bif\b)|(\or\b)).)\bstop emailing\b)) Would also be great if I could keep it to looking just at words within 6 words or so. Also, if possible I'd also like to check if a question was asked and if so then return false. I was trying to add something like (?!\?) and (^(?:(?!(\. when\b)|(\. what\b)|(\. why\b)|(\. where\b)|(\. how\b)|(\. are\b)).)+$) to the above but no success. Thank you.
has answer: http://stackoverflow.com/a/50181188
has comment: http://stackoverflow.com/comment/87378382
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87378330
tagged with: regex
score: 0
has comment: http://stackoverflow.com/comment/87383192
answer count: 1
type: Question
has title: Regex to check for words before phrase

http://stackoverflow.com/comment/87363776
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50128747
type: Comment
has text: @alvinwan this is great. thanks!!

http://stackoverflow.com/a/50137618
answers question: http://stackoverflow.com/q/50137367
downvote count: 0
type: Answer
has body: Why use another library when you have your friend filter method import statistics number_list = [2, -1000, 3, 4, -1000, -1000] not_1000 = list(filter(lambda x: x != -1000, number_list)) not_1000_mean = statistics.mean(not_1000)
score: 2
upvote count: 2

http://stackoverflow.com/comment/87370679
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50172122
type: AnswerComment
has text: That's why I told you that Anaconda isn't worthwhile in Ubuntu. Almost all the same packages from Anaconda are in the 18.04 default repos. Anaconda is known for being unable to find the paths to any package that conda didn't install, so you have to add the [**path**](https://askubuntu.com/questions/922154/allow-older-version-of-python/922157#922157) to each Python executable manually or else Anaconda won't be able to find it. Anaconda is selling you the idea that it's easier to use than the Ubuntu default repos, but in the long run it's much harder to use Anaconda in Ubuntu.

http://stackoverflow.com/q/50075970
has title: Filtering Foreign Keys in Django 2.0
answer count: 1
accepted answer: http://stackoverflow.com/a/50076046
has answer: http://stackoverflow.com/a/50076046
type: Question
tagged with: django
tagged with: python
tagged with: key
has comment: http://stackoverflow.com/comment/87168671
has body: So I need to filter posts, posted by users, who the user currently logged in is following. Here's my models: class ProfileDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) provider = models.CharField(max_length=20, null=True, blank=True) firstname = models.CharField(max_length=25, null=True, blank=True) lastname = models.CharField(max_length=25, null=True, blank=True) username = models.CharField(max_length=24, null=True, blank=True, unique=True) def __str__(self): return str(self.user) class Posts(models.Model): post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(ProfileDetails, on_delete=models.CASCADE, null=True) text = models.TextField(max_length=280, null=True, blank=True) video = models.CharField(max_length=24, null=True, blank=True) timestamp = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return str(self.user) class Connection(models.Model): follower = models.ForeignKey(ProfileDetails, related_name='follower', on_delete=models.SET_NULL, null=True) following = models.ForeignKey(ProfileDetails, related_name='following', on_delete=models.SET_NULL, null=True) # follower = models.ManyToManyField(ProfileDetails, related_name='follower') # following = models.ManyToManyField(ProfileDetails, related_name='following') date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.follower) And then in my views, my bit of Python / Django knowledge kind of directed me to write something like this (take a look particularly at the last bit, where I try to filter it so it only gets details from the users I follow. def index(request): checkuser = request.user print(checkuser) if ProfileDetails.objects.filter(user=checkuser): print("user previously logged in") sns = get_object_or_404(SocialAccount, user=checkuser) autoupdateprofile = get_object_or_404(ProfileDetails, user=checkuser) autoupdateprofile.lastlogi…
type: AnsweredQuestion
tagged with: postgresql
score: 0
tagged with: foreign-keys

http://stackoverflow.com/q/50178361
type: AnsweredQuestion
score: 0
has title: ValueError: Input arrays should have the same number of samples as target arrays. Found 1600 input samples and 1800 target samples
has answer: http://stackoverflow.com/a/50179920
type: Question
tagged with: numpy
has body: I am following this tutorial here to do image classification. Link: Keras image classification The code I am referencing is Bottleneck feature The problem I am facing: 1. The original tutorial has only two classes but I am trying to do multi-class classification. My file structure looks like: data train class1 class2 class3 class4 test class1 class2 class3 class4 The following code in the original code is for two class classification. train_labels = np.array( [0] * (nb_train_samples / 2) + [1] * (nb_train_samples / 2)) validation_data = np.load(open('bottleneck_features_validation.npy')) validation_labels = np.array( [0] * (nb_validation_samples / 2) + [1] * (nb_validation_samples / 2)) I understand that in order to multi-class classification I have to change it to: train_labels = np.array( [0] * (class0_train_size) + [1] * (class1_train_size)+ [2] * (class2_train_size) + [3] * (class3_train_size)) validation_data = np.load(open('bottleneck_features_validation.npy')) validation_labels = np.array( [0] * (class0_test_size) + [1] * (class1_test_size)+ [2] * (class2_test_size) + [3] * (class3_test_size)) My question is my train test size vary for different classes so it's kind of hard for me to hardcode them. Is there a way I can allocate them dynamically based on the actual number of images inside a folder instead of hardcoding the size? Thanks for your generous help!
answer count: 1
tagged with: python
tagged with: keras
accepted answer: http://stackoverflow.com/a/50179920

http://stackoverflow.com/q/50146279
linked to: http://stackoverflow.com/q/7100242
has answer: http://stackoverflow.com/a/50146400
upvote count: 6
linked to: http://stackoverflow.com/q/49397704
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87310775
has title: Check if 2d array exists in 3d array in Python?
has comment: http://stackoverflow.com/comment/87310743
score: 5
accepted answer: http://stackoverflow.com/a/50146326
answer count: 3
has body: I have an 3d array with shape (1000, 12, 30), and I have a list of 2d array's of shape (12, 30), what I want to do is check if these 2d arrays exist in the 3d array. Is there a simple way in Python to do this? I tried keyword in but it doesn't work.
tagged with: pandas
has answer: http://stackoverflow.com/a/50146326
possible better answer: http://stackoverflow.com/a/50146616
linked to: http://stackoverflow.com/q/16970982
has comment: http://stackoverflow.com/comment/87310717
downvote count: 1
has answer: http://stackoverflow.com/a/50146616
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87310780
has comment: http://stackoverflow.com/comment/87310758
linked to: http://stackoverflow.com/q/48988038
tagged with: python

http://stackoverflow.com/q/50159625
score: 4
has body: This is how I scale a single vector: vector = np.array([-4, -3, -2, -1, 0]) # pass the vector, current range of values, the desired range, and it returns the scaled vector scaledVector = np.interp(vector, (vector.min(), vector.max()), (-1, +1)) # results in [-1. -0.5 0. 0.5 1. ] How can I apply the above approach to each column of a given matrix? matrix = np.array( [[-4, -4, 0, 0, 0], [-3, -3, 1, -15, 0], [-2, -2, 8, -1, 0], [-1, -1, 11, 12, 0], [0, 0, 50, 69, 80]]) scaledMatrix = [insert code that scales each column of the matrix] Note that the first two columns of the scaledMatrix should be equal to the scaledVector from the first example. For the matrix above, the correctly computed scaledMatrix is: [[-1. -1. -1. -0.64285714 -1. ] [-0.5 -0.5 -0.96 -1. -1. ] [ 0. 0. -0.68 -0.66666667 -1. ] [ 0.5 0.5 -0.56 -0.35714286 -1. ] [ 1. 1. 1. 1. 1. ]] My current approach (wrong): np.interp(matrix, (np.min(matrix), np.max(matrix)), (-1, +1))
favorite count: 0
type: Question
tagged with: matrix
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/87342963
has comment: http://stackoverflow.com/comment/87345071
tagged with: numpy
has answer: http://stackoverflow.com/a/50160768
downvote count: 0
has title: How to scale each column of a matrix
type: UnansweredQuestion
tagged with: arrays
answer count: 1

http://stackoverflow.com/comment/87308338
comment on: http://stackoverflow.com/a/50145071
score: 0
type: AnswerComment
has text: @abarnert I do agree that there is no clean way to parse the file as it currently stands, however, I did add a solution that will correct the code that the OP has currently written.
type: Comment

http://stackoverflow.com/a/50144194
score: -2
has body: This will not detect if the file is open by other processes! try: a = open('example.xlsx','w') print 'file is closed' execute_certain_actions(a) a.close() except IOError: print 'file is open' execute_different_set_of_actions() This works because you cannot write to a file that is already open so the try statement will fail. If you really want to make sure the file is not being used by any process, go check out this question.
type: Answer
has comment: http://stackoverflow.com/comment/87306934
has comment: http://stackoverflow.com/comment/87307300
has comment: http://stackoverflow.com/comment/87307531
has comment: http://stackoverflow.com/comment/87307129
has comment: http://stackoverflow.com/comment/87307089
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/50143994
has comment: http://stackoverflow.com/comment/87312711
has comment: http://stackoverflow.com/comment/87307496
has comment: http://stackoverflow.com/comment/87307030
has comment: http://stackoverflow.com/comment/87307012
has comment: http://stackoverflow.com/comment/87306796
has comment: http://stackoverflow.com/comment/87307557
has comment: http://stackoverflow.com/comment/87307197
has comment: http://stackoverflow.com/comment/87307128
has comment: http://stackoverflow.com/comment/87307027
has comment: http://stackoverflow.com/comment/87307698

http://stackoverflow.com/comment/87201740
score: 0
type: AnswerComment
has text: do i have to connect the models in any way ??
type: Comment
comment on: http://stackoverflow.com/a/50092692

http://stackoverflow.com/q/50152689
favorite count: 0
type: Question
tagged with: python-2.7
answer count: 2
tagged with: subprocess
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50152885
possible better answer: http://stackoverflow.com/a/50153045
has answer: http://stackoverflow.com/a/50152885
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50153045
score: 1
has title: subprocess.check_output gives windows error
has body: I was trying to run this file named develop.py written in python. But it gives error. Here is my code: import base64 import getpass import os import subprocess import sys credentials = subprocess.check_output([ 'openssl', 'aes-256-cbc', '-d', '-in', 'credentials.development' ], shell=True) env = os.environ.copy() env['CREDENTIALS'] = credentials env['CONFIG'] = 'config.yaml.development' env['ENVIRONMENT'] = 'development' subprocess.check_call(['grunt', 'web:develop'], env=env) Here is the result when I run the file: E:\QA\QA&gt;python develop.py 'openssl' is not recognized as an internal or external command, operable program or batch file. Traceback (most recent call last): File "develop.py", line 13, in &lt;module&gt; ], shell=True) File "C:\Python27\lib\subprocess.py", line 219, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['openssl', 'aes-256-cbc', '-d', '-in', 'credentials.development']' returned non-zero exit status 1 Environment: Windows 10 (64 bit) Python 2.7 How to fix this ??
tagged with: python

http://stackoverflow.com/q/50120735
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has title: How to create a counter with a for loop?
has body: I am trying to write a for loop that will iterate through and for each unique ID will calculate the time spent in each SubmissionStatus(e.g. pending OSPA, Pending Department) and store the results in a list of dictionaries where each dictionary corresponds to each unique ID. The time spent is calculated by taking the earliest LastModified value while the status is in a particular phase and subtracting that value from the LastModified value when the status changes to the next phase (when SubmissionStatus goes from Pending OSPA to Pending Department, I would take the LastModified timestamp from the row and subtract the lowest Last Modified timestamp when SubmissionStatus is Pending OSPA e.g. 04/05/2018-04/01/2018=4 days + 04/06/2018-04/05/2018=1 day so total = 5 days ) input is a pandas dataframe: ID LastModified SubmissionStatus 0 1 04/01/2018 Pending OSPA 1 1 04/03/2018 Pending OSPA 2 1 04/05/2018 Pending Department 3 1 04/06/2018 Pending OSPA 4 2 04/02/2018 Pending OSPA 5 2 04/03/2018 Pending Department 6 2 04/05/2018 Complete output is a list of dictionaries: [ { ID : 1, DaysWithOSPA: 5, DaysWithDepartment: 1}, { ID : 2, DaysWithOSPA:1 DaysWithDepartment:2}]
has answer: http://stackoverflow.com/a/50120788
has comment: http://stackoverflow.com/comment/87259144
tagged with: pandas
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87296297
favorite count: 0
type: Question

seaborn
tags question: http://stackoverflow.com/q/50190900
tags question: http://stackoverflow.com/q/50192121
tags question: http://stackoverflow.com/q/50201227
tags question: http://stackoverflow.com/q/50154976
tags question: http://stackoverflow.com/q/50130445
tag name: seaborn
tags question: http://stackoverflow.com/q/50161140
tags question: http://stackoverflow.com/q/50135676
tags question: http://stackoverflow.com/q/50180620
tags question: http://stackoverflow.com/q/50218109
tags question: http://stackoverflow.com/q/50203934
tags question: http://stackoverflow.com/q/50195997
type: Tag
tags question: http://stackoverflow.com/q/50139778
tags question: http://stackoverflow.com/q/50091591

http://stackoverflow.com/q/50081086
accepted answer: http://stackoverflow.com/a/50081138
answer count: 2
has body: Creating a json file using python which will have multiple entries as follows : out='' with open('data.json', 'w') as outfile: i=0; for i in range(3): string = "test_"+str(i)+'"'+':{ "status": "false", "test_id": 123453},' out= out+string.replace("\\",""); i=i+1; json.dump("{"+out+"}", outfile) The file getting output as: "{test_0\":{ \"status\": \"false\", \"test_id\": 123453},test_1\":{ \"status\": \"false\", \"test_id\": 123453},test_2\":{ \"status\": \"false\", \"test_id\": 123453},}" But ideally correct output should be as : { "test_0": { "status": "false", "test_id": 123453 }, "test_1": { "status": "false", "test_id": 123453 }, "test_2": { "status": "false", "test_id": 123453 } } So the output which is coming has "\" how do i remove them all. Its always appearing inside the file, have tried using strip too but not worth. Help!!
has answer: http://stackoverflow.com/a/50081138
downvote count: 0
has comment: http://stackoverflow.com/comment/87178089
tagged with: python
has comment: http://stackoverflow.com/comment/87178184
has title: how to create a valid json file using python?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12943819
has answer: http://stackoverflow.com/a/50081146
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50081146

http://stackoverflow.com/q/50183834
type: AnsweredQuestion
has title: ValueError: Input arrays should have the same number of samples as target arrays. Found 32 input samples and 128 target samples
score: 0
has body: I am following this tutorial here to do image classification. Link: [Keras image classification][1] I expanded the code to 8 classes but I got the following error: ValueError: Input arrays should have the same number of samples as target arrays. Found 32 input samples and 128 target samples My train top model code looks like: def train_top_model(): train_data = np.load(open('bottleneck_features_train', 'rb')) train_labels = np.array([0] * (nb_train_samples // 8) + [1] * (nb_train_samples // 8) + [2] * (nb_train_samples // 8) + [3] * (nb_train_samples // 8) + [4] * (nb_train_samples // 8) + [5] * (nb_train_samples // 8) + [6] * (nb_train_samples // 8) + [7] * (nb_train_samples // 8)) validation_data = np.load(open('bottleneck_features_validation', 'rb')) validation_labels = np.array([0] * (nb_train_samples // 8) + [1] * (nb_train_samples // 8) + [2] * (nb_train_samples // 8) + [3] * (nb_train_samples // 8) + [4] * (nb_train_samples // 8) + [5] * (nb_train_samples // 8) + [6] * (nb_train_samples // 8) + [7] * (nb_train_samples // 8)) train_labels = keras.utils.to_categorical(train_labels, num_classes = 8) validation_labels = keras.utils.to_categorical(validation_labels, num_classes = 8) model = Sequential() model.add(Flatten(input_shape=train_data.shape[1:])) model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(8, activation='softmax')) sgd = SGD(lr=1e-2, decay=0.00371, momentum=0.9, nesterov=False) model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_data, train_labels, epochs=epochs, batch_size=batch_size, validation_data=(validation_data, validation_labels)) model.save_weights(top_model_weights_path) I think what the error is trying to say is that the input should have 128 samples but it's only getting 32. I am not sure about the reason because I am also getting this Found 128 images belonging to 8 classes. I think it indicates it successfully get all 128 images. Can someone please help? Tha…
accepted answer: http://stackoverflow.com/a/50186308
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50186308
answer count: 1
tagged with: python
tagged with: keras

http://stackoverflow.com/comment/87327828
comment on: http://stackoverflow.com/q/50154930
type: Comment
type: QuestionComment
has text: Other than performance, there isn't any other difference?
score: 0

http://stackoverflow.com/comment/87200102
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50091897
has text: Try to use environment variables for these things
type: Comment

http://stackoverflow.com/comment/87382767
score: 0
comment on: http://stackoverflow.com/q/50181584
has text: What are you looking for in the header? If you need source and destination IPs, use [`Protocol.transport.getPeer()`](https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.ITCPTransport.html#getPeer) or `getHost()`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50195406
favorite count: 0
has answer: http://stackoverflow.com/a/50195592
has body: I'm trying to build port checker myself , I did everything i could but i want to use thread inside the loop. After fetch an IP from my-hosts file and then i can run checker on the new thread instead of blocking the main thread.Is there anyone know how to make this happen or correct my code ? import socket import threading import time counting_open = [] counting_close = [] port = 25 hosts = "ip.txt" def scan(): with open(hosts) as e: p = e.read().split("\n") for host in p : #iwant to use this for threading into the function s = socket.socket() result = s.connect_ex((host,port)) print('working on port &gt; '+(str(port))) if result == 0: counting_open.append(port) print((str(port))+' -&gt; open on ' + str(host)) s.close() else: counting_close.append(port) print((str(port))+' -&gt; close on ' + str(host))`
has title: How to check if a port is available?
type: AnsweredQuestion
downvote count: 1
score: -1
has answer: http://stackoverflow.com/a/50195507
accepted answer: http://stackoverflow.com/a/50195507
type: Question
upvote count: 0
answer count: 2
tagged with: multithreading
tagged with: python
possible better answer: http://stackoverflow.com/a/50195592

http://stackoverflow.com/a/50171556
score: 1
type: Answer
has body: intput only returns objects of type str (string). However, you can be inventive by specifying a certain format and performing the conversion using datetime from the standard library: from datetime import time time = input('Enter a time in the format HH:MM \n') # input 15:25 h, m = map(int, time.split(':')) res = time(hour=h, minute=m) print(res) 15:25:00
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50171466

http://stackoverflow.com/comment/87303097
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50139421
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thanks a lot -- voted and accepted!

http://stackoverflow.com/a/50127322
type: Answer
score: 1
downvote count: 0
has body: I ran the serialized function definition through pickletools.dis to see what was taking up so much space. It seems to be due entirely to a CombineFn's extract_output definition. Going from: def extract_output(self, accumulator): output = zip(self.id_list, accumulator[1], *accumulator[0]) return output to def extract_output(self, accumulator): return accumulator brings content-length from '74538844' to '858884' about a factor of 100 times less. accumulator holds two numpy arrrays with dimensions len(id_list) x len(id_list) and len(id_list). id_list provides integer labels (roughly 3000 in this case) for each row of the arrays and is known when constructing the pipeline. I don't know why this happens, but keying with ID in a DoFn after the CombineFn generates a reasonably sized request and produces roughly the same output.
upvote count: 1
answers question: http://stackoverflow.com/q/50093478

http://stackoverflow.com/comment/87463980
type: Comment
comment on: http://stackoverflow.com/q/50222743
type: QuestionComment
score: 0
has text: `ffmpy` is just a wrapper for calling the ffmpeg program.

http://stackoverflow.com/a/50167544
upvote count: 2
answers question: http://stackoverflow.com/q/50166987
downvote count: 0
has body: This is how I save and download model files from Collab. Save only the trainable variables(These are my store/restore fns): code is as below : def store(sess_var, model_path): if model_path is not None: saver = tf.train.Saver(var_list=tf.trainable_variables()) save_path = saver.save(sess_var, model_path) print("Model saved in path: %s" % save_path) else: print("Model path is None - Nothing to store") def restore(sess_var, model_path): if model_path is not None: if os.path.exists("{}.index".format(model_path)): saver = tf.train.Saver(var_list=tf.trainable_variables()) saver.restore(sess_var, model_path) print("Model at %s restored" % model_path) else: print("Model path does not exist, skipping...") else: print("Model path is None - Nothing to restore") Compress the directory where you stored your model - Make sure it contains nothing else: !tar -czvf model.tar.gz models/ Download the model: from google.colab import files files.download('model.tar.gz') Since your only storing the trainable variables instead of the entire session, the size of the model is small and thus it is able to download. Be sure to use Chrome - I've not been able to get the last snippet working on Firefox.
has comment: http://stackoverflow.com/comment/87353330
has comment: http://stackoverflow.com/comment/87355866
has comment: http://stackoverflow.com/comment/87353609
type: Answer
has comment: http://stackoverflow.com/comment/87352777
has comment: http://stackoverflow.com/comment/87353292
has comment: http://stackoverflow.com/comment/87353504
score: 2
has comment: http://stackoverflow.com/comment/87354099

http://stackoverflow.com/q/50152170
has answer: http://stackoverflow.com/a/50152425
accepted answer: http://stackoverflow.com/a/50152410
favorite count: 0
has comment: http://stackoverflow.com/comment/87322820
type: Question
has body: I've got a matrix like this: df = pd.DataFrame({'a':[7, 0, 3], 'b':[0, 4, 2], 'c':[3, 2, 9]}) df.index = list(df) df a b c a 7 0 3 b 0 4 2 c 3 2 9 And I'd like to get something like this: C1 C2 V 0 a a 7 1 a b 0 2 a c 3 3 b a 0 4 b b 4 5 b c 2 6 c a 3 7 c b 2 8 c c 9 For which I've written the following code: vv = pd.DataFrame(columns=['C1', 'C2', 'V']) i = 0 for cat1 in df.index: for cat2 in df.index: vv.loc[i] = [cat1, cat2, d[cat1][cat2]] i += 1 vv['V'] = vv['V'].astype(int) Is there a better/faster/more elegant way of doing this?
possible better answer: http://stackoverflow.com/a/50152271
has answer: http://stackoverflow.com/a/50152410
upvote count: 2
has title: Unroll a matrix in Pandas
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50152679
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50152456
tagged with: pandas
has answer: http://stackoverflow.com/a/50152271
downvote count: 0

http://stackoverflow.com/q/50198753
downvote count: 0
upvote count: 1
tagged with: flask
favorite count: 0
type: Question
tagged with: python
has title: SqlALchemy ForeignKey error linking two tables
tagged with: sqlalchemy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50198892
has body: I have trouble linking two tables with 'Posts' and 'Comments' so comments are only displayed on particular post, where they have been created. With linking post and user I used current_user.id to make link between tables, but using ForeignKey gaves me always error: sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Post.post_rel - there are no foreign keys linking these tables Below is my code: class Post(db.Model): __tablename__ = 'post' id = db.Column(Integer, primary_key=True) title = db.Column(String(50)) subtitle = db.Column(String(50)) author = db.Column(String(20)) date_posted = db.Column(DateTime) content = db.Column(Text) post_rel = relationship('Post', back_populates='comment_rel', foreign_keys='[Comment.post_id]') def get_comments(self): return Comments.query.filter_by(post_id=post.id).order_by(Comments.timestamp.desc()) def __repr__(self): return '&lt;Post %r&gt;' % (self.body) class Comment(db.Model): __tablename__ = 'comment' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(140)) author = db.Column(db.String(32)) timestamp = db.Column(db.DateTime(), default=datetime.utcnow, index=True) post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False) comment_rel = relationship('Comment', uselist=False, back_populates='post_rel') def __init__(self, text, author, timestamp): """""" self.text = text self.author = author self.timestamp = timestamp def __repr__(self): return '&lt;Post %r&gt;' % (self.body) def show(self): return self.author + '\n' + self.text
score: 1
has answer: http://stackoverflow.com/a/50198892
answer count: 1

http://stackoverflow.com/a/50128505
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87274956
accepted answer of: http://stackoverflow.com/q/50128111
has comment: http://stackoverflow.com/comment/87275447
has body: Here is a working version of your code. Just corrected the necessary parts, but undoubtedly you should consider writing a more clean, and better indented code. import random # make a list of words words = [ 'apple', 'banana', 'orange', 'coconut', 'strawberry', 'lime', 'grapefruit', 'lemon', 'kiwi', 'blueberry', 'melon' ] while True: start = input("Press enter/return to start, or Q to quit") if start.lower() == 'q': break bad_guesses = [] good_guesses = [] # pick rand word secret_word = random.choice(words) while len(bad_guesses) &lt; 7 and len(good_guesses) != len(list(secret_word)): # draw guessed letters, spaces, and strikes for letter in secret_word: if letter in good_guesses: print(letter, end='') else: print('_', end='') print('\Bad guesses: {}/7\n'.format(len(bad_guesses))) # take guess guess = input("Guess a letter: ").lower() if len(guess) != 1: print("You can only guess a single letter!") continue elif guess in bad_guesses or guess in good_guesses: print("You already guessed that letter!") continue elif not guess.isalpha(): print("You can only guess letters!") continue if guess in secret_word: good_guesses.append(guess) else: bad_guesses.append(guess) if len(good_guesses) == len(set(secret_word)): print("You Win! The word was {}".format(secret_word)) break print("You didn't get it! My secret word was {}".format(secret_word))
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50128111

http://stackoverflow.com/q/50224867
has comment: http://stackoverflow.com/comment/87469871
has title: Create histogram using matplotlib in python using input file
has comment: http://stackoverflow.com/comment/87505671
tagged with: file-io
type: Question
tagged with: matplotlib
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87483407
score: 0
has body: I have a txt file with 5 columns e.g. 'data.txt': data.txt I want to create a histogram using data from col 2 (age) as x-axis and have the entire column counted as 'count' for the y-axis I am currently using the code below but i'm only getting weird results with open('Players.txt') as f: v = np.loadtxt(f, delimiter= ' ', dtype="str", skiprows=1, usecols=2) plt.hist(v, bins=100) plt.xlabel('Age') plt.ylabel('Count') plt.title('Histogram of Age') plt.show() Any help would be greatly appreciated!!
answer count: 0
tagged with: histogram
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87474385
favorite count: 0

http://stackoverflow.com/a/50148690
answers question: http://stackoverflow.com/q/50148237
downvote count: 0
type: AcceptedAnswer
has body: This what your method should look like - def move(): value = lb.get(lb.curselection()) x1 = lb.curselection()[0] lb.selection_clear(x1) if x1+1==lb.size(): lb.selection_set(0) else: lb.selection_set(x1+1) label_var.set(value) Please note that, you need to handle corner cases, i.e. end of the list. In this code, at the end of the list, I restart at beginning.
type: Answer
accepted answer of: http://stackoverflow.com/q/50148237
score: 2
upvote count: 2

http://stackoverflow.com/a/50082286
score: 2
has comment: http://stackoverflow.com/comment/87180679
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50082076
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: IIUC Using wide_to_long to fatten your df, then we using agg with groupby + unstack to calculated and format the result s=pd.wide_to_long(junkdf2'Cohort_x','Cohort_y','Rev/Payout_x','Rev/Payout_y'.reset_index().reset_index(),stubnames=['Rev/Payout','Cohort'],i=['index','User_ID'],j='xory',sep='_',suffix='\w+').set_index('Cohort',append=True) s.reset_index(inplace=True) s.groupby(['Cohort','xory']).agg({'Rev/Payout':'sum','User_ID':'nunique'}).unstack() Out[298]: User_ID Rev/Payout xory x y x y Cohort 2010-01 2 2 70 127 2010-02 3 2 135 61 2010-03 1 2 40 131 2010-04 1 2 105 169
answers question: http://stackoverflow.com/q/50082076

http://stackoverflow.com/a/50116812
upvote count: 6
type: AcceptedAnswer
downvote count: 0
score: 6
has body: As suggested was likely in the comment by PM 2Ring, your book seems be using Python 2 while you are using Python 3. The map function returns a list in Python 2, but in Python 3 it returns a map object unless you explicitly convert it to a list. You should be able to make your code work by changing this line: fltLine = map(float,curLine) To: fltLine = list(map(float,curLine))
accepted answer of: http://stackoverflow.com/q/50116405
type: Answer
answers question: http://stackoverflow.com/q/50116405

http://stackoverflow.com/comment/87215474
type: AnswerComment
has text: @EnrikShaumann If my answer helped, you can consider accepting it so that the question can be closed.
comment on: http://stackoverflow.com/a/50075072
type: Comment
score: 0

http://stackoverflow.com/comment/87336294
type: QuestionComment
comment on: http://stackoverflow.com/q/50159000
score: 0
has text: Added some examples. Also, I am having problems with the square approach, as small numbers get smaller. I intend to get «small numbers» (below average) bigger, and «big numbers» (over average) smaller.
type: Comment

http://stackoverflow.com/a/50104566
has comment: http://stackoverflow.com/comment/87337018
downvote count: 0
has comment: http://stackoverflow.com/comment/87338130
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87337762
accepted answer of: http://stackoverflow.com/q/50103918
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/50103918
has body: Try this: I crate 2 indexes, and then set rows 2-4 to be duplicates: import numpy as np test_master = pd.DataFrame(np.random.rand(3, 3), columns=['A', 'B', 'C']) test_daily = pd.DataFrame(np.random.rand(5, 3), columns=['A', 'B', 'C']) test_daily.iloc[1:4] = test_master[:3].values print(test_master) print(test_daily) output: A B C 0 0.009322 0.330057 0.082956 1 0.197500 0.010593 0.356774 2 0.147410 0.697779 0.421207 A B C 0 0.643062 0.335643 0.215443 1 0.009322 0.330057 0.082956 2 0.197500 0.010593 0.356774 3 0.147410 0.697779 0.421207 4 0.973867 0.873358 0.502973 Then, add a multiindex level to identify which data is from which dataframe: test_master['master'] = 'master' test_master.set_index('master', append=True, inplace=True) test_daily['daily'] = 'daily' test_daily.set_index('daily', append=True, inplace=True) Now merge as you suggested and drop duplicates: merged = test_master.append(test_daily) merged = merged.drop_duplicates().sort_index() print(merged) output: A B C master 0 daily 0.643062 0.335643 0.215443 master 0.009322 0.330057 0.082956 1 master 0.197500 0.010593 0.356774 2 master 0.147410 0.697779 0.421207 4 daily 0.973867 0.873358 0.502973 There you see the combined dataframe with the origin of the data labeled in the index. Now just slice for the daily data: idx = pd.IndexSlice print(merged.loc[idx[:, 'daily'], :]) output: A B C master 0 daily 0.643062 0.335643 0.215443 4 daily 0.973867 0.873358 0.502973
has comment: http://stackoverflow.com/comment/87294431
has comment: http://stackoverflow.com/comment/87342205

http://stackoverflow.com/comment/87374872
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50178702
type: AnswerComment
has text: Problem is that it is not deterministic as the computations are performed in parallel.

http://stackoverflow.com/comment/87242345
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50112351
has text: Please copy and paste the relevant part of the output into the actual question. An image of text is never as useful as the text itself (unless it's a question about rendering text or something).
type: Comment

http://stackoverflow.com/q/50133805
type: Question
score: -5
has body: hello stack overflow members my question is how i can get the Button names when the buttons are automatically generating from a database like this for index, dat in enumerate(data2): ttk.Button(master, text=dat[0]).grid(row=index+1, column=1,pady=0,padx=0) any help&lt;3
has title: python how to get button name from database
downvote count: 5
accepted answer: http://stackoverflow.com/a/50134837
tagged with: python
has answer: http://stackoverflow.com/a/50134837
type: AnsweredQuestion
tagged with: tkinter
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87285945

http://stackoverflow.com/comment/87351082
type: AnswerComment
comment on: http://stackoverflow.com/a/50166539
type: Comment
score: 0
has text: @P.Camilleri I don't really know, but my guess would be no.

http://stackoverflow.com/comment/87297601
type: QuestionComment
has text: @juvian Cost. Waste has cost, and so does reconfiguring.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50136954

http://stackoverflow.com/a/50093309
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87203173
answers question: http://stackoverflow.com/q/50093119
type: Answer
has comment: http://stackoverflow.com/comment/87202911
has body: The reason why your only getting the first 10 sections is because only the first ten courses are shown. You might be logged in on your browser, so when you go to check it out, it shows every section. But for me and your scraper it's only showing the first 10. You'll need to click that .section-container--more-sections button before looking for the titles. As for the weird case of the titles not being scraped properly: It's because when a element is hidden text attribute will always be undefined, which is why it only works for the first section. I'd try using the WebElement.get_attribute('textContent') to scrape the text.
accepted answer of: http://stackoverflow.com/q/50093119

http://stackoverflow.com/a/50168869
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50168663
downvote count: 0
answers question: http://stackoverflow.com/q/50168663
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87403881
has body: As per your code trial you can remove the time.sleep(30) and induce WebDriverWait for the element to be clickable as follows : from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC # lines of code WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "proceed"))).click() Note : Configure the WebDriverWait instance with the maximum time limit as per your usecase. The expected_conditions method element_to_be_clickable() will return the WebElement as soon as the element is visible and enabled such that you can click it.
type: Answer

http://stackoverflow.com/q/50184952
tagged with: virtualenv
tagged with: macos
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50185361
tagged with: pipenv
has title: Failing to initialize pipenv in mac (TypeError: sequence item 0: expected str instance, NoneType found)
has body: I'm a Mac user, and I frequently face frustrations when installing python packages. This time, pipenv seems not working properly. I successfully installed pipenv. $pipenv --version pipenv, version 11.10.1 However, When I try to init pipenv shell, I got error like this: Creating a virtualenv for this project… Using /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 (3.6.4) to create virtualenv… ⠋Already using interpreter /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6' Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/virtualenv.py", line 2349, in &lt;module&gt; main() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/virtualenv.py", line 712, in main symlink=options.symlink) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/virtualenv.py", line 927, in create_environment site_packages=site_packages, clear=clear, symlink=symlink)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/virtualenv.py", line 1140, in install_python copy_required_modules(home_dir, symlink) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/virtualenv.py", line 1070, in copy_required_modules dst_filename = change_prefix(filename, dst_prefix) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/virtualenv.py", line 1044, in change_prefix (filename, prefixes) AssertionError: Filename /Users/ChaewonKong/Desktop/dev/re.py does not start with any of these prefixes: ['/Library/Frameworks/Python.framework/Versions/3…
tagged with: pip
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50185361
upvote count: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87399606
type: Comment
score: 0
type: AnswerComment
has text: As well as putting the address in the body, you can set a reply-to header.
comment on: http://stackoverflow.com/a/50191025

http://stackoverflow.com/q/50081408
has title: Decrypted Image from hex string cannot be open
tagged with: python
has body: I have a question regarding my two codes I'm working on. The purpose of this program is to encrypt an image of .png format. Then I'll work on displaying the encrypted image as a bitmap image. And finally, I would like to decrypt it into its original image. So far, I'm simply working on taking the image -> converting it into hex -> encrypting by DES in ECB mode and decrypting it back. However, I have an issue when I try to display the image after it's decrypted! The code itself is fine and doesn't give any Traceback. But the image which was saved and I intend to open gives the following error: "Could not load image 'newSavedImage.png'. Fatal error reading PNG image file: Not a PNG file" from PIL import Image import binascii import blockcipher as bc def load_image(img_name): with open(img_name, 'rb') as f: img_obj = f.read() img_obj = binascii.hexlify(img_obj) # binascii.a2b_hex(img_obj.replace(' ', '')) return img_obj def save_image(img_obj): temp = open("newSavedImage.png", "wb") # with original image extension # write into the object by decoding base64 object temp.write(binascii.unhexlify(img_obj)) temp.close() def choose_encr(img_obj): key, encr_img = bc.myDESencr(img_obj, 1) encr_img = binascii.hexlify(encr_img) return key, encr_img def decrypt(encr_obj, key): orig_img = bc.myDESdecr(encr_obj, key, 1) orig_img = binascii.hexlify(orig_img) return orig_img if __name__ =="__main__": img_str = 'pic3.png' # the img is in my working dir img = load_image(img_str) # save_image(img) key, enc = choose_encr(img) img = decrypt(enc, key) save_image(img) and this is my code for DES encryption I use from Crypto.Cipher import DES3, DES from Crypto import Random import Crypto.Util # mode is integer values ranging from 1 to 4 def myDESencr(orig_image, mode): # generate random key key = Random.get_random_bytes(8) # pad if not byte size of % 8 orig_image = pad(orig_image) # instantiation with the right mode if mode == 1: des = DES.new(key, DES.MODE_ECB) encrypted_image = des.encrypt…
has comment: http://stackoverflow.com/comment/87178812
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87178845
has comment: http://stackoverflow.com/comment/87179333
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87179644
answer count: 0
type: UnansweredQuestion
tagged with: encryption

http://stackoverflow.com/q/50206382
has comment: http://stackoverflow.com/comment/133372935
duplicate of: http://stackoverflow.com/q/27974126
tagged with: python
possible better answer: http://stackoverflow.com/a/50206410
has comment: http://stackoverflow.com/comment/87430103
score: 2
type: AnsweredQuestion
answer count: 2
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50206448
linked to: http://stackoverflow.com/q/27974126
has comment: http://stackoverflow.com/comment/87429966
favorite count: 0
has answer: http://stackoverflow.com/a/50206448
type: Question
has answer: http://stackoverflow.com/a/50206410
has body: I want to get the combinations of a list of list, for example [['a0', 'a1'], ['b0', 'b1'], ['c0', 'c1', 'c2']] I can use list(itertools.product(*listOfTuples)) and get [('a0', 'b0', 'c0'), ('a0', 'b0', 'c1'), ('a0', 'b0', 'c2')... ('a1', 'b1', 'c2')] How would I get a list with the possible combinations of length 2? For example: [('a0', 'b0'), ('a0', 'c0'), ('b0', 'c0')...
has title: Generating combinations of values from a list of lists python

http://stackoverflow.com/a/50098390
has body: IIUC you could use cut to achieve this: In[33]: pd.cut(df['a'], bins=[0,3,7,11], right=True, labels=False)+1 Out[33]: 0 2 1 3 2 3 3 1 4 1 5 1 6 1 7 3 8 2 9 2 Here you'd pass the cutoff values to cut, and this will categorise your values, by passing labels=False it will give them an ordinal value (zero-based) so you just +1 to them Here you can see how the cuts were calculated: In[34]: pd.cut(df['a'], bins=[0,3,7,11], right=True) Out[34]: 0 (3, 7] 1 (7, 11] 2 (7, 11] 3 (0, 3] 4 (0, 3] 5 (0, 3] 6 (0, 3] 7 (7, 11] 8 (3, 7] 9 (3, 7] Name: a, dtype: category Categories (3, interval[int64]): [(0, 3] &lt; (3, 7] &lt; (7, 11]]
type: Answer
upvote count: 11
answers question: http://stackoverflow.com/q/50098025
downvote count: 0
score: 11

http://stackoverflow.com/q/50097521
answer count: 1
downvote count: 3
linked to: http://stackoverflow.com/q/37289951
favorite count: 0
type: Question
tagged with: format
has body: I used the following code import itertools f = list(itertools.combinations(['Javad', 'love', 'python'], 2)) print (f) An I got the following result: [('Javad', 'love'), ('Javad', 'python'), ('love', 'python')] I'm looking for a way to transfer them to a csv or excel file as follow:
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/50097679
upvote count: 1
tagged with: python
tagged with: nlp
duplicate of: http://stackoverflow.com/q/37289951
tagged with: http://stackoverflow.com/tag/csv
has title: parentheses and comma formatting to csv columns

http://stackoverflow.com/a/50190817
has comment: http://stackoverflow.com/comment/87398693
answers question: http://stackoverflow.com/q/50190720
score: 1
has comment: http://stackoverflow.com/comment/87405333
downvote count: 1
has comment: http://stackoverflow.com/comment/87405456
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/87398796
has comment: http://stackoverflow.com/comment/87400459
has body: In my opinion, a list of dictionaries is inefficient and not a recommended solution to hold structured data of this kind. You can use collections.namedtuple from the standard library, but I prefer 3rd party library pandas, which accepts a list of dictionaries directly: import pandas as pd players = [{'name': 'John', 'points': '27', 'Played': '6'}, {'name': 'Emil', 'points': '43', 'Played' : '13'}, {'name': 'Susan', 'points': '11', 'Played': '2'}, {'name': 'Peter', 'points': '4', 'Played': '3'}] df = pd.DataFrame(players) print(df) Played name points 0 6 John 27 1 13 Emil 43 2 2 Susan 11 3 3 Peter 4 You can then perform manipulations using the pandas API: # Add a new column and specify value for a given name df['Score'] = 0 df.loc[df['name'] == 'John', 'Score'] = 1 # Add 1 to John played df.loc[df['name'] == 'John', 'Played'] += 1
has comment: http://stackoverflow.com/comment/87405376

http://stackoverflow.com/a/50221000
has comment: http://stackoverflow.com/comment/87461290
type: Answer
has comment: http://stackoverflow.com/comment/87459799
has comment: http://stackoverflow.com/comment/87459754
score: 0
has body: Your workaround is correct, but you can make the database do most of the work by setting a busy timeout. (For 1000 connections, this needs to be set extremely high, essentially inifinite, like you're already doing.) But this still results in random wait times. SQLite does not wait until one writer's transaction has finished and then signals the next, because there is no portable API for this. However, in Windows, you could use a named mutex object (which requires some trickery to access it from Python).
answers question: http://stackoverflow.com/q/50220147

http://stackoverflow.com/q/50167021
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50170370
answer count: 2
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/50170370
type: AnsweredQuestion
score: 3
upvote count: 3
possible better answer: http://stackoverflow.com/a/50171486
downvote count: 0
has title: How can I make a regular expression which finds the first inner pair words?
has body: I would like to make a regular expression which capture the first inner pair words. My code following works in a condition but it does not work in another. It captures the last pair words. Please see the my code below. def testReplaceBetweenWords(): head_dlmt='Head' tail_dlmt='Tail' line0 = "abc_Head_def_Head_inner_inside_Tail_ghi_Tail_jkl" line1 = "abc_Head_first_Tail_ghi_Head_second_Tail_opq" between_pattern = "(^.*(?&lt;={0}))(?!.*{0}).*?(?={1})(.*)$".format(head_dlmt, tail_dlmt) compiled_pattern = re.compile(between_pattern) # Case 0: good case: It captures the first inner words. result0 = re.search(compiled_pattern, line0) print("original 0 : {0}".format(result0.group(0))) print("expected Head : abc_Head_def_Head") print("found Head : {0}".format(result0.group(1))) print("expected Tail : Tail_ghi_Tail_jkl") print("found Tail : {0}{1}".format(' ' * (result0.regs[2][0]), result0.group(2))) print() # Case 1: Bad case: It captures the last pair words. result1 = re.search(compiled_pattern, line1) print("original 1 : {0}".format(result1.group(0))) print("expected Head : abc_Head") print("found Head : {0}".format(result1.group(1))) print("expected Tail : Tail_ghi_Head_second_Tail_opq") print("found Tail : {0}{1}".format(' ' * (result1.regs[2][0]), result1.group(2))) And the outputs are following. original 0 : abc_Head_def_Head_inner_inside_Tail_ghi_Tail_jkl expected Head : abc_Head_def_Head found Head : abc_Head_def_Head expected Tail : Tail_ghi_Tail_jkl found Tail : Tail_ghi_Tail_jkl original 1 : abc_Head_first_Tail_ghi_Head_second_Tail_opq expected Head : abc_Head found Head : abc_Head_first_Tail_ghi_Head expected Tail : Tail_ghi_Head_second_Tail_opq found Tail : Tail_opq The first case works well. It captures the first inner pair words. The second case does not work. It captures the last pair words but I expected the first pair words. How can I make a regular express which satisfies the two cases above? Thank you very much.
has answer: http://stackoverflow.com/a/50171486

http://stackoverflow.com/comment/87174310
type: QuestionComment
comment on: http://stackoverflow.com/q/50079136
has text: Showing what you have tried so far...
score: 1
type: Comment

http://stackoverflow.com/comment/87269596
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50124174
score: 0
has text: If I activate the virtualenv and type "which python3" it shows me $virtualenvpath/bin/python3. However, I didn't install a separate Python version. To set up the virtualenv I typed "virtualenv --system-site-packages -p python3 $virtualenvpath" (from the Tensorflow install instructions: https://www.tensorflow.org/install/install_linux#InstallingVirtualenv) Also, everything else about the virtualenv works fine. I also verified that readline is installed in the virtualenv.

http://stackoverflow.com/comment/87415688
type: QuestionComment
has text: You were right. It is there to change the RGB ratio of the picture.
score: 0
comment on: http://stackoverflow.com/q/50199320
type: Comment

http://stackoverflow.com/q/50083900
has comment: http://stackoverflow.com/comment/87186902
type: AnsweredQuestion
score: 0
answer count: 2
has body: I am trying to plot 3 level category in bokeh python, but I am facing issue and my plot is not working, Could you give me a hand on this ? below is my code : from bokeh.models import ColumnDataSource, FactorRange from bokeh.io import show p = figure(plot_height=250, title="Fruit Counts by Year") #tp is my data as pandas DataFrame x1=list(tp['SRN']) x2=list(tp['SN']) x3=list(tp['PN']) counts = list(tp['VS.FEGE.RXMAXSPEED']) x=[("SRN"+str(a1),"SN"+str(a2),"pN"+str(a3)) for a1,a2,a3 in zip(x1,x2,x3)] source = ColumnDataSource(data=dict(x=x, counts=counts)) p =figure(x_range=FactorRange(*x),plot_height=250,title="title",toolbar_location=None, tools="") p.vbar(x='x', top='counts', width=0.9,source=source) show(p) tp data is as below : SRN SN PN VS.FEGE.RXMAXSPEED VS.FEGE.TXMAXSPEED 0 0 18 0 1.794 0.307 1 0 18 1 1.896 0.307 2 0 19 0 131238.122 574793.502 3 0 19 1 31806.984 126149.078 4 0 20 0 4.968 0.307 I am not receiving any specific error, just plot is not shown. Also I want to know how "x_range=FactorRange(*x)" is working and is there any alernative way instead ?
upvote count: 1
downvote count: 1
tagged with: bar-chart
tagged with: bokeh
favorite count: 0
has answer: http://stackoverflow.com/a/50152028
type: Question
accepted answer: http://stackoverflow.com/a/50152028
has answer: http://stackoverflow.com/a/50084402
possible better answer: http://stackoverflow.com/a/50084402
has comment: http://stackoverflow.com/comment/87184120
has title: categorized barchart in bokeh python
has comment: http://stackoverflow.com/comment/87195097
tagged with: python
has comment: http://stackoverflow.com/comment/87184111

http://stackoverflow.com/comment/87492629
score: 0
comment on: http://stackoverflow.com/a/50231770
type: Comment
type: AnswerComment
has text: so the `is` just only compare 2 diferrent variable , and if i try to compare same variabel i only get the 'False' for the result , Because if i do `print (id(var_1) is id(var_1))` i creating the diferrent a nameless variable ?

http://stackoverflow.com/q/50219352
type: UnansweredQuestion
tagged with: python
has title: Insert array into postgres array
has comment: http://stackoverflow.com/comment/87455978
upvote count: 2
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/50220733
answer count: 1
tagged with: sqlalchemy
has body: I'm trying to insert an array into a postrges table as an array. I'm receiving the following error: jobsArray = ['Vice President', 'Technical Services Consultant'] db.execute("""INSERT INTO test VALUES (%s)""", (jobsArray,)) TypeError: not all arguments converted during string formatting I've tried many different solutions recommended on stackoverflow but with no success, errors vary but this is the most common error. I tried converting to a tuple but same behavior.
favorite count: 0
type: Question
tagged with: postgresql
has comment: http://stackoverflow.com/comment/87459328
has comment: http://stackoverflow.com/comment/87455877

http://stackoverflow.com/comment/87180224
comment on: http://stackoverflow.com/a/50082108
type: Comment
type: AnswerComment
score: 1
has text: I got it now. I totally forgot about set and word[-1]. Thank you that was a big help

http://stackoverflow.com/q/50131396
tagged with: sys
accepted answer: http://stackoverflow.com/a/50131533
tagged with: python
has answer: http://stackoverflow.com/a/50131533
type: AnsweredQuestion
score: 0
tagged with: printing
tagged with: flush
answer count: 1
has body: I want to see the progress of my for loop by repeatedly overwriting the print function. I expected the printed line to be overwritten every time the loop progresses. What happened was that after every loop a new line was printed right under the previous printed line. This was solved by removing the \n from the print line, because the \n caused a new empty line to be overwritten each time, instead of overwriting the first printed line. import sys import time count1=0 x=10 for i in range(x): count1+=1 sys.stdout.write("\r{} out of {}...\n".format(count1, x)) sys.stdout.flush() time.sleep(.1) I am using Python 3.6 (64-bit) in Jupter Notebook 4.3.1. on Windows 10. I have looked over several issues posted on Stack Overflow, but I haven't been able to solve it yet. Thanks!
has title: Python sys.stdout.flush() doesn't seem to work
has comment: http://stackoverflow.com/comment/87281011
has comment: http://stackoverflow.com/comment/87281321
type: Question
tagged with: overwrite

http://stackoverflow.com/comment/87370079
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50176449
has text: `numpy.timedelta64(137,'ns')` is what you did.

http://stackoverflow.com/comment/87296997
type: AnswerComment
comment on: http://stackoverflow.com/a/50120507
has text: Please open first or any CSV in a text editor (Notepad, TextEdit, gedit, etc.) and check if last column has blanks: `data,data,,` or `data,data,"",`. If so, check how CSVs were originally created. These render as ghost columns in Excel, Lotus, or LibreOffice which cannot be seen without content. See where CTRL (CMD in MacOS) + END takes cursor at end of content.
score: 0
type: Comment

http://stackoverflow.com/a/50588855
answers question: http://stackoverflow.com/q/50111539
has comment: http://stackoverflow.com/comment/97096331
score: 7
upvote count: 7
type: Answer
downvote count: 0
has body: I was trying to do this as well (read a local image and make it my background in a plotly graph) and kept going around and around with it (likely because I am pretty new to the whole image thing and was also trying to understand base64 encoding). This is my simple solution in a Jupyter notebook using plotly offline: import base64 with open("C:/My.png", "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode() #add the prefix that plotly will want when using the string as source encoded_image = "data:image/png;base64," + encoded_string Now your layout for the plotly graph can look like this (in this case - keep in mind that you are using the actual data ranges in the graph to place the image on it, so the x and Y have to be in the appropriate range): "layout": Layout(title='Graph Title', yaxis=dict(title='Y Label'), xaxis=dict(title='X Label'), images=[dict( source= encoded_image, xref= "x", yref= "y", x= 0, y= 10, sizex= 20, sizey= 10, sizing= "stretch", opacity= 0.7, layer= "below")])

http://stackoverflow.com/comment/87300894
type: QuestionComment
has text: Keep in mind that `1` isn't a float. If you want to accept ints, doing so adds complexity, particularly for cases where `float(x) != x`.
comment on: http://stackoverflow.com/q/50141308
score: 0
type: Comment

http://stackoverflow.com/comment/87374661
has text: @Life2Day thanks, not sure I understand the rest of your comment. is it another question?
score: 0
comment on: http://stackoverflow.com/a/50177228
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87346458
comment on: http://stackoverflow.com/a/50145804
type: Comment
has text: sacul . god bless you
score: 0
type: AnswerComment

http://stackoverflow.com/q/50168670
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: python
tagged with: django-rest-framework
has title: Compressing and Decompressing on POST and GET requests using lz4 + django + rest_framework
tagged with: lossless-compression
score: 2
has body: I am using django 1.11 + rest_framework trying to implement lossless compression method using lz4 python library. In a nutshell,I have Implemented a class based view POST method that has the compression method defined. I would later want to implement a decompression method when a GET request is done. When I try to make a POST request I get TypeErrorr log: a bytes-like object is required, not 'InMemoryUploadedFile' I not really familiar with compression of losseless compression some proper direction would be nice. Lastly, is there any other way I would implement compressing and decompressing of files on POST and GET methods? My model is as follows: class EmployeeDocument(models.Model): """ Model, Which holds Employee documents uploaded. """ employee = models.ForeignKey( Employee, related_name="employee_docs", null=True, blank=True) document = models.FileField( upload_to='Images/', default='Images/None/No-img.jpg') details = models.TextField() # url = models.URLField(null=True) # path_to_image = models.CharField(null=True, max_length=100) # upload_date = models.DateTimeField(auto_now=True, db_index=True) def __str__(self): return 'DOC - %s' % (self.employee.user.username) Then Views.py class EmployeeDocumentPOST(APIView): """ compress Document """ permission_class = [AllowAny] serializer_class = EmployeeDocumentSerializer def compressed_doc(self,document): document = lz4.frame.compress(document) return document def post(self, request, *args, **kwargs): compressd_doc = self.compressed_doc(document) employee = Employee.objects.get(id=request.data.pop('employee')) detail = request.data.get('detail') employee_doc = EmployeeDocument.objects.create(**request.data) employee_doc.compressed_doc = compressed_doc employee_doc.employee = employee employee_doc.detail = detail employee_doc.save() serializer = EmployeeDocument(employee_doc) return Response(serializer.data, status = status, status = status.HTTP_200_OK)
favorite count: 0
type: Question

http://stackoverflow.com/q/50110474
type: UnansweredQuestion
tagged with: vim
has answer: http://stackoverflow.com/a/69164151
type: Question
has comment: http://stackoverflow.com/comment/87238457
score: 3
tagged with: windows
answer count: 3
has body: I've started the Anaconda python distribution. This comes with something called 'Anaconda prompt' that has conda and git available at the Windows command line. When I make a commit from this command line, Vim comes up as the editor. When I type 'vim' or 'vi' at this prompt I get the message: 'vim' is not recognized as an internal or external command, operable program or batch file. How can I access vim from the Anaconda prompt?
has title: How can I access the vim installed with the anaconda prompt?
favorite count: 0
has answer: http://stackoverflow.com/a/50110608
upvote count: 3
has answer: http://stackoverflow.com/a/72019157
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/87299902
type: AnswerComment
has text: No, the interpreter should *not* evaluate that string as if it were inserted into the code stream. I certainly wouldn't want it to treat my true string data that way!
score: 0
comment on: http://stackoverflow.com/a/50140749
type: Comment

http://stackoverflow.com/comment/87442094
type: QuestionComment
has text: Did you possibly consider it's not the "python" part that takes so long, but possibly the way you were doing it? Clearly C++ isn't your bag so rather than "presuming" that was the way to improve things, you really should have approached us here asking how to improve the python code instead. Because C++ alone is not going to give you the performance boost you are looking for anyway.
comment on: http://stackoverflow.com/q/50212165
score: 0
type: Comment

http://stackoverflow.com/q/50120822
has title: Replace excel column values by values in another file
has body: I have a excel file with these columns: v1,v2,commID I have another file with columns: Index, Name Now I want to replace v1 and v2 with corresponding names by referring to second file and write it in a new file.The format is v1,v2,commID, but this time v1 and v2 should be names whereas commID should be the same numbers. I can do it in excel or python or matlab.
has answer: http://stackoverflow.com/a/50122791
tagged with: python
has comment: http://stackoverflow.com/comment/87260483
tagged with: matlab
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50122902
has answer: http://stackoverflow.com/a/50122902
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: excel
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50122791

http://stackoverflow.com/a/50187147
has comment: http://stackoverflow.com/comment/138148294
has comment: http://stackoverflow.com/comment/97875804
has comment: http://stackoverflow.com/comment/129051294
upvote count: 214
has comment: http://stackoverflow.com/comment/93286586
has comment: http://stackoverflow.com/comment/140258004
type: Answer
accepted answer of: http://stackoverflow.com/q/50186904
has comment: http://stackoverflow.com/comment/128952936
has comment: http://stackoverflow.com/comment/100531252
has comment: http://stackoverflow.com/comment/128331198
has comment: http://stackoverflow.com/comment/140256569
answers question: http://stackoverflow.com/q/50186904
downvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/133367104
score: 212
has body: As you already know, the only two Path methods for removing files/directories are .unlink() and .rmdir() and neither does what you want. Pathlib is a module that provides object oriented paths across different OS's, it isn't meant to have lots of diverse methods. The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them. The "uncommon" file system alterations, such as recursively removing a directory, is stored in different modules. If you want to recursively remove a directory, you should use the shutil module. (It works with Path instances too!) import shutil import pathlib import os # for checking results print(os.listdir()) # ["a_directory", "foo.py", ...] path = pathlib.Path("a_directory") shutil.rmtree(path) print(os.listdir()) # ["foo.py", ...]
has comment: http://stackoverflow.com/comment/138150051

http://stackoverflow.com/q/50083682
upvote count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/60632483
has title: ValidationError : [u'ManagementForm data is missing or has been tampered with'] on Django template page when I try to view my formset
has comment: http://stackoverflow.com/comment/87183304
has body: Django version 1.8.7 I'm creating a pages where the user has to add a list of invitees to his weeding so I needed to use the same form many times on the same page to create mnay model instances of the invitees; In order to do that I used model formsets using modelformset_factory function . So in my forms.py class InviteesForm(ModelForm): class Meta: model = Invitees fields = ['user', 'invitee_name' , 'invitee_address', 'invitee_count', 'invitee_email'] exclude = ('user',) #creating a formset InviteesFormSet = modelformset_factory(Invitees, form = InviteesForm ) Above you can see my model form for the invitees model and my InviteesFormSet which uses modelformser_factory fucntion. In my views.py def preview(request): formset = forms.InviteesFormSet(queryset=Invitees.objects.all()) if request.method == 'POST': formset = forms.InviteesFormSet(request.POST) if formset.is_valid(): formset.save(commit = False) return redirect('/invitees/') else: formset = forms.InviteesFormSet(request.POST) return render(request, 'preview.html', {'formset': formset} ) In my Preview.html {% csrf_token %} {{ formset.management_form }} Add an Invitee The formset is not rendering in my html, am not sure what I'm doing wrong here, it's basic code! but I get this error [u'ManagementForm data is missing or has been tampered with'] I tried the solution mentioned here by adding .management_form to the formset on template page : referred here https://docs.djangoproject.com/en/dev/topics/forms/formsets/#understanding-the-managementform Can you please help me figure out the issue? Thanks
tagged with: formset
tagged with: modelform
score: 1
answer count: 1
tagged with: django-models
favorite count: 0
linked to: http://stackoverflow.com/q/25331500
type: Question
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87218128

microphone
tag name: microphone
tags question: http://stackoverflow.com/q/50111287
type: Tag

decode
tag name: decode
tags question: http://stackoverflow.com/q/50159721
tags question: http://stackoverflow.com/q/50185419
type: Tag

http://stackoverflow.com/q/50205618
has comment: http://stackoverflow.com/comment/87428297
has title: elif for except ValueError
downvote count: 1
has comment: http://stackoverflow.com/comment/87428316
has comment: http://stackoverflow.com/comment/87602623
score: 1
has answer: http://stackoverflow.com/a/50205659
tagged with: input
tagged with: python
favorite count: 0
has body: Why does this code not work? No easy way to explain. def main(): while True: mon = input("What is the month? ( 1 - 12 )") try: mon = int(mon) except ValueError: print("Try again.") elif mon &gt; 0 and mon &lt; 13: break else: print("Try again.")
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/32115375
linked to: http://stackoverflow.com/q/23294658
upvote count: 2
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/50166144
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50166111
type: Answer
has body: enumerate will numerate iterable list , by default it starts from 0 If 1 is desired pass start=1 f = (['a', 'b', 7]) list(enumerate(f, start=1))

build
tag name: build
tags question: http://stackoverflow.com/q/50136514
type: Tag

http://stackoverflow.com/a/50202419
answers question: http://stackoverflow.com/q/50202224
has comment: http://stackoverflow.com/comment/87422990
has comment: http://stackoverflow.com/comment/87421692
has comment: http://stackoverflow.com/comment/87422051
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/87421950
type: Answer
has comment: http://stackoverflow.com/comment/87422019
has body: While you can use a named value (or what you might think of as a 'variable') to construct a dictionary: &gt;&gt;&gt; x=22 &gt;&gt;&gt; di={x:x} &gt;&gt;&gt; di {22: 22} You can also demonstrate that the value of the named value (if that value is immutable) is used at the time of construction and not dynamic: &gt;&gt;&gt; x=5 &gt;&gt;&gt; di {22: 22} The keys of a dict must be hashable (ie, unchanging; immutable) which would preclude the use of a list, set, or other named value that can change: &gt;&gt;&gt; changeable_list=[22] &gt;&gt;&gt; di={changeable_list:changeable_list} Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unhashable type: 'list' But the value of a dict can be dynamic and mutable: &gt;&gt;&gt; di={tuple(changeable_list):changeable_list} &gt;&gt;&gt; di {(22,): [22]} And that list can be modified: &gt;&gt;&gt; changeable_list.append(44) &gt;&gt;&gt; changeable_list [22, 44] &gt;&gt;&gt; di {(22,): [22, 44]} Notice how the value of the dict changes as the list changes because they are the same object.
upvote count: 1
has comment: http://stackoverflow.com/comment/87421820
has comment: http://stackoverflow.com/comment/87421589
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50202224
has comment: http://stackoverflow.com/comment/87423177

http://stackoverflow.com/a/50219864
has comment: http://stackoverflow.com/comment/87536339
answers question: http://stackoverflow.com/q/50219763
has comment: http://stackoverflow.com/comment/87456806
has comment: http://stackoverflow.com/comment/87536036
has comment: http://stackoverflow.com/comment/87456867
accepted answer of: http://stackoverflow.com/q/50219763
type: Answer
has comment: http://stackoverflow.com/comment/87456896
score: 4
upvote count: 4
has body: Here is a Pythonic approach using a generator expression : In [12]: from itertools import accumulate, chain In [13]: list(chain.from_iterable((i,) if i &lt; 5 else (next(j for j in range(i, 0, -1) if j%5 == 0), i) for i in accumulate(nums))) Out[13]: [1, 3, 5, 7, 10, 13] The logic is that you loop over the accumulated result and then for numbers greater than 5 you find the first number before it (using a reverse range and next function) that is a multiple of 5. Then concatenating the result using itertools.chain(). From an algorithmic perspective, instead of performing multiple loops over the list, one by accumulate and another once for finding the expected numbers, you can do this at one traverse as following: In [18]: def myaccumulate(lst): ...: total = 0 ...: for num in lst: ...: total += num ...: for i in range(total, num, -1): ...: if i%5 == 0: ...: yield i ...: break ...: yield total ...: Demo: In [19]: list(myaccumulate(nums)) Out[19]: [1, 3, 5, 7, 10, 13] This approach is actually faster than the generator-based one: In [20]: %timeit list(myaccumulate(nums)) 2.65 µs ± 47.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [21]: %timeit list(chain.from_iterable((i,) if i &lt; 5 else (next(j for j in range(i, 0, -1) if j%5 == 0), i) for i in accumulate(nums))) 4.12 µs ± 21.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87457185
downvote count: 0

http://stackoverflow.com/comment/87423180
score: 1
type: QuestionComment
type: Comment
has text: @MihaiAlexandru-Ionut `recall_score()` is function from `sklearn`. As the OP is doing a binary classification, just set `pos_label='neg'` in the call to `recall_score()`.
comment on: http://stackoverflow.com/q/50203106

http://stackoverflow.com/q/50121477
has answer: http://stackoverflow.com/a/72809583
has answer: http://stackoverflow.com/a/52021657
tagged with: python
has answer: http://stackoverflow.com/a/65559190
score: 19
has answer: http://stackoverflow.com/a/77168298
has answer: http://stackoverflow.com/a/77714391
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/50122617
has answer: http://stackoverflow.com/a/66829170
accepted answer: http://stackoverflow.com/a/50122617
has answer: http://stackoverflow.com/a/63566667
possible better answer: http://stackoverflow.com/a/63566667
has comment: http://stackoverflow.com/comment/94122348
downvote count: 0
has body: I am trying to use the nets from the official mnist directory of tensorflows model repository. On my windows system I receive this error: C:\Users\ry\Desktop\NNTesting\models\official\mnist&gt;mnist_test.py Traceback (most recent call last): File "C:\Users\ry\Desktop\NNTesting\models\official\mnist\mnist_test.py",line 24, in &lt;module&gt; from official.mnist import mnist ModuleNotFoundError: No module named 'official' I have followed their official directions and set my python path using set PYTHONPATH="PYTHONPATH:"%cd%" and can confirm that PYTHONPATH="$PYTHONPATH:C:\Users\ry\Desktop\NNTesting\models" and I have also installed the dependencies successfully. Does anyone have experience using these models on a windows system and can help me with this pathing issue? I'm not sure what I have done incorrectly here. Thanks
has title: Tensorflow no module named official
has answer: http://stackoverflow.com/a/53640319
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53120853
answer count: 12
has answer: http://stackoverflow.com/a/60149893
has answer: http://stackoverflow.com/a/55115000

http://stackoverflow.com/a/50132258
has body: The shape of constant x is (2,), i.e. a one-dimensional array, and you are trying to multiply it with a two-dimensional array w1 of shape (2, 3), which is not possible for matrix multiplication, as number of columns of first parameter must be equal to number of rows in second parameter. Also, I think tf.matmul only works if both arrays are two-dimensional. One of the many ways you can change your declaration of x as x = tf.constant([[0.7], [0.9]]) This will create a two-dimensional constant tensor of shape (2, 1). And, then multiply it as, a = tf.matmul(tf.transpose(x), w1) tf.transpose() is used to create transpose of array x with shape (2, 1) to shape (1, 2). Hope this helps.
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/102979601
type: Answer
answers question: http://stackoverflow.com/q/50130413
upvote count: 6

http://stackoverflow.com/a/50205659
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87428860
downvote count: 1
has comment: http://stackoverflow.com/comment/87428876
has comment: http://stackoverflow.com/comment/87428977
type: Answer
has body: There are a few changes you should make to your code for it to work. You should use else as part of a try / except / else structure. Also use continue to signify explicitly where a loop will continue. Your code is invalid as an if / else clause cannot start with elif. Here is a working example: def main(): while True: mon = input("What is the month? ( 1 - 12 )") try: mon = int(mon) except ValueError: print("Try again.") continue if mon &gt; 0 and mon &lt; 13: break else: print("Try again.") return mon
answers question: http://stackoverflow.com/q/50205618
has comment: http://stackoverflow.com/comment/87428960

http://stackoverflow.com/comment/87569777
type: Comment
type: QuestionComment
has text: Per latest edit, not that it will make a difference, but you should not have ``/usr/local/pulseenv/lib/python3.5/site-packages`` in ``python-path``. See http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html
comment on: http://stackoverflow.com/q/50206007
score: 0

http://stackoverflow.com/comment/87331502
type: Comment
type: AnswerComment
score: 1
has text: Thanks, that really helped. I was looking at the {}, rather than what was inside them. While it's worked for all the other keys, '3h' doesn't appear to actually be the key: File "weather.py", line 63, in <module> rain = (rain["3h"]) KeyError: '3h' But thanks for getting me on the right track.
comment on: http://stackoverflow.com/a/50155692

http://stackoverflow.com/comment/87386707
type: QuestionComment
score: 2
has text: This feature is (controversially) [planned for Python 3.8](https://www.python.org/dev/peps/pep-0572/)
type: Comment
comment on: http://stackoverflow.com/q/50184706

http://stackoverflow.com/comment/87329649
has text: @MikeMcNeil See @Alex Hall's answer, that will go through each directory and create the sub-directories you've indicated in your list. You also should also be aware that `os.chdir(root_dir)` should throw an error, as `root_dir` is a list.
type: Comment
comment on: http://stackoverflow.com/a/50143313
score: 0
type: AnswerComment

dill
tags question: http://stackoverflow.com/q/50213578
tag name: dill
type: Tag

http://stackoverflow.com/a/50154031
type: Answer
answers question: http://stackoverflow.com/q/50153832
score: 0
has body: It looks like it can be won by Docs: setrecursionlimit(). But remember, that recursion is not free - it consumes memory_of_function_consumes * amount_of_circles_of_recursion - so you can run out of memory when you have a huge amount of recursion runs. Thats why that limit is hardcoded in Python, and I think it is bad idea to overwrite it.

http://stackoverflow.com/q/50155689
has answer: http://stackoverflow.com/a/50155863
type: UnansweredQuestion
has title: 'builtin_function_or_method' object is not subscriptable." 5
has comment: http://stackoverflow.com/comment/87328962
tagged with: python
score: 0
has body: Trying to make a code about usernames: User=input("type a username with 4 numbers, then 2 letters.") test=(User.isdigit[0:3]) trial=(User.isaplha[4:5]) if test ==True: if trial ==True: print("This is a valid username.") else: print("The last two characters must be numbers.") else: print("The first four characters must be letters.") I receive this error Traceback (most recent call last): File "python", line 2, in TypeError: 'builtin_function_or_method' object is not subscriptable
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87273750
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50127618
score: 0
has text: @chrisz thanks for the link. While the top answer is enlightening, my question is why the caret shifts the way it does, which isn't explained in that link (or at least, I don't see it).

http://stackoverflow.com/a/50139331
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50139189
has body: +, -, etc... are binary operators. &gt;&gt;&gt; tree=ast.parse('a+b+c') &gt;&gt;&gt; astpretty.pprint(tree) Module( body=[ Expr( lineno=1, col_offset=0, value=BinOp( lineno=1, col_offset=3, left=BinOp( lineno=1, col_offset=0, left=Name(lineno=1, col_offset=0, id='a', ctx=Load()), op=Add(), right=Name(lineno=1, col_offset=2, id='b', ctx=Load()), ), op=Add(), right=Name(lineno=1, col_offset=4, id='c', ctx=Load()), ), ), ], ) So, no, there is no way to override those operators to get what you want. Go with the static method.

http://stackoverflow.com/comment/87365527
has text: James: the implementation will be on an FPGA so im looking for an algorithm. Kefeng91: I want the argument
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50174228

http://stackoverflow.com/comment/87359727
comment on: http://stackoverflow.com/a/50170453
score: 0
has text: My apologies: "Traceback (most recent call last): File "C:\Users\MICHAEL\Desktop\Project Y\Test.py", line 25, in <module> response = requests.get(quote_pageverify=False, headers= {'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'}) TypeError: get() missing 1 required positional argument: 'url'"
type: Comment
type: AnswerComment

identifier
tag name: identifier
type: Tag
tags question: http://stackoverflow.com/q/50154201

facet-wrap
tag name: facet-wrap
type: Tag
tags question: http://stackoverflow.com/q/50086651
tags question: http://stackoverflow.com/q/50164001

http://stackoverflow.com/comment/87247764
has text: That was my initial plan but I have 5 document types so I had to repeat the document in documents part 5 times which is not very DRY.
type: Comment
comment on: http://stackoverflow.com/q/50115125
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87217655
comment on: http://stackoverflow.com/a/50092095
type: Comment
score: 0
type: AnswerComment
has text: `yourfunction` has as its core loop: `while listofrouterids: thisrouterid = listofrouterids.pop()`. Then there are embedded functions inside that loop: `d = acquiredata(thisrouterid)` & `result = processdata(d)`

http://stackoverflow.com/q/50154835
possible better answer: http://stackoverflow.com/a/50154890
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50154890
answer count: 2
downvote count: 0
has title: Drop duplicates, but ignore nulls
favorite count: 0
accepted answer: http://stackoverflow.com/a/50154887
has answer: http://stackoverflow.com/a/50154887
type: Question
has body: So I know you can use something like this to drop duplicate lines: the_data.drop_duplicates(subset=['the_key']) However, if the_key is null for some values, like below: the_key C D 1 NaN * * 2 NaN * 3 111 * * 4 111 It will keep the ones marked in the C column. Is it possible to get drop_duplicates to treat all nan as distinct and get an output keeping the data like in the D column?
tagged with: python
upvote count: 10
score: 10

http://stackoverflow.com/q/50202762
has answer: http://stackoverflow.com/a/50242727
has answer: http://stackoverflow.com/a/50358334
downvote count: 1
tagged with: unit-testing
has body: Is it possible to implement a Python project with a file structure like the following?: myproj ├── a.py ├── b.py ├── c.py └── test/ ├── a.py ├── b.py └── c.py Note, in particular, that the test scripts under test/ have the same basenames as the module files they are testing &nbsp;1. (In other words, test/a.py contains the unit tests for a.py; test/b.py contains those for b.py, etc.) The tests under test/ all import unittest and define subclasses of unittest.TestCase. I want to know how to run the tests under test/, both individually, and all together. I've tried many variations of python -m unittest ..., but they all either fail (examples below), or end up running zero tests. For example, % python -m unittest test.a Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/lib/python2.7/unittest/__main__.py", line 12, in &lt;module&gt; main(module=None) File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs self.createTests() File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests self.module) File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName parent, obj = obj, getattr(obj, part) AttributeError: 'module' object has no attribute 'a' If I change the name of the test/ directory to t/, then the error becomes: % python -m unittest t.a Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/lib/python2.7/unittest/__main__.py", line 12, in &lt;mod…
favorite count: 0
type: Question
answer count: 8
tagged with: testing
has comment: http://stackoverflow.com/comment/87719330
has title: How to run unitests of the form test/a.py?
upvote count: 9
has comment: http://stackoverflow.com/comment/87422346
has comment: http://stackoverflow.com/comment/87422290
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87719185
tagged with: project
has comment: http://stackoverflow.com/comment/87422576
has answer: http://stackoverflow.com/a/50313302
tagged with: python
has answer: http://stackoverflow.com/a/50311323
has answer: http://stackoverflow.com/a/50207976
has comment: http://stackoverflow.com/comment/87424115
score: 8
has answer: http://stackoverflow.com/a/50322414
has answer: http://stackoverflow.com/a/50253786
has comment: http://stackoverflow.com/comment/87706892
has answer: http://stackoverflow.com/a/50250868
has comment: http://stackoverflow.com/comment/87422403
has comment: http://stackoverflow.com/comment/87422255

http://stackoverflow.com/a/50117720
score: 7
upvote count: 7
has body: If you can edit your click command functions, you can organize them like this: @cli.command() @click.argument('some_argument', type=str) @click.pass_context def say_something(ctx, some_argument): return _say_something(ctx, some_argument): def _say_something(ctx, some_argument): print(some_argument) If built like this, then you can call _say_something() function as an undecorated (normal) Python function. If you can not edit your commands Building on this answer you can pass the context to another click command using this function: Code: def call_click_command_with_ctx(cmd, ctx, *args, **kwargs): """ Wrapper to call a click command with a Context object :param cmd: click cli command function to call :param ctx: click context :param args: arguments to pass to the function :param kwargs: keyword arguments to pass to the function :return: None """ # monkey patch make_context def make_context(*some_args, **some_kwargs): child_ctx = click.Context(cmd, parent=ctx) with child_ctx.scope(cleanup=False): cmd.parse_args(child_ctx, list(args)) return child_ctx cmd.make_context = make_context prev_make_context = cmd.make_context # call the command call_click_command(cmd, *args, **kwargs) # restore make_context cmd.make_context = prev_make_context How does this work? This works because click is a well designed OO framework. The @click.Command object can be introspected to determine what parameters it is expecting. Then a command line can be constructed that will look like the command line that click is expecting. In addition, the make_context method of the command can be overridden to allow the command context to used by the command. Code from Previous Answer: def call_click_command(cmd, *args, **kwargs): """ Wrapper to call a click command :param cmd: click cli command function to call :param args: arguments to pass to the function :param kwargs: keywrod arguments to pass to the function :return: None """ # Get positional arguments from args arg_values = {c.name: a for a, c in zi…
has comment: http://stackoverflow.com/comment/87280184
type: Answer
answers question: http://stackoverflow.com/q/50077553
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50077553

http://stackoverflow.com/comment/87444999
type: QuestionComment
has text: What is `-` suppose to mean? I figure `+` means _more than one_.
comment on: http://stackoverflow.com/q/50214026
score: 0
type: Comment

http://stackoverflow.com/q/50219994
has title: Numpy fromfile reading after EOF
tagged with: python
type: Question
tagged with: numpy
tagged with: python-3.x
tagged with: numpy-ndarray
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87460179
has comment: http://stackoverflow.com/comment/87463475
has comment: http://stackoverflow.com/comment/87464413
has body: All, have some float values stored in a binary file and am reading them back. Windows 10, x64, Anaconda 5.1, Python 3.6, Numpy 0.14.1. File is open with 'rb' flag. Reading with 'np.fromfile' works fine except when I tried to read beyond the file. I have piece of code which checks if file is at EOF try: _ = struct.unpack('f', f.read(4))[0] # if successfull, means we did something wrong, should be an exception thrown raise RuntimeError("There is something wrong with KDD file, it's TOO LONG!") except struct.error as ex: # got and exception, file is ok, return good values pass which basically check that I read everything from file. Works very well. Today I played with it and thought that I could remove dependency on struct and just replace line _ = struct.unpack('f', f.read(4))[0] with _ = np.fromfile(f, dtype=np.float32, count=1, sep="") , supposed to get different exception and handle it in the same way, ... But! No exception was raised, none, and I got my own RuntimeError. Is it a bug? How in general I suppose to know if I read beyond EOF?
has comment: http://stackoverflow.com/comment/87463029
score: 0
has comment: http://stackoverflow.com/comment/87464174

http://stackoverflow.com/comment/87322026
type: Comment
comment on: http://stackoverflow.com/a/50151864
type: AnswerComment
score: 0
has text: @Chris_Rands: `(a.append, a.extend)[key.endswith('list')](val)` :p

http://stackoverflow.com/comment/87324537
type: Comment
has text: I think this does what you want: `ref_dst, ref_src = [[sorted(x)[y] for x in u] for y in [0, 1]]`
type: AnswerComment
comment on: http://stackoverflow.com/a/50153115
score: 0

http://stackoverflow.com/comment/87427222
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50204679
type: QuestionComment
has text: Hi, welcome to Stack Overflow, thanks for taking your time in exploring solutions to your problem, which will surely make your problem more easy to tackle, making it more likely for you to recieve a good answer in little time. I don't know anything about python-pptx, but I think it would also be useful to include the error message you got when you tried the solution you linked.

http://stackoverflow.com/comment/124671238
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50097779
type: AnswerComment
has text: Using numpy *then* Python built-in `sum` isn't' that efficient.

http://stackoverflow.com/comment/87478370
type: QuestionComment
comment on: http://stackoverflow.com/q/50215761
has text: Thanks all for your effort. I am creating user while signup but i am not creating userprofile. Now i am able to get user.userprofiles for all users
score: 1
type: Comment

http://stackoverflow.com/q/50134178
has title: Partial match to regex?
tagged with: python
tagged with: regex
has body: I have several lines that look like this: test=['S123X_ILL_BE_BACK','BA34_HASTA_LA_VISTA_BABY','JA3841_SARAH','J102_CONNOR'] And I am trying to retrieve all that comes after the first \_. In my regex I am trying import re [re.sub(".+\_(.+)","\g&lt;1&gt;",gg) for gg in test] but this truncates to the last word. How can I get ['ILL_BE_BACK','HASTA_LA_VISTA_BABY','SARAH','CONNOR']
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50134398
has answer: http://stackoverflow.com/a/50134199
accepted answer: http://stackoverflow.com/a/50134199
type: Question
has comment: http://stackoverflow.com/comment/87286344
has answer: http://stackoverflow.com/a/50134340
possible better answer: http://stackoverflow.com/a/50134340

http://stackoverflow.com/comment/106490491
score: 1
has text: This is addressed in the [latest OpenCV documentation](https://docs.opencv.org/trunk/d5/dae/tutorial_aruco_detection.html) (section "Selecting a dictionary"). It basically confirms your thoughts.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50076117

http://stackoverflow.com/comment/87229748
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50093717
has text: I'm not sure that I understand what functionality you're trying to implement. Can you provide some references or maybe detailed explanation/examples?

http://stackoverflow.com/comment/87448241
score: 1
type: Comment
type: QuestionComment
has text: @geisterfurz007 moved to answers.
comment on: http://stackoverflow.com/q/50204825

http://stackoverflow.com/a/50236454
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50226193
has body: If A is identical to B and B is identical to C, I think you want B and C to to be removed and A to be kept. Now, what you can do is the following: for A in `ls`; do -e $A || continue; mkdir identical for B in `ls`; do [ "$A" != "$B" ] &amp;&amp; comparestructures "$A" "$B" &amp;&amp; mv "$B" identical done rm -r identical done This is clearly not the best and fastest solution but I am too tired to imagine a better one. If you want to test this script, I'd suggest that you put the mkdir identical expression outside the loop and remove the rm -r identical line, then just see if there are no problems with it.
type: Answer
accepted answer of: http://stackoverflow.com/q/50226193
score: 1

http://stackoverflow.com/q/50114827
has body: Is there any way to label individual bars using matplotlib? The best case would be vertical labelling under each bar to avoid overlaps For example the red bar should have the x-label as red, the green one as green and the blue one as blue. The main group 'A, B, C, D' remains as it is. Also, is there any way to produce the legend of the different colors? Following my code: fig = plt.figure() ax = fig.add_subplot(111) n_groups = 4 bar_width = 0.1 opacity = 0.4 index = np.arange(0, 2*n_groups, 2) data = [1,2,3,4] data2 = [5,6,7,8] chart = plt.bar(index, data, bar_width, color='blue', edgecolor='black') chart = plt.bar(index+bar_width, data2, bar_width, color='red', edgecolor='black') chart = plt.bar(index+2*bar_width, data, bar_width, color='green', edgecolor='black') ax.set_xlabel('y_axis') ax.set_ylabel('x_axis') ax.set_title('Title') plt.xticks(index+bar_width*0.5, ('A', 'B', 'C', 'D')) plt.legend() plt.tight_layout() plt.show() and the output is:
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50115240
tagged with: python
score: 0
upvote count: 1
tagged with: matplotlib
has title: matplotlib bar chart with individual labels for each bar and a group label
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50119503
type: Question
upvote count: 2
tagged with: scripting
tagged with: python
has title: Maya: Python: How to open arnoldRenderView in the script editor
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50241579
has body: I am stuck on the Arnold's Python command list. For this current exercise, I need to make a light-painter (e.g. https://evermotion.org/articles/show/8837/light-painter-1-0) in Maya. I need to make it so that the ArnoldRenderView opens up automatically. I have been searching for this quite a while now. All I have been able to find is this: "from mtoa.cmds.arnoldRenderView import arnoldRenderView". Where can I find what flags I can use to make the ArnoldRenderView open up (by a button click)? Or is there a more simple way to open up the ArnoldRenderView without accessing the "mtoa.cmds.arnoldRenderView"? With Kind Regards, Rik. EDIT: I have found two helpfull links with scripting in maya (Python) for arnold: https://arnoldsupport.com/2015/03/04/arnold-getting-started-with-the-arnold-python-api/ and https://trac.solidangle.com/arnoldpedia/chrome/site/Arnold-4.1.3.3/doc/api/index.html
has answer: http://stackoverflow.com/a/50241579
has comment: http://stackoverflow.com/comment/87302465
score: 1
answer count: 1
tagged with: maya
has comment: http://stackoverflow.com/comment/87278119
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50144717
type: UnansweredQuestion
tagged with: python
has body: I'm sure this question has been asked (probably in much more eloquent ways), but I can't find an answer, thus I apologize if this is a duplicate. I am trying to iterate through a list and add each element that is not a number into another list. However, each time a number is encountered in the original list, I want a new list to be created within the secondary list. For example, if 'a3buysi8byjs' is the input, the output would be: [[a], [b,u,y,s,i], [b,y,j,s]]. I have tried several things, and decided to simplify my code and start from scratch, which led to the following: for e in S_li: #going through initial list, all elements available if e.isdigit() != True: # if it is an integer, create another list within poss poss.extend(e) #if it is a letter add to the same list in poss. *I also left my comments, because maybe that will help clarify my intent. Thanks in advance!
has answer: http://stackoverflow.com/a/50144913
tagged with: list
has title: Creating a list from elements in another list, while dividing the elements into subsequent lists in python
score: 0
type: Question
has answer: http://stackoverflow.com/a/50144841
answer count: 2

http://stackoverflow.com/comment/87364510
type: Comment
score: 0
type: AnswerComment
has text: Sorry to bother you again. I found that images with a file name similar to `'FINAL 77718_02.jpeg'` are not being matched. I suppose that is because of the `(?!\d)` negative lookahead?
comment on: http://stackoverflow.com/a/50173121

http://stackoverflow.com/q/50145982
has title: Grouping DataFrame by start of decade using pandas Grouper
upvote count: 7
has answer: http://stackoverflow.com/a/50146087
has answer: http://stackoverflow.com/a/50146350
favorite count: 0
type: Question
has body: I have a dataframe of daily observations from 01-01-1973 to 12-31-2014. Have been using Pandas Grouper and everything has worked fine for each frequency until now: I want to group them by decade 70s, 80s, 90s, etc. I tried to do it as import pandas as pd df.groupby(pd.Grouper(freq = '10Y')).mean() However, this groups them in 73-83, 83-93, etc.
tagged with: pandas
tagged with: group-by
score: 7
possible better answer: http://stackoverflow.com/a/50146350
tagged with: python
accepted answer: http://stackoverflow.com/a/50146095
has answer: http://stackoverflow.com/a/50146378
answer count: 4
has answer: http://stackoverflow.com/a/50146095
type: AnsweredQuestion
tagged with: pandas-groupby
downvote count: 0

http://stackoverflow.com/comment/87365395
type: QuestionComment
comment on: http://stackoverflow.com/q/50174228
score: 0
has text: For speed, you could use `parabola.max()`, but the iteration is hidden
type: Comment

http://stackoverflow.com/a/50179022
has body: One way is to restructure your dictionary and flatten using itertools.chain. For performance, you should benchmark with your data. from itertools import chain res = list(chain.from_iterable(i['_source']['TYPES'] for i in d['hits']['hits'])) df = pd.DataFrame(res) print(df) _ID _NM 0 130 ARB-130 1 131 ARB-131 2 132 ARB-132 3 902 ARB-902 4 903 ARB-903 5 904 ARB-904
has comment: http://stackoverflow.com/comment/87375744
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50178925
downvote count: 0

http://stackoverflow.com/q/50113938
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50114382
tagged with: python
type: UnansweredQuestion
has body: with tf.Session() as sess: t1 = [ [[0],[1],[2]], [[3],[4],[5]], ] print(sess.run(tf.shape(t1))) print(sess.run(tf.concat(t1,1))) print("**********") t2 = np.arange(6).reshape([2,3,1]) print(sess.run(tf.shape(t2))) print(sess.run(tf.concat(t2,1))) then it shows [2 3 1] [[0 3] [1 4] [2 5]] [2 3 1] [[[0] [1] [2]] [[3] [4] [5]]] t1 and t2 have the same shape and value, why the result is different?
downvote count: 0
score: 1
upvote count: 1
has title: Tensorflow-tf.concat() shows different results
tagged with: tensorflow
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50114095

http://stackoverflow.com/a/50189230
has body: According to the Safe Browsing API documentation, if you receive an empty object is because there was no match found: Note: If there are no matches (that is, if none of the URLs specified in the request are found on any of the lists specified in a request), the HTTP POST response simply returns an empty object in the response body.
answers question: http://stackoverflow.com/q/50188251
downvote count: 0
type: Answer
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50188251
upvote count: 1

http://stackoverflow.com/a/74142458
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50140371
upvote count: 1
downvote count: 1
has body: I'm sure that there is an analytical solution but I just pulled an all night coding a solution to this problem with a genetic algorithm. I'm not familiar with genetic algorithms, so I sort of just based it off intuition - accordingly, I think this code manages to sit in the intersection of both being moderately intelligent work, and profoundly dumb lmfao. I'll put push it to GitHub if anyone might find it useful. Pic related - converging on decent distribution fit. Given mode and upper and lower 95% confidence interval bounds.
has comment: http://stackoverflow.com/comment/130946415

http://stackoverflow.com/comment/87316926
type: QuestionComment
comment on: http://stackoverflow.com/q/50148148
has text: I took the liberty to edit your question a little, since it turned up in the "Help and Improvement" queue. However, since your question is a debugging question, it is lacking some important information. Can you tell us what you expect to happen and what actually happens? That would make your question a easier to understand and hence easier to answer.
score: 1
type: Comment

http://stackoverflow.com/comment/87411942
type: QuestionComment
comment on: http://stackoverflow.com/q/50195864
score: 0
type: Comment
has text: @coldspeed - though i do believe this is sort of same concept, the scenario is very different and might be helpful for some one new to Python.

http://stackoverflow.com/comment/87307813
type: QuestionComment
has text: One thing to keep in mind: I frequently have, say, an emacs window both foregrounded and focused, and a browser window that's in the background, but not blocked by anything, and still responding to trackpad swipes. If that's not a problem you're worried about, and you're happy reporting that only emacs is "active" at the moment, your life is a lot easier.
comment on: http://stackoverflow.com/q/50144762
score: 0
type: Comment

http://stackoverflow.com/q/50147156
score: 1
upvote count: 1
has title: Pygame doesn't change font
tagged with: pygame
has comment: http://stackoverflow.com/comment/87469553
has body: I'm trying to change the font that's being used on my Pygame project. So I've tried to use system fonts, like this: pygame.font.SysFont('arial', 24) Nothing changed. Pygame still using the default ugly font. I tried to run pygame.font.get_fonts() but the result is [None] on my Mac. So I tried to use a custom font, like this: font_small = pygame.font.Font('fonts/Roboto-Regular.ttf', 24) Nothing changes. Still the same font and there's no Exception saying that it wasn't able to open the file. I've tried even to use os.path.abspath() to get the full path, with no success. Any sugestion? UPDATE I created this gist to test all possibilities. I had success rendering a font from a ttf file. The solution were to change the second parameter antialias from False to True. But I still don't understand why I'm not being able to use my System Fonts.
has comment: http://stackoverflow.com/comment/87575553
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50155504
tagged with: fonts
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87326265
answer count: 1
tagged with: python
downvote count: 0

http://stackoverflow.com/comment/87359022
type: Comment
type: QuestionComment
has text: But if you look at the bottom of my post, you can see that `form.cleaned_data` doesn't contain the data I need. I only accessed `form.fields` and `form.data` because I was curious what's there, and where do the answers get lost, as I could see them in the `request.POST`.
comment on: http://stackoverflow.com/q/50170649
score: 0

http://stackoverflow.com/q/50222697
has comment: http://stackoverflow.com/comment/87465012
type: AnsweredQuestion
tagged with: mapping
answer count: 2
has answer: http://stackoverflow.com/a/75486154
tagged with: python
upvote count: 2
has body: Let us consider a grayscale value with values in the range of [0, 255]. How can we efficiently map each value to a RGB value? So far, I have come up with the following implementation: # function for colorizing a label image: def label_img_to_color(img): label_to_color = { 0: [128, 64,128], 1: [244, 35,232], 2: [ 70, 70, 70], 3: [102,102,156], 4: [190,153,153], 5: [153,153,153], 6: [250,170, 30], 7: [220,220, 0], 8: [107,142, 35], 9: [152,251,152], 10: [ 70,130,180], 11: [220, 20, 60], 12: [255, 0, 0], 13: [ 0, 0,142], 14: [ 0, 0, 70], 15: [ 0, 60,100], 16: [ 0, 80,100], 17: [ 0, 0,230], 18: [119, 11, 32], 19: [81, 0, 81] } img_height, img_width = img.shape img_color = np.zeros((img_height, img_width, 3)) for row in range(img_height): for col in range(img_width): label = img[row, col] img_color[row, col] = np.array(label_to_color[label]) return img_color However, as you can see it is not efficient as there are two "for" loops. This question was also asked in Convert grayscale value to RGB representation?, but no efficient implementation was suggested.
tagged with: grayscale
accepted answer: http://stackoverflow.com/a/50222888
has comment: http://stackoverflow.com/comment/87504457
has answer: http://stackoverflow.com/a/50222888
has title: map grayscale values to RGB values in image
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/75486154
linked to: http://stackoverflow.com/q/835753
score: 1
has comment: http://stackoverflow.com/comment/88254007
tagged with: rgb
tagged with: image

http://stackoverflow.com/comment/87416006
score: 0
comment on: http://stackoverflow.com/q/50199606
has text: @mhawke yes i just tried that and i did receive the same exception
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50186897
answer count: 1
type: Question
has title: Not defined method
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/1286235
score: 0
has answer: http://stackoverflow.com/a/50186910
duplicate of: http://stackoverflow.com/q/1286235
has comment: http://stackoverflow.com/comment/87390501
has body: below is my code (all the methods are indented in original), after running that code I get this error: NameError: global name 'checkDate' is not defined the method are defined so i don't know whats the issue here (the code was in Java and work well there I just did the modification for this to work in python) class Date: def __init__(self, *args): if len(args) == 3: self._day, self._month, self._year = args elif len(args) == 1: self._day = args[0]._day self._month = args[0]._month self._year = args[0]._year else: raise TypeError("wrong number of arguments to Date constructor") # methods # checkDate - Check if the date is valid def checkDate (self, day, month, year): if year &gt; 0 and month &gt; 0 and month &lt; 13 and day &gt; 0 and day &lt; 32: if month == 1 or 3 or 5 or 7 or 8 or 10 or 12: return True if month == 4 or 6 or 9 or 11: if day == 31: return False return True if month == 2: if (month % 4 == 0 and (month % 100 != 0 or (month % 100 == 0 and month % 400 == 0))): if day &gt; 28: return False elif day &gt; 27: return False return False # calculateDate - Computes the day number since the beginning of the Christian counting of years. def calculateDate (self, day, month, year): if month &lt; 3: year -= 1 month = month + 12 return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62); # getDay - Return the day def getDay(self): return self._day # getMonth - Return the month def getMonth(self): return self._month # getYear - Return the year def getYear(self): return self._year # setDay - Sets the day (only if date remains valid) def setDay(self, dayToSet): if checkDate(dayToSet,_month,_year): _day = dayToSet # setMonth - Sets the month (only if date remains valid) def setMonth (self, monthToSet): if checkDate(_day,monthToSet,_year): _month = monthToSet # setYear - sets the year (only if date remains valid) def setYear(self, yearToSet): if checkDate(_day,_month,yearToSet): _year = yearToSet def main(): birthDate = Date(1,1,2000) print(birt…
has comment: http://stackoverflow.com/comment/87390477

http://stackoverflow.com/a/50107612
score: 2
answers question: http://stackoverflow.com/q/50107313
type: Answer
has body: I am assuming you are working with MNIST, or a dataset similar to this with a set of 28 x 28 images. Perhaps these images are presented in an array of length 784. x = [] for _ in range(10): x.append(range(28 ** 2)) np.array(x).reshape([-1, 28, 28, 1]) This will convert your dataset into a set of 28 x 28 x 1 matrices, which would be useful if you're trying to learn on an image that is 28 x 28 and only has a single color. it will also determine that you have 10 images, and convert your array to 10 matrices with shape 28 x 28 x 1. np.array(x).reshape([-1, 28, 28, 1]).shape == (10, 28, 28, 1) The reason it's 28 x 28 x 1 instead of 28 x 28 is sometimes this is a cleaner way to interpret that there are 28 x 28 squares and a single color. It's not necessary to add the single dimensional width if it's confusing you, you could just as easily map it to a matrix with shape 28 x 28. But imagine you had a dataset of colored images, you'd probably map it to 28 x 28 x 3 to indicate that it's an image with 28 x 28 squares, and each square has a value for each of the three colors. Therefore, it's a set of -1 images, where -1 means calculate the correct number of images (10), and each image has 28 * 28 values, and give each value it's own dimension (1).
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87465449
type: QuestionComment
has text: Maybe you are using an older version of `pattern` that tries to access twitter without `https`? https://github.com/clips/pattern/issues/68
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50223686

http://stackoverflow.com/a/50140622
answers question: http://stackoverflow.com/q/50140450
has comment: http://stackoverflow.com/comment/87444781
has comment: http://stackoverflow.com/comment/87301639
has comment: http://stackoverflow.com/comment/87339106
has comment: http://stackoverflow.com/comment/87394732
has comment: http://stackoverflow.com/comment/87302806
has comment: http://stackoverflow.com/comment/87340299
has comment: http://stackoverflow.com/comment/87304291
has comment: http://stackoverflow.com/comment/87303944
has body: Seems like you have not to run quickstart.py, but create there some function, import your from quickstart import your_function into your views.py and call that your_function from your_custom_view. Simplified logic like that: from quickstart import your_function def your_custom_view(request): button_was_pressed = request.GET.get("button") if button_was_pressed: your_function() return HttpResponse("Button pressed") else: return HttpResponse("No button pressed") And make your Button work like a link (if you dont need a POST request), smth like: Button NOTE: This is not working code, but simplified logic, with so short information that you gave. UPDATE 1: settings.py: BASE_DIR = os.path.dirname(os.path.abspath(__file__)) views.py: from your_project.settings import BASE_DIR path_to_json = os.path.join(BASE_DIR, r'client_secret.json') flow = client.flow_from_clientsecrets(path_to_json, SCOPES)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87302910
has comment: http://stackoverflow.com/comment/87301191
has comment: http://stackoverflow.com/comment/87444980
has comment: http://stackoverflow.com/comment/87337031

http://stackoverflow.com/a/51089943
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50204595
answers question: http://stackoverflow.com/q/50204595
has body: Consider using Firebase instead. You also have the address to your VM, but you'll have to run the python script in an appropriate WSGI server - exactly how you do that depends on what framework your code is using. For testing you can probably ssh into the server and run the script as you'd do locally.
score: 0
type: Answer

multiprocessing
tags question: http://stackoverflow.com/q/50221512
tags question: http://stackoverflow.com/q/50157700
tags question: http://stackoverflow.com/q/50083498
tags question: http://stackoverflow.com/q/50162249
tags question: http://stackoverflow.com/q/50215033
tags question: http://stackoverflow.com/q/50091695
tags question: http://stackoverflow.com/q/50172934
tags question: http://stackoverflow.com/q/50123027
tags question: http://stackoverflow.com/q/50135922
tags question: http://stackoverflow.com/q/50178900
tags question: http://stackoverflow.com/q/50180414
tags question: http://stackoverflow.com/q/50091779
tags question: http://stackoverflow.com/q/50214502
tags question: http://stackoverflow.com/q/50175869
tags question: http://stackoverflow.com/q/50163530
tags question: http://stackoverflow.com/q/50151486
tags question: http://stackoverflow.com/q/50084557
tags question: http://stackoverflow.com/q/50170109
tags question: http://stackoverflow.com/q/50118036
tags question: http://stackoverflow.com/q/50179792
tags question: http://stackoverflow.com/q/50120110
tags question: http://stackoverflow.com/q/50136799
tags question: http://stackoverflow.com/q/50177644
tags question: http://stackoverflow.com/q/50079165
type: Tag
tags question: http://stackoverflow.com/q/50210921
tags question: http://stackoverflow.com/q/50118941
tags question: http://stackoverflow.com/q/50154204
tags question: http://stackoverflow.com/q/50131489
tag name: multiprocessing

http://stackoverflow.com/a/50225655
answers question: http://stackoverflow.com/q/50225549
upvote count: 2
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87468711
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50225549
has body: Its good to know that you should use %s for strings %d(decimal) for numbers, you can read this Link for getting better information about these two. but in your cases: Case1: the usercount=(6) lines just returns an Integer value and its true way to use %d. Case2: the usercount=(6) lines just returns an Integer value and its can be casted to string and printed so you can use%s for that too. Case3: the usercount=(6,) lines just returns a Tuple value and its can be casted to string and printed so you can use%s for that too. Case4: the usercount=(6,) lines just returns a Tuple value and in this case you can not cast a tuple to an Integer so you cant use %d for that.

http://stackoverflow.com/q/50178576
downvote count: 1
has comment: http://stackoverflow.com/comment/87374732
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1665511
duplicate of: http://stackoverflow.com/q/20449427
tagged with: python
accepted answer: http://stackoverflow.com/a/50178614
has answer: http://stackoverflow.com/a/50178614
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87378953
has body: I'm trying to complete a school project where I create a maths quiz that randomly generates questions. You have to login with a name and classroom your in. All my code works apart from the section of code where I am trying to use a range for my class (Between class 1 and 3). It keeps popping up with an error saying: TypeError: '&lt;=' not supported between instances of 'int' and 'str' while True: classCode=input("What class are you in? 1, 2, or 3? ") if 1 &lt;= classCode &lt;= 3: break else: print("That isn't a class. Please try again.") continue Anyone know whats wrong with this code? This is my first question so if it's not in the right format I apologize.
has comment: http://stackoverflow.com/comment/87374504
has title: Range for numbers 1 to 3
has comment: http://stackoverflow.com/comment/87374414
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/20449427

http://stackoverflow.com/comment/87262020
type: Comment
type: QuestionComment
has text: I just uploaded some more rows of the data. If you look at the data I posted you can see that the output is not what it should be.
score: 0
comment on: http://stackoverflow.com/q/50120823

http://stackoverflow.com/comment/87210015
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50095511
score: 0
has text: @BugHunter: in that case the `s.save()` function should have raised an error since `save` is not an attribute of `None`.

http://stackoverflow.com/q/50108028
accepted answer: http://stackoverflow.com/a/50108174
has body: I want to store a bunch of protobuf messages in a file, and read them later. In java, I can just use 'writeDelimitedTo' and 'parseDelimitedFrom' to read and write to a file. However, I want to read it in Python, which only seems to have a 'ParseFromString' method. Some SO questions are very similar, such as, Parsing Protocol Buffers, written in Java and read in Python, but that is only for a single message: not for multiple.
upvote count: 1
has answer: http://stackoverflow.com/a/50108174
favorite count: 0
type: Question
tagged with: protocol-buffers
score: 1
tagged with: java
linked to: http://stackoverflow.com/q/34507714
tagged with: python
has title: Serialize multiple protobuf messages in java and desesrialize them in Python
type: AnsweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/87302802
type: Comment
comment on: http://stackoverflow.com/a/50140929
type: AnswerComment
score: 0
has text: @Darkwilmore Thanks for the follow up. It seemed like your actual data was returning something else. Meanwhile, for your sample data, the original code worked for me. Which answer are you using?

http://stackoverflow.com/comment/87257005
has text: So I tried setting `Debug=True` but it doesn't report anything, all I see is `Server Error(500)`. And interesting, @marxin... It worked fine when I was hosting it on another server, and flawlessly as well in my development environment
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50118183

http://stackoverflow.com/a/50125550
has comment: http://stackoverflow.com/comment/87340360
answers question: http://stackoverflow.com/q/50124621
score: 10
downvote count: 0
type: Answer
has body: I'm going to suggest that you back off and approach this instead in a way that directly addresses your goal: shrinking peak memory use to begin with. No amount of analysis &amp; fiddling later can overcome using a doomed approach to begin with ;-) Concretely, you got off on a wrong foot at the first step, via data=f.read(). Now it's already the case that your program can't possibly scale beyond a data file that fits entirely in RAM with room to spare (to run the OS and Python and ...) too. Do you actually need all the data to be in RAM at one time? There are too few details to tell about later steps, but obviously not at the start, since you immediately want to throw away 75% of the lines you read. So start off by doing that incrementally instead: def getlines4(f): for i, line in enumerate(f): if i % 4 == 1: yield line Even if you do nothing other than just that much, you can skip directly to the result of step 3, saving an enormous amount of peak RAM use: with open(file, 'r') as f: data = list(getlines4(f)) Now peak RAM need is proportional to the number of bytes in the only lines you care about, instead of to the total number of file bytes period. To continue making progress, instead of materializing all the lines of interest in data in one giant gulp, feed the lines (or chunks of lines) incrementally to your worker processes too. There wasn't enough detail for me to suggest concrete code for that, but keep the goal in mind and you'll figure it out: you only need enough RAM to keep incrementally feeding lines to worker processes, and to save away however much of the worker processes' results you need to keep in RAM. It's possible that peak memory use doesn't need to more than "tiny", regardless of input file size. Fighting memory management details instead is enormously harder than taking a memory-friendly approach to begin with. Python itself has several memory-management subsystems, and a great deal can be said about each of them. They in turn rely on the platfo…
has comment: http://stackoverflow.com/comment/87338787
has comment: http://stackoverflow.com/comment/87300011
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/105611576
accepted answer of: http://stackoverflow.com/q/50124621
upvote count: 10
has comment: http://stackoverflow.com/comment/87311273

http://stackoverflow.com/comment/87302573
type: Comment
has text: But I don't see any checkboxes in your codes, maybe some parts is missing
type: AnswerComment
comment on: http://stackoverflow.com/a/50125309
score: 0

http://stackoverflow.com/comment/87308602
comment on: http://stackoverflow.com/q/50137512
type: QuestionComment
has text: The code should be added to the original question, don't post part of your question as an answer. give it another go!
score: 0
type: Comment

http://stackoverflow.com/comment/87467267
comment on: http://stackoverflow.com/a/50173178
score: 0
type: AnswerComment
type: Comment
has text: If I use `__slots__` to make the `__dict__` go away, the circle is still there...

http://stackoverflow.com/comment/87431562
type: Comment
score: 2
type: AnswerComment
has text: sklearn handles the text targets on its own. No need to encode.
comment on: http://stackoverflow.com/a/50202819

http://stackoverflow.com/comment/87201524
type: QuestionComment
has text: Thanks @tadman I will have a look at Amazon S3 now
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50092592

http://stackoverflow.com/comment/87600948
has text: Yeah I don't think your view is being called. You'd need to have `views.index` if you wanted to hardcode the URL for the index view above. Then the next job is dealing with `get` and `post` methods in the view.
score: 1
comment on: http://stackoverflow.com/q/50149341
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50189140
tagged with: pycharm
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87396067
score: 0
answer count: 0
tagged with: user-interface
has body: Does anybody know how to build a dynamic calculator that functions as follows: GUI With Buttons and 4 Display Text Widgets (Number1, Operator, Number2, Result) First Number to be pushed is number1 (append number1 if multiple pushed) Next the operator has to be pushed (change operator if multiple pushed) Next number2 has to be pushed (append number2 if multiple pushed) If "=" is pushed, print result If "=" is not pushed but any other operator (+-,/,) print result and save next operator, - save result as number1 for next operation* I am a beginner at coding and after several months of learning I decided to create a calculator in Python with tkinter. I have to say that I did not ask anyone for help until now. It probably won't work but below you can find my try of creating my first program..: from tkinter import * import operator root = Tk() display1 = None display2 = None number1 = None number2 = None result = None op_char = None op_func = None op_display = None T_num1 = Text(root, height=2, width=30) T_num1.pack() T_num2 = Text(root, height=2, width=30) T_num2.pack() T_op = Text(root, height=2, width=30) T_op.pack() T_result = Text(root,height=2, width=30) T_result.pack() ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv} def numberpush(input): global result global number1 global number2 global result global op_char global op_func global op_display global ops global display1 global display2 if result != None: if number1 != None: if number2 == None: number2 = input display2 = input result = op_func(display1, number2) number1 = result else: number2.append(input) display2.append(input) T_num2.insert(END, display2) result = op_func(display1, display2) number1 = result else: number1 = result display2 = result T_num2.insert(END, display2) elif operator_func == None: if number1 == None: number1 = input display1 = input T_num1.insert(END, display1) else: number1 = number1.append(input) display1.append(input) T_num1.insert(END, display1) el…
tagged with: calculator
has comment: http://stackoverflow.com/comment/87395216
has title: Failing to create my first dynamic GUI Calculator
type: Question
tagged with: tkinter

http://stackoverflow.com/comment/87247198
type: AnswerComment
has text: @jicocaer the rnn cell in tf.nn.dynamic_rnn(cell, ...) may take nested tuple of Tensors as an input, thus dynamic_rnn may produce the nested tuple of outputs, therefore tf.concat() might be necessary. Obviously I cannot tell why the programmer did what he did unless I see the full code. As the other user mentioned, the documentation on [tf.nn.dynamic_rnn](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn) provides more details on output shapes.
comment on: http://stackoverflow.com/a/50114382
type: Comment
score: 0

http://stackoverflow.com/comment/87424429
comment on: http://stackoverflow.com/a/50203550
type: Comment
type: AnswerComment
score: 1
has text: This gives the following error: `AttributeError: 'FacetGrid' object has no attribute 'get_legend'`. Its also mentioned in the comment on that linked answer.

http://stackoverflow.com/comment/87485814
type: Comment
comment on: http://stackoverflow.com/q/50215247
type: QuestionComment
has text: What if you delete that first channel? `conda config --remove channels pypi.python.org/simple`?
score: 2

http://stackoverflow.com/q/50109747
linked to: http://stackoverflow.com/q/44404349
has comment: http://stackoverflow.com/comment/87254752
has comment: http://stackoverflow.com/comment/87309650
tagged with: python
has comment: http://stackoverflow.com/comment/87254749
has comment: http://stackoverflow.com/comment/87256144
tagged with: image
duplicate of: http://stackoverflow.com/q/44404349
score: 0
has comment: http://stackoverflow.com/comment/87237232
answer count: 0
has comment: http://stackoverflow.com/comment/87254504
has body: I have a long program (script: face.py, main function: livevideo()). upon running the program, it shows webcam live video (display 1), I press 'm' to pause + capture webcam image + add detected faces in the webcam image into an averaged face (display 2). face.py program works well with 2 python windows for the 2 displays. Now, I am building a simple user interface (script: interface.py). I want to fit the 2 displays into 2 QLabel/ QFrame panels in the interface. I am very new to PyQt, and I am really confused by examples with PyQt code endlessly inter-referencing. In interface.py, I have already imported face.livevideo. I would prefer to modify only interface.py and leave face.py untouched. How can I do it? Thanks. face.py (hundreds of lines of code): livevideo() (showing only relevant lines) def livevideo(): cap=cv2.VideoCapture(0) cv2.imshow("Live Video",image) if cv2.waitKey(1)==ord('m'): break # lines for face averaging process are excluded cv2.imshow("Averaged Face",output) cv2.waitKey(1) interface.py: import sys import face from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * class HelloWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) menu = self.menuBar().addMenu('Add Frames to Averaged Face') action1 = menu.addAction('Start Webcam') action1.triggered.connect(face.livevideo) liveVideoImage = QLabel(self) liveVideoImage.setGeometry(50,100,500,375) liveVideoImage.setFrameShape(QFrame.Panel) averagedFaceOutput = QLabel(self) averagedFaceOutput.setGeometry(600,100,375,375) averagedFaceOutput.setFrameShape(QFrame.Panel) if __name__ == "__main__": def run_app(): app = QApplication(sys.argv) mainWin = HelloWindow() mainWin.show() app.exec_() run_app()
type: UnansweredQuestion
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/87254756
has title: Fit 2 Displays (from Script A) in 2 Panels of PyQt Interface (Script B)
has comment: http://stackoverflow.com/comment/87237643
type: Question
has comment: http://stackoverflow.com/comment/87256317
tagged with: display

http://stackoverflow.com/a/50191849
answers question: http://stackoverflow.com/q/50190934
has comment: http://stackoverflow.com/comment/87401069
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I don't have much knowledge on onclick event attribute. I suppose, when it is set to return false then the request usually skips that portion. However, if you try the way I showed below, you may get the result very close to what you want. import requests from scrapy import Selector res = requests.get("https://allevents.in/bangalore/project-based-summer-training-program/1851553244864163") sel = Selector(res) for items in sel.css("div[property='schema:description']"): emailid = items.css("span::text").extract_first() print(emailid) Output: htindialabsworkshops | gmail ! com
accepted answer of: http://stackoverflow.com/q/50190934
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87400926

http://stackoverflow.com/q/50182600
has title: Changing values of a column based on other two column comparison in pandas
tagged with: python
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: For the following data table created in pandas, Date Score Study_Date 02/2011 70 11/2012 03/2011 72 11/2012 10/2011 60 11/2012 12/2011 50 11/2012 01/2012 40 11/2012 02/2012 60 11/2012 03/2012 75 11/2012 11/2012 70 11/2012 12/2012 70 11/2012 01/2013 30 11/2012 02/2013 20 11/2012 04/2013 60 11/2012 06/2013 80 11/2012 I would like to replace all the scores for rows whose date is before the study date by 0. I tried the following: df[df.Date &lt; df.Study_Date, 'Score']=0 but I get: TypeError: 'Series' objects are mutable, thus they cannot be hashed Any help would be greatly appreciated.
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50182654
tagged with: indexing
tagged with: time-series
has answer: http://stackoverflow.com/a/50182654

http://stackoverflow.com/comment/87437058
comment on: http://stackoverflow.com/a/50210133
score: 0
type: Comment
type: AnswerComment
has text: can you share any document for this?

http://stackoverflow.com/a/67072525
type: Answer
has body: Tricky, but it seems to work: class ForeignKeyAsOneToOneField(models.OneToOneField): def __init__(self, to, on_delete, to_field=None, **kwargs): super().__init__(to, on_delete, to_field=to_field, **kwargs) self._unique = False class LinkData(models.Model): # link_target = models.ForeignKey(LinkTargets, verbose_name="Link Target", on_delete=models.PROTECT) link_target = ForeignKeyAsOneToOneField(LinkTargets, verbose_name="Link Target", on_delete=models.PROTECT, related_name='linkdata_helper') interface_description = models.CharField(max_length=200, verbose_name='Interface Description', blank=True, null=True) link_data = LinkTargets.objects.filter(dashboard=True) \ .prefetch_related( Prefetch( 'linkdata_helper', queryset=LinkData.objects.all().order_by('-id'), 'linkdata' ) ) # Now you can access linkdata: link_data[0].linkdata Ofcourse with this approach you can't use linkdata_helper to get related objects.
score: 0
answers question: http://stackoverflow.com/q/50219904

http://stackoverflow.com/comment/87175369
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50079694
score: 3
has text: `x.reset_index()`?

http://stackoverflow.com/comment/87327432
type: Comment
type: QuestionComment
has text: Pretty sure there are 1000 duplicates for this..
comment on: http://stackoverflow.com/q/50154945
score: 2

http://stackoverflow.com/a/50161980
type: Answer
has comment: http://stackoverflow.com/comment/87344415
has comment: http://stackoverflow.com/comment/87360601
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50161880
has comment: http://stackoverflow.com/comment/87343408
has comment: http://stackoverflow.com/comment/87352712
answers question: http://stackoverflow.com/q/50161880
has body: Sure, just send a edit_message passing the new modified embed contents, and it should work.

http://stackoverflow.com/q/50207822
has comment: http://stackoverflow.com/comment/87432543
has answer: http://stackoverflow.com/a/50208159
score: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50222108
upvote count: 1
has title: How to merge pandas dataset onto itself based on a condition and a groupby
has answer: http://stackoverflow.com/a/50220139
has body: To best illustrate consider the following SQL Illustration: Table StockPrices, BarSeqId is a sequential number where each increment is information from next minute of trading. The goal to achieve in pandas data frame is to transform this data: StockPrice BarSeqId LongProfitTarget 105 0 109 100 1 105 103 2 107 103 3 108 104 4 110 105 5 113 into this data: StockPrice BarSeqId LongProfitTarget TargetHitBarSeqId 106 0 109 Nan 100 1 105 3 103 2 107 5 105 3 108 Nan 104 4 110 Nan 107 5 113 Nan to create a new column which describes at which soonest sequential time-frame a price target will be hit in the future from the current time-frame Here is how it could be achieved in SQL: SELECT S1.StockPrice, S1.BarSeqId, S1.LongProfitTarget, min(S2.BarSeqId) as TargetHitBarSeqId FROM StockPrices S1 left outer join StockPrices S2 on S1.BarSeqId&lt;s2.BarSeqId and S2.StockPrice&gt;=S1.LongProfitTarget GROUP BY S1.StockPrice, S1.BarSeqId, S1.LongProfitTarget I would like the answer to be as follows: someDataFrame['TargetHitBarSeqId'] = (pandas expression here ...** assume that someDataFrame already has columns: StockPrice, BarSeqId, LongProfitTarget data edited to illustrate case so in the second row result should be 100 1 105 3 and NOT 100 1 105 0 since 3 and not 0 occurs after 1. It is important that the barseq in question shall occur in the future (greater than current BarSeq) df = pd.DataFrame({'StockPrice':[105,100,103,105,104,107],'BarSeqId':[0,1,2,3,4,5], 'LongProfitTarget':[109,105,107,108,110,113]}) def get_barseqid(longProfitTarget): try: idx = df.StockPrice[df.StockPrice &gt;= longProfitTarget].index[0] return df.iloc[idx].BarSeqId except: return np.nan df['TargetHitBarSeqId'] = df.apply(lambda row: get_barseqid(row['LongProfitTarget']), axis=1)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87432763
type: UnansweredQuestion
downvote count: 1
tagged with: python

http://stackoverflow.com/q/50172305
tagged with: ajax
score: 0
has answer: http://stackoverflow.com/a/50172642
has body: I'm trying to figure out which image has been clicked on my page (generated with Flask) and send the id of this image to a python program with Ajax. These images are displayed by a loop like so: _result_remote.html: {% for key, value in resultat.vars_buttons.items() %} &lt;div class="tuile{{1+loop.index%23}} news col-xs-4 col-lg-2"&gt; &lt;img id ="{{key}}"style="margin-top:-5px;" src="../static/img/remote/tvb.png" width="30" &gt;{{ value }} &lt;/div&gt; {% endfor %} I've tried to put this script just before the {% endfor %} statement: $(function() { $('img#{{key}}').on("click", function (e) { var id = $(this).attr("id"); $.ajax({ url: "/remote", type: "POST", id: id}) }); }); and finally in my app.py: app.py: @app.route('/remote', methods=['POST']) def remote(): commande = request['id']; return print(commande) another information: my page is named _result_remote.html because it's actually an include in another page that is rendered like this: app.py: @app.route('/') def accueil(): resultat = {'module_identique' : "", "module":"", "vars": {}} return render_template("accueil_modulable.html", titre="Bienvenue!",resultat=resultat) accueil_modulable.html: &lt;div class="row result {{ resultat.module_identique }}" id="ajax_result"&gt; {% for module in modules %} {% if resultat.module == module %} {% include '_result_'+ module +'.html' %} {% endif %} {% endfor %} &lt;/div&gt; The include works well by the way. Thank you very much for your help
answer count: 1
tagged with: post
type: Question
has title: Python / Flask / Ajax : send a dict key from client to server
type: UnansweredQuestion
tagged with: python
tagged with: flask

http://stackoverflow.com/comment/87447539
type: QuestionComment
has text: Well, those are the values that aren't matching. The NaNs are expected, but you should figure out why the Filled_Q1 values (which both look like 1) aren't equal to each other. Maybe one's a float and one's a string, or something, or something weirder.
comment on: http://stackoverflow.com/q/50214908
score: 1
type: Comment

http://stackoverflow.com/comment/87257708
type: Comment
type: QuestionComment
has text: There are quite a few ways to run requests in parallel. Try the keywords "threading" or "asyncio" on Google.
comment on: http://stackoverflow.com/q/50120110
score: 0

http://stackoverflow.com/comment/87215577
type: QuestionComment
has text: Please, [edit] your question, rather that posting unformatted code in a comment.
score: 0
comment on: http://stackoverflow.com/q/50099347
type: Comment

http://stackoverflow.com/q/50098338
tagged with: split
answer count: 2
has title: Better way to change specific chars in a string separated by underscores without using re
has answer: http://stackoverflow.com/a/50099777
has answer: http://stackoverflow.com/a/50101854
possible better answer: http://stackoverflow.com/a/50101854
tagged with: python
type: AnsweredQuestion
has body: I have files with names like centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg. I want to change the last string i.e. image_name.split('_')[5].split('.')[0] to some other string. I can't seem to find a neat way to do this and ended up doing the following which is very crude new_name = image_base.split('_')[0] + image_base.split('_')[1] + image_base.split('_')[2] + image_base.split('_')[3] + image_base.split('_')[4] + frameNumber That is, my output should be centerOne_camera_2_2018-04-11_15:11:21_&lt;some string&gt;.0.jpg Any better way is appreciated. Note: I want to retain the rest of the string too.
score: 0
tagged with: list
accepted answer: http://stackoverflow.com/a/50099777
type: Question

http://stackoverflow.com/comment/87261658
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50110691
has text: @SteveBarnes adding the directive did the trick - thank you! Would be nice to not have to do that though.

http://stackoverflow.com/comment/87412788
score: 0
comment on: http://stackoverflow.com/q/50197984
type: Comment
type: QuestionComment
has text: yes, I am trying to write a .DLL for my python to call.

http://stackoverflow.com/q/50104127
downvote count: 1
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50104215
accepted answer: http://stackoverflow.com/a/50104215
tagged with: pandas
has title: Partial string match with str.contains using dict comprehension with python/pandas
upvote count: 3
has body: I have a data frame with a column called course_names with a mapping dictionary with a list of course names i'd like to match in the key and the value I would want to assign in the value column import pandas as pd df = pd.DataFrame({'course_name' : ['Phsyics, Maths','Algebra &amp; Maths','History','Geology','Biology']}) mapping = {'Algebra &amp; Maths' : 'Mathematics', 'Phsyics' : 'Science', 'History' : 'History', 'Geology' : 'Geology', 'Biology' : 'Science'} # this goes on for about another 35 lines. #my attempt so far. df['keys'] = [k for k, v in mapping.items() if df['course_name'] in k] when I run this code I get : TypeError: 'in &lt;string&gt;' requires string as left operand, not Series expected output : course_name key 0 Phsyics, Maths Science 1 Algebra &amp; Maths Mathematics 2 History History 3 Geology Geology 4 Biology Science
answer count: 1

http://stackoverflow.com/q/50197920
possible better answer: http://stackoverflow.com/a/50198063
accepted answer: http://stackoverflow.com/a/50198000
has comment: http://stackoverflow.com/comment/87412674
has body: I am trying to to read and write to the same file. currently the data in 2289newsML.txt exists as normal sentences but I want to append the file so it stores only tokenized versions of the same sentences. I used the code below but even tho it prints out tokenized sentences it doesnt write them to the file. from pathlib import Path from nltk.tokenize import word_tokenize news_folder = Path("file\\path\\") news_file = (news_folder / "2289newsML.txt") f = open(news_file, 'r+') data = f.readlines() for line in data: words = word_tokenize(line) print(words) f.writelines(words) f.close any help will be appreciated. Thanks :)
tagged with: python
has comment: http://stackoverflow.com/comment/87412637
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50198000
answer count: 2
linked to: http://stackoverflow.com/q/16208206
has title: Issue with appending to txt file
type: Question
has answer: http://stackoverflow.com/a/50198063

http://stackoverflow.com/comment/87252311
score: 0
type: Comment
type: QuestionComment
has text: @Carcigenicate After reading the answers in the dupe, just out of curiosity: couldn't you just do a `if __name__ == "__main__":` in the loop?
comment on: http://stackoverflow.com/q/50117432

http://stackoverflow.com/comment/87784802
has text: @s6hebern When using your code on my Mac+Python3, I do see 4 child process running (plus 1 parent process) each with 25% CPU occupation
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50170302

http://stackoverflow.com/q/50203063
type: UnansweredQuestion
has title: Implementing Tags using Django rest framework
score: 6
tagged with: django
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/54350084
answer count: 2
downvote count: 0
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/54956902
favorite count: 0
type: Question
has body: TDLR : what is the best way to implement tags in django-rest-framework. where the tags has a created_by field which is the currently authenticated user. I am trying to achieve a very simple/common thing, add tags to posts. But apparently its not a piece of cake. So i have a posts model and a tags models (may to many relation). I want the user to be able to update and create the posts. when creating or updating posts he should be able to update the tags of the posts. When a post is tagged with a new tag, that tag should be created if it dosent exist. Also i want to user to be able to specify the tags as a list of strings in the request. Example request { "name": "testpost1", "caption": "test caption", "tags": ["tag1", "tag2"], }, models.py class Tags(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=50, unique=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_tags") class Posts(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=50) caption = models.TextField(max_length=1000) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') tags = models.ManyToManyField('Tags', related_name='posts') serializers.py class TagsSerializerMini(serializers.ModelSerializer): created_by = serializers.PrimaryKeyRelatedField(default=serializers.CurrentUserDefault(), queryset=User.objects.all()) class Meta: model = Tags fields = ('name', 'created_by') extra_kwargs = { 'created_by': {'write_only': True}, 'name': {'validators': []}, } def create(self, validated_data): tag, created = Tags.objects.get_or_create(**validated_data) if not created: raise exceptions.ValidationError(validated_data['name']+" already exists.") return tag def to_representation(self, instance): ret = super(TagsSerializerMini, self).to_representation(instance) data = dict() data['name'] = ret['name'] re…

mapreduce
tags question: http://stackoverflow.com/q/50188649
type: Tag
tag name: mapreduce

http://stackoverflow.com/q/50223940
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87467905
tagged with: python
linked to: http://stackoverflow.com/q/12385179
has comment: http://stackoverflow.com/comment/87465803
has body: I'm porting code from NodeJS to python3. I want to post image binary data and text. I red urllib3 User Guide but I can't do it. How can I do it ? Thank you. NodeJS filePath = "xxx.jpeg" text = "xxx" return chakram.request("POST", "http://xxx", { "multipart" : [ { "body" : fs.createReadStream(filePath), "Content-Type" : "image/jpeg", "Content-Disposition" : "name='file'; filename='" + filePath + "'" }, { "body" : JSON.stringify(this.RequestData(text)), "Content-Type" : "text" } ], "headers" : { "Authorization" : "xxx" } }) My Wrong Python Code with requests: filePath = "xxx.jpeg" text = "xxx" headers = { "Authorization" : "xxx" } binary_data = None with open(file_path, 'rb') as fp: binary_data = fp.read() request_body = self.create_request_body(text) files = { "file": (filePath, binary_data, 'image/jpeg'), "": ("", request_body, "xxx") } resp = requests.post("http://xxx", files=files, headers=headers) I got 500 error.
downvote count: 0
tagged with: urllib3
answer count: 0
score: 1
upvote count: 1
has title: How can I post image and text MultipartForm on python3?
has comment: http://stackoverflow.com/comment/87465581
tagged with: urllib
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87467740
linked to: http://stackoverflow.com/q/50225264
has comment: http://stackoverflow.com/comment/87465553

macos
tags question: http://stackoverflow.com/q/50183857
tags question: http://stackoverflow.com/q/50162466
tags question: http://stackoverflow.com/q/50131358
tags question: http://stackoverflow.com/q/50184590
tags question: http://stackoverflow.com/q/50134882
tags question: http://stackoverflow.com/q/50205646
tags question: http://stackoverflow.com/q/50160196
tags question: http://stackoverflow.com/q/50131893
tags question: http://stackoverflow.com/q/50109922
tags question: http://stackoverflow.com/q/50126234
tags question: http://stackoverflow.com/q/50181586
tags question: http://stackoverflow.com/q/50184241
type: Tag
tags question: http://stackoverflow.com/q/50111172
tags question: http://stackoverflow.com/q/50084766
tags question: http://stackoverflow.com/q/50121569
tags question: http://stackoverflow.com/q/50093119
tags question: http://stackoverflow.com/q/50078384
tags question: http://stackoverflow.com/q/50168647
tags question: http://stackoverflow.com/q/50196561
tags question: http://stackoverflow.com/q/50148821
tags question: http://stackoverflow.com/q/50182828
tag name: macos
tags question: http://stackoverflow.com/q/50092954
tags question: http://stackoverflow.com/q/50094162
tags question: http://stackoverflow.com/q/50193478
tags question: http://stackoverflow.com/q/50121330
tags question: http://stackoverflow.com/q/50199070
tags question: http://stackoverflow.com/q/50175564
tags question: http://stackoverflow.com/q/50229772
tags question: http://stackoverflow.com/q/50184736
tags question: http://stackoverflow.com/q/50093030
tags question: http://stackoverflow.com/q/50184952

http://stackoverflow.com/comment/87335121
has text: if I'm not mistaken, do you not need to set the 'train' attribute? It doesn't look like you've done this, svhn['train']= "value"
comment on: http://stackoverflow.com/q/50158589
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87199553
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50084077
type: Comment
has text: The fraction of the problematic messages is small, but their absolute quantity is large enough to be handled programmatically. However, in this particular case, I want to compare two messages to detect duplicates and the originals are never directly written back. So reversibility isn't an issue. Could you give some code samples to show how to set `surrogateescape` vs. `ignore` when serializing the message? From the documentation, it wasn't clear how to attach custom codec error handlers.

http://stackoverflow.com/q/50156135
type: Question
has body: My goal is to iterate thru data frame from CSV file and perform a point in polygon operation and assign this to a new column in the data frame. I was able to construct function and my only problem is how to iterate thru data frame and append with results of the function. from shapely.geometry import Point, shape point = Point(10.2023019,8.43254802) fc = fiona.open("ngaadmbndaadm2osgof20170222.geojson") print (fc.schema) and then print value for values from the point: for feature in fc: if shape(feature['geometry']).contains(point): df_data['Admin2name'] = (feature['properties']['admin2Name']) My data frame looks like this
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50157075
has answer: http://stackoverflow.com/a/50156569
upvote count: 1
tagged with: python
tagged with: gis
has answer: http://stackoverflow.com/a/50163012
answer count: 3
tagged with: pandas
tagged with: shapely
score: 1
has title: Python iterate thru csv and execute point in polygon operation
favorite count: 0

http://stackoverflow.com/a/50124916
accepted answer of: http://stackoverflow.com/q/50124650
answers question: http://stackoverflow.com/q/50124650
has body: Perhaps you could create a new file that has all backslashes replaced with an empty string "" or some other replacement character. An example snippet: input_csv_filename = "original.csv" output_csv_filename = "no_backslashes.csv" # Read original contents with open(input_csv_filename, 'rb') as f: csv_contents = f.read() # Replace backslash with empty string # b'\\' is the bytes literal for b'\' csv_contents = csv_contents.replace(b'\\', b'') # Write replaced contents to the output csv file with open(output_csv_filename, 'wb') as f: f.write(csv_contents) You can then go onto read the output csv file with your code: import pandas as pd df = pd.read_csv(output_csv_filename) Edit - 1: Beware that this will indiscriminately replace all backslashes in your original csv file. If you're confident that there wouldn't be backslashes anywhere else, then you can use this approach. Edit - 2: My bad, I initially assumed that file would not contain unicode characters. I have changed by code to now deal with the files in bytes.
type: Answer
has comment: http://stackoverflow.com/comment/87305031
has comment: http://stackoverflow.com/comment/87338722
has comment: http://stackoverflow.com/comment/87428165
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/50204607
has comment: http://stackoverflow.com/comment/87426409
has body: Suppose your data frame looks like this: df = pd.DataFrame({'publisher_name': ['john', 'mark', 'john', 'fred','john'], 'book_name' : ['aa', 'bb', 'cc', 'dd','ee']}) book_name publisher_name 0 aa john 1 bb mark 2 cc john 3 dd fred 4 ee john We can get the dictionary using dictionary comprehension: {name: list(book_publisher(name, df)[0].values) for name in df['publisher_name']} If numpy array is also acceptable you can drop the list(). I don't know what your data looks like. If it's just a dataframe with book_name and publisher_name columns, you may also want to change return [books] to return books in your function, and then you can drop the [0] from my answer above.
accepted answer of: http://stackoverflow.com/q/50204441
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50204441
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87426974

http://stackoverflow.com/comment/87323851
has text: @bro-grammer, I understand you now. Never thought of the trivial solution. Feel free to post an answer (I can figure it out myself, but this could help others).
type: Comment
comment on: http://stackoverflow.com/q/50152841
type: QuestionComment
score: 1

http://stackoverflow.com/comment/87412195
score: 0
has text: I've asked that question to no results quite a while ago: https://stackoverflow.com/questions/49201498/pip-install-accepts-fails I've given up on that approach after many failed attempts and am trying to focus on moving the library that I have already manually.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50196426

http://stackoverflow.com/comment/87280838
type: Comment
comment on: http://stackoverflow.com/a/50131347
score: 0
type: AnswerComment
has text: I'll take care of that, thanks for the guideline @PM2Ring

http://stackoverflow.com/comment/87413377
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50198310
has text: Your question doesn't match your code. Your question's title is asking how to _check_ if a list contains a value, but your code _deleting_ elements from a list and the error is completely unrelated to the membership testing. It's unclear what the code is intended to do, so we can't fix it for you. Please clarify what you're trying to do.
score: 3

http://stackoverflow.com/comment/87472253
type: QuestionComment
has text: is `7087708705` not a valid Indian phone number?
type: Comment
comment on: http://stackoverflow.com/q/50227399
score: 0

http://stackoverflow.com/a/64736819
answers question: http://stackoverflow.com/q/50077928
has body: The solution of the first problem is: global IP_PACKET IP_PACKET =[]
has comment: http://stackoverflow.com/comment/114461661
score: 0
type: Answer

http://stackoverflow.com/q/50110044
score: 20
upvote count: 20
tagged with: dask
tagged with: parquet
tagged with: pyarrow
answer count: 1
tagged with: python
has body: Is there a way to force a parquet file to encode a pd.DataFrame column as a given type, even though all values for the column are null? The fact that parquet automatically assigns "null" in its schema is preventing me from loading many files into a single dask.dataframe. Trying to cast the pandas column using df.column_name = df.column_name.astype(sometype) didn't work. Why I'm asking this I want to load many parquet files into a single dask.dataframe. All files were generated from as many instances of pd.DataFrame, using df.to_parquet(filename). All dataframes have the same columns, but for some a given column might contain only null values. When trying to load all files into the dask.dataframe (using df = dd.read_parquet('*.parquet') , I get the following error: Schema in filename.parquet was different. id: int64 text: string [...] some_column: double vs id: int64 text: string [...] some_column: null Steps to reproduce my problem import pandas as pd import dask.dataframe as dd a = pd.DataFrame(['1', '1'], columns=('value',)) b = pd.DataFrame([None, None], columns=('value',)) a.to_parquet('a.parquet') b.to_parquet('b.parquet') df = dd.read_parquet('*.parquet') # Reads a and b This gives me the following: ValueError: Schema in path/to/b.parquet was different. value: null __index_level_0__: int64 metadata -------- {b'pandas': b'{"index_columns": ["__index_level_0__"], "column_indexes": [{"na' b'me": null, "field_name": null, "pandas_type": "unicode", "numpy_' b'type": "object", "metadata": {"encoding": "UTF-8"}}], "columns":' b' [{"name": "value", "field_name": "value", "pandas_type": "empty' b'", "numpy_type": "object", "metadata": null}, {"name": null, "fi' b'eld_name": "__index_level_0__", "pandas_type": "int64", "numpy_t' b'ype": "int64", "metadata": null}], "pandas_version": "0.22.0"}'} vs value: string __index_level_0__: int64 metadata -------- {b'pandas': b'{"index_columns": ["__index_level_0__"], "column_indexes": [{"na' b'me": null, "field_name": null, "pand…
favorite count: 0
linked to: http://stackoverflow.com/q/49172428
has answer: http://stackoverflow.com/a/50137686
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50137686
downvote count: 0
tagged with: pandas
has title: How to force parquet dtypes when saving pd.DataFrame?
type: Question

http://stackoverflow.com/comment/87334628
has text: @Alasdair added. Please have a look.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50158139
score: 0

http://stackoverflow.com/comment/87299666
type: QuestionComment
comment on: http://stackoverflow.com/q/50140676
has text: Something simple, for instance I'd expect something like x**2
score: 0
type: Comment

http://stackoverflow.com/comment/87432933
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50207717
type: AnswerComment
has text: @AntoshaShmonoff did you want to use cascade deletions? This post might be useful: https://stackoverflow.com/questions/3937194/django-cascade-deletion-in-manytomanyrelation

http://stackoverflow.com/comment/87435780
comment on: http://stackoverflow.com/q/50208954
score: 0
type: QuestionComment
has text: @PaoloStefan Sir, I changed SERVER_EMAIL = 'mymail@gmail.com'. But, still facing the same problem :(
type: Comment

http://stackoverflow.com/q/50212780
has comment: http://stackoverflow.com/comment/87447446
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/87452181
has title: Gtk 3.0 MenuItem() with Grid()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87443427
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87443609
favorite count: 0
has comment: http://stackoverflow.com/comment/87443376
has body: I'm trying to create a Menu with Gtk3 and Python which has its entries aligned like a HTML-table. the values of the columns are of different length. i want the menu look like this: entry 1 text-of-some-length 1000 entry 2 shorter-text 10 entry 2 shorter-text 100 I thougth i can simply use a Gtk.Grid() add Gtk.Labels() to it and then append the grid to the Gtk.MenuItem(). Here is my attempt gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject gi.require_version('AppIndicator3', '0.1') from gi.repository import AppIndicator3 as appindicator from os.path import expanduser #init AppIndicator3 in class self.ind = appindicator.Indicator.new ("todo-txt-indicator", PANEL_ICON, appindicator.IndicatorCategory.OTHER) self.ind.set_status (appindicator.IndicatorStatus.ACTIVE) #generate menu for AppIndicator3 menu = Gtk.Menu() label_1 = Gtk.Label () label_1.set_text ('entry 1') label_2 = Gtk.Label () label_2.set_text ('text-of-some-length') label_3 = Gtk.Label () label_3.set_text ('1000') grid = Gtk.Grid () grid.add (label_1) grid.attach_next_to (label_2, label_1, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to (label_3, label_2, Gtk.PositionType.RIGHT, 1, 1) menu_item = Gtk.MenuItem () menu_item.add (grid) menu.append (menu_item) #set menu to AppIndicator3 self.ind.set_menu (menu) But this don't work. only the last element (label_3) gets displayed (at the most left position). I don't see why this isn't working. Any help is appreciated.
tagged with: ubuntu-18.04
score: 1
tagged with: gtk3

http://stackoverflow.com/a/50181888
score: 1
has comment: http://stackoverflow.com/comment/87442604
has body: Your code should be client.time_series('activities/heart', period='1d') to get heart rate. For the first parameter resource, it doesn't need the resource URL, but it asks you to put one of these: activities, body, foods, heart, sleep. Here is the link of source code from python-fitbit: http://python-fitbit.readthedocs.io/en/latest/_modules/fitbit/api.html#Fitbit.time_series Added: If you want to get the full heart rate data per minute (["activities-heart-intraday"] dataset), try client.intraday_time_series('activities/heart'). It will return data with the one-minute/one-second detail.
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87395169
has comment: http://stackoverflow.com/comment/87400710
has comment: http://stackoverflow.com/comment/87395882
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50141362
has comment: http://stackoverflow.com/comment/87393909
has comment: http://stackoverflow.com/comment/87392750
accepted answer of: http://stackoverflow.com/q/50141362

http://stackoverflow.com/a/50215332
score: 0
answers question: http://stackoverflow.com/q/50214691
has comment: http://stackoverflow.com/comment/87456504
type: Answer
has body: This should do it: import re resp =[] seq = 'G**ATG**ATCG**ATG**C**TGA**CGTA**TAG**GT**TAA**C' while re.findall(r'(?&lt;=ATG)(.*)(?=(TGA|TAA|TAG))',seq): seq = re.findall(r'(?&lt;=ATG)(.*)(?=(TGA|TAA|TAG))', seq) resp.append("ATG"+seq[0][0]+seq[0][1]) seq="ATG"+seq[0][0] print(resp)

http://stackoverflow.com/q/50140985
has title: Writing brute force for a caeser cipher, getting error
has answer: http://stackoverflow.com/a/50141602
tagged with: pyenchant
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50142218
answer count: 2
has answer: http://stackoverflow.com/a/50142218
tagged with: brute-force
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87302036
tagged with: encryption
has comment: http://stackoverflow.com/comment/87300742
has body: So im writing a caeser cipher in python, and i have a brute force option to see if it can decode a word with a random offset. For some reason i get the error: Traceback (most recent call last): File "C:\Users\nameredacted\Desktop\Python\CipherV2.py", line 60, in &lt;module&gt; print(getTranslatedMessage(mode, message, key)) File "C:\Users\nameredacted\Desktop\Python\CipherV2.py", line 47, in getTranslatedMessage ciphertext += alpha2[ (alpha1[i] + brutekey)] KeyError: 26 my code is : from PyDictionary import PyDictionary import enchant MAX_KEY_SIZE = 26 dictionary = PyDictionary() d = enchant.Dict("en_US") alpha1 = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26))) alpha2 = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ")) #gets if the user wants to encrypt or decrypt def getMode(): while True: print('Do you wish to encrypt, decrypt or brute force a message') mode = input().lower() if mode in 'encrypt e decrypt d bruteforce bf'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d" or "bruteforce" or "bf".') #gets offset value if needed def getKey(mode): key = 0 if mode[0]=='b': pass else: while True: key = int(input('Enter the offset number (1-%s)' % (MAX_KEY_SIZE))) if (key &gt;= 1 and key &lt;= MAX_KEY_SIZE): return key #translates the message def getTranslatedMessage(mode, message, key): ciphertext='' if mode[0] == 'd': key = -key for c in message.upper(): if c.isalpha(): ciphertext += alpha2[ (alpha1[c] + key)] else: ciphertext += c elif mode[0] =='e': for x in message.upper(): if x.isalpha(): ciphertext += alpha2[ (alpha1[x] + key) ] else: ciphertext += x else: while True: for i in message.upper(): for brutekey in range (26): ciphertext += alpha2[ (alpha1[i] + brutekey)] print(ciphertext) if d.check(ciphertext): break return ciphertext mode = getMode() message = input("please input your message") key = getKey(mode) print('Your translated text is:') print(getTranslatedMessage(mode, message, key)) Thanks for reading, also id appreciate…
possible better answer: http://stackoverflow.com/a/50141602
tagged with: python
has comment: http://stackoverflow.com/comment/87300399

http://stackoverflow.com/comment/87350682
score: 0
type: Comment
type: AnswerComment
has text: still getting ip2 from it
comment on: http://stackoverflow.com/a/50166408

http://stackoverflow.com/a/50128593
upvote count: 1
has body: You can locate by attribute without value driver.find_elements_by_xpath('//*[@data-time]')
score: 1
answers question: http://stackoverflow.com/q/50128136
type: Answer
has comment: http://stackoverflow.com/comment/87275368
downvote count: 0

http://stackoverflow.com/q/50226541
tagged with: python
possible better answer: http://stackoverflow.com/a/50264862
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50264862
answer count: 2
accepted answer: http://stackoverflow.com/a/50246705
tagged with: pyhive
downvote count: 0
has answer: http://stackoverflow.com/a/50246705
upvote count: 1
tagged with: jinja2
favorite count: 0
tagged with: hive
type: Question
has title: How to execute query on hive with jinjasql
has body: Is it possible to execute query for hive using jinjasql and pyhive? When I tried it I got following error. pyhive.exc.ProgrammingError: Unsupported param format: odict_values(['XXXXXXX']) I can execute query with jinjasql as well as with pyhive but I need to use both together to prevent sql injection. Environment (all on the same VM.) Hortonworks Data Platform (HDP®) 2.6.4 on Hortonworks Sandbox for VirtualBox Jinjasql 0.1.6 PyHive 0.5.1 Python 3.5.5
score: 1
tagged with: sql-injection

http://stackoverflow.com/q/50134014
accepted answer: http://stackoverflow.com/a/50174328
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50174328
answer count: 2
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
has body: I have this code: date = program.last_registration_date.strftime('%d %B %Y, %H:%M') program is my model and last_registration_date is a normal value from a DateTimeField Now my problem is that date returns an English date, which I don't want. In my default.py I've set my TIME_ZONE correctly ('Europe/Berlin'), my LANGUAGE_CODE ('de') and ofc USE_L1ON is set on True. But it still not German. I tried to import locale and use a setlocale after my imports, but that also won't work (just shows me an error that locale is an unsupported setting). So, anyone can help me how to turn this date German?
type: Question
possible better answer: http://stackoverflow.com/a/50134119
tagged with: strftime
has title: Django - returning German date with strftime
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50134119
tagged with: date

http://stackoverflow.com/q/50190132
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/18697417
has comment: http://stackoverflow.com/comment/104924234
answer count: 1
downvote count: 0
has title: Not plotting 'zero' values in a list on a pie chart in matplotlib [Python,Jupyter NoteBooks]
upvote count: 1
score: 1
favorite count: 0
type: Question
has body: I just need help with Not plotting 'zero' values on a pie chart in matplotlib as per title using python. I have tried using the solution from Not plotting 'zero' in matplotlib or change zero to None [Python] from a different post but I keep getting cannot convert float NaN to integer error. Solution from other post: values = [3, 5, 0, 3, 5, 1, 4, 0, 9] def zero_to_nan(values): """Replace every 0 with 'nan' and return a copy.""" return [float('nan') if x==0 else x for x in values] print(zero_to_nan(values)) This is a shortened down version of my code: #For plotting and visualization from IPython.display import display import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline #Possible solution - however i get error cannot convert float NaN to integer error sample = [innercitybypass,others,kingsfordcount] ##E.g.[0,1,2] def zero_to_nan(sample): return [float('nan') if x==0 else x for x in sample] labels = ['InnerCityBypass','OtherRds','KingsfordRd'] ###sizes = [innercitybypass,others,kingsfordcount] sizes = zero_to_nan(sample) #Set different colors colors = ['green','red','blue'] plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140) plt.axis('equal') plt.show() Any help will be appreciated, thanks!
has answer: http://stackoverflow.com/a/50190673
type: UnansweredQuestion

http://stackoverflow.com/comment/87464597
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50194503
has text: Nice. This works in most cases but, I want to omit other sections like [doc], [test] etcetera. The accepted answer covers that.
type: Comment

http://stackoverflow.com/a/50107579
has body: What you will want to do is create your own instances of Stratified K Folds object and pass it in to the cv argument in cross_val_score. This way you can supply different random seeds for splitting the data. from sklearn.model_selection import StratifiedKFold clf = linear_model.RidgeClassifier() for n in range(5): strat_k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=n) scores = cross_val_score(clf, X_train, y_train, cv=strat_k_fold)
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/50106143
has comment: http://stackoverflow.com/comment/106548907
has comment: http://stackoverflow.com/comment/97389020
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/107261716

http://stackoverflow.com/comment/87265459
type: Comment
type: QuestionComment
has text: What do you not understand from the documentation?
comment on: http://stackoverflow.com/q/50123534
score: 0

http://stackoverflow.com/q/50200023
has comment: http://stackoverflow.com/comment/87417307
has comment: http://stackoverflow.com/comment/87417033
has comment: http://stackoverflow.com/comment/87416758
has comment: http://stackoverflow.com/comment/87416809
has comment: http://stackoverflow.com/comment/87416559
has comment: http://stackoverflow.com/comment/87416948
has comment: http://stackoverflow.com/comment/87416514
has comment: http://stackoverflow.com/comment/87416625
score: 0
has comment: http://stackoverflow.com/comment/87416829
has comment: http://stackoverflow.com/comment/87420961
has comment: http://stackoverflow.com/comment/87416791
has comment: http://stackoverflow.com/comment/87416561
has comment: http://stackoverflow.com/comment/87416717
has title: Django cannot import module after deployment
has comment: http://stackoverflow.com/comment/87417215
has comment: http://stackoverflow.com/comment/87416657
has comment: http://stackoverflow.com/comment/87416743
has comment: http://stackoverflow.com/comment/87416954
has comment: http://stackoverflow.com/comment/87417013
type: Question
has body: I transferred my Django project to another server and did the following steps. Took a list with installed python modules on my virtual environment with pip freeze > requirements.txt Transfered my project folder with scp (from one server to another) Created a virtual environment with mkvirtualenv Installed the requirements with pip install -r requirements.txt in my virtual environment Double-checked the modules, one by one, to verify they all are in the same version Tried to ./manage.py runserver and ./manage.py runworker and got "cannot import name patterns" So, I have the same modules installed, at the same version, with the same version of Django and it throws me an import error about "patterns" module, the same time that it is working correctly on the previous server with exactly the same modules installed. I am struggling for three days now, I also did the whole process from the beginning to make sure I don't forget anything. Any direction will be totally appreciated. EDIT: "patterns" refers to urls.py's patterns. The error: (amanet_venv) [kourtdim@web640 main_folder]$ amanet/manage.py runserver /home/kourtdim/lib/python2.7/floppyforms/__init__.py:21: UserWarning: Unable to import floppyforms.gis, geometry widgets not available "Unable to import floppyforms.gis, geometry widgets not available") /home/kourtdim/lib/python2.7/floppyforms/__init__.py:21: UserWarning: Unable to import floppyforms.gis, geometry widgets not available "Unable to import floppyforms.gis, geometry widgets not available") Performing system checks... Unhandled exception in thread started by &lt;function wrapper at 0x33592a8&gt; Traceback (most recent call last): File "/home/kourtdim/.virtualenvs/amanet_venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/kourtdim/.virtualenvs/amanet_venv/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 44, in inner_run self.check(display_num_errors=True) File "/home/kou…
has comment: http://stackoverflow.com/comment/87419281
has comment: http://stackoverflow.com/comment/87416703
has comment: http://stackoverflow.com/comment/87416566
answer count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87416730
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87416622

http://stackoverflow.com/q/50075783
tagged with: python
has body: I am trying to create a tensorflow layer. At this point, the goal is very simple. In my custom layer, I want to multiply the input by 2. So every time the input passes through the custom layer it should do the following input = 2 * input // just multiplying the input by 2 I am using the following code. from __future__ import print_function import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.normalization import local_response_normalization from tflearn.layers.estimator import regression from tensorflow.examples.tutorials.mnist import input_data # number 1 to 10 data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) def add_layer(inputs, out_size, activation_function=None): in_size = int(inputs.shape[1]) Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1) inputs_temp = inputs.eval(session=tf.Session()) ############# Do changes to input. Like input = 2 * input ################# inputs = tf.convert_to_tensor(inputs) Wx_plus_b = tf.matmul(inputs, Weights) + biases sess = tf.InteractiveSession() if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b) return outputs def compute_accuracy(v_xs, v_ys): global prediction y_pre = sess.run(prediction, feed_dict={xs: v_xs}) correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys}) return result # define placeholder for inputs to network xs = tf.placeholder(tf.float32, [None, 784]) # 28x28 ys = tf.placeholder(tf.float32, [None, 10]) # Network network = tflearn.flatten(xs) network = add_layer(network, 256) network = tflearn.reshape(network, (-1, 16, 16, 1)) network = conv_2d(network, 32, 3, activation='re…
tagged with: keras
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87176635
tagged with: deep-learning
has answer: http://stackoverflow.com/a/50456955
accepted answer: http://stackoverflow.com/a/50456955
has title: Error creating a custom layer in tensorflow
answer count: 1
has comment: http://stackoverflow.com/comment/87172637
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/87197968
has text: There is a loophole for your particular example, though: `lambda x: setattr(c, 'v', 99)`.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50090868

http://stackoverflow.com/comment/87412775
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50197954
type: Comment
has text: I know that part why 1. actually why there is "1" out of that code? "1+length(blabla"

http://stackoverflow.com/q/50222720
score: 0
has comment: http://stackoverflow.com/comment/87463135
answer count: 2
type: Question
has comment: http://stackoverflow.com/comment/87463294
accepted answer: http://stackoverflow.com/a/50223729
has answer: http://stackoverflow.com/a/50223729
downvote count: 1
tagged with: http
favorite count: 0
has comment: http://stackoverflow.com/comment/87463269
has comment: http://stackoverflow.com/comment/87464551
possible better answer: http://stackoverflow.com/a/50223715
tagged with: http://stackoverflow.com/tag/json
has body: I have json output from a curl command where I want to get one value and cannot figure out how to do it. I'm trying to get the "X-Subject-Token" as seen below. Reading similar answers I found I could use json.load(sys.stdin)['X-Subject-Token']'. I tried to run the snippet below... $ curl -v -s -X POST https://host.com:13000/v3/auth/tokens?nocatalog \ -H "Content-Type: application/json" -d '{\ "auth": {\ "identity": {\ "methods": [\ "password"\ ],\ "password": {\ "user": {\ "domain": {\ "name": "'"$OS_USER_DOMAIN_NAME"'"\ },\ "name": "'"$OS_USERNAME"'",\ "password": "'"$OS_PASSWORD"'"\ }\ }\ },\ "scope": {\ "project": {\ "domain": {\ "name": "'"$OS_PROJECT_DOMAIN_NAME"'"\ },\ "name": "'"admin"'"\ }\ }\ }\ }' | \ python -m json.tool | \ python -c 'import sys, json; print json.load(sys.stdin)['X-Subject-Token']' ...which gives me the error below: File "&lt;string&gt;", line 1, in &lt;module&gt; KeyError: 'X-Subject-Token' Tried to replace double quotes for single quotes... print json.load(sys.stdin)["X-Subject-Token"]' ...to get a different error: NameError: name 'X' is not defined. This is a snippet of the output I'm trying to extract from: &gt; Accept: */* &gt; Content-Type: application/json &gt; Content-Length: 245 &gt; } [data not shown] * upload completely sent off: 245 out of 245 bytes &lt; HTTP/1.1 201 Created &lt; X-Subject-Token: xxxxxxxxxxxxxxxxxxxxxxx &lt; Vary: X-Auth-Token &lt; Content-Type: application/json &lt; Content-Length: 489 How can I get X-Subject-Token ? I have also tried grep and awk which I have a bit more experience with but Python seemed to be the cleanest.
tagged with: python
upvote count: 1
has answer: http://stackoverflow.com/a/50223715
has comment: http://stackoverflow.com/comment/87463245
has title: Retrieve a single value from json output?
tagged with: curl
type: AnsweredQuestion

http://stackoverflow.com/comment/87279137
type: Comment
comment on: http://stackoverflow.com/a/50130619
type: AnswerComment
has text: my file has static content and never change (and no need to render as html), is there any way to not use template?
score: 0

http://stackoverflow.com/q/50109656
type: UnansweredQuestion
tagged with: python
has title: Tensorflow TOCO python API
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/50110427
tagged with: tensorflow
has body: I'm following the tensorflow for poets (tflite) tutorial here: https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2-tflite/#3 I'm attempting to convert a customised graph from .pb to tflite using the python TOCO API : https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/toco/g3doc/python_api.md The following code loads the retrained_graph.pb file, finds the input and output tensor, then calls toco_convert and writes the .tflite file. import tensorflow as tf def load_graph(graph_filename): with tf.gfile.GFile(graph_filename, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def( graph_def, input_map=None, return_elements=None, name="prefix", op_dict=None, producer_op_list=None ) graph = load_graph("retrained_graph.pb") x = graph.get_tensor_by_name('prefix/input:0') #input tensor y = graph.get_tensor_by_name('prefix/final_result:0') #output tensor with tf.Session(graph=graph) as sess: tflite_model = tf.contrib.lite.toco_convert(sess.graph_def, [x], [y]) open("test.tflite", "wb").write(tflite_model) This produces a test.tflite file. To check to see if it works, I run the label_image script from tf for poets, which produces this error: KeyError: "The name 'import/input' refers to an Operation not in the graph." Looking for solutions, I tried changing input_layer = "input" to input_layer = "Mul", but this only produces the error: KeyError: "The name 'import/Mul' refers to an Operation not in the graph." If there are any suggestions to what I am doing wrong they would be greatly appreciated.
type: Question
has answer: http://stackoverflow.com/a/50111238

http://stackoverflow.com/a/50239954
has body: To understand gradient boosting, you need first to understand individual trees. I will show a small example. Here is the setup: a small GB model trained on Iris dataset to predict whether a flower belongs to the class 2. # import the most common dataset from sklearn.datasets import load_iris from sklearn.ensemble import GradientBoostingClassifier X, y = load_iris(return_X_y=True) # there are 150 observations and 4 features print(X.shape) # (150, 4) # let's build a small model = 5 trees with depth no more than 2 model = GradientBoostingClassifier(n_estimators=5, max_depth=2, learning_rate=1.0) model.fit(X, y==2) # predict 2nd class vs rest, for simplicity # we can access individual trees trees = model.estimators_.ravel() print(len(trees)) # 5 # there are 150 observations, each is encoded by 5 trees, each tree has 1 output applied = model.apply(X) print(applied.shape) # (150, 5, 1) print(applied[0].T) # [[2. 2. 2. 5. 2.]] - a single row of the apply() result print(X[0]) # [5.1 3.5 1.4 0.2] - the pbservation corresponding to that row print(trees[0].apply(X[[0]])) # [2] - 2 is the result of application the 0'th tree to the sample print(trees[3].apply(X[[0]])) # [5] - 5 is the result of application the 3'th tree to the sample You can see that each number in the sequence [2. 2. 2. 5. 2.] produced by model.apply() corresponds to an output of a single tree. But what do these numbers mean? We can easily analyse decision trees by visual examination. Here is a function to plot one # a function to draw a tree. You need pydotplus and graphviz installed # sudo apt-get install graphviz # pip install pydotplus from sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphviz import pydotplus def plot_tree(clf): dot_data = StringIO() export_graphviz(clf, out_file=dot_data, node_ids=True, filled=True, rounded=True, special_characters=True) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) return Image(graph.create_png()) # …
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/50111612
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50111612

http://stackoverflow.com/a/50141426
type: Answer
has comment: http://stackoverflow.com/comment/87301747
has body: self.combined_scores might be a float. I see the following lines in your code: normalized_dist_weight = self.dist_weight / sum_weights ... self.combined_scores = normalized_dist_weight The names suggest that both self.dist_weight and sum_weights could both very well be float. The result of the division would then be a float. Edit: The last line can only work, if self.combined_scores is a multidimensional container. A pandas.DataFrame probably. I think the error is in: self.combined_scores = normalized_dist_weight Something seems to be missing here. The similarly named self.combined_scores_df is bound to a pandas.DataFrame in the line below. I believe, a line that created a pandas.DataFrame and bound it to self.combined_scores was erroneously deleted.
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87305877
accepted answer of: http://stackoverflow.com/q/50141139
answers question: http://stackoverflow.com/q/50141139
has comment: http://stackoverflow.com/comment/87368396
score: 1

http://stackoverflow.com/q/50164698
upvote count: 3
score: 3
tagged with: anaconda
has title: anaconda3 graphviz - ModuleNotFoundError: No module named 'pygraphviz'
tagged with: graphviz
type: Question
has body: I'm trying to run visualization of Stories (Rasa) by using graphviz I'm using Windows 10, PyCharm, Anaconda3, Python3.6 I tried to goolge some solution about installing graphviz and pygraphviz First solution (doesn't solve the following errors): 1a. conda update matplotlib 1b. conda install -c anaconda graphviz 1c. conda install -c anaconda python-graphviz Second solution (doesn't solve the following errors): 1 . Download and install graphviz-2.38.msi from https://graphviz.gitlab.io/_pages/Download/Download_windows.html 2 . Set the path variable (a) Control Panel &gt; System and Security &gt; System &gt; Advanced System Settings &gt; Environment Variables &gt; Path &gt; Edit (b) add 'C:\Program Files (x86)\Graphviz2.38\bin' 3. run python -m pip install graphviz 4. run python -m pip install git+https://github.com/pygraphviz/pygraphviz.git --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/" Then it returns Failed building wheel for pygraphviz Running setup.py clean for pygraphviz Failed to build pygraphviz Installing collected packages: pygraphviz Running setup.py install for pygraphviz ... error Complete output from command C:\Users\xxxx\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\xxxx\\AppData\\Local\\Temp\\pip-req-build-kh81ij8k\\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\xxxx\AppData\Local\Temp\pip-record-82zdsb0t\install-record.txt --single-version-externally-managed --compile --include-path=/usr/include/graphviz --library-path=/usr/lib/graphviz/: C:\Users\xxxx\Anaconda3\lib\site-packages\setuptools\dist.py:355: UserWarning: Normalizing '1.5.dev' to '1.5.dev0' normalized_version, running install running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\pygraphviz copying pygraphviz\agraph.py -&gt; buil…
downvote count: 0
tagged with: pygraphviz
has answer: http://stackoverflow.com/a/60345296
type: UnansweredQuestion
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/87398719
type: Comment
comment on: http://stackoverflow.com/q/50185897
score: 0
has text: Good question! Its common for each to have their own source repository and not have any hardcoded relationship to each other. Users would `pip install` them and developers would either either `pip install --editable` or `pip install --develop` them. Even if they are in the same repository of other reasons, they are still separate python entities. (This is all my humble opinion of course)
type: QuestionComment

http://stackoverflow.com/comment/87416402
type: Comment
score: 1
has text: Actually i am trying to select all values from df that matches values of sample. Ignoring T2. In this case i would like to compare T1,C,C1,C2,C3
type: QuestionComment
comment on: http://stackoverflow.com/q/50199913

http://stackoverflow.com/q/50204828
has comment: http://stackoverflow.com/comment/87460890
answer count: 1
score: -1
has answer: http://stackoverflow.com/a/58404130
has comment: http://stackoverflow.com/comment/87437543
has title: Unable to retrive G-mail with python3
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: pop3
linked to: http://stackoverflow.com/q/606191
type: UnansweredQuestion
upvote count: 0
has body: I'm unable to find ANY code that will function to retrieve Gmail. import poplib from email import parser SERVER = "pop.gmail.com" USER = "user@gmail.com" PASSWORD = "password" pop_conn = poplib.POP3_SSL(SERVER) pop_conn.user(USER) pop_conn.pass_(PASSWORD) #Get messages from server: messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print(message['subject']) print(message['body']) This produces only: Traceback (most recent call last) <ipython-input-8-e557fa99ae8d> in <module>() 12 messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] 13 # Concat message pieces: ---> 14 messages = ["\n".join(mssg[1]) for mssg in messages] 15 #Parse message intom an email object: 16 messages = [parser.Parser().parsestr(mssg) for mssg in messages] <ipython-input-8-e557fa99ae8d> in <listcomp>(.0) 12 messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] 13 # Concat message pieces: ---> 14 messages = ["\n".join(mssg[1]) for mssg in messages] 15 #Parse message intom an email object: 16 messages = [parser.Parser().parsestr(mssg) for mssg in messages] TypeError: sequence item 0: expected str instance, bytes found I'VE SPENT DAYS trying to do a "simple" e-mail retrieve, and EVERY scrap of code I've found is totally non-functional. Can anyone actually get Gmail, with subjects, etc?
tagged with: python
duplicate of: http://stackoverflow.com/q/606191
tagged with: gmail
tagged with: poplib
has comment: http://stackoverflow.com/comment/87431049

http://stackoverflow.com/a/50214592
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87447633
answers question: http://stackoverflow.com/q/50214084
has comment: http://stackoverflow.com/comment/87447752
has body: Or maybe you don't need a csv in order to work with the Auto Insurance in Sweden dataset: import requests url = 'https://www.math.muni.cz/~kolacek/docs/frvs/M7222/data/AutoInsurSweden.txt' r = requests.get(url, allow_redirects=True) open('AutoInsurSweden.txt', 'wb').write(r.content) with open('AutoInsurSweden.txt') as f: lines_after_11 = f.readlines()[11:] for line in lines_after_11: values = line.split("\t") print("X:"+values[0] + ", Y:"+ values[1])
type: Answer
accepted answer of: http://stackoverflow.com/q/50214084

http://stackoverflow.com/comment/87235269
type: Comment
type: QuestionComment
has text: Yes, I get another content correctly for ample just feed
comment on: http://stackoverflow.com/q/50108314
score: 0

http://stackoverflow.com/q/50109321
score: 1
tagged with: django-models
tagged with: python
tagged with: django-autocomplete-light
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: django
upvote count: 1
favorite count: 0
has title: Django AutoComplete Light not working with OneToOne Field
tagged with: django-views
has body: I am trying to add auto-complete for the OneToOneField in Django admin using django-autocomplete-light. This field is available in Django Rest Framework's auth_token model. class Token(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='auth_token', on_delete=models.CASCADE, verbose_name=_("User") ) created = models.DateTimeField(_("Created"), auto_now_add=True) models.py from rest_framework.authtoken.models import Token class CustomAuthTokenModel(Token): search_fields = ['user', ] def __str__(self): return str(self.user) views.py from dal import autocomplete from rest_framework.authtoken.models import Token class AuthUserAutocompleteView(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Token.objects.all().order_by('user__username') if self.q: qs = qs.filter(user__username__icontains=self.q) return qs admin.py from django.contrib import admin from rest_framework.authtoken.models import Token from rest_framework.authtoken.admin import TokenAdmin from .forms import AuthUserForm class CustomTokenAdmin(TokenAdmin): form = AuthUserForm admin.site.unregister(Token) admin.site.register(Token, CustomTokenAdmin) forms.py from dal import autocomplete from .models import CustomAuthTokenModel class AuthUserForm(autocomplete.FutureModelForm): class Meta: model = CustomAuthTokenModel fields = ('user', ) search_fields = ['user__username'] widgets = { 'user': autocomplete.ModelSelect2(url='autocomplete_auth_user') } And in urls.py file, I have: url('^autocomplete_auth_user/$', AuthUserAutocompleteView.as_view(), name='autocomplete_auth_user') I am pretty sure, I must be missing something, because I can't see the user names while entering the form in admin panel for auth token. Let me know what I am missing. I am using Django 1.11 and django-autocomplete light 3.2.10.

http://stackoverflow.com/a/50229795
answers question: http://stackoverflow.com/q/50229523
has body: You can use pickle to store files on the local disk.It is used for serializing and de-serializing temp = get_list_from_pickle('alerted_dict.pickle') word = {"ikkje": "ikke"} #TAKES INPUT FROM USER; THE WORD IN THE FIRST "LANGUAGE" nynorsk = input("WRITE THE 'NYNORSKE' WORD NOW:") bokmål = input("WRITE THE SAME WORD IN 'BOKMÅL' NOW:") #A FUNCTION THAT ADDS A NEW WORD WITH TRANSLATION TO THE DICTIONARY "word" def add_word(self,var): word[nynorsk] = bokmål add_word(nynorsk, bokmål) with open('alerted_dict.pickle', 'wb') as fp: pickle.dump(temp, fp) print(word) def get_list_from_pickle(filename): try: with open(filename, 'rb') as fp: return pickle.load(fp) except FileNotFoundError: with open(filename, 'wb') as fp: pickle.dump([], fp)
type: Answer
score: 0

http://stackoverflow.com/a/50159650
score: 0
answers question: http://stackoverflow.com/q/50154465
has body: You can compute the maximal separation between entity mentions linked by a relation and choose an input width greater than this distance. This will ensure that every input (relation mention) has same length by trimming longer sentences and padding shorter sentences with a special token.
type: Answer

http://stackoverflow.com/q/50139187
downvote count: 0
has answer: http://stackoverflow.com/a/50139471
has title: Match Key in a Dict to a String
favorite count: 0
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/50139434
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50139360
tagged with: python
possible better answer: http://stackoverflow.com/a/50139360
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87296855
has body: Hello beautiful people! dict = {'Awesome' : 'Sauce', 'Foo' : 'Barr'} Col A Col B 1 'This is Awesome' 2 'I really foo him' I'm trying to find the most pythonic way to iterate over a data set/frame and return any string matches with the value of the dict. so for number 1 i'd like to return Sauce in column c for example, and 2 'barr' in the respective row but in col c. I'm dealing with an csv / excel file if that matters. Any help would be appreciated. I'm happy to use the Pandas and NP library. Edit for Wen: ID Name of Course 0 Super Event Training: English Event... 1 Start with our Maths Training... 2 Live online Biology Training... 3 Maths throughout time... 4 Online Q&amp;A Webinar: History.. 5 Start with our Creative ... 6 Spring Conf with Author 7 Physics in our age ... 8 Spring Conf 9 Start with our educational items... 10 Education delivery in India... 11 English IELTS, Access to University.. 12 Our Core Products for Empowerment.. I have a DF like this that goes on for about 500 rows that I'm scraping with the help of an API, I need to transform this free form text into values that are in my dict. What I've done is identified key words that I've put into my key values and assigned to the dict values, so we can analyse the data. Perhaps using a dict is not the best way to do this? any advice would be much appreciated. DN.
answer count: 4
has answer: http://stackoverflow.com/a/50139511
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50139434
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/97887234

http://stackoverflow.com/a/50097543
has body: Multiple-parse list comprehension This is inefficient compared to the dict and groupby solutions. However, for small lists where performance is not a concern, you can perform a list comprehension which parses the list for each unique identifier. res = [(i, ''.join([j[1] for j in data if j[0] == i])) for i in set(list(zip(*data))[0])] [(1, 'ab'), (2, 'x')] The solution can be split into 2 parts: set(list(zip(*data))[0]) extracts the unique set of identifiers which we iterate via a for loop within the list comprehension. (i, ''.join([j[1] for j in data if j[0] == i])) applies the logic we require for the desired output.
upvote count: 0
score: -3
downvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50086452

http://stackoverflow.com/q/50102481
has answer: http://stackoverflow.com/a/50102610
downvote count: 1
favorite count: 0
has title: DJANGO: create a button that allows to download a zip file
has comment: http://stackoverflow.com/comment/87222270
type: Question
tagged with: http://stackoverflow.com/tag/zip
has answer: http://stackoverflow.com/a/50103160
type: UnansweredQuestion
has body: I've created a little site with django: i'd like to insert a button that allows the user to download a zip file. How could i make it? I can't find the right tool to do that.
tagged with: django
tagged with: python
score: -1
upvote count: 0
answer count: 2
tagged with: button
tagged with: archive

http://stackoverflow.com/a/50140217
type: AcceptedAnswer
has body: With the QFileDialog you only get the name of the file, you must use that information to read the bytes of the file for it use QFile and save that data in BLOBs. In the next part I show an example: import sys from PyQt4.QtGui import * from PyQt4.QtSql import * from PyQt4.QtCore import * def createConnection(): db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName(':memory:') if not db.open(): QMessageBox.critical(None, "Cannot open database", "Unable to establish a database connection.\n" "This example needs SQLite support. Please read the Qt SQL " "driver documentation for information how to build it.\n\n" "Click Cancel to exit.", QMessageBox.Cancel) return False query = QSqlQuery() return query.exec_('''CREATE TABLE IF NOT EXISTS imgTable (id INTEGER primary key AUTOINCREMENT, filename TEXT, imagedata BLOB)''') class Widget(QWidget): def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) vbox = QVBoxLayout(self) self.load_btn = QPushButton("Select Image") self.combo = QComboBox() self.label = QLabel() self.model = QSqlTableModel() self.model.setTable("imgTable") self.model.select() self.combo.setModel(self.model) self.combo.setModelColumn(1) vbox.addWidget(self.load_btn) vbox.addWidget(self.combo) vbox.addWidget(self.label) self.load_btn.clicked.connect(self.load_image) self.combo.currentIndexChanged.connect(self.on_change_select) def on_change_select(self, row): ix = self.combo.model().index(row, 2) pix = QPixmap() pix.loadFromData(ix.data()) self.label.setPixmap(pix) def load_image(self): fname = QFileDialog.getOpenFileName(self, 'Open file', QDir.currentPath(), "Image files (*.jpg, *.gif, *.png)") if fname: self.saveImage(fname) def saveImage(self, filename): file = QFile(filename) if not file.open(QIODevice.ReadOnly): return ba = file.readAll() name = QFileInfo(filename).fileName() record = self.model.record() record.setValue("filename", name) record.setValue("imagedata", ba) if self.model.insertRecord(-1, record): self.model.select…
answers question: http://stackoverflow.com/q/50133693
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50133693
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87315418

http://stackoverflow.com/comment/133963423
has text: @PrithviBoinpally the latter—calling `mypath.mkdir(exist_ok=True)` will not raise an error, and will leave the existing directory associated with `mypath` intact.
type: Comment
score: 4
comment on: http://stackoverflow.com/a/50110841
type: AnswerComment

http://stackoverflow.com/comment/87352367
score: 0
comment on: http://stackoverflow.com/a/50153215
type: AnswerComment
has text: i am considering [b'top-L', ' '] as one so i have 9 elements so it can be arranged, but then i might not able to access "top-L" and " " values individually, right?
type: Comment

http://stackoverflow.com/comment/87232940
score: 0
type: Comment
type: QuestionComment
has text: friend you have any tips.
comment on: http://stackoverflow.com/q/50106975

http://stackoverflow.com/q/50162098
has answer: http://stackoverflow.com/a/50162213
has title: How to scan a json file for a certain string? With Python
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87342059
has comment: http://stackoverflow.com/comment/87342146
type: Question
score: 0
type: UnansweredQuestion
has body: I am using the json libary with the following code: config = json.load(open("config/config.json")) to load my json file. However I cannot find out how to scan this file for a certain string. The code in this file is: [ { "name": "SID", "path": "/", "domain": test.com } ] I'm trying to make an if statement that if test.com is the set domain it does one thing but if not it does another. Help is appreciated
has comment: http://stackoverflow.com/comment/87342122
has comment: http://stackoverflow.com/comment/87342099
answer count: 1
tagged with: python

http://stackoverflow.com/a/50104773
upvote count: 8
type: Answer
score: 8
has body: I was able to resolve this (thanks to Goyo) by replacing both .pack and .grid geometry managers with the .place geometry manager i.e I added :- self.button.place(relwidth = 0.07, relheight = 0.03, relx = 0.489, rely = 0.243) and self.entry.place(relwidth=0.07, relheight=0.03, relx=0.489, rely=0.276) what that did was allowed me to specify the location to place the widget and the button and tied their size to the relative size of my window.Another thing I added as a quality of life issue was to post the location of the cursor on the gui using this code(special thanks to unutbu's answer here on stack overflow):- def motion(event): x, y = event.x, event.y print('{}, {}'.format(x, y)) #in ms root.bind('&lt;Motion&gt;', motion) root.mainloop() This printed the co-ordinates of the location I wanted, so that I could properly position my buttons and edit text widget
answers question: http://stackoverflow.com/q/50098072
downvote count: 0

http://stackoverflow.com/comment/87170551
comment on: http://stackoverflow.com/q/50077084
type: QuestionComment
score: 0
has text: @RoryDaulton Done, thanks for the feedback
type: Comment

http://stackoverflow.com/q/50120062
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/50120297
accepted answer: http://stackoverflow.com/a/50120096
tagged with: arrays
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50120096
has title: Cutting numpy array based on index
favorite count: 0
tagged with: optimization
possible better answer: http://stackoverflow.com/a/50120297
type: AnsweredQuestion
score: 1
has body: I have a 1D numpy array. The difference between two succeeding values in this array is either one or larger than one. I want to cut the array into parts for every occurrence that the difference is larger than one. Hence: arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) should become [array([77, 78, 79, 80]), array([90, 91, 92]), array([100, 101, 102, 103, 104])] I have the following code that does the trick but I have the feeling I am being to complicated here. There has to be a better/more pythonic way. Anyone with a more elegant approach? import numpy def split(arr, cut_idxs): empty_arr = [] for idx in range(-1, cut_idxs.shape[0]): if idx == -1: l, r = 0, cut_idxs[0] elif (idx != -1) and (idx != cut_idxs.shape[0] - 1): l, r = cut_idxs[idx] + 1, cut_idxs[idx + 1] elif idx == cut_idxs.shape[0] - 1: l, r = cut_idxs[-1] + 1, arr.shape[0] empty_arr.append(arr[l:r + 1]) return empty_arr arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) cuts = numpy.where(numpy.ediff1d(arr) &gt; 2)[0] print split(arr, cuts)

http://stackoverflow.com/comment/87352702
score: 1
type: Comment
has text: You could also point out that `+=` and friends can "make an implicit copy" (e.g., `tup += ()`). Of course what's actually happening is the `__iadd__` or `__add__` method making a copy, followed by assignment not making a copy—but people coming from C++ are sometimes mislead by this behavior.
type: AnswerComment
comment on: http://stackoverflow.com/a/50167512

http://stackoverflow.com/q/50158883
has title: Using loc to replace values gives error
has answer: http://stackoverflow.com/a/50158971
has answer: http://stackoverflow.com/a/50158937
possible better answer: http://stackoverflow.com/a/50158937
tagged with: dataframe
tagged with: python
has body: My code looks like: import pandas as pd df = pd.read_excel("Energy Indicators.xls", header=None, footer=None) c_df = df.copy() c_df = c_df.iloc[18:245, 2:] c_df = c_df.rename(columns={2: 'Country', 3: 'Energy Supply', 4:'Energy Supply per Capita', 5:'% Renewable'}) c_df['Energy Supply'] = c_df['Energy Supply'].apply(lambda x: x*1000000) print(c_df) c_df = c_df.loc[c_df['Country'] == ('Korea, Rep.')] = 'South Korea' When I run it, I get the error "'str' has no attribute 'loc'". It seems like it is telling me that I can't use loc on the dataframe. All I want to do is replace the value so if there is an easier way, I am all ears.
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50158971
type: Question

http://stackoverflow.com/q/50186384
answer count: 0
tagged with: web-scraping
tagged with: beautifulsoup
has body: My urllib is not particularly downloading the image from following url. Otherwise urllib is working fine. It is downloading images from other urls too. please help me out. thanks in advance import urllib urllib.urlretrieve("https://media.ed.edmunds-media.com/acura/ilx/2018/evox/2018_acura_ilx_sedan_technology-plus-package_tds3_evox_2_500.jpg","E:/crawler/a.jpg")
has comment: http://stackoverflow.com/comment/87392780
has comment: http://stackoverflow.com/comment/87390485
has comment: http://stackoverflow.com/comment/87393010
type: Question
has comment: http://stackoverflow.com/comment/87392717
has title: Downloading images using python
tagged with: python
type: UnansweredQuestion
tagged with: urllib
has comment: http://stackoverflow.com/comment/87390313
score: 0
has comment: http://stackoverflow.com/comment/87390490

http://stackoverflow.com/comment/87271675
type: QuestionComment
has text: have you tried anything yet? do all CSVs have similar data and operations to be performed? do you overwrite initial CSV file?
type: Comment
comment on: http://stackoverflow.com/q/50126843
score: 1

range
tags question: http://stackoverflow.com/q/50114208
tags question: http://stackoverflow.com/q/50184575
type: Tag
tags question: http://stackoverflow.com/q/50128514
tag name: range

http://stackoverflow.com/q/50127821
tagged with: web-scraping
tagged with: web-crawler
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87273418
type: UnansweredQuestion
has body: I tried to write a program that can automatically down files (with php links). However, I have two issue right now First, my target website requires registration for the first time access. Then, every time when I clicked the download link, it automatically downloads the file I want. It looks like searched some cookies that saved on my computer to determine who I am. How to make my python program deal with my local cookies? if multiples? Second, can anyone provide me an example code about how to deal with php download link file? I want to save all these files on a specific location with a specific name. How should I do that in python3?
has answer: http://stackoverflow.com/a/50128496
tagged with: python
tagged with: php
score: 2
upvote count: 2
has title: how to make Python3 web scraping program deal with local cookies?
answer count: 1
downvote count: 0
tagged with: session-cookies

http://stackoverflow.com/q/50127352
tagged with: sed
score: 1
has comment: http://stackoverflow.com/comment/87315088
downvote count: 0
has comment: http://stackoverflow.com/comment/87300308
tagged with: shell
upvote count: 1
has comment: http://stackoverflow.com/comment/87314550
has comment: http://stackoverflow.com/comment/87298260
has title: find difference between old and new mapping for each clientId
has comment: http://stackoverflow.com/comment/87336996
has comment: http://stackoverflow.com/comment/87303301
favorite count: 0
has comment: http://stackoverflow.com/comment/87273198
type: Question
has comment: http://stackoverflow.com/comment/87274334
tagged with: linux
possible better answer: http://stackoverflow.com/a/50135993
has comment: http://stackoverflow.com/comment/87304221
accepted answer: http://stackoverflow.com/a/50163124
has comment: http://stackoverflow.com/comment/87323957
has comment: http://stackoverflow.com/comment/87315857
tagged with: python
has answer: http://stackoverflow.com/a/50135993
has answer: http://stackoverflow.com/a/50163124
has comment: http://stackoverflow.com/comment/87277189
has comment: http://stackoverflow.com/comment/87273097
has comment: http://stackoverflow.com/comment/87304904
has comment: http://stackoverflow.com/comment/87274378
type: AnsweredQuestion
has body: I have mappings file like this as shown below: new_primary_mapping.txt {1=[343, 0, 686, 1372, 882, 196], 2=[687, 1, 1373, 883, 197, 736, 1030, 1569], 3=[1374, 2, 884, 737, 198, 1570]} new_secondary_mapping.txt {1=[1152, 816, 1488, 336, 1008], 2=[1153, 0, 817, 337, 1489, 1009, 1297], 3=[1, 1154, 1490, 338]} In the above mapping files, each clientId has new primary and new secondary mapping. For example: clientId 1 has 343, 0, 686, 1372, 882, 196 new primary mapping and 1152, 816, 1488, 336, 1008 new secondary mapping. Similarly for other clientIds as well. Below is my script which prints arrays for each clientId: #!/bin/bash mapfiles=(new_primary_mapping.txt new_secondary_mapping.txt) declare -a arr mappingsByClientID () { id=$1 # 1 to 5 file=${mapfiles[$2]} # 0 to 1 arr=($(sed -r "s/.*\b${id}=\[([^]\]+).*/\1/; s/,/ /g" $file)) echo "${arr[@]}" } # assign output of function to an array # and get mapping for clientId 3 pri=($(mappingsByClientID 3 0)) snd=($(mappingsByClientID 3 1)) # print whole array echo "whole arr pri: ${pri[@]}" echo "whole arr snd: ${snd[@]}" Now I have two other files as shown below which has old mapping for same clientId's. old_primary_mapping.txt {1=[686, 1372, 882, 196], 2=[883, 197, 736, 1030, 1569], 3=[1374, 2, 884, 737]} old_secondary_mapping.txt {1=[1488, 336, 1008], 2=[817, 337, 1489, 1009, 1297], 3=[1490, 338]} Problem Statement Now I need to read all four files and for each clientId I need to figure out what is not common (meaning difference) between new and old mapping. For example: clientId 1 has 343, 0, 686, 1372, 882, 196 new primary mapping and 1152, 816, 1488, 336, 1008 new secondary mapping. Also clientId 1 has 686, 1372, 882, 196 old primary mapping and 1488, 336, 1008 old secondary mapping. So I will make a pri array which will have this entry: 343 0 and sec array which will have this entry: 1152 816. Because these are the difference between old and new mapping for each clientId. How can I do that in shell script? Is this poss…
has comment: http://stackoverflow.com/comment/87274112
answer count: 2
tagged with: bash

http://stackoverflow.com/q/50112086
has title: Reindex a series output doesn't match pandas example in the documentation
type: AnsweredQuestion
score: 0
has body: I have a series like the following. In [53]: aStack Out[53]: Age_cat S0102_gender _1 Male 167.047843 Female 211.292291 All 378.340134 _2 Male 132.055426 Female 171.780338 All 303.835764 All Male 299.103269 Female 383.072629 All 682.175898 dtype: float64 In [54]: I would like to convert the series to something that looks like this. In [53]: aStack Out[53]: Age_cat S0102_gender _1 Male 167.047843 _1 Female 211.292291 _2 All 378.340134 _2 Male 132.055426 _2 Female 171.780338 _2 All 303.835764 All Male 299.103269 All Female 383.072629 All All 682.175898 I have a list of tuples. combos Out[54]: [('_1', 'Male'), ('_1', 'Female'), ('_1', 'All'), ('_2', 'Male'), ('_2', 'Female'), ('_2', 'All'), ('All', 'Male'), ('All', 'Female'), ('All', 'All')] According to the documentation. If I run, aStack.reindex(combos) I should get that output. However, when I run the instruction, I get the same output as my input. What am I missing?
tagged with: pandas
has answer: http://stackoverflow.com/a/50112227
accepted answer: http://stackoverflow.com/a/50112227
tagged with: python
tagged with: multi-index
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50112370
has answer: http://stackoverflow.com/a/50112370

python-multithreading
tags question: http://stackoverflow.com/q/50191406
tags question: http://stackoverflow.com/q/50104669
tags question: http://stackoverflow.com/q/50131596
tag name: python-multithreading
tags question: http://stackoverflow.com/q/50136143
tags question: http://stackoverflow.com/q/50120089
tags question: http://stackoverflow.com/q/50123140
tags question: http://stackoverflow.com/q/50133484
type: Tag

http://stackoverflow.com/a/50133387
has body: You wrote None in that case as string. Remove the quotes ' df = pd.DataFrame([{'A':None,'B':False,'C':1,'D':'a','E':np.NaN,'F':True,'G':'a','H':np.NaN},{'A':1,'B':2,'C':3,'D':None,'E':1,'F':True,'G':'b'}, ...) If you cannot modify the df, replace the string: df = df.replace({'None':'New_Value'})
type: Answer
accepted answer of: http://stackoverflow.com/q/50133254
score: 0
answers question: http://stackoverflow.com/q/50133254
type: AcceptedAnswer

http://stackoverflow.com/q/50164258
has comment: http://stackoverflow.com/comment/87346618
type: AnsweredQuestion
has title: How to replace ™ in a string?
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87346532
answer count: 3
upvote count: 2
score: 2
has body: I have a string looks like this: Getting Started with NetX™ DHCP rev1.05 I want to replace TM with %E2%84%A2. I added:# -- coding: utf-8 -- to the very top of the file, still not work, no errors pop up I am using Python 2.7 Here's my python code: def create_link(title): temp_title = title.replace(' ', '%20') # first replace space with %20. works fine temp_title.replace('™', '%E2%84%A2') # then replace TM, not working link = 'https://ApplicationNotes/'+ temp_title return link
possible better answer: http://stackoverflow.com/a/50164302
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/50164302
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/87346515
type: Question
has comment: http://stackoverflow.com/comment/87346528
accepted answer: http://stackoverflow.com/a/50164424
has answer: http://stackoverflow.com/a/50164424
tagged with: python-unicode
tagged with: python
has answer: http://stackoverflow.com/a/50164528

http://stackoverflow.com/comment/87447709
comment on: http://stackoverflow.com/a/50181564
type: Comment
type: AnswerComment
score: 0
has text: @Python_newbie I'm glad we got it sorted out in the end. :)

http://stackoverflow.com/a/50220935
score: 3
upvote count: 3
downvote count: 0
has body: I would suggest using a combination of: How do I capture SIGINT in Python? and How can I explicitly free memory in Python? #!/usr/bin/env python import signal import sys import gc def signal_handler(signal, frame): print('Cleaning up...') gc.collect() print('Bye.') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) signal.pause()
type: Answer
answers question: http://stackoverflow.com/q/50220796

http://stackoverflow.com/comment/87306423
has text: No no no no no. Use [`getattr`](https://docs.python.org/3/library/functions.html#getattr).
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50144068

http://stackoverflow.com/q/50180751
tagged with: python-3.x
type: Question
linked to: http://stackoverflow.com/q/50176661
has title: How to fill a QHBoxLayout to align multiple QGroupBox'es without creating filling buttons?
tagged with: python
linked to: http://stackoverflow.com/q/44230856
has answer: http://stackoverflow.com/a/50181916
tagged with: pyqt
type: AnsweredQuestion
score: 0
tagged with: layout
has body: I got this layout: But I would like to the first text box to be aligned with the second like this: But without have to have to create a useless button just to fill in the space. This is the minimal example code I come up with: import sys from PyQt5 import QtGui from PyQt5 import QtWidgets from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * def main(): app = QtWidgets.QApplication(sys.argv) programWindow = ProgramWindow() programWindow.show() sys.exit(app.exec_()) class ProgramWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setup_main_window() self.first_input_text() self.second_input_text() self.set_window_layout() def setup_main_window(self): self.resize( 800, 600 ) self.centralwidget = QWidget() self.setCentralWidget( self.centralwidget ) def first_input_text(self): self.textEditWidget1 = QPlainTextEdit( self ) self.startSimulationButton1 = QPushButton( "Start Simulation" ) self.startSimulationButtonDumb = QPushButton( "Start Simulation fillingg" ) verticalInnerLayout = QVBoxLayout() verticalInnerLayout.addWidget( self.startSimulationButton1 ) verticalInnerLayout.addWidget( self.startSimulationButtonDumb ) horizontalInnerLayout = QHBoxLayout() horizontalInnerLayout.addLayout( verticalInnerLayout ) horizontalInnerLayout.addWidget( self.textEditWidget1 ) self.groupBox1 = QGroupBox( "First Group" ) self.groupBox1.setLayout( horizontalInnerLayout ) def second_input_text(self): self.textEditWidget2 = QPlainTextEdit( self ) self.startSimulationButton2 = QPushButton( "Start Simulation bigger" ) verticalInnerLayout = QVBoxLayout() verticalInnerLayout.addWidget( self.startSimulationButton2 ) horizontalInnerLayout = QHBoxLayout() horizontalInnerLayout.addLayout( verticalInnerLayout ) horizontalInnerLayout.addWidget( self.textEditWidget2 ) self.groupBox2 = QGroupBox( "Second Group" ) self.groupBox2.setLayout( horizontalInnerLayout ) def set_window_layout(self): main_vertical_layout = QVBoxLayout( sel…
answer count: 2
tagged with: pyqt5
linked to: http://stackoverflow.com/q/49127653
linked to: http://stackoverflow.com/q/4963220
accepted answer: http://stackoverflow.com/a/50182031
linked to: http://stackoverflow.com/q/19011464
possible better answer: http://stackoverflow.com/a/50181916
has answer: http://stackoverflow.com/a/50182031

http://stackoverflow.com/q/50092701
has title: python element wise operation in function
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
has body: In python, I am trying to change the values of np array inside the function def function(array): array = array + 1 array = np.zeros((10, 1)) function(array) For array as function parameter, it is supposed to be a reference, and I should be able to modify its content inside function. array = array + 1 performs element wise operation that adds one to every element in the array, so it changes inside values. But the array actually does not change after the function call. I am guessing that the program thinks I am trying to change the reference itself, not the content of the array, because of the syntax of the element wise operation. Is there any way to make it do the intended behavior? I don't want to loop through individual elements or make the function return the new array.
has answer: http://stackoverflow.com/a/50092725
tagged with: python
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/77914246
answer count: 3
has answer: http://stackoverflow.com/a/50092720

http://stackoverflow.com/q/50165911
type: Question
has title: difference between two dates in azure ml
type: UnansweredQuestion
tagged with: azure
tagged with: python
score: -1
tagged with: pandas
has answer: http://stackoverflow.com/a/50166061
upvote count: 0
answer count: 1
has body: I am trying to find difference between two dates in terms of number of days. I am trying the following code d1=pd.to_datetime(dataframe1['Order Date']) d=str(d1) dates=datetime.strptime(d,'%m-%d-%Y') d2=pd.to_datetime(dataframe1['Dispatch Date']) dd=str(d2) dates1=datetime.strptime(dd,'%m-%d-%Y') dataframe1['Months_difference']=dates1-dates But it's being displaying the error like this: ValueError: time data '0 2017-02-13\n1 2017-02-24\n2 2017-03-02\n3 2017-03-06\n4 2017-03-06\n5 2017-03-06\n6 2017-03-11\n7 2017-03-23\n8 2017-03-23\n9 2017-03-24\n10 2017-04-07\n11 2017-04-07\n12 2017-04-07\n13 2017-04-07\n14 2017-04-07\n...\n855 2018-02-02\n856 2018-02-02\n857 2018-02-02\n858 2018-02-02\n859 2018-02-02\n860 2018-02-01\n861 2018-02-06\n862 2018-03-15\n863 2018-03-21\n864 2018-03-21\n865 2018-04-05\n866 2018-04-07\n867 2018-04-07\n868 2018-04-11\n869 2018-04-10\nName: Order Date, Length: 870, dtype: datetime64[ns]' does not match format '%m-%d-%Y' Process returned with non-zero exit code 1 How to solve this
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50140323
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/50140915
type: Question
has comment: http://stackoverflow.com/comment/87298924
tagged with: fractions
has title: Calculating large fractions in Python?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87298906
has answer: http://stackoverflow.com/a/50140888
has comment: http://stackoverflow.com/comment/87298979
has body: I am trying to calculate fractions in Python 2.7. The limit_denominator method works great for the first 15 iterations of this code. However, then the code gets stuck in a loop, outputting denominators less than 1,000,000 Fraction = 1217471/860882 When I don't use limit_denominator, I get repeat outputs like this: Fraction = 141421356237/100000000000 Eventually I want to iterate i to 1000, so my fractions will be very large. Any help? from fractions import * i = 0 x = 1/2.0 x1 = 0 count = 0 while i &lt; 20: (y) = (1.0 + (x)) (x) = (1 / (2.0 + (x))) y1 = Fraction(str(y)).limit_denominator() print("\nFraction = " + str(y1)) i += 1
has answer: http://stackoverflow.com/a/50140477
score: 0

http://stackoverflow.com/comment/87411546
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50155584
score: 0
has text: Hi again,Thanks for your help. I'm trying now all the options and have no success.. My case is that I have 2 folders with .py files inside, some of the files in the folders import functions from other etc. How can I include these two folders with all their files in the path?

http://stackoverflow.com/q/50123485
has comment: http://stackoverflow.com/comment/87265126
has body: I have some data and a date column. By running the command below, it goes through the DF and counts all the events happened during that week. df['date'].groupby(df.date.dt.to_period("W")).agg('count') The result is something like: 2018-04-16/2018-04-22 40 2018-04-23/2018-04-29 18 The weeks starts on Monday and end Sunday. I want the week to start on Sunday and end on Saturday. So, the data should be 2018-04-15/2018-04-21 40 2018-04-22/2018-04-28 18
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87265303
answer count: 2
possible better answer: http://stackoverflow.com/a/50123567
tagged with: pandas
upvote count: 2
has answer: http://stackoverflow.com/a/50123567
downvote count: 0
has title: Pandas Start Week on Sunday when Using Group By for Dates and counting events in the period
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50123582
has answer: http://stackoverflow.com/a/50123582
tagged with: dataframe
tagged with: python
tagged with: date

http://stackoverflow.com/q/50218054
favorite count: 0
has comment: http://stackoverflow.com/comment/87455579
has answer: http://stackoverflow.com/a/50218495
type: Question
has comment: http://stackoverflow.com/comment/87455941
tagged with: tuples
tagged with: list
has answer: http://stackoverflow.com/a/50232135
tagged with: python
has comment: http://stackoverflow.com/comment/87455052
has body: I was wondering if it is possible to print a value that is inside a list of lists of tuples if you already know the indexes path. 1. List[i][j] 2. list2[x][y] 3. list3[z][w] 4. etc. I would like to do something like this: str( list[i][0 [0][2 [0][0]] ) To get the value at indexes 0,0 in the tuple at indexes 0,2 of a list at indexes i,0 of the main list. Edit: Sorry, I'm learning. Console returns this: [Record(items=set({'item1','item2'}), id=6439, stats=[OrderedStatistic(items_b=set({'item2'}), items_a=set({'item1'}), row=123, col=321)]), Record(... I'm looking for the "row" value. I didn't know it had a name, it wasn't showed in my viewer. Edit 2: Improvement. It works, but I'm using a temporary variable because oldList[0].stats[0].row returns a 'stats' object has no attribute row. for i in range(0, len(oldList)): tmpList = oldList[i][2] newList.append('ID:\t' + str(oldList[i][1])+ '\nROW:\t' + str(tmpList[0][2]) or for i in range(0, len(oldList)): tmpList = oldList[i][2] newList.append('ID:\t' + str(oldList[i][1])+ '\nROW:\t' + str(tmpList[0].row)
has comment: http://stackoverflow.com/comment/87453127
has comment: http://stackoverflow.com/comment/87459768
tagged with: namedtuple
has comment: http://stackoverflow.com/comment/87453111
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/87454997
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87453107
has title: Python: specific value in a named tuple of a list of tuples
downvote count: 1

http://stackoverflow.com/comment/87194090
score: 0
has text: To my best understanding of the question, you want to set the `level` to something other than `level=logging.DEBUG`
comment on: http://stackoverflow.com/q/50089015
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87264719
has text: Have it return a HTTPResponse of Hello World. Does that work?
comment on: http://stackoverflow.com/q/50123129
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87421589
comment on: http://stackoverflow.com/a/50202419
score: 0
type: Comment
has text: But `foo.x=22` does the same thing. And if you do `x=[22]` you do assign a dynamic object. "dynamic" is a property of the object assigned, not the assignment.
type: AnswerComment

http://stackoverflow.com/comment/87397974
has text: I tried now this code: with open("classifications.txt", "a") as myfile: np.savetxt(myfile, npaClassifications) with open("flattened_images.txt", "a") as myfile: np.savetxt(myfile, npaFlattenedImages) It seems to work but Im not completely sure whether the classifications and flattended images files work better than before.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50185383

http://stackoverflow.com/q/50137697
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: can i use fuzzy wuzzy in columns of dataframe for performing operations
has comment: http://stackoverflow.com/comment/87312740
has comment: http://stackoverflow.com/comment/87312897
tagged with: pandas
tagged with: dataframe
score: 1
has body: I am new to DataFrame and python please help me in this, I have a dataframe with looks like: index col1 col2 col3 0 A1 B1 C1 1 A1 B1 C2 2 A2 B1 C3 3 A3 B2 C4 4 A2 B1 C5 5 A4 B3 C6 6 A1 B1 C7 and i want to add more columns in this dataframe after few operations, which should look like index col1 col2 col3 count 0 A1 B1 C1 1 1 A1 B1 C2 2 2 A2 B1 D3 1 3 A3 B2 C4 1 4 A2 B1 D5 2 5 A4 B3 D6 1 6 A1 B1 C1 3 The values of this count column increases like a counter only when col1 &amp; col2 &amp; (values of col3 matches more than or equal to 50%) if these 3 conditions are true only then the counter should increase. Do i have to use FuzzyWuzzy? like: col1 col2 col3 count 0 A1 B1 C1 1 1 A1 B1 C 2 (Matches) (Matches) (Matches 50%)
favorite count: 0
has comment: http://stackoverflow.com/comment/87312981
type: Question

http://stackoverflow.com/comment/87313391
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50147302
type: Comment
has text: It is more idiomatic. `join` is often used when you want to concat several stings with a separator (e.g. space, comma). And you can use `re.sub` and `re.split`, both of them allows you to specify regex.

http://stackoverflow.com/q/50139114
tagged with: greenlets
answer count: 0
tagged with: google-cloud-platform
has title: Greenlet not installing to lib directory
has body: I'm trying to deploy my app to Google Cloud Platform, which requires me to install all dependencies in the project directory. To do so, I ran pip install -t lib -r requirements.txt, but it didn't work for some of the modules. For example, gevent is installed in the lib directory (there is a subdirectory lib/gevent), but greenlet is not. The only subdirectory that I get is lib/greenlet-0.4.13.dist-info, and there is a file lib/greenlet.pyd. As a result, the Cloud Platform is not detecting greenlet, and I get an import error. I have tried uninstalling it and installing manually using pip install -t lib greenlet, but I get the same result. How do I get it to install properly?
has comment: http://stackoverflow.com/comment/88944746
tagged with: pip
has comment: http://stackoverflow.com/comment/88944965
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/87177337
has text: How is `Pre Available` supposed to be calculated?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50080530

http://stackoverflow.com/comment/87551118
score: 0
has text: Did you installed the gdal binaries or did you compile them? This error could be related to an ABI issue between the libstdc++ used to compile gdal and the one that is present in your system, especially if it is an old version of Red Hat.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50183550

http://stackoverflow.com/comment/87240854
score: 0
has text: @Nishitha literally what Jordan said
type: QuestionComment
comment on: http://stackoverflow.com/q/50111591
type: Comment

http://stackoverflow.com/comment/87405548
type: Comment
has text: Repeating to ensure understanding: **This substitution cipher can be broken very easily**.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50192975

http://stackoverflow.com/q/50137029
answer count: 2
score: 0
possible better answer: http://stackoverflow.com/a/75336637
tagged with: glib
accepted answer: http://stackoverflow.com/a/50137918
has answer: http://stackoverflow.com/a/75336637
has body: When I need a part of my program that has GLib timeout functions set with self.timeout_id = GLib.timeout_add_seconds(refresh, self._check_price) I use def stop(self): if self.timeout_id: GLib.source_remove(self.timeout_id) to make sure this timeout_id still exists before attempting to remove it. Yet I still get these pesky error messages from time to time: Warning: Source ID 443 was not found when attempting to remove it GLib.source_remove(self.timeout_id) how do?
type: AnsweredQuestion
has title: Avoiding warning from GLib with GLib.source_remove()
tagged with: python
has answer: http://stackoverflow.com/a/50137918
type: Question

http://stackoverflow.com/comment/87463110
score: 1
type: QuestionComment
type: Comment
has text: Unrelated to your question. You are aware that `frame.pack` is _not_ a function call and does not pack anything, aren't you?
comment on: http://stackoverflow.com/q/50222747

tree
tags question: http://stackoverflow.com/q/50161648
tags question: http://stackoverflow.com/q/50187087
tags question: http://stackoverflow.com/q/50213116
type: Tag
tag name: tree
tags question: http://stackoverflow.com/q/50109047
tags question: http://stackoverflow.com/q/50125658
tags question: http://stackoverflow.com/q/50164830

http://stackoverflow.com/q/50228699
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50230642
tagged with: apache-kafka
has body: I have been using AIOKafka for some time, I had no problems with it, until today. Strange TypeError shows up when I try to send a message using AIOKafkaProducer.send_and_wait. I also posted this question as issue on AIOKafka's github repository, but it looks like they are kind of inactive. Maybe here someone can help me. here is the code: import asyncio from aiokafka import AIOKafkaConsumer, AIOKafkaProducer loop = asyncio.get_event_loop() producer = AIOKafkaProducer(loop=loop, bootstrap_servers="localhost:9092") async def _initialize(prod, future): await prod.start() await prod.send_and_wait("main_topic", str.encode("hello!!")) future = asyncio.Future() task = asyncio.ensure_future(_initialize(producer, future)) loop.run_until_complete(task) print("loop ended!") loop.close() here is the error message I get: yilmazali@yilmazali:~$ python3 aiokafkatest.py Unexpected error in sender routine Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/aiokafka/producer/producer.py", line 374, in _sender_routine task.result() File "/usr/local/lib/python3.6/dist-packages/aiokafka/producer/producer.py", line 418, in _send_produce_req response = yield from self.client.send(node_id, request) File "/usr/local/lib/python3.6/dist-packages/aiokafka/client.py", line 415, in send request, expect_response=expect_response) File "/usr/local/lib/python3.6/dist-packages/aiokafka/conn.py", line 165, in send message = header.encode() + request.encode() File "/usr/local/lib/python3.6/dist-packages/kafka/util.py", line 159, in __call__ return self.method()(self.target(), *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/kafka/protocol/struct.py", line 42, in _encode_self [self.__dict__[name] for name in self.SCHEMA.names] File "/usr/local/lib/python3.6/dist-packages/kafka/protocol/types.py", line 132, in encode for i, field in enumerate(self.fields) File "/usr/local/lib/python3.6/dist-packages/kafka/protocol/types.py", line 132, in &lt;listcomp&gt; for i, fi…
tagged with: python-asyncio
tagged with: python
accepted answer: http://stackoverflow.com/a/50230642
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/50505225
has title: AIOKafka: Formerly working code now fails at send_and_wait
downvote count: 0
has answer: http://stackoverflow.com/a/50505225
score: 1
upvote count: 1

http://stackoverflow.com/q/50106651
tagged with: pandas-groupby
has title: Pandas compute datetime diff, but for each user
tagged with: pandas
score: 1
tagged with: group-by
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/50106962
favorite count: 0
type: Question
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50106962
has body: Dataset is related to time user spent on viewing items: user_id item_id view_started 121 160 2015-10-20 17:02:02 231 160 2015-10-18 11:02:29 231 161 2015-10-18 11:05:23 121 166 2015-10-18 11:04:34 231 180 2015-10-18 11:06:16 121 182 2015-10-20 17:02:10 134 182 2015-10-18 11:02:53 124 185 2015-10-18 11:04:23 231 187 2015-10-18 11:04:45 124 190 2015-10-18 11:05:43 The goal is to create time spent viewing (or Gap Between Viewing Item) item by the user per item. user_id item_id minutes 121 160 4320 ... The difference should get calculated between the immediate item that user has viewed. Example: X1, X2, X3 | Time between X1-X2, X2-X3... and for each group time needs to be reset. I believe using diff is not the right approach. df.groupby(['user_id']).apply( lambda x: x.sort_values(['view_started'], ascending = True))['view_started'].diff() This gives the first value NaT. Time difference should get reset per group (per user) * Time probably don't reflect the above data frame due to sort 0 NaT 1 0 days 00:08:58 2 0 days 00:04:51 3 0 days 00:06:46 4 0 days 17:05:03 5 0 days 00:00:51 6 -9 days +10:21:49 7 0 days 00:02:33
type: AnsweredQuestion

win32com
tags question: http://stackoverflow.com/q/50119565
tag name: win32com
tags question: http://stackoverflow.com/q/50152251
tags question: http://stackoverflow.com/q/50138212
type: Tag
tags question: http://stackoverflow.com/q/50195314
tags question: http://stackoverflow.com/q/50127959

http://stackoverflow.com/q/50088343
has title: Python3 date and time formatting
has answer: http://stackoverflow.com/a/50088451
has body: I'm using an API that sends a date in a wierd format "YYYY-MM-DDTHH:MM:SSZ". So the date comes out as 2018-04-27T23:59:18Z, I have never seen a date and time formatted like this. Its a string and I would like to format it as MM-DD-YYYY HH:MM:SS. I can't even wrap my head around removing the T and Z. Any help would be appreciated! Thanks in advance!
tagged with: python
accepted answer: http://stackoverflow.com/a/50088451
has answer: http://stackoverflow.com/a/50088441
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 3
has comment: http://stackoverflow.com/comment/87193209
downvote count: 1
possible better answer: http://stackoverflow.com/a/50088402
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50088402
has comment: http://stackoverflow.com/comment/87192513

http://stackoverflow.com/comment/87332879
has text: What databases do you want to check?
type: Comment
comment on: http://stackoverflow.com/q/50157501
score: 0
type: QuestionComment

http://stackoverflow.com/comment/95156322
has text: Strings will create problems with `Sequence` because they are considered a sequence, even a single character string, so you will need to guard against strings, e.g. `if isinstance(e, Sequence) and not isinstance(e, str)` you would have the same issue with `bytes` if you use them.
type: AnswerComment
comment on: http://stackoverflow.com/a/50127241
score: 1
type: Comment

http://stackoverflow.com/q/50189866
has comment: http://stackoverflow.com/comment/87396695
has comment: http://stackoverflow.com/comment/87397082
score: 0
has comment: http://stackoverflow.com/comment/87396913
tagged with: while-loop
has comment: http://stackoverflow.com/comment/87396790
has comment: http://stackoverflow.com/comment/87396784
tagged with: pandas
has comment: http://stackoverflow.com/comment/87396609
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87397098
tagged with: jupyter-notebook
type: Question
linked to: http://stackoverflow.com/q/34398054
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87397094
upvote count: 1
has title: While true, pandas dataframe won't show?
downvote count: 1
has body: Using Jupyter Notebook, if I put in the following code: import pandas as pd df = pd.read_csv('path/to/csv') while True: df The dataframe won't show. Can anyone tell me why this is the case? I'm guessing it's because the constant looping is preventing the dataframe from loading fully. Is that what's happening here? I need code that would let me get a user's input. If they type in a name, for example, I'll extract the person with that name's info from the dataframe and display it, then the program needs to ask them to give another name. This will continue until they type in "quit". I figured a while loop would be the best for that, but it looks like there's just something about while loops and pandas that won't mix. Does anyone have any suggestions on what I can do instead?
favorite count: 0
has comment: http://stackoverflow.com/comment/87397086

http://stackoverflow.com/a/56080656
score: 20
downvote count: 0
upvote count: 20
type: Answer
answers question: http://stackoverflow.com/q/50202829
has body: enter cmd+shft+p Python: Select Interpreter Enter your version

http://stackoverflow.com/q/50074853
score: 2
has title: Reading 5th TIFF's channel in Python?
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: nuke
answer count: 1
tagged with: maya
has answer: http://stackoverflow.com/a/50076180
favorite count: 0
type: Question
tagged with: tiff
tagged with: python
accepted answer: http://stackoverflow.com/a/50076180
has body: I have some TIFF files that are the output of a Maya renderer, and I need to composite them with some real footage. The TIFF files have 5 channels, rgba + depth channel for compositing. However, all the TIFF loading libraries I have tried seem to discard the 5th layer. Is there a way to load this with the rest of the image?

http://stackoverflow.com/q/50083362
type: Question
tagged with: network-programming
type: UnansweredQuestion
tagged with: python-sockets
tagged with: sockets
has title: How to get http server response on a different device in LAN?
tagged with: python
has body: I am new to python and my networking logics are at the beginner level. I have an HTTP server running in a VM and when I curl it from a different terminal on the same machine, I get the expected response. I am looking for a functionality where I can get the same response on my mobile device when I type the ip and port in the browser. My mobile device is connected to the same WiFi. Here's the server code: import socket MAX_PACKET = 32768 def recv_all(sock): r'''Receive everything from `sock`, until timeout occurs, meaning sender is exhausted, return result as string.''' # dirty hack to simplify this stuff - you should really use zero timeout, # deal with async socket and implement finite automata to handle incoming data prev_timeout = sock.gettimeout() try: sock.settimeout(0.01) rdata = [] while True: try: rdata.append(sock.recv(MAX_PACKET)) except socket.timeout: return ''.join(rdata) # unreachable finally: sock.settimeout(prev_timeout) def normalize_line_endings(s): r'''Convert string containing various line endings like \n, \r or \r\n, to uniform \n.''' return ''.join((line + '\n') for line in s.splitlines()) def run(): r'''Main loop''' # Create TCP socket listening on 10000 port for all connections, # with connection queue of length 1 server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, \ socket.IPPROTO_TCP) server_sock.bind(('10.0.2.15',80)) server_sock.listen(1) while True: # accept connection client_sock, client_addr = server_sock.accept() # headers and body are divided with \n\n (or \r\n\r\n - that's why we # normalize endings). In real application usage, you should handle # all variations of line endings not to screw request body request = normalize_line_endings(recv_all(client_sock)) # hack again request_head, request_body = request.split('\n\n', 1) # first line is request headline, and others are headers request_head = request_head.splitlines() request_headline = request_head[0] # headers have their name up to first ': '. In real world uses, they…
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87186830
has comment: http://stackoverflow.com/comment/87182642
tagged with: http

http://stackoverflow.com/a/50204757
has comment: http://stackoverflow.com/comment/87427447
has comment: http://stackoverflow.com/comment/87426996
score: 2
has comment: http://stackoverflow.com/comment/87427370
upvote count: 2
has comment: http://stackoverflow.com/comment/87451531
type: AcceptedAnswer
downvote count: 0
has body: You can do this by overriding save method in your Model class Clean(models.Model): name = models.CharField(max_length=100) cv = models.TextField(max_length=10000, blank = True, null = True) cvfile = models.FileField() def save(self, *args, **kwargs): get_text = self.cvfile.open().read() self.cv = get_text super(Clean, self).save(*args, **kwargs) # Call the "real" save() method. Or by Using post_save signal def writeCV(sender, instance, **kwargs): get_text = instance.cvfile.open().read() instance.cv = get_text instance.save() post_save.connect(writeCV, sender=Clean)
has comment: http://stackoverflow.com/comment/87435407
has comment: http://stackoverflow.com/comment/87446812
has comment: http://stackoverflow.com/comment/87427144
accepted answer of: http://stackoverflow.com/q/50204566
has comment: http://stackoverflow.com/comment/87426713
has comment: http://stackoverflow.com/comment/87427261
answers question: http://stackoverflow.com/q/50204566
type: Answer
has comment: http://stackoverflow.com/comment/87452193

setup.py
tags question: http://stackoverflow.com/q/50097534
tags question: http://stackoverflow.com/q/50083553
tags question: http://stackoverflow.com/q/50134329
tags question: http://stackoverflow.com/q/50142020
tags question: http://stackoverflow.com/q/50101740
tag name: setup.py
type: Tag
tags question: http://stackoverflow.com/q/50084303

http://stackoverflow.com/comment/87300622
has text: @Darkwilmore Did you add the `.item()` at the end of the sQ calculation?! It won't work otherwise.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50140929
type: AnswerComment

http://stackoverflow.com/q/50082612
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50092209
has body: I'm using selenium on a Python script to get some data and execute some scripts on a javascript/ajax rendered website, which means some buttons or scripts will change the DOM without loading a new page or changing the URL. The situation is: as soon as the page is loaded, I execute the following script: driver1.execute_script("javascript:changeOption('a', 'b','otherPage.html');") changeOption is a script written directly inside the script tags of the HTML. It works, and the script will cause the DOM to change. Now, the DOM has changed and there are new scripts written directly on the HTML, which I can clearly see inside Chrome's inspector "Elements" tab. I wait some seconds and try to run one of the new scripts: driver1.execute_script("javascript:filterOption(0);") And I get an error! It says this script 'filterOption' doesn't exist. After some investigation, I notice selenium isn't recognising that the DOM has changed and that there are new elements and scripts inside the page! That's why it says the new script doesn't exist. What I've tried so far: Implicit and explicit waits. Neither worked. time.sleep(), with several seconds, before executing the second script. Didn't work either. Forcibly try to execute the script with "try...except" statement inside a while loop. Never works, always goes to the exception. Checked whether the page selenium is 'seeing' is the updated page, by executing again the first script, checking for some elements, waiting for new elements to appear etc. No, it isn't: selenium really hasn't noticed the DOM was updated, that's for sure. I did some research here and on the documentation looking for some way to force selenium to read the DOM again without refreshing the page, because refreshing would cause it to go back to the very first page and lose all the changes. It looks like there is no way to do it and every single answer I found was different and didn't work. Do you have any suggestions of what I could do so Selenium will notice there …
downvote count: 0
answer count: 1
tagged with: selenium
has title: Selenium in Python doesn't recognise changes in the DOM even after waiting
favorite count: 0
has comment: http://stackoverflow.com/comment/87181551
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87181760
has comment: http://stackoverflow.com/comment/87200364
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/50148270
has title: Unable to run audit2allow located in android source code
score: 3
upvote count: 3
tagged with: android-source
has comment: http://stackoverflow.com/comment/87553365
tagged with: python
has comment: http://stackoverflow.com/comment/92881211
has answer: http://stackoverflow.com/a/69271828
has body: Location of audit2allow python script is external/selinux/prebuilts/bin/audit2allow When I try to run the script, I get the following error: Traceback (most recent call last): File "/home/shobhit/Desktop/Code/aosp/msm8909_android/external/selinux/policycoreutils/audit2allow/audit2allow", line 24, in &lt;module&gt; import sepolgen.audit as audit File "/home/shobhit/Desktop/Code/aosp/msm8909_android/prebuilts/python/linux-x86/2.7.5/lib/python2.7/site-packages/sepolgen/audit.py", line 20, in &lt;module&gt; import refpolicy File "/home/shobhit/Desktop/Code/aosp/msm8909_android/prebuilts/python/linux-x86/2.7.5/lib/python2.7/site-packages/sepolgen/refpolicy.py", line 22, in &lt;module&gt; import selinux File "/home/shobhit/Desktop/Code/aosp/msm8909_android/prebuilts/python/linux-x86/2.7.5/lib/python2.7/site-packages/selinux/__init__.py", line 28, in &lt;module&gt; _selinux = swig_import_helper() File "/home/shobhit/Desktop/Code/aosp/msm8909_android/prebuilts/python/linux-x86/2.7.5/lib/python2.7/site-packages/selinux/__init__.py", line 24, in swig_import_helper _mod = imp.load_module('_selinux', fp, pathname, description) ImportError: /home/shobhit/Desktop/Code/aosp/msm8909_android/prebuilts/python/linux-x86/2.7.5/lib/python2.7/site-packages/selinux/_selinux.so: undefined symbol: selabel_partial_match
tagged with: selinux
downvote count: 0
has comment: http://stackoverflow.com/comment/87708845
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87518261
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50169361
answer count: 0
has comment: http://stackoverflow.com/comment/87382203
tagged with: function
type: UnansweredQuestion
tagged with: alias
type: Question
linked to: http://stackoverflow.com/q/19562356
score: 0
has comment: http://stackoverflow.com/comment/87356898
has comment: http://stackoverflow.com/comment/87357577
tagged with: python
linked to: http://stackoverflow.com/q/8744113
has body: So I have a 4 dimensional array, and a really simple function to aid with grabbing elements from said array. Board=[[ [['K','D','S'] , ['T','R','T'] , ['X','B','R']], [['P','P','P'] , ['P','P','P'] , ['P','P','P']], [['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'] , ['0','0','0'] , ['0','0','0']] ],[ [['0','0','0'] , ['0','0','0'] , ['0','0','0']], [['p','p','p'] , ['p','p','p'] , ['p','p','p']], [['j','r','x'] , ['t','r','t'] , ['s','d','d']] ]] def GrabAPeice(title): BigLet={'A':0,'B':1,'C':2,'D':3,'E':4} SmallLet={'a':0,'b':1,'c':2,'d':3,'e':4} BigNum={'5':0,'4':1,'3':2,'2':3,'1':4} SmallNum={'5':0,'4':1,'3':2,'2':3,'1':4} return Board[BigNum[title[2]]][SmallNum[title[4]]][BigLet[title[0]]][SmallLet[title[1]]] Where title would be something like 'Aa1:2' respectively The only problem is when I try to use the function for assignment, GrabAPeice('Bb2:2')='Q' it does not let me assign a value. Is it possible to have a function return a reference or an alias to another object in python? I know about get and set functions and I really won't use them.
tagged with: reference
has title: How do I return a modifiable alias python function?
tagged with: return

http://stackoverflow.com/a/50176834
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50176661
has body: The proper way to use QMainWindow is having a "centralWidget", set this central widget with your layout , and you got it. See setCentralWiget

http://stackoverflow.com/q/50082843
has title: Python Equivalent of Scheme/Lisp CAR and CDR Functions
tagged with: higher-order-functions
favorite count: 0
type: Question
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50083066
tagged with: python
has comment: http://stackoverflow.com/comment/87200299
has comment: http://stackoverflow.com/comment/87182414
has comment: http://stackoverflow.com/comment/87193539
has body: I am currently trying to implement fold/reduce in Python, since I don't like the version from functools. This naturally involved implementing something like the Lisp CDR function, since Python doesn't seem to have anything like it. Here is what I am thinking of trying: def tail(lat): # all elements of list except first acc = [] for i in range(1,len(lat)): acc = acc + [lat[i]] Would this be an efficient way of implementing this function? Am I missing some kind of built-in function? Thanks in advance!
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87196185

http://stackoverflow.com/a/53756452
type: Answer
has comment: http://stackoverflow.com/comment/94365657
score: 0
has body: def max_min(): my_list = [] for i in range(1, 6): temp_val = input("Enter number {}: ".format(i)) my_list.append(int(temp_val)) max_val = max(my_list) min_val = min(my_list) return "max value is {} and min value is {}".format(max_val, min_val) print(max_min())
answers question: http://stackoverflow.com/q/50100161

http://stackoverflow.com/comment/87394224
score: 0
type: Comment
type: QuestionComment
has text: If I do it like this in the command line it works. There's no error.
comment on: http://stackoverflow.com/q/50186375

http://stackoverflow.com/a/50233226
accepted answer of: http://stackoverflow.com/q/50229777
score: 0
has body: You are almost there. Expand dimensions and use broadcasting to perform the operation for each feature simultaneously: aux = tf.subtract(A_feature[None, :, :], P_feature[:, None, :]) # Shape=(5, 10, feat_dim) aux = tf.reduce_sum(tf.square(aux), -1) # Shape=(5, 10) P_dist3 = tf.norm(aux, ord=2, axis=-1) # Shape=(5,) with tf.Session() as sess: pos_dist3_np = sess.run(P_dist3) Note that this works both when A_feature and P_feature are NumPy arrays and TensorFlow tensors.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50229777
has comment: http://stackoverflow.com/comment/87506153
type: Answer

http://stackoverflow.com/comment/87453813
type: QuestionComment
score: 1
has text: If you are worried about performance try to use native pyspark functions as much as possible. Having example data would be helpful, but one potential workaround would be to use pyspark's `explode()` function on your time series column then do a `groupby` on the date column and utilize pyspark's `mean` and `stddev` functions.
comment on: http://stackoverflow.com/q/50215791
type: Comment

http://stackoverflow.com/comment/87366675
score: 2
comment on: http://stackoverflow.com/q/50174445
type: QuestionComment
has text: The README for parquet-python says "currently with only read-support"
type: Comment

http://stackoverflow.com/q/50131489
tagged with: django
tagged with: python
has body: I'm on a dockerized Django 1.11 and want to run my longstanding test suite parallel now: manage.py test mainfolder --parallel -v2 Though it fails 2 minutes into my test suite (after all so-far run tests succeeded) with a pickle error. The stack trace however does not give me an indication where it occurs. How could I get closer to what fails it? tblib is installed. test_foo (myapp.some.testmodule.SomeTestCase) ... ok Traceback (most recent call last): File "./myapp/manage.py", line 34, in &lt;module&gt; execute_from_command_line() File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/var/venv-stable/lib/python2.7/site-packages/django/test/runner.py", line 603, in run_tests result = self.run_suite(suite) File "/var/venv-stable/lib/python2.7/site-packages/django/test/runner.py", line 567, in run_suite return runner.run(suite) File "/usr/lib/python2.7/unittest/runner.py", line 151, in run test(result) File "/usr/lib/python2.7/unittest/suite.py", line 70, in __call__ return self.run(*args, **kwds) File "/var/venv-stable/lib/python2.7/site-packages/django/test/runner.py", line 370, in run subsuite_index, events = tes…
tagged with: unit-testing
favorite count: 0
type: AnsweredQuestion
has title: Django 1.11: What fails `pickle` in my parallel test run?
accepted answer: http://stackoverflow.com/a/50230640
answer count: 1
has answer: http://stackoverflow.com/a/50230640
upvote count: 6
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/87372459
type: Question
has comment: http://stackoverflow.com/comment/87282454
has comment: http://stackoverflow.com/comment/87282184
has comment: http://stackoverflow.com/comment/87282676
has comment: http://stackoverflow.com/comment/87345266
downvote count: 0
score: 6

http://stackoverflow.com/a/68010469
answers question: http://stackoverflow.com/q/50190676
type: Answer
score: 0
has body: Next I share you our Dockerfile which builds Ok with Python 3.9 and Alpine 3.13. This is meant to work with a Postgresql 12 via SQLAlchemy. It was very helpful the Kevin Smith post here, but with some add ons. FROM python:3.9-alpine3.13 ENV MAIN_DIR=/home/my_dir RUN mkdir &quot;${MAIN_DIR}&quot; WORKDIR &quot;${MAIN_DIR}&quot; RUN apk add --no-cache --update \ python3-dev gcc \ gfortran musl-dev g++ \ libffi-dev openssl-dev \ libxml2 libxml2-dev \ libxslt libxslt-dev \ libjpeg-turbo-dev zlib-dev \ libpq postgresql-dev \ COPY /requirements.txt &quot;${MAIN_DIR}&quot; RUN pip install --upgrade cython \ &amp;&amp; pip install --upgrade pip \ &amp;&amp; pip install -r requirements.txt And the requirements.txt: pandas==1.2.3 SQLAlchemy==1.4.11 psycopg2-binary

http://stackoverflow.com/comment/87201135
has text: Possible duplicate of [Error message: "'chromedriver' executable needs to be available in the path"](https://stackoverflow.com/questions/29858752/error-message-chromedriver-executable-needs-to-be-available-in-the-path)
comment on: http://stackoverflow.com/q/50091420
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50159089
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/87359035
linked to: http://stackoverflow.com/q/34957283
favorite count: 0
tagged with: xampp
has comment: http://stackoverflow.com/comment/87383138
downvote count: 0
score: 1
has body: I am using PHP and XAMPP. I have enabled port localhost:8080 and I want to execute a python script (Main.py) from my PHP script (index.php). My PHP script is located at: /Users/User/.bitnami/stackman/machines/xampp/volumes/root/htdocs/index.php and the Python script is located at: /Users/User/.bitnami/stackman/machines/xampp/volumes/root/htdocs/Main.py. My Python script is the following: print('Hello World') My PHP script is the following: &lt;?php $output = exec('/usr/local/bin/python3 /Users/User/.bitnami/stackman/machines/xampp/volumes/root/htdocs/Main.py ' . ' 2&gt;&amp;1'); var_dump($output); ?&gt; (/usr/local/bin/python3 is the output of which python3 at the terminal) However, the output that I am getting at localhost:8080 is: string(40) "sh: 1: /usr/local/bin/python3: not found" I have also tested different variations of my line with exec() by writing for example exec('/Users/User/.bitnami/stackman/machines/xampp/volumes/root/htdocs/Main.py ' . ' 2&gt;&amp;1') but nothing returns the right output. What am I doing wrong and how can I fix it? I am aware of similar posts on StackOverflow (Running a Python script from PHP, Can&#39;t execute Python script from PHP document, Python Script Failing to Execute from PHP exec(), How to properly call Python 3 script from PHP?) but none of this works as such for me. I am wondering if my problem is related to the fact that I did not make any configuration to run the Python script on XAMPP as it is described at some posts here (Running Python scripts with Xampp).
linked to: http://stackoverflow.com/q/15594946
has comment: http://stackoverflow.com/comment/87365978
linked to: http://stackoverflow.com/q/42704846
type: Question
answer count: 0
has title: Python script is not executed from PHP script on local server
linked to: http://stackoverflow.com/q/32598420
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87383031
linked to: http://stackoverflow.com/q/19735250
has comment: http://stackoverflow.com/comment/87344836

http://stackoverflow.com/comment/87278681
type: Comment
comment on: http://stackoverflow.com/a/50130121
score: 0
type: AnswerComment
has text: If only I had found that other article that makes mine a duplicate before asking the question, sorry about that!

http://stackoverflow.com/comment/87282976
comment on: http://stackoverflow.com/a/50132327
type: Comment
has text: But that is the whole point of a Pool. You run fetch_pending_updates and get a new pending_updates list, then you will use pool.map to map this new list to the pool. Trust me, it works. Move your pool definition outside your loop, keep your code exactly as it is and you will see. It works. Your list gets mapped at pool.map, not at pool creation. You can use pool.map as many times as you want, with a different iterable as a parameter.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50205997
downvote count: 0
answer count: 1
has body: I am wondering how I can define a function that allows the range to be set to whatever the starting index is for a certain list. For example: def pTrend(stock): pTrend = [] for x in range(0, len(stock)): if x &gt; 0: print('This') if x &lt; 0: print('That') I have lists of stock data, and the first one is from range(0, 250) and the next is from (250, 500) and etc.. how could i create a function that sets the start at the range = to the particular index of each stock i will be plugging in?
has answer: http://stackoverflow.com/a/50206027
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87429142
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87430577
has title: How To Set A Range That Has An Unknown Starting Index
tagged with: python
has comment: http://stackoverflow.com/comment/87429553
has comment: http://stackoverflow.com/comment/87429168
has comment: http://stackoverflow.com/comment/87457554

http://stackoverflow.com/q/50106516
type: Question
has answer: http://stackoverflow.com/a/50111966
answer count: 2
has body: I'm using K-Means for extracting topics from text. I know it is not the best way but this is just one step towards a more complex model. What puzzles me is the elbow curve I get (below). How would you interpret it? Why is there a sudden spike around 50 K? Or the elbow method doesn't really work when dealing with text? from sklearn.cluster import MiniBatchKMeans wcse = [] for k in range(5, 100, 5): kmeans_model = MiniBatchKMeans(n_clusters=num_clusters, init='k-means++', n_init=1, init_size=1000, batch_size=1000, verbose=False, max_iter=1000) kmeans = kmeans_model.fit(X) # where X is my data wcse.append(kmeans_.inertia_) #plot it fig = plt.figure(figsize=(15, 5)) plt.plot(range(5, 100, 5), wcse) plt.grid(True) plt.title('Elbow curve')
type: UnansweredQuestion
tagged with: k-means
tagged with: cluster-analysis
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50106733
has title: K-Means for topic modelling - Elbow method
favorite count: 0

http://stackoverflow.com/comment/87382040
has text: @abarnert How can I recovery these privileges to plain pip?
score: 0
comment on: http://stackoverflow.com/q/50182155
type: Comment
type: QuestionComment

pywin32
tags question: http://stackoverflow.com/q/50212849
tags question: http://stackoverflow.com/q/50074881
tags question: http://stackoverflow.com/q/50089607
tag name: pywin32
tags question: http://stackoverflow.com/q/50157943
type: Tag
tags question: http://stackoverflow.com/q/50121282

http://stackoverflow.com/comment/87192499
comment on: http://stackoverflow.com/q/50088215
has text: This is a Pandas question in that you need to ensure the function is returning copies. But this is mostly a Python question and is explained by @roganjosh’s link. This is as close to a dupe target as we can get https://stackoverflow.com/q/240178/2336654
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50089338
favorite count: 0
type: Question
tagged with: network-programming
type: UnansweredQuestion
tagged with: sockets
tagged with: python
tagged with: raw-sockets
answer count: 0
score: 1
has title: send ip raw packet in python error
has body: Why i can't send the packet? I want to send a raw ip packet Usage: python ip.py {Source-IP} {Destination-IP} {IFACE} Here my code: #! /usr/bin/python import socket import struct import sys def Create_SOCKET(): global ST try: ST = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) except socket.error as MSG: print "[ERROR] Socket creation error:\n", MSG sys.exit() def IP_HEADER(Source_IP, Destination_IP): global IP_PACKET #Variable validation IP_VER = 4 IP_IHL = 5 IP_TOS = 0 IP_TOL = 60 IP_IDT = 54331 IP_FLG = 2 # 0x02 DF IP_FOS = 0 IP_TTL = 64 IP_PROTO = socket.IPPROTO_TCP IP_CHECKSUM = 0 IP_IHL_VER = (IP_VER &lt;&lt; 4) + IP_IHL SRC_IP = socket.inet_aton(Source_IP) DST_IP = socket.inet_aton(Destination_IP) IP_PACKET = struct.pack("!BBHHHBBH4s4s", IP_IHL_VER, IP_TOS, IP_TOL, IP_IDT, IP_FOS, IP_TTL, IP_PROTO, IP_CHECKSUM, SRC_IP, DST_IP) def Send_PACKET(IFACE): try: Create_SOCKET() ST.bind((IFACE, 0)) ST.send(IP_PACKET) print "[SUCESS] Packet was sent." except socket.error as MSG: print "[ERROR] Packet can't send:\n", MSG sys.exit() IP_HEADER(sys.argv[1], sys.argv[2]) Send_PACKET(sys.argv[3]) This is output: Traceback (most recent call last): File "ip.py", line 52, in &lt;module&gt; Send_PACKET(sys.argv[3]) File "ip.py", line 43, in Send_PACKET ST.bind((IFACE, 0)) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.gaierror: [Errno -2] Name or service not known How can fix it? I think this error come from binding function port. I can send it with this fortmat : ST.sendto(IP_PACKET, ("192.168.1.100", 0)) Why i can't use the send() function? Thanks for your help//
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87236633
type: Comment
type: QuestionComment
has text: Yes, the text file shows the state name followed by the town names and universities (I don't need the universities, which I need to eliminate later in the data cleaning process.)
comment on: http://stackoverflow.com/q/50107276
score: 0

http://stackoverflow.com/a/50197869
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50197686
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50197686
has body: Notice that the sum over k in your expression only affects the first factor, while the sum over l only involves the second: sum_{k=1,...,n} sum_{l=1,...,n} A[i, k] * A[j, l] = (sum_{k=1,...,n} A[i, k]) * (sum_{l=1,...,n} A[j, l]) The expressions in parentheses are, except for the names of the indices, the same, so define sA = np.sum(A, axis=1) Then your B is the so-called outer product of sA with itself: B = np.outer(sA, sA)

http://stackoverflow.com/comment/87319333
comment on: http://stackoverflow.com/q/50150813
type: QuestionComment
has text: Can you post a sample of your text?
score: 0
type: Comment

http://stackoverflow.com/comment/87224480
type: AnswerComment
score: 1
type: Comment
has text: Doesn't work anyway :( Could be a problem of the name of ~/.pypirc?
comment on: http://stackoverflow.com/a/50103611

http://stackoverflow.com/q/50148814
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to get the Firefox profile path dynamically in Python?
tagged with: firefox
has comment: http://stackoverflow.com/comment/87315715
tagged with: python
upvote count: 4
type: AnsweredQuestion
score: 2
answer count: 2
has body: data_path = "C:\\Users\\Cortex\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\5cfpvg5b.default" Is there any way get this file path dynamically? Here,5cfpvg5b.default is not same for every computer.
downvote count: 2
has answer: http://stackoverflow.com/a/71111512
possible better answer: http://stackoverflow.com/a/71111512
has answer: http://stackoverflow.com/a/50150471
accepted answer: http://stackoverflow.com/a/50150471

http://stackoverflow.com/comment/87431043
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50206065
has text: did you replace group(2) with group(3) as in above?

http://stackoverflow.com/q/50092205
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87200861
has comment: http://stackoverflow.com/comment/87200759
has comment: http://stackoverflow.com/comment/87200895
tagged with: wrapper
has comment: http://stackoverflow.com/comment/87200640
score: 1
has comment: http://stackoverflow.com/comment/87200785
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87200936
has comment: http://stackoverflow.com/comment/87200879
accepted answer: http://stackoverflow.com/a/50092377
upvote count: 1
has body: I have this situation: module1.py: class AudioEngine: def __init__(self): self.liverecording = False def getaudiocallback(self): def audiocallback(in_data, frame_count, time_info, status): # these 4 parameters are requested by pyaudio data = None # normally here we process the audio data if self.liverecording: print("Recording...") return data return audiocallback main.py: import module1 a = module1.AudioEngine() f = a.getaudiocallback() f(0, 0, 0, 0) a.liverecording = True f(0, 0, 0, 0) # prints "Recording...", which is the expected behaviour, but why does it work? Question: How to make the callback function audiocallback(...) change accordingly to the new value of a.liverecording? If it works out of the box, why does it? More specifically, does f, once created with f = a.getaudiocallback(), keep in his code a pointer to a.liverecording (so if the latter is modified, this will be taken into consideration), or a copy of the value of a.liverecording (i.e. False) at the time of the creation of f?
tagged with: import
has answer: http://stackoverflow.com/a/50092377
favorite count: 0
type: Question
has title: How can a class generate a callback function, that changes according to a class attribute?
has comment: http://stackoverflow.com/comment/87201059
has comment: http://stackoverflow.com/comment/87200675
has comment: http://stackoverflow.com/comment/87200870
has comment: http://stackoverflow.com/comment/87200683
linked to: http://stackoverflow.com/q/2005956
tagged with: python-module
tagged with: python
has comment: http://stackoverflow.com/comment/87200751
has comment: http://stackoverflow.com/comment/87200800
has comment: http://stackoverflow.com/comment/87200817
has comment: http://stackoverflow.com/comment/87200619
tagged with: class
has comment: http://stackoverflow.com/comment/87200705

http://stackoverflow.com/comment/87262566
comment on: http://stackoverflow.com/q/50122268
has text: have you tried: `print(program_duration.total_seconds() * 11.4)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50095160
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87206451
type: Answer
answers question: http://stackoverflow.com/q/50095114
upvote count: 1
has body: encoded_str = unicode_str.encode("ascii",'ignore') This line of your code encodes your text as ascii. Ascii does not contain special characters such as é or à. I am not sure why you decode from UTF8, which includes those characters, to ascii, which doesn't contain them.
downvote count: 1
has comment: http://stackoverflow.com/comment/87206531
accepted answer of: http://stackoverflow.com/q/50095114
score: 0

http://stackoverflow.com/a/50147435
type: Answer
has body: Also, I write a tool class to mimic "with" statements in matlab. helper.py: class With(object): def __init__(self, obj): self._obj = obj self._p = self._obj.__enter__() def __del__(self): self._obj.__exit__(None, None, None) def get(self): return self._p Matlab: with_vs = py.helper.With(py.tensorflow.variable_scope('X')); with_vs.get().name ... clear with_vs;
score: 0
answers question: http://stackoverflow.com/q/50128336

http://stackoverflow.com/a/50141805
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
has body: I eventually figured out that NODE_PATH is set to &lt;myproject&gt;/venv/lib/node_modules. If I put my package.json file in venv/lib/ then run npm install from this directory, I can use npx babel from any folder in the project.
accepted answer of: http://stackoverflow.com/q/50139016
upvote count: 2
answers question: http://stackoverflow.com/q/50139016

http://stackoverflow.com/q/50211488
has comment: http://stackoverflow.com/comment/87440106
type: Question
has comment: http://stackoverflow.com/comment/87439995
has comment: http://stackoverflow.com/comment/87442241
has answer: http://stackoverflow.com/a/50212430
score: 2
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87440104
downvote count: 1
has title: How to add two nested python dictionaries?
has answer: http://stackoverflow.com/a/50217186
favorite count: 0
has body: a= {u'1009': {u'Avg': 188, u'amount_spent': 2820, u'size': 15, u'users': {u'0': 346041, u'1': 658546, u'2': 658194, u'3': 658316 }}, u'1056': {u'Avg': 140, u'amount_spent': 140, u'size': 1, u'users': {u'0': 645767}}, u'1103': {u'Avg': 95, u'amount_spent': 285, u'size': 3, u'users': {u'0': 339285, u'1': 658440}} b = {u'1009': {u'Avg': 246.25, u'amount_spent': 1970, u'size': 8, u'users': {u'0': 61496, u'1': 1350, u'2': 164852, u'3': 517760, u'4': 576458, u'5': 203840, u'6': 52239, u'7': 516672}}, u'1056': {u'Avg': 170, u'amount_spent': 680, u'size': 4, u'users': {u'0': 503737, u'1': 624418, u'2': 642471}}} I have multiple nested dictionaries, which I wanted to merge and add by their inner keys, so my output looked something like this. c = {u'1009': {u'Avg': 434.25, u'amount_spent': 4790, u'size': 23, u'users': {u'0': 61496, u'1': 1350, u'2': 164852, u'3': 517760, u'4': 576458, u'5': 203840, u'6': 52239, u'7': 516672, u'8': 346041, u'9': 658546, u'10': 658194, u'11': 658316 }},,,,, The idea is to just add the values for the keys that are already present. If they aren't just add the new key instead. Adding them with + opperand doesn't work. Any idea on how i could do this ? EDIT1: A lot of the issues in merging the users key was due to the values being user_id themselves. Hence they can't be added, rather just appended in the users key. One way to solve this issue was through making the value for users key as an array : {u'1009': {u'Avg': 188, u'amount_spent': 2820, u'size': 15, u'users': [346041, 658546, 658194, 658316]}, u'1056': {u'Avg': 140, u'amount_spent': 140, u'size': 1, u'users': [645767]} Hope this helps!
answer count: 3
has comment: http://stackoverflow.com/comment/87481553
tagged with: python
has answer: http://stackoverflow.com/a/50212997
has comment: http://stackoverflow.com/comment/87440162

http://stackoverflow.com/a/56945420
score: 0
has body: Also it's possible to create data migration which set initial order for already created model. def reorder(apps, schema_editor): Tag = apps.get_model("main", "Tag") for order, item in enumerate(Tag.objects.all()): item.order = order item.save() class Migration(migrations.Migration): dependencies = [ ('main', '0011_auto_20190517_1336'), ] operations = [ migrations.RunPython(reorder, RunPython.noop),
answers question: http://stackoverflow.com/q/50133222
type: Answer

http://stackoverflow.com/q/50168719
accepted answer: http://stackoverflow.com/a/50240117
has title: Python load library from different platform (Windows, Linux or OS X)
has body: I am a Python beginner from C language. Now I have plan to implement a cross platform project with Python + C library (ctypes) running on Windows, Linux and OS X and I have win32.dll, win64.dll, mac_osx.so linux.so files ready. How to load them by a single Python (.py) file? My idea is to use Python OS or platform module to check environment, like this (sorry this is not the real Python program): if Windows and X86 then load win32.dll else if Windows and X64 then load win64.dll else if OSX then load osx.so else if Linux then load linux.so Are there any simple and clear way to do this work?
favorite count: 0
type: Question
tagged with: ctypes
score: 6
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/50240117
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87354843
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50143741
tagged with: python-3.x
tagged with: conditional-statements
possible better answer: http://stackoverflow.com/a/50143873
has answer: http://stackoverflow.com/a/50143873
tagged with: dataframe
has body: I'm trying to create a new dataframe column that acts as a running variable that resets to zero or "passes" under certain conditions. Below is a simplified example of what I'm looking to accomplish. Let's say I'm trying to quit drinking coffee and I'm tracking the number of days in a row i've gone without drinking any. On days where I forgot to make note of whether I drank coffee, I put "forgot", and my tally does not get influenced. Below is how i'm currently accomplishing this, though I suspect there's a much more efficient way of going about it. Thanks in advance! import pandas as pd Day = [1,2,3,4,5,6,7,8,9,10,11] DrankCoffee = ['no','no','forgot','yes','no','no','no','no','no','yes','no'] df = pd.DataFrame(list(zip(Day,DrankCoffee)), columns=['Day','DrankCoffee']) df['Streak'] = 0 s = 0 for (index,row) in df.iterrows(): if row['DrankCoffee'] == 'no': s += 1 if row['DrankCoffee'] == 'yes': s = 0 else: pass df.loc[index,'Streak'] = s
tagged with: python
accepted answer: http://stackoverflow.com/a/50143892
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50143962
has title: Python Pandas: Create Column That Acts As A Conditional Running Variable
has answer: http://stackoverflow.com/a/50143892
answer count: 3
tagged with: pandas
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87305983
favorite count: 0
type: Question

http://stackoverflow.com/comment/102427720
type: Comment
type: QuestionComment
score: 0
has text: Looks like if a column is named 'labels', `df.labels` returns the error: `AttributeError: 'DataFrame' object has no attribute 'labels'` but `df['labels']` works perfectly fine.
comment on: http://stackoverflow.com/q/50099922

http://stackoverflow.com/a/50144651
has comment: http://stackoverflow.com/comment/87442645
type: Answer
has comment: http://stackoverflow.com/comment/87449140
score: 0
has comment: http://stackoverflow.com/comment/87427770
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50144570
has body: It might not be the best answer but I always convert the data I want to export as csv to a pandas dataframe. This solution also works well for unequal list values. data1 = pd.DataFrame(dict_data["Data 1"]) data2 = pd.DataFrame(dict_data["Data 2"]) master = pd.concat([data1, data2], axis=1) master.to_csv("file_name", encoding='utf-8', index=False, header=None)
accepted answer of: http://stackoverflow.com/q/50144570

http://stackoverflow.com/q/50197056
tagged with: pip
has title: pip not recognizing "-r" command
has comment: http://stackoverflow.com/comment/87411077
favorite count: 0
upvote count: 5
has answer: http://stackoverflow.com/a/66060652
tagged with: python
has comment: http://stackoverflow.com/comment/87411133
has body: I am new to using flask, and I am trying to set it up on my computer through terminal. I download pip/python3, create a virtual environment and then activate it. Then I try running "pip install –r requirements.txt". When I do this, I get a huge error written in red, most of which is a traceback. But the first line says: "Invalid requirement: '–r'" I don't understand how -r is an invalid argument? What am I doing wrong? This is the command everyone says to use, so I assume I made a mistake earlier.
type: Question
has comment: http://stackoverflow.com/comment/87411059
has comment: http://stackoverflow.com/comment/87420549
score: 5
has comment: http://stackoverflow.com/comment/87411139
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/a/57892171
has comment: http://stackoverflow.com/comment/120212745
answers question: http://stackoverflow.com/q/50186904
downvote count: 0
score: 19
has body: Otherwise, you can try this one if you want only pathlib: from pathlib import Path def rm_tree(pth: Path): for child in pth.iterdir(): if child.is_file(): child.unlink() else: rm_tree(child) pth.rmdir() rm_tree(your_path)
upvote count: 19
type: Answer
has comment: http://stackoverflow.com/comment/120317378

http://stackoverflow.com/comment/87172695
type: QuestionComment
has text: @MarkRotteveel: and it got approved by two reviewers ...
type: Comment
comment on: http://stackoverflow.com/q/50075291
score: 1

http://stackoverflow.com/comment/87175534
score: 0
type: AnswerComment
has text: Ah... sort remaining maybe what I was looking for.
comment on: http://stackoverflow.com/a/50078347
type: Comment

http://stackoverflow.com/q/50116318
score: 3
tagged with: python
tagged with: web-crawler
type: Question
tagged with: pypdf
has body: I am trying to extract this text: DLA LAND AND MARITIME ACTIVE DEVICES DIVISION PO BOX 3990 COLUMBUS OH 43218-3990 USA Name: Desmond Forshey Buyer Code:PMCMTA9 Tel: 614-692-6154 Fax: 614-692-6930 Email: Desmond.Forshey@dla.mil from this pdf file. I was able to extract some text between two references using the code below: import PyPDF2 pdfFileObj = open('SPE7M518T446E.pdf', 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) print(pdfReader.numPages) pageObj1 = pdfReader.getPage(0) pagecontent = pageObj1.extractText() def between(value, a, b): # Find and validate before-part. pos_a = value.find(a) if pos_a == -1: return "" # Find and validate after part. pos_b = value.rfind(b) if pos_b == -1: return "" # Return middle part. adjusted_pos_a = pos_a + len(a) if adjusted_pos_a &gt;= pos_b: return "" return value[adjusted_pos_a:pos_b] desired = between(pagecontent,"5. ","8. ") print(desired) The code above outputs this: 20 REQUEST FOR QUOTATIONSTHIS RFQ IS IS NOT A SMALL BUSINESS SET-ASIDE 4. CERT.FOR NAT. DEF. UNDER BDSA REG. 2 AND/OR DMS REG. 15. ISSUED BY7. DELIVERY 9. DESTINATION10. PLEASE FURNISH QUOTATIONS TO THE ISSUING OFFICE IN BLOCK 5 ON OR BEFORE CLOSE OF BUSINESS (Date)IMPORTANT: This is a request for information, and quotations furnished are not offers. If you are unable to quote, please so indicate on this form and return it to the address in Block 5. This request does not commit the Government to pay any costs incurred in the preparation of the submission of this quotation or to contract for supplies or services. Supplies are of domestic origin unless otherwise indicated by quoter. Any representations and/or certifications attached to this Request for Quotations must be completed by the quoter.11. SCHEDULE (See Continuation Sheets) 12. DISCOUNT FOR PROMPT PAYMENTd. CALENDAR DAYSNUMBERPERCENTAGE NOTE: Additional provisions and representations are are not attached.13. NAME AND ADDRESS OF QUOTERa. NAME OF QUOTER16. SIGNERAUTHORIZED FOR LOCAL REPRODUCTION Previ…
upvote count: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/101174586
favorite count: 0
has title: How extract extract specific text from pdf file - python
has answer: http://stackoverflow.com/a/50118807
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50118807

http://stackoverflow.com/a/50130803
type: AcceptedAnswer
has body: You have the right idea with combine_first, but need to align indices first via set_index: import pandas as pd, numpy as np df1 = pd.DataFrame({'Group': ['A', 'A', 'A', 'B', 'B', 'B'], 'Key': ['AA1', 'AB2', 'AC3', 'BD4', 'BE5', 'BF6'], 'Value1': [np.nan, 20, 40, 60, np.nan, np.nan], 'Value2': [np.nan, 30, 50, 23, np.nan, np.nan]}) df2 = pd.DataFrame({'Key': ['AA1', 'BE5', 'BF6'], 'Value1': [66, 20, 21], 'Value2': [33, 60, 70]}) res = df1.set_index('Key').combine_first(df2.set_index('Key')).reset_index() print(res) Key Group Value1 Value2 0 AA1 A 66 33 1 AB2 A 20 30 2 AC3 A 40 50 3 BD4 B 60 23 4 BE5 B 20 60 5 BF6 B 21 70
accepted answer of: http://stackoverflow.com/q/50130592
downvote count: 1
type: Answer
score: -1
answers question: http://stackoverflow.com/q/50130592
upvote count: 0
has comment: http://stackoverflow.com/comment/87507924

http://stackoverflow.com/comment/87307379
type: Comment
has text: @profhoff I forgot to put the `format` in my code. See my edited version.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50144328

http://stackoverflow.com/q/50159058
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50159238
type: Question
has comment: http://stackoverflow.com/comment/87336040
type: UnansweredQuestion
has body: I am attempting to create a new column in my pandas data frame(df). The value for each row in this column (call it column_new) needs to look at a reference column (column_ref) that already exists in the data frame. I used the unique values in column_ref and assigned them as keys in a dictionary, d: d = {'column_ref_value1': 'a', 'column_ref_value2': 'b', 'column_ref_value3': 'c',} The values in dict(d) are values that I want to assign to to column_new in my data frame. Here is what I tried to no avail: for i in df['column_ref']: for k, v in d.items(): if k == i: df['column_new'] = v When I call my df I am seeing column_new populated with value 'c' in every row, and I am not sure why. I'm guessing my issue has to do with improper iterating through a pandas dataframe or series. Thanks in advance!
has title: Python Pandas - Create a new df column based on matching criteria
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87335912
score: 0

http://stackoverflow.com/a/50146078
score: 1
downvote count: 0
has body: You need to choose the key which will give you quick access to a student record. The name seems the most useful: students = { 'Fred': {'name': 'Fred', 'age': 17, 'grades':[85, 80, 75]} 'Sean': {'name': 'Sean', 'age': 16, 'grades':[65, 70, 100]} } Then you can get the record for Fred with students['Fred'].
answers question: http://stackoverflow.com/q/50146025
type: Answer
upvote count: 1

rabbitmq
tags question: http://stackoverflow.com/q/50131164
tags question: http://stackoverflow.com/q/50229676
tags question: http://stackoverflow.com/q/50223831
tags question: http://stackoverflow.com/q/50228134
tags question: http://stackoverflow.com/q/50121287
tags question: http://stackoverflow.com/q/50203203
tag name: rabbitmq
tags question: http://stackoverflow.com/q/50099449
type: Tag
tags question: http://stackoverflow.com/q/50219254

http://stackoverflow.com/comment/87344041
has text: now i have this error, i refresh the token whit the permission, but nothing
comment on: http://stackoverflow.com/a/50162861
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87302443
has text: Fix this line: `position2[t2] = position[t2-1] - 1`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50141990
score: 0

http://stackoverflow.com/q/50142569
has answer: http://stackoverflow.com/a/50142621
has comment: http://stackoverflow.com/comment/87303536
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
upvote count: 11
type: Question
tagged with: numpy
has body: Here is the .csv file : 0 0 1 1 1 0 1 1 0 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 0 1 0 0 1 1 0 0 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 2 0 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1 1 0 0 1 0 1 0 2 0 1 1 0 1 1 1 1 0 1 1 1 1 0 0 1 0 0 0 0 0 0 1 1 0 1 0 1 1 1 0 1 1 0 0 0 0 1 1 where the first column must be indices like (0,1,2,3,4 ...) but due to some reasons they are zeros. Is there any way to make them normal when reading the csv file with pandas.read_csv ? i use df = pd.read_csv(file,delimiter='\t',header=None,names=[1,2,3,4,5,6,7,8,9,10,11,12]) and getting something like: 1 2 3 4 5 6 7 8 9 10 11 12 0 0 1 1 1 0 1 1 0 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 0 1 0 0 1 1 0 0 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 2 0 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1 1 0 0 1 0 1 0 2 0 1 1 0 1 1 1 1 0 1 1 1 1 0 0 1 0 0 0 0 0 0 1 1 0 1 0 1 1 1 0 1 1 0 0 0 0 1 1 and it's nearly i need, but first column (indices) is still zeros. Can pandas for example ignore this first column of zeros and automatically generate new indices to get this: 0 1 2 3 4 5 6 7 8 9 10 11 12 0 0 1 0 1 1 0 0 0 1 1 1 0 1 1 0 1 0 1 1 0 0 0 1 1 1 1 2 2 0 1 1 1 0 0 1 1 1 1 1 1 2
answer count: 2
has title: Pandas read data without header or index
downvote count: 0
accepted answer: http://stackoverflow.com/a/50142695
tagged with: python
score: 11
possible better answer: http://stackoverflow.com/a/50142621
favorite count: 0
has answer: http://stackoverflow.com/a/50142695
type: AnsweredQuestion

http://stackoverflow.com/comment/87181737
comment on: http://stackoverflow.com/q/50082938
score: 1
type: Comment
has text: I think you may be confusing classes with instances of those classes. Your `b` and `c` are both `A` instances as well as `B` or `C` instances, but they're not the _same_ `A` instance, any more than `a1 = A()` and `a2 = A()` would be. So they don't have the same `a` member. So your question doesn't make sense as stated.
type: QuestionComment

http://stackoverflow.com/comment/98517585
type: QuestionComment
has text: Imho this is not a duplicate of https://stackoverflow.com/questions/35119831/ipython-notebook-keyboard-shortcut-search-for-text. There is a huge semantic difference between renaming a variable and a simple text replace: without direct user interaction, the second replaces all instances of a certain text while the first can be way more clever, e.g. checking if an occurrence of the text actually is a variable name. Cf. the rename-variable functionalities in other IDEs. To the question itself: seems this unfortunately is not provided in Jupyter atm.
comment on: http://stackoverflow.com/q/50177616
type: Comment
score: 24

http://stackoverflow.com/q/50198530
tagged with: primes
has answer: http://stackoverflow.com/a/50217310
accepted answer: http://stackoverflow.com/a/50217310
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87414910
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87413951
tagged with: key
has comment: http://stackoverflow.com/comment/87414084
favorite count: 0
has body: at the moment I try to implement a Miller-Rabin-Test from the algorithm shown in NIST FIPS186-4 Appendix C.3.1. But at the moment the results of my both primes seems not to be perfect, because, for example during all my tests of my code: &gt;&gt;&gt; n,e,d = generating_Pairs() &gt;&gt;&gt; message = 1234567890 &gt;&gt;&gt; cipher = pow(message, e, n) &gt;&gt;&gt; plain = pow(cipher, d, n) &gt;&gt;&gt; plain == message False (The plain is always a very large int, larger than the original message) My generating_keys()-function: def generating_Pairs(): p, q = gen_Random_Primes() n = p*q e = 65537 phi = (p-1)*(q-1) d = inverse(e, phi) return(n,e,d) The inverse-function for calculating d: def inverse(e,phi): a, b, u = 0, phi, 1 while(e &gt; 0): q = b // e e, a, b, u = b%e, u, e, a-q*u if(b == 1): return a%phi else: print("Must be co-prime!") My generating_keys()-function seems to be correct, because if I use provable primes (for example p = 13th mersenne prime and q = 14th mersenne prime, see here) the result of the abovementioned test will be True. I think there is a mistake in my is_prime()-function, which is based on the Miller-Rabin-Test... from random import randrange def is_prime(w): iteration = 5 #p and q should be 1024 bits =&gt; 4 iterations are minimum? m = w - 1 a = 0 while not(m &amp; 1): a += 1 m &gt;&gt;= 1 for _ in range(iteration): b = randrange(2, w-1) while((b &lt;= 1) or b &gt;= w - 1): b = randrange(2, w - 1) z = power(b, m, w) #see ANN1 for _ in range(a): z = power(z, 2, w) #see ANN1 if z == 1: return False if z == w - 1: break return True ANN1: I am using a the power()-function instead of math.pow() (edit3: sorry, built_in pow(x,y [,z]), which is (x**y)%z), because the code should run on a special system with a special python-version (because of system constraints), without pow(a,b,c)... Maybe this special power-function will be the problem, but I think there is a mistake in my is_prime(), which is the core function of my gen_Random_Primes()-functio…
type: Question
has title: Python: What is wrong with my Miller-Rabin implementation?
has comment: http://stackoverflow.com/comment/87413884
tagged with: rsa
has comment: http://stackoverflow.com/comment/87417599
tagged with: python
score: -1

http://stackoverflow.com/comment/87174552
comment on: http://stackoverflow.com/q/50079247
type: Comment
type: QuestionComment
has text: How expensive are the lines of your sourcefile? Why is shorter more efficient? What about readaility/communication of intent of your code and maintainability?
score: 1

http://stackoverflow.com/comment/87303488
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ also, it should be `array[:, :, None]` or `array[..., None]`
comment on: http://stackoverflow.com/q/50142392
score: 1
type: Comment

http://stackoverflow.com/comment/87432939
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50207877
type: Comment
has text: can you provide more code and explanation how you got those outputs?

http://stackoverflow.com/q/50155527
has body: I want to install a new package GraphLab in my Anaconda environment but its not coming when I searched there so not able to install it from Anaconda, please suggest how to install from Anaconda itself Then I want to install it from PIP but its is also showing error, then I tried to install any popular package to check if PIP is working as expected then again also showing below mentioned error Python Version : 3.6.4 PIP Version : 10.0.1 Error Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection VerifiedHTTPSConnection object at 0x000000000463C278&gt;, 'Connection to files.pyt onhosted.org timed out. (connect timeout=15)')': /packages/5e/1f/6c2204b9ae14ed ab615c5e2ee4956c65ed533e0a9986c23eabd801ae849/selenium-3.11.0-py2.py3-none-any. hl Can someone please help me to find my next steps.
has title: Not able to install any new package by PIP | Anaconda
score: 0
tagged with: anaconda
answer count: 1
has comment: http://stackoverflow.com/comment/87432346
type: Question
has answer: http://stackoverflow.com/a/50156905
type: UnansweredQuestion
tagged with: pip
tagged with: python

http://stackoverflow.com/a/50097815
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50091118
upvote count: 1
has body: There are actually several sources for the image you are looking for in page source. Simply click ctrl+u (may differ on some browsers) to "view page source" and search for your url string. I found that you can get the image your looking underneath meta tag: $ scrapy shell https://allevents.in/pune/filmmaking-workshop/20001033616713 In : response.xpath('//meta[@property="og:image"]/@content').extract() Out: ['https://cdn-az.allevents.in/banners/2d76d5624f4e4b83155a51d60b3872fb-rimg-w525-h350-gmir.jpg']
accepted answer of: http://stackoverflow.com/q/50091118

built-in-types
tags question: http://stackoverflow.com/q/50118488
tag name: built-in-types
tags question: http://stackoverflow.com/q/50203630
type: Tag

http://stackoverflow.com/comment/87197010
comment on: http://stackoverflow.com/a/50090272
has text: Then somebody puts some evil code in that url, you execute it with `eval` and you are screwed. Just because you weren't careful enough to use `a = r.json()` instead.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/50185383
type: Question
tagged with: opencv
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
tagged with: ocr
has title: Python - Ocr with Knn-Algorithm expand testdata
has body: I try to write a Ocr for numbers in Python using OpenCV and the Knn-Algorithm. The code works pretty well but i want to expand my input data to move on to handwritten digits. Training / input of data works like that: You run the script, where the path of a image is, then the image opens with a rectangle around the number and you have to press the number on the keyboard. At the end it saves the classifications and flattened images in a textfile. The problem is that it overrides the old textfiles so this data gets lost. Is it possible / does it work to append the new and the old textfile? This is the code: import sys import numpy as np import cv2 import os MIN_CONTOUR_AREA = 35 RESIZED_IMAGE_WIDTH = 20 RESIZED_IMAGE_HEIGHT = 30 def main(): imgTrainingNumbers = cv2.imread("training_chars.png") if imgTrainingNumbers is None: # if image was not read successfully print "error: image not read from file \n\n" # print error message to std out os.system("pause") # pause so user can see error message return # and exit function (which exits program) # end if imgGray = cv2.cvtColor(imgTrainingNumbers, cv2.COLOR_BGR2GRAY) # get grayscale image imgBlurred = cv2.GaussianBlur(imgGray, (5,5), 0) # blur # filter image from grayscale to black and white imgThresh = cv2.adaptiveThreshold(imgBlurred, # input image 255, # make pixels that pass the threshold full white cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # use gaussian rather than mean, seems to give better results cv2.THRESH_BINARY_INV, # invert so foreground will be white, background will be black 11, # size of a pixel neighborhood used to calculate threshold value 2) # constant subtracted from the mean or weighted mean cv2.imshow("imgThresh", imgThresh) # show threshold image for reference imgThreshCopy = imgThresh.copy() # make a copy of the thresh image, this in necessary b/c findContours modifies the image imgContours, npaContours, npaHierarchy = cv2.findContours(imgThreshCopy, # input image, make sure to use a copy since the function wil…
score: 0
has comment: http://stackoverflow.com/comment/87397974
has comment: http://stackoverflow.com/comment/87388038
answer count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/53572774

http://stackoverflow.com/a/50210541
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50210397
has body: using ipaddr , first install the module pip install ipaddr then import IPv4Network from it from ipaddr import IPv4Network masknet = IPv4Network('192.168.1.1') # Ip Address print masknet.netmask # OR masknet = IPv4Network('192.168.1.1/8') print masknet.netmask Result: &gt;&gt;&gt; print masknet.netmask 255.255.255.255 &gt;&gt;&gt; print masknet.netmask 255.0.0.0
score: 1

http://stackoverflow.com/q/50125391
tagged with: tcp
has comment: http://stackoverflow.com/comment/87269303
has body: I'm parsing data from a binary format and want to stream the resulting JSON strings to a listening server. These streams are independent I would like to have each stream run concurrently to speed up ingest of my data into the server. I've tried using the multithreading library: import multiprocessing as mp def write_tcp_stream(host, port, packet): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) except socket.error as msg: sys.stderr.write("[ERROR] %s\n", msg[1]) sock.close() return sock.sendall(packet) sock.close() ... p = mp.Pool(4) for s in objects_to_stream.values() # assume s is a JSON string p.apply_async(write_tcp_stream, args=(HOST,PORT, s.encode()) p.close() p.join() but depending on the file I'm parsing I may get out-of-memory errors. I'm guessing it has to do with using the pool, but I don't know enough to understand what's happening behind the scenes. I don't think I actually need to use multiprocessing but I don't know if it's possible to open multiple TCP sockets and write to them concurrently? I want to "fire-and-forget" the TCP writes. Is this possible?
answer count: 1
has comment: http://stackoverflow.com/comment/87268892
tagged with: concurrency
has answer: http://stackoverflow.com/a/50125932
accepted answer: http://stackoverflow.com/a/50125932
type: Question
has title: How do I write to multiple TCP sockets concurrently?
has comment: http://stackoverflow.com/comment/87268928
has comment: http://stackoverflow.com/comment/87268872
has comment: http://stackoverflow.com/comment/87268915
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/53516457
upvote count: 3
has body: Unfortunately, tqdm is not working with starmap. You can use the following: def f(args): arg1, arg2 = args ... do something with arg1, arg2 ... for _ in tqdm.tqdm(pool.imap_unordered(f, zip(list_of_args, list_of_args2)), total=total): pass
answers question: http://stackoverflow.com/q/50154204
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/q/50156552
has title: CloudML RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb
tagged with: google-cloud-platform
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50157570
type: Question
tagged with: google-cloud-ml
has body: Everything seems to work fine when I test locally. When I submit the job remotely: gcloud ml-engine jobs submit training $JOB_NAME \ --job-dir gs://$BUCKET_NAME/$JOB_NAME \ --runtime-version 1.7 \ I get the following errors: In my code, the only place I use numpy is to load my file - data.npz using: train_file = gs://path_to_data.npz f = BytesIO(file_io.read_file_to_string(train_file, binary_mode=True)) data = np.load(f) To create the .npz, I used google-datalab which has numpy v 1.14, while 1.7 runtime for CloudML has 1.13.3, but I doubt this is the reason. My local machine also has 1.13.3 and doesn't seem to display errors. The job still gets completed successfully, I would just like to get rid of these warnings/errors.
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/50090536
accepted answer: http://stackoverflow.com/a/50101081
type: Question
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50101081
has title: stream standard output with PyZMQ
type: AnsweredQuestion
score: 0
tagged with: pyzmq
has body: I have a client-side application which sends a message to a remote server, the message gets processed from the server and the result is sent back to the client. A simplified example looks like: client.py import zmq def get_message(msg, ip, port, socket, send_socket_type='pyobj'): socket.connect("tcp://%s:%s" % (ip, port)) socket.send_string(msg) if send_socket_type=='pyobj': msg = socket.recv_pyobj() if send_socket_type=='string': msg = socket.recv_string() if send_socket_type=='json': msg = socket.recv_json() return msg socket.close() server.py import zmq import time port=9999 context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % port) def processmessage(msg): for i in range(10): print(i) time.sleep(1) return msg while True: msg = socket.recv() print('message received from client:', msg) cmd = processmessage(msg) socket.send_pyobj(cmd) print('sending to client: %s ' % msg) time.sleep(0.2) Testing: server_env={'IP': ip, 'PORT': port} context = zmq.Context() socket = context.socket(zmq.REQ) messages = ['first message', 'second message', 'third message'] for i in messages: msg = get_message('message', ip=server_env['IP'], port=server_env['PORT'], socket) print(msg) My Question: How can I extend this simple client-server example to allow the client to receive the standard output generated by the process processmessage() running server side?

http://stackoverflow.com/q/50092815
type: Question
score: 2
tagged with: for-loop
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87201871
tagged with: loops
has title: Why does my "if" statement not exit out when I use the "break" function?
has body: This code is like a ticket box counter, where the user selects if they want a ticket based on the price, or the seat. I haven't gotten to the seat selection part of the code, but when I was making my price selection one, after it's done, it prints out the layout too many times (instead of one, how it should be). After the "if" is triggered the first time, it should print out the layout, and then break. Though, it doesn't do this, and instead keeps on printing out the layout and going through the if function many times. Please help me fix this. Thank you! line1 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10] line2 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10] line3 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10] line4 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10] line5 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10] line6 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10] line7 = [20 , 20 , 30 , 30 , 40 , 40 , 30 , 30 , 20 , 20] line8 = [20 , 30 , 30 , 40 , 50 , 50 , 40 , 30 , 30 , 20] line9 = [30 , 40 , 50 , 50 , 50 , 50 , 50 , 50 , 40 , 30] seats = [line1, line2 , line3 , line4 , line5 , line6 , line7 , line8 , line9] for line in seats: print(line) seatFound = False SorP = input("Would you like to select a seat based on the price (P) or seat (S)") if SorP == "P": price = int(input("What price would you like?")) for line in seats: for seat in line: if seat == price: print("There is a seat available for that price") seatFound = True position = line.index(seat) line.remove(seat) line.insert(position , 0) for line in seats: print(line) break if seatFound != True: print("There is not a seat available for this price. Try again")
favorite count: 0
tagged with: if-statement
tagged with: break
has comment: http://stackoverflow.com/comment/87201857
has comment: http://stackoverflow.com/comment/87202143
tagged with: python
has comment: http://stackoverflow.com/comment/87201852
has comment: http://stackoverflow.com/comment/87202129
has answer: http://stackoverflow.com/a/50092843

http://stackoverflow.com/q/50145389
has body: Is there anything that allows visual studio code to tell you if you are writing python code that is not compatible with both python 2 and 3 versions? I know that PyCharm has this feature but I'd prefer not to switch between IDEs depending on the language I'm coding in. For example, print "Hello world!" should give me an error because its not compatible with python 3. assert 3 / 2 == 1.5 should give me an error because it's not compatible with python 2.
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50162868
favorite count: 0
type: Question
tagged with: visual-studio-code
upvote count: 2
has comment: http://stackoverflow.com/comment/87310266
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87310051
tagged with: python
has title: Make visual studio code detect python compatibility errors
score: 2

http://stackoverflow.com/comment/87468563
type: Comment
type: QuestionComment
has text: I am unclear what the question here is?
comment on: http://stackoverflow.com/q/50225549
score: 0

http://stackoverflow.com/a/50215861
downvote count: 0
has body: You need to read input arguments as a list def Test(*colors): colorarray = [*colors] print(colorarray) Test('red','blue')
has comment: http://stackoverflow.com/comment/87448919
has comment: http://stackoverflow.com/comment/87449070
type: Answer
accepted answer of: http://stackoverflow.com/q/50215808
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87448697
has comment: http://stackoverflow.com/comment/87448465
has comment: http://stackoverflow.com/comment/87448726
answers question: http://stackoverflow.com/q/50215808
has comment: http://stackoverflow.com/comment/87448640
score: 3
upvote count: 3

http://stackoverflow.com/a/50142286
answers question: http://stackoverflow.com/q/50137099
has body: This is not exactly what you want but may help you. There is an Atom extension "platformio-ide-terminal" which when run will open a regular bash shell at the bottom of your Atom window. Using this you can easily move around your directories using unix commands. Hope this helps some.
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50137099

http://stackoverflow.com/a/50184577
type: Answer
has body: names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford'] search = str(input("Please enter search term ")) ref = list(search.lower()) # this is your search text out = [] count = 1 ind = 0 for i in names: # loops over your list #print () #take the hash out to see what is i for j in list(i.lower()): # list converts your variable into a list ie shakira = ['s','h'..] if j == ref[ind]: ind += 1 else: ind = 0 if ind == len(ref): #ind is gonna go over each index in ref, if ind = the length of your # search text then you have found a match out.append(i) ind = 0 break if len(out) == 0: out.append(" Nothing found ") count = 0 for i in out: print ("{}. {}".format(count,i), end = "\t\t") count += 1 Okay! there are a lot of ways to do this, tried to make it as simple as possible. Flaws: If there are two names which are similar, eg Will and William and you search for will, you will get both names. If you search for william it will give you Willaim only. Also the design is not that efficient, two for loops, basically it running linear to the number of letters in the list, (total letters.) See how it goes.
score: 0
answers question: http://stackoverflow.com/q/50184303

java
tags question: http://stackoverflow.com/q/50207465
tags question: http://stackoverflow.com/q/50108028
tags question: http://stackoverflow.com/q/50200917
tags question: http://stackoverflow.com/q/50218325
tags question: http://stackoverflow.com/q/50142099
tags question: http://stackoverflow.com/q/50204595
tags question: http://stackoverflow.com/q/50216132
tags question: http://stackoverflow.com/q/50114862
tag name: java
tags question: http://stackoverflow.com/q/50191768
tags question: http://stackoverflow.com/q/50212552
tags question: http://stackoverflow.com/q/50172289
tags question: http://stackoverflow.com/q/50196447
tags question: http://stackoverflow.com/q/50086395
tags question: http://stackoverflow.com/q/50078995
tags question: http://stackoverflow.com/q/50225795
tags question: http://stackoverflow.com/q/50207292
tags question: http://stackoverflow.com/q/50089210
tags question: http://stackoverflow.com/q/50113511
tags question: http://stackoverflow.com/q/50137442
type: Tag
tags question: http://stackoverflow.com/q/50086216

http://stackoverflow.com/a/50141290
score: 2
accepted answer of: http://stackoverflow.com/q/50115014
upvote count: 2
type: AcceptedAnswer
has body: I have the same problem with Django 2.0.4. Seems like it does not supports latest versions of Django. The problem is that PyInstaller can't resolve hidden imports, so you have to add them to hooks manually. Edit .spec file, which is created after first build with pyinstaller, fill array of hidden_imports with missing packages and make build pointing .spec file instead of manage.py. Unfortunelly, after adding few packages, new errors appears. https://pythonhosted.org/PyInstaller/when-things-go-wrong.html Pyinstaller works fine with Django 1.8, so try using this version. Project based on Django 1.8 builds successfully, and runs well using runserver
downvote count: 0
answers question: http://stackoverflow.com/q/50115014
has comment: http://stackoverflow.com/comment/87365420
has comment: http://stackoverflow.com/comment/96311760
type: Answer

http://stackoverflow.com/q/50108601
upvote count: 1
has comment: http://stackoverflow.com/comment/92426087
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87371155
has comment: http://stackoverflow.com/comment/87248845
tagged with: pyspark
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/92398968
has comment: http://stackoverflow.com/comment/87403332
has title: How to enforce using cloudpickle in pyspark?
answer count: 0
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/92426100
has body: It seems like spark has trouble with pickling/unpickling on the remote workers. Is there a way to tell it to use cloudpickle?
type: UnansweredQuestion
score: 1
downvote count: 0

http://stackoverflow.com/q/50109283
tagged with: vim
type: AnsweredQuestion
tagged with: terminal
has answer: http://stackoverflow.com/a/50265251
has comment: http://stackoverflow.com/comment/87236386
tagged with: python
has body: When saving python files, vim-syntactic starts debugging and raises syntax errors (specifically commas), whether its in a list, dictionary, tuple etc. Here is an image after saving python file.
type: Question
has answer: http://stackoverflow.com/a/50109762
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/87236549
has title: Comma errors while using vim-syntastic plugin
accepted answer: http://stackoverflow.com/a/50265251
downvote count: 1
tagged with: vim-syntastic
possible better answer: http://stackoverflow.com/a/50109762
favorite count: 0

http://stackoverflow.com/comment/87292579
type: AnswerComment
has text: @nos added more details as to why, and updated the answer for that **exact** use case even though it did not change the point...
comment on: http://stackoverflow.com/a/50137082
type: Comment
score: 0

http://stackoverflow.com/comment/87334141
type: QuestionComment
has text: I was having trouble getting the sender info using `message.Sender` in a previous project. Instead, I used `message.SenderName` to get their name and `message.SenderEmailAddress` for their email address. I'd also recommend using the `unidecode` package on the sender names since some people can have special characters in their name: `unidecode(message.SenderName)`. Adding a [doc](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mailitem_properties.aspx) for MailItem properties.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50157943

http://stackoverflow.com/a/50187754
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50157360
has body: (Frank-ZvIKOxyS) bash-3.2$ exit exit MacBook-Pro-Frank:~ Frank$ pipenv --python 3.6 Virtualenv already exists! Removing existing virtualenv… Creating a virtualenv for this project… Using /usr/local/bin/python3.6m (3.6.5) to create virtualenv… Running virtualenv with interpreter /usr/local/bin/python3.6m Using base prefix '/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6' New python executable in /Users/Frank/.local/share/virtualenvs/Frank-ZvIKOxyS/bin/python3.6 Also creating executable in /Users/Frank/.local/share/virtualenvs/Frank-ZvIKOxyS/bin/python Installing setuptools, pip, wheel...done. Virtualenv location: /Users/Frank/.local/share/virtualenvs/Frank-ZvIKOxyS Testing: MacBook-Pro-Frank:~ Frank$ pipenv shell Spawning environment shell (/bin/bash). Use 'exit' to leave. bash-3.2$ . /Users/Frank/.local/share/virtualenvs/Frank-ZvIKOxyS/bin/activate Frank-ZvIKOxyS) bash-3.2$ python --version Python 3.6.5 (Frank-ZvIKOxyS) bash-3.2$ pip --version pip 10.0.1 from /Users/Frank/.local/share/virtualenvs/Frank- ZvIKOxyS/lib/python3.6/site-packages/pip (python 3.6) (Frank-ZvIKOxyS) bash-3.2$ Thanks to Alberto, this solved my puzzle. Puzzling on...
score: 0
answers question: http://stackoverflow.com/q/50157360

http://stackoverflow.com/a/50128014
has body: What do I need to do to be able to get the status of get_blob? You can wrap get_blob in a function that will store information about whether it succeeded, and store the return value if any. Instead of target=self.blob_service.get_blob_to_path, you can write target=self._get_blob_background. The new _get_blob_background method can call self.result = self.blob_service.get_blob_to_path and use try and except Exception as e to catch all exceptions and, in case of exception, execute self.result_exception = e, so that the main thread can distinguish the result from the exception. Even better, you can use the concurrent.futures library to do all that for you: pool = concurrent.futures.ThreadPoolExecutor() def get_blob(self): return pool.submit(self.blob_service.get_blob_to_path, self.container_name, self.blob_name, self.file_path) Now get_blob() will run in the background, like in your code, but here it will return a Future object that you can query to find out whether the job completed, and how it completed.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50123140
has comment: http://stackoverflow.com/comment/87312221
has comment: http://stackoverflow.com/comment/87296024
answers question: http://stackoverflow.com/q/50123140
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50181084
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50181329
accepted answer: http://stackoverflow.com/a/50181186
has body: Can I do the following with pandas.Series math on a and b without looping through explicitly? In [38]: a = pd.Series([4, 8, 3, 6, 2]) In [39]: b = pd.Series([3, 9, 5, 5, 4]) In [40]: alist = a.tolist() ...: blist = b.tolist() ...: for i in range(len(alist)): ...: diff = max(0, alist[i] - blist[i]) ...: try: ...: alist[i + 1] = alist[i + 1] + diff ...: except IndexError: ...: if diff &gt; 0: ...: alist.append(diff) ...: blist[i] = max(0, blist[i] - alist[i]) ...: In [41]: alist Out[41]: [4, 9, 3, 6, 3] In [42]: blist Out[42]: [0, 0, 2, 0, 1] I'm incrementing the next value of a with the difference of a and b if it is greater than zero, and then subtracting b from that cumulative-sum-like calc.
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/50181186
downvote count: 0
has answer: http://stackoverflow.com/a/50181175
favorite count: 0
type: Question
has title: Cumulative sums and carryovers - vectorize with pandas
has comment: http://stackoverflow.com/comment/87433068
has answer: http://stackoverflow.com/a/50181546
possible better answer: http://stackoverflow.com/a/50181175

http://stackoverflow.com/q/50135612
has comment: http://stackoverflow.com/comment/87289220
score: 0
has comment: http://stackoverflow.com/comment/87289224
answer count: 1
type: Question
has body: I am building a python class in which I create a dictionnary using the method "new". Then, I would like to define a method to affect a unit for some of the keys. Below an example of the code: class MyClass(object): def __new__(cls): dict = {key1:None, key2:None} return dict def unit(self, unit): self[KEY].unit = unit Where, in the unit method, KEY should take any key of the dictionnary. Could you please help me to understand how to code it? In advance thank you,
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87310835
has title: Python create a dictionary using __new__ and add an attribute for each key
tagged with: python
has answer: http://stackoverflow.com/a/50135724

http://stackoverflow.com/comment/87428596
has text: Also, the computation up to 2^45 is trivial. The sum is just the number itself.
comment on: http://stackoverflow.com/a/50161307
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87379153
has text: That's a really interesting solution, thanks for your help! I didn't even consider using a dictionary in this way.
comment on: http://stackoverflow.com/a/50180611
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50228162
downvote count: 0
tagged with: input
tagged with: python
has body: In terms of using this: names = [] # Here we define an empty list. while True: eingabe = input('Please enter a name: ') if not eingabe: break names.append(eingabe) print(eingabe) How do you use it for multiple inputs?
answer count: 3
has answer: http://stackoverflow.com/a/50228531
score: 1
has title: How do you add users multiple inputs to a list?
has answer: http://stackoverflow.com/a/50228314
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50228425
has comment: http://stackoverflow.com/comment/87473597
type: UnansweredQuestion

http://stackoverflow.com/q/50215279
has title: pythonic way of decorating classmethods
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50215331
has comment: http://stackoverflow.com/comment/87447339
accepted answer: http://stackoverflow.com/a/50215331
answer count: 2
has comment: http://stackoverflow.com/comment/87447267
tagged with: python
has comment: http://stackoverflow.com/comment/87448593
has body: Given the following example: class A: def f(self, x): return 2*x I would like to write another method which uses f above but adds a constant, i.e. class A: def f(self, x): return 2*x def g(self, x): return self.f(x) + 10 This would be one way. However, this smells very much like decorating! What would be the proper pythonic way to do this?
tagged with: python-decorators
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50215750
has comment: http://stackoverflow.com/comment/87447257
downvote count: 0
has comment: http://stackoverflow.com/comment/87447312
has answer: http://stackoverflow.com/a/50215750
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87447861

http://stackoverflow.com/a/50104890
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50104434
answers question: http://stackoverflow.com/q/50104434
has body: Identical pickles don't imply byte-for-byte identical objects, and byte-for-byte identical objects aren't necessarily equal. You might think it's easy to make byte-for-byte identical objects automatically equal, but that runs into a lot of problems. For example, consider the following: class Foo(object): __slots__ = ['x'] x = Foo() y = Foo() x.x = y.x = x Aside from GC metadata, x and y are probably byte-for-byte identical. Should x and y be automatically equal? x is the only one whose x attribute points to itself; that seems like a big enough difference that they shouldn't be automatically equal. This is only one of the problems with trying to do what you want by default. It turns out the least confusing default is to have == work by identity; unless an __eq__ override comes into play, objects will only be equal to themselves.
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50156609
answers question: http://stackoverflow.com/q/50156391
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50156391
upvote count: 1
score: 1
has body: If you're happy using itertools, you can use itertools.combinations: from itertools import combinations a = [1, 3, 5, -1] o = sorted(set(combinations(sorted(a), 2))) &gt;&gt;&gt; [(-1, 1), (-1, 3), (-1, 5), (1, 3), (1, 5), (3, 5)] a = [1, 1, 5, 5] o = sorted(set(combinations(sorted(a), 2))) &gt;&gt;&gt; [(1, 1), (1, 5), (5, 5)] The inner call to sorted ensures that each pair will be ordered, which I understand was your intention. The outer call to sorted ensures that the pairs are ordered. If this is not necessary, you can replace this sorted with simply list.

http://stackoverflow.com/q/50091475
has body: I have an SQL .log file that's around 5GB. It was provided by a client so I'd hate to ask them to export it for me in a different format. It has the following structure: Header 1 Header 2 Header 3 Header 4 -------- -------- -------- -------- value a value 1 value 2 value 3 value a value 4 value 5 value 6 value b value 7 value 8 value 9 Header 1 Header 2 Header 3 Header 4 -------- -------- -------- -------- value b value 10 value 11 value 12 value b value 13 value 14 value 15 value b value 16 value 17 value 18 I've tried parsing it by converting it to a .txt reading each line separately, processing it then moving on to the next line by doing the following: with open(filename) as infile: for line in infile: Is there a more efficient way of doing this? Is there a way of converting a .log file to a pandas data frame directly? Thanks in advance!
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87200400
has comment: http://stackoverflow.com/comment/87199341
has comment: http://stackoverflow.com/comment/87200373
has comment: http://stackoverflow.com/comment/87199196
tagged with: parsing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87200265
has comment: http://stackoverflow.com/comment/87241831
answer count: 0
type: UnansweredQuestion
has title: How can I go about efficiently transforming an SQL log to a CSV?
has comment: http://stackoverflow.com/comment/87254616
has comment: http://stackoverflow.com/comment/87224738
has comment: http://stackoverflow.com/comment/87200375
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/87200254
has comment: http://stackoverflow.com/comment/87200348
score: 0

http://stackoverflow.com/comment/87402548
type: Comment
type: QuestionComment
score: 0
has text: wildplasser, thank you for your remark but this functionality use in the context of simple fetch queries like a "SELECT * FROM ..."
comment on: http://stackoverflow.com/q/50192645

http://stackoverflow.com/a/50161836
has body: You can using pd.cut (BTW , 40 is not old man :-() pd.cut(df.age,bins=[0,20,39,np.inf],labels=['kid','young','old']) Out[179]: 0 old 1 old 2 young 3 young 4 old Name: age, dtype: category Categories (3, object): [kid &lt; young &lt; old]
answers question: http://stackoverflow.com/q/50161537
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87416343
type: QuestionComment
comment on: http://stackoverflow.com/q/50199840
type: Comment
has text: I'm going to guess that you don't really need to do this. Often, people print out values and see the double-backslash, but that's just Python's way of unambigiously showing you that there is a single backslash in the string. Can you say more about where this string came from, and why you want to change it?
score: 2

http://stackoverflow.com/q/50162556
favorite count: 0
type: Question
has title: Legend Text Color in Matplotlib with Errorbar Plot
has answer: http://stackoverflow.com/a/50162800
tagged with: python
linked to: http://stackoverflow.com/q/13828246
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: matplotlib
answer count: 1
accepted answer: http://stackoverflow.com/a/50162800
has body: I'm trying to get the text in my legend to match the color of the lines from the plot. There is a nice summary of how to do this by Dan, over here: Matplotlib: Color-coded text in legend instead of a line However, it does not seem to work for errorbar plot types. Does anyone have an idea of what handle I should use to make this change? Here's some example code that shows how it works with the plot type element, but doesn't work with the errorbar type element: import matplotlib.pyplot as plt import numpy as np x = np.arange(0.1,4,0.5) y1 = np.exp(-x) y2 = np.exp(-x)*1.2+0.25 plot = plt.figure() ax = plot.add_axes([0,0,1,1]) ax.plot(x,y1,color="red",label="Y1") ax.errorbar(x,y2,yerr=0.1,color="blue",marker='*',capsize=4,label="Y2") leg = ax.legend(); for line, text in zip(leg.get_lines(), leg.get_texts()): text.set_color(line.get_color()) And here's an example of how that plot looks: Code will change text color of plot types but not errorbar types Thanks for any advice!

http://stackoverflow.com/a/50117167
has body: You can just store the .value_counts() method output and then just filter it: &gt;&gt;&gt; counts = df.groupby('A')['B'].value_counts() &gt;&gt;&gt; counts[counts &gt;= 2] A B bar no 4 foo yes 3 no 2 Name: B, dtype: int64 If you want to get your desired output, you can call .reset_index() method and rename the new column: &gt;&gt;&gt; counts[counts &gt;= 2].reset_index(name='count') A B count 0 bar no 4 1 foo yes 3 2 foo no 2
type: Answer
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50117068

http://stackoverflow.com/q/50128747
tagged with: regex
duplicate of: http://stackoverflow.com/q/22444
upvote count: 4
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/7014903
accepted answer: http://stackoverflow.com/a/50128858
downvote count: 2
has answer: http://stackoverflow.com/a/50128858
linked to: http://stackoverflow.com/q/399078
has comment: http://stackoverflow.com/comment/87275269
answer count: 1
has comment: http://stackoverflow.com/comment/87363776
favorite count: 0
type: Question
has title: Removing LaTeX characters from string in python
duplicate of: http://stackoverflow.com/q/399078
has body: I have a TeX document like so s = '\textbf{1 + 1} \begin{center} \textbf{some text in here:} \end{center} and \textbf{2} etc' I would like to remove the \textbf{ and the closing brace } So the final text would look something like this 1 + 1 \begin{center} some text in here: \end{center} and 2 etc' This is what I have tried so far import re re.sub(r'\textbf{(.*)}', '\\1', s)
has comment: http://stackoverflow.com/comment/87319523
tagged with: python

http://stackoverflow.com/comment/87306436
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50144068
type: AnswerComment
has text: @Aran-Fey Is `__getattribute__` considered bad practice? I hadn't heard that it was.

python-3.6
tags question: http://stackoverflow.com/q/50191406
tags question: http://stackoverflow.com/q/50177939
tags question: http://stackoverflow.com/q/50190676
tags question: http://stackoverflow.com/q/50118684
tags question: http://stackoverflow.com/q/50138831
tags question: http://stackoverflow.com/q/50129135
tags question: http://stackoverflow.com/q/50090942
tags question: http://stackoverflow.com/q/50199145
tags question: http://stackoverflow.com/q/50120955
tags question: http://stackoverflow.com/q/50171754
type: Tag
tag name: python-3.6
tags question: http://stackoverflow.com/q/50160783
tags question: http://stackoverflow.com/q/50215285
tags question: http://stackoverflow.com/q/50112359
tags question: http://stackoverflow.com/q/50120769
tags question: http://stackoverflow.com/q/50110164
tags question: http://stackoverflow.com/q/50133579
tags question: http://stackoverflow.com/q/50225864
tags question: http://stackoverflow.com/q/50151490

http://stackoverflow.com/q/50138862
tagged with: python
has comment: http://stackoverflow.com/comment/87297711
has title: not all scatter points are shown on plot_surface
has body: I am trying to visualize points on 3d surface. For some reason only some points are shown in the plot. When I start to move the plot around, some points suddenly appear. Is there a way to visualize points on a 3d surface? This is the result I am getting right now: And below the code used to generate it: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') # Make data. X = np.arange(-5, 5, 0.1) Y = np.arange(-5, 5, 0.1) X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) X = np.arange(-5, 5, 1) Y = np.arange(-5, 5, 1) X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) ax.scatter(X, Y, Z, c='r', marker='o') # Customize the z axis. ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: matplotlib

http://stackoverflow.com/q/50194797
type: UnansweredQuestion
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87470028
score: 0
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/50197024
has body: I know this is a problem that's been asked here a bundle of times before, but I'm seriously at my wits end with this thing. I'm learning Python 3 and I decided I'd work on a little text based game. I made some good progress, got most of a tutorial done, title card, half of a save file system written, etc. I decided, hey, I should try and see if I can package this thing before I go any further (because where's the fun in not showing your friends?). I've used Pyinstaller before on some simple one file apps (dice rollers, etc.) and it worked flawlessly. However, I'm having a hell of a time with my larger game. When I bundle it with Pyinstaller it throws a ton of missing lib errors. I Googled around and those are apparently not a huge issue. Aside from that, everything seems to have run just fine... until I go to launch the program. It's just a simple program that runs in the command line, but when I launch it it crashes immediately. Now, I thought maybe this had to do with the modules I imported (or the fact that the program relies on calling from multiple .py files). So I made a smaller program that includes all the same imports and calls to an external file, and that one packaged and launched just fine! So at this point, the working hypothesis is that there's something rightly messed with my code, but I can't for the life of me figure out what it is. Here's a link to the program itself: https://www.dropbox.com/s/ouog4ccbibpibgx/AsciiLand.zip?dl=0 Seriously, I've been at this all day and I've made exactly zero progress. Any help would be greatly appreciated here guys.
tagged with: python
has title: Pyinstaller packaged app crashes on launch
tagged with: python-3.x
linked to: http://stackoverflow.com/q/49949336

http://stackoverflow.com/comment/87210158
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50095950
has text: After this line : `df = df.dropna(axis=0, how='all')`, do you see another `NaN` values in your dataset ?

http://stackoverflow.com/q/50093238
tagged with: apply
score: 2
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
upvote count: 2
downvote count: 0
has body: import numpy as np import pandas as pd import matplotlib.pyplot as plt data={'state':[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], 'year':[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3], 'pop':[11, 22, 0, 33, 44, 32, 45, 66, 34, 12, 32, 0], 'gdp':[123, 341, 554, 654, 245, 665, 332 ,321, 344, 232, 542, 221]} frame=pd.DataFrame(data) def treat(group): if group.ix[group.year==3, 'pop']!=0: group['Treated']=1 else: group['Treated']=0 frame.groupby('state').apply(treat) I am trying to create a variable frame['Treated'] according to some condition. if ('year'==3) and ('pop'!=0) - I think the 'state' is in the Treated group (so I created a variable called 'Treated' ). Unfortunately I end up with an error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). What's wrong with my code? Do you know how I could solve this problem? Reedit Thank for your kind answer, and I'm sorry for having not described my problem clearly. I'm trying to describe my problem again. For state 1 , the pop is 0 in the year 3 ,so state 1 is not in the treated group (as following shows, frame['Treated']=0 for state 1 in every year) For state 2， the pop is not equal to 0 in the year 3, so state 2 is in the treated group (as following shows, frame['Treated']=1 for state 2 in every year) other states are processed for similar reason. The final result is like the following. state year pop gdp Treated 0 1 1 11 123 0 1 1 2 22 341 0 2 1 3 0 554 0 3 2 1 33 654 1 4 2 2 44 245 1 5 2 3 32 665 1 6 3 1 45 332 1 7 3 2 66 321 1 8 3 3 34 344 1 9 4 1 12 232 0 10 4 2 32 542 0 11 4 3 0 221 0
has title: How can I apply function to create dummy variable?
has answer: http://stackoverflow.com/a/50093302
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50093514
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50095425
tagged with: python

http://stackoverflow.com/a/75912289
type: Answer
score: -1
has body: Universal function to create dirs/files that do not exist def check_and_create_path(self, path: Path): path_way = path.parent if path.is_file() else path path_way.mkdir(parents=True, exist_ok=True) if not path.exists(): path.touch()
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/50110800

http://stackoverflow.com/comment/87439755
has text: What's your desired result? The `tf.train.batch` is used mostly with input pipeline.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50201953
type: QuestionComment

http://stackoverflow.com/comment/87447390
type: QuestionComment
comment on: http://stackoverflow.com/q/50163198
score: 0
has text: As reported on error, you need to get a new version of Visual Studio, because your version not fully support C++11. You have two option: full update 2015 or full update 2017.
type: Comment

http://stackoverflow.com/comment/87351294
type: QuestionComment
comment on: http://stackoverflow.com/q/50166721
score: 0
has text: It's actually somewhat of a duplicate, I'll sign it for you. Happy to help though.
type: Comment

http://stackoverflow.com/comment/87389181
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50185399
type: QuestionComment
has text: The second thing thats returned is not variance but standard deviation.

http://stackoverflow.com/comment/87281611
type: QuestionComment
score: 2
has text: That is the maximum number of possible processes. On Linux it can be retreived via `cat /proc/sys/kernel/pid_max` and a typical value is 32768, but other limitations like available RAM apply. It might differ on the architecture, the OS and it's settings.
comment on: http://stackoverflow.com/q/50131836
type: Comment

http://stackoverflow.com/q/50136944
type: Question
has comment: http://stackoverflow.com/comment/87292286
has title: Iterate and change values of a column if a pandas Data Frame
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87292090
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87292905
has comment: http://stackoverflow.com/comment/87293154
has body: I have a Data frame and one of the columns is 'ip' in which each row is a ip address. I want to use the values and make a call to project honeypot and change the value of the column with the threat score. I'm using this client to make the calls. I tried with for loop and the apply function but i can't get it to do nothing :(. Does anyone have some suggestion or example? import httpbl bl = httpbl.HttpBL('****') df['ip'] = df.ip.apply(bl.query(df.ip.get_values, axis =1) a ... ip 1 ... 123.123.123.123 2 ... 123.24.2.1 and after the call get something like: a ... ip 1 ... 17 2 ... 0
has comment: http://stackoverflow.com/comment/87292995
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/87293084
answer count: 0
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87293425

http://stackoverflow.com/comment/87334524
has text: Can you then provide that link so that your code turns into a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50114993
score: 1

http://stackoverflow.com/comment/90548254
has text: Hi gyoza, thanks for the solution. I am actually looking for automated way of scanning the excel file with an "If" statement. Something like.
type: Comment
comment on: http://stackoverflow.com/q/50082849
type: QuestionComment
score: 0

http://stackoverflow.com/q/50151228
has comment: http://stackoverflow.com/comment/87320280
has body: I have a list of dict, and i tried to write as CSV file with below code, it works. Sample Code: logKeys = logList[0].keys() with open('/home/ec2-user/lascsvoutputfiles/'+inputFileName+'_'+'logdata.csv', 'wb') as logFile: w = csv.DictWriter(logFile, logKeys) w.writeheader() w.writerows(logList) I tried to pass the delimiter as below, but it throws error. w = csv.DictWriter(logFile, delimiter='~', logKeys) Error log: File "LasioParser.py", line 44 w = csv.DictWriter(logFile, delimiter='~', logKeys) SyntaxError: non-keyword arg after keyword arg
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87320534
has title: Write list of dict to CSV with custom delimiter
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87320532
tagged with: python
has comment: http://stackoverflow.com/comment/87320393
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87320403
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50151357
accepted answer: http://stackoverflow.com/a/50151357
has comment: http://stackoverflow.com/comment/87320656
answer count: 1

http://stackoverflow.com/q/50162738
has answer: http://stackoverflow.com/a/50218541
has comment: http://stackoverflow.com/comment/87382480
downvote count: 0
tagged with: mod-wsgi
score: 1
upvote count: 1
has body: I have a Django project that runs without issue using the dev server (runserver), but fails when serving through Apache/WSGI. Ubuntu 16.04 Python 3.5.2 Django 2.0.4 mod_wsgi 4.6.4 The error is ImportError: No module named 'home' and here's the trace from Apache's error log: [Thu May 03 19:01:11.010623 2018] [mpm_event:notice] [pid 8568:tid 139727981401984] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.6.4 Python/3.5 configured -- resuming normal operations [Thu May 03 19:01:11.010742 2018] [mpm_event:info] [pid 8568:tid 139727981401984] AH00490: Server built: 2018-04-18T14:53:04 [Thu May 03 19:01:11.010763 2018] [core:notice] [pid 8568:tid 139727981401984] AH00094: Command line: '/usr/sbin/apache2' [Thu May 03 19:01:11.011684 2018] [wsgi:info] [pid 8572:tid 139727981401984] mod_wsgi (pid=8572): Python home /home/xxx/is_websites/webenv/. [Thu May 03 19:01:11.011766 2018] [wsgi:info] [pid 8572:tid 139727981401984] mod_wsgi (pid=8572): Initializing Python. [Thu May 03 19:01:11.014159 2018] [wsgi:info] [pid 8571:tid 139727981401984] mod_wsgi (pid=8571): Python home /home/xxx/is_websites/webenv/. [Thu May 03 19:01:11.014238 2018] [wsgi:info] [pid 8571:tid 139727981401984] mod_wsgi (pid=8571): Initializing Python. [Thu May 03 19:01:11.052639 2018] [wsgi:info] [pid 8572:tid 139727981401984] mod_wsgi (pid=8572): Attach interpreter ''. [Thu May 03 19:01:11.054513 2018] [wsgi:info] [pid 8571:tid 139727981401984] mod_wsgi (pid=8571): Attach interpreter ''. [Thu May 03 19:01:11.073009 2018] [wsgi:info] [pid 8571:tid 139727981401984] mod_wsgi (pid=8571): Adding '/home/xxx/is_websites/' to path. [Thu May 03 19:01:11.075298 2018] [wsgi:info] [pid 8572:tid 139727981401984] mod_wsgi (pid=8572): Adding '/home/xxx/is_websites/' to path. [Thu May 03 19:01:23.330027 2018] [wsgi:info] [pid 8572:tid 139727768385280] mod_wsgi (pid=8572): Create interpreter '127.0.1.1|'. [Thu May 03 19:01:23.346866 2018] [wsgi:info] [pid 8572:tid 139727768385280] mod_wsgi (pid=8572): Adding '/home/xxx/is_websi…
answer count: 1
has comment: http://stackoverflow.com/comment/87454019
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87451728
accepted answer: http://stackoverflow.com/a/50218541
has title: Django mod_wsgi: ImportError: No module named 'home'
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87453825
has comment: http://stackoverflow.com/comment/87381376
has comment: http://stackoverflow.com/comment/87346316
type: AnsweredQuestion

http://stackoverflow.com/comment/87455089
comment on: http://stackoverflow.com/q/50203272
type: Comment
type: QuestionComment
score: 0
has text: The `input_data.read_data_sets()` call already imports the MNIST images into your program. What are you trying to achieve by adjusting the code?

http://stackoverflow.com/q/50179326
answer count: 1
has body: I'm trying to run dockerfiles/django-uwsgi-nginx with my django project. https://github.com/dockerfiles/django-uwsgi-nginx 1.I replaced 'app' folder by my django project folder. 2.Comment out this line form Dockerfile #RUN django-admin.py startproject mailzon /home/docker/code/app/ 3.docker build -t my_app_name . 4.docker run -d -p 80:80 my_app_name Then I opened http://127.0.0.1/ I got error message. [ Internal Server Error ] last line of the manual. uWSGI chdirs to /app so in uwsgi.ini you will need to make sure the python path to the wsgi.py file is relative to that. I think I need this setting. but I'm not sure about uWSGI and this setting. What should I do next...? Please tell me how to resoleve this problem.
tagged with: django
tagged with: uwsgi
has answer: http://stackoverflow.com/a/50179532
type: Question
tagged with: nginx
tagged with: python
accepted answer: http://stackoverflow.com/a/50179532
tagged with: docker
type: AnsweredQuestion
score: 0
has title: How to run my django project in dockerfiles/django-uwsgi-nginx?

http://stackoverflow.com/a/55984511
has comment: http://stackoverflow.com/comment/117211415
type: Answer
answers question: http://stackoverflow.com/q/50193538
upvote count: 71
score: 69
downvote count: 2
has body: The accepted answer doesn't work for me, probably because nvidia-smi has different formats across different versions/hardware. I'm using a much cleaner command: nvidia-smi | grep 'python' | awk '{ print $3 }' | xargs -n1 kill -9 You can replace $3 in the awk expression to fit your nvidia-smi output. It is the n-th column in which the PIDs occur.
has comment: http://stackoverflow.com/comment/118284698
has comment: http://stackoverflow.com/comment/124169887
has comment: http://stackoverflow.com/comment/110608741
has comment: http://stackoverflow.com/comment/104301032
has comment: http://stackoverflow.com/comment/105255212

http://stackoverflow.com/comment/87486202
type: QuestionComment
score: 0
has text: I'm always a bit sceptical about `drawnow`. Would it be possible to get rid of that?
comment on: http://stackoverflow.com/q/50215803
type: Comment

http://stackoverflow.com/comment/87253380
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50117960
score: 0
has text: This is a lot of code to expect volunteers on SO to read. Please try to cut it down to the minimal amount of code necessary to reproduce your error. Try to create a [mcve]. However, based on your error message, it seems like you didn't pass in a required positional argument when calling the program. See if [this post](https://stackoverflow.com/questions/4117530/sys-argv1-meaning-in-script) helps you.

http://stackoverflow.com/comment/87324839
comment on: http://stackoverflow.com/q/50153245
has text: This is a common example when students are learning stack...
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87463621
has text: I think using [cron jobs](https://en.wikipedia.org/wiki/Cron) or some other system scheduler (no idea on Windows, sorry) will allow you to run a script daily. Just wrap your python script with a command line script to kick it off, and run that script with the cron job and you're good to go. EDIT: Vscode doesn't matter, that's just your IDE. If you're on a Mac, you can use cron jobs since they are unix! Look up a tutorial, they are super cool!
comment on: http://stackoverflow.com/q/50223024
type: QuestionComment
score: 3
type: Comment

http://stackoverflow.com/a/61617645
answers question: http://stackoverflow.com/q/50125844
type: Answer
score: 0
has body: You can use this class if you're dealing with pipelines from sklearn.base import TransformerMixin,BaseEstimator from sklearn.preprocessing import StandardScaler class Scaler(BaseEstimator,TransformerMixin): def __init__(self): self.scaler = StandardScaler() def fit(self,X,y=None): self.scaler.fit(X.reshape(X.shape[0], -1)) return self def transform(self,X): return self.scaler.transform(X.reshape(X.shape[0], -1)).reshape(X.shape)

http://stackoverflow.com/a/50155820
upvote count: 1
has body: First find the table which has all the info using its id=web_hosting_tbl attribute. Then iterate over all the rows of the table. But, if you look at the page source, the rows you need are not consecutive, but, alternate, and they don't have any class names. Also, the first row of the table is the header row, so we've to skip that. After getting the required rows (using table.find_all('tr')[1::2]), find all the columns and then get the required information from the corresponding columns. Code: import requests from bs4 import BeautifulSoup r = requests.get('https://myip.ms/browse/web_hosting/World_Web_Hosting_Global_Statistics.html') soup = BeautifulSoup(r.text, 'lxml') table = soup.find('table', id='web_hosting_tbl') for row in table.find_all('tr')[1::2]: all_columns = row.find_all('td') name = all_columns[1].a.text link = all_columns[1].a['href'] country = all_columns[2].a.text print(name, link, country, sep=' | ') Partial output: Godaddy.com, LLC | /view/web_hosting/2433/Godaddy_com_LLC.html | USA Cloudflare, Inc | /view/web_hosting/4638/Cloudflare_Inc.html | USA Amazon.com, Inc | /view/web_hosting/615/Amazon_com_Inc.html | USA Ovh Sas | /view/web_hosting/7593/Ovh_Sas.html | France Hetzner Online Ag | /view/web_hosting/45081/Hetzner_Online_Ag.html | Germany Hostgator.com Llc | /view/web_hosting/26757/Hostgator_com_Llc.html | USA Google Inc | /view/web_hosting/617/Google_Inc.html | USA Bluehost Inc | /view/web_hosting/3886/Bluehost_Inc.html | USA ...
has comment: http://stackoverflow.com/comment/87375967
has comment: http://stackoverflow.com/comment/87356767
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87375945
has comment: http://stackoverflow.com/comment/87334332
answers question: http://stackoverflow.com/q/50153092
has comment: http://stackoverflow.com/comment/87376263
downvote count: 0

http://stackoverflow.com/comment/87589851
type: AnswerComment
has text: I will try this as soon as possible. Seems a good example. Thanks.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50282803

http://stackoverflow.com/q/50185390
upvote count: 0
answer count: 1
has body: import os import cv2 import numpy as np from PIL import Image recognizer=cv2.face.LBPHFaceRecognizer_create(); path='dataSet' def getImagesWithID(path): imagePaths=[os.path.join(path,f) for f in os.listdir(path)] print imagePaths getImageWithID(path) this code is not working showing the problem related to title
score: -7
downvote count: 7
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/87387930
type: UnansweredQuestion
has title: unindent does not match any outer indentation level python3.6.4
linked to: http://stackoverflow.com/q/492387
tagged with: python
has comment: http://stackoverflow.com/comment/87387920
has answer: http://stackoverflow.com/a/50185472
has comment: http://stackoverflow.com/comment/87387944

http://stackoverflow.com/q/50127949
tagged with: python-3.x
answer count: 0
has body: The resulting file shows the year 0 0 0 eg 1985 0 0 0, 1986 0 0 0 and so on. It's not taking real values from given input file. I don't understand, where am I going wrong. I have 5 specific values in .txt files, such as file name, year, average max, average min and average precipitation. The data in YearlyAvarage.txt: USC00339312.txt 1985 14.11 3.96 100.67 USC00339312.txt 1986 15.09 5.13 94.76 USC00339312.txt 1987 15.66 5.28 81.15 USC00339312.txt 1988 15.22 3.66 89.82 USC00339312.txt 1989 14.48 3.98 101.83 My code: import glob import os import sys script_dir = os.path.dirname(os.path.realpath('__file__')) path = os.path.join(script_dir[0:-3],'YearlyAverages.txt') path1 = os.path.join(script_dir[0:-3],'YearHistogram.txt') file_list = glob.glob(os.path.join(os.getcwd(), "wx_data", "*.txt")) filelist = [] final_output = open('YearHistogram.txt', 'w') for files in sorted(file_list): filelist.append(files.split('/')[8]) file = open('YearlyAverages.txt','r') lines = file.read().splitlines() row_sets = [[c for c in line.split()] for line in lines] # print(row_sets) data=[] for f in filelist: subset = [row for row in row_sets if row[0] == str(f)] data.append(subset) diction = {} for dd in data: maxT = -sys.maxsize minT = sys.maxsize total = 0 diction[dd[0][0]] = {} for result in dd: #print(result) if maxT &lt; float(result[2]): maxT = max(maxT, float(result[2])) #print(maxT) tempMax = result[1] #print(tempMax) if minT &gt; float(result[3]): minT = min(minT, float(result[3])) tempMin = result[1] #print(tempMin) if total &lt; float(result[4]): total = max(total, float(result[4])) tempTotal = result[1] #print(tempTotal) diction[dd[0][0]]['max'] = tempMax diction[dd[0][0]]['min'] = tempMin diction[dd[0][0]]['total'] = tempTotal #print(diction) for year in range(1985, 2015): maxtotal = 0 mintotal = 0 prectotal = 0 for v in diction.values(): if v['max'] == str(year): maxtotal = maxtotal + 1 if v['min'] == str(year): mintotal = mintotal + 1 if v['total'] == str(year): prectotal = …
upvote count: 2
has title: Unable to generate the split values in new file
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87274684
favorite count: 0
has comment: http://stackoverflow.com/comment/87273851
score: 2
tagged with: python
type: Question

http://stackoverflow.com/comment/87356501
score: 0
comment on: http://stackoverflow.com/q/50168647
type: QuestionComment
has text: Unfortunately, I have no specific knowledge on this topic. All I can do is use Google to find related issues, e.g. [this possible workaround](https://bugs.python.org/issue30385#msg293958).
type: Comment

http://stackoverflow.com/a/50153639
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50150783
type: Answer
has body: This snippet might get you started. .... entry_text = ['e1', 'e2', 'e3'] .... # add text entries for x, text in enumerate(entry_text): e = ttk.Entry(mFrame, width=80, name=text) e.grid(column=1, row=x, sticky='WE', padx=5, pady=5) e.insert(0, text) .... e1Text = master.children['mFrame'].children['e1'].get() e2Text = master.children['mFrame'].children['e2'].get()
answers question: http://stackoverflow.com/q/50150783

http://stackoverflow.com/comment/87337319
comment on: http://stackoverflow.com/q/50159760
score: 0
type: Comment
has text: To _load_ data, open the file in _read_ mode.
type: QuestionComment

http://stackoverflow.com/comment/87360234
comment on: http://stackoverflow.com/q/50171466
score: 1
type: Comment
has text: Is your intention to get the current time or to put the time in the input display or to get the time when a user inputs a response or...?
type: QuestionComment

http://stackoverflow.com/q/50221820
has title: How can I remove last printed line in python?
linked to: http://stackoverflow.com/q/5419389
accepted answer: http://stackoverflow.com/a/50226948
has comment: http://stackoverflow.com/comment/87461248
type: AnsweredQuestion
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/4897359
has answer: http://stackoverflow.com/a/50226948
answer count: 2
has answer: http://stackoverflow.com/a/50221929
tagged with: countdown
type: Question
has body: I'm trying to make countdown program with python. I want to turn that into it removes last printed line, so i can print new second. import time def countdown(): minute = 60 while minute &gt;= 0: m, s = divmod(minute, 60) time_left = str(m).zfill(2) + ':' + str(s).zfill(2) print(time_left) time.sleep(1) minute -= 1 countdown() I am running python 2.7.13 on Raspberry Pi.
tagged with: time
possible better answer: http://stackoverflow.com/a/50221929
tagged with: python
has comment: http://stackoverflow.com/comment/87461231

http://stackoverflow.com/q/50177182
has body: I have moved our test framework into a docker container. One of my goals is to make it so we can spin up 1 container per test and then report he results. I have this working with the following [please remember this is a WIP]: api_test_runner.py import subprocess from api_test_list import single_test_list for test in single_test_list: command = subprocess.check_output(['docker', 'run', '-e', 'USER=root', '-e', 'TEST=' + test, 'api_test_container']) print(command) This runs through a list of tests and spins up a container for each one, but it waits for one container to stop before moving onto the next test: (py3_api_automation) remmac05674:api_automation$ python api_test_runner.py b'============================= test session starts ==============================\nplatform linux -- Python 3.6.4, pytest-3.2.5, py-1.5.2, pluggy-0.4.0\nrootdir: /app, inifile:\nplugins: xdist-1.20.1, forked-0.2, cloud-2.0.0\ncollected 1 item\n\ntest_1.py .\n\n=========================== 1 passed in 1.81 seconds ===========================\n' b'============================= test session starts ==============================\nplatform linux -- Python 3.6.4, pytest-3.2.5, py-1.5.2, pluggy-0.4.0\nrootdir: /app, inifile:\nplugins: xdist-1.20.1, forked-0.2, cloud-2.0.0\ncollected 1 item\n\ntest_2.py . What I am trying to sort out is how to have python run through the list of tests and kick off a container for each and not wait for other containers to finish.
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: docker
score: 2
answer count: 2
has title: Running docker containers asynchronously with python
has answer: http://stackoverflow.com/a/50179565
upvote count: 2
has answer: http://stackoverflow.com/a/50184233
downvote count: 0

http://stackoverflow.com/comment/87271271
comment on: http://stackoverflow.com/q/50126502
type: Comment
type: QuestionComment
has text: I wonder why you did add this `(?P<topic_pk>\d+)` in your url named 'topic_posts'?
score: 0

installation
tags question: http://stackoverflow.com/q/50103218
tags question: http://stackoverflow.com/q/50110917
tags question: http://stackoverflow.com/q/50181586
tags question: http://stackoverflow.com/q/50196561
tags question: http://stackoverflow.com/q/50170782
tags question: http://stackoverflow.com/q/50193551
tags question: http://stackoverflow.com/q/50200611
tag name: installation
tags question: http://stackoverflow.com/q/50205891
tags question: http://stackoverflow.com/q/50183068
tags question: http://stackoverflow.com/q/50182513
tags question: http://stackoverflow.com/q/50194070
tags question: http://stackoverflow.com/q/50195080
tags question: http://stackoverflow.com/q/50189972
tags question: http://stackoverflow.com/q/50129208
type: Tag
tags question: http://stackoverflow.com/q/50177846

http://stackoverflow.com/q/50213156
has comment: http://stackoverflow.com/comment/87443866
score: 0
answer count: 1
tagged with: reportlab
accepted answer: http://stackoverflow.com/a/50213521
type: Question
has title: Printing in memory object using win32api
has answer: http://stackoverflow.com/a/50213521
type: AnsweredQuestion
tagged with: winapi
tagged with: windows
tagged with: python
has body: Attempting to print a PDF generated with reportlab but ShellExecute() is throwing TypeError: Objects of type 'bytes' can not be converted to Unicode. I've tried pdf.decode('utf-8') but am getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0x93 in position 10: invalid start byte from io import BytesIO import win32api from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter x = 100 y = 100 buffer = BytesIO() p = canvas.Canvas(buffer, pagesize=letter) p.drawString(x, y, "Hello World") p.showPage() p.save() pdf = buffer.getvalue() buffer.close() win32api.ShellExecute(0, "print", pdf, None, ".", 0)

http://stackoverflow.com/comment/87280808
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50125824
score: 1
has text: Have you tried the ol' turn it on and off again/uninstall and reinstall?

http://stackoverflow.com/comment/87437779
type: AnswerComment
has text: @smci both computers are Windows 10. Sadly I forgot to mention the pip version and I have reinstalled python because I had to get some work done immediately.
comment on: http://stackoverflow.com/a/50190086
type: Comment
score: 0

http://stackoverflow.com/comment/87461325
score: 0
has text: thanks for the detailed answer but the error is __Error reading file 'XSLT_Script.xsl': failed to load external entity "XSLT_Script.xsl"__
type: Comment
comment on: http://stackoverflow.com/a/50220641
type: AnswerComment

http://stackoverflow.com/q/50100664
type: AnsweredQuestion
tagged with: view
score: 1
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/7357256
tagged with: forms
tagged with: templates
has comment: http://stackoverflow.com/comment/87244217
favorite count: 0
accepted answer: http://stackoverflow.com/a/50116142
type: Question
has answer: http://stackoverflow.com/a/50116142
has body: I have a Django view like this: def viewA(request): if request.POST.get('Go'): # Get all fields all = {} for key, values in request.POST.lists(): all[key]=values print (all) With this html: Numero de telefono When i click 'Go' button, i get "all" dict with the phone value inside. Ok. My problem is that i have another view where i create input elements with a template like this: {% for table, campos in tables.items %} {{table}} {% for campo in campos %} Varchar Int ... In this case, when i click 'Go' button don't retrieve the data for this elements created dynamically with django template. How can I get this? Thanks!
linked to: http://stackoverflow.com/q/1355728
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87240891
has comment: http://stackoverflow.com/comment/87236921
has title: Retrieve data from textfield elements created dynamically with Django templates

http://stackoverflow.com/comment/87289220
has text: Most probably you want to have an __init__ function.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50135612
type: Comment

http://stackoverflow.com/a/50140151
score: 0
has body: Here's something that's very similar to the second technique mentioned in @Bryan Oakley's answer except that does bind an event handler to each canvas item, not the the Canvas widget itself. To detect button clicks on widget itself that aren't on any item within it, a background rectangle item that fills the entire canvas is added first and given a special tag, which allows clicks which aren't on top of any other items on the canvas to be handled as special cases (such as calling a different event handler function). import tkinter as tk import random BKGR_TAG = '_background' BKGR_COLOR = 'bisque' RECT_SIZE = 50 WIDTH, HEIGHT = 400, 400 def on_click(event): current = event.widget.find_withtag('current') if current: item = current[0] tags = canvas.gettags(item) if BKGR_TAG in tags: msg = 'You clicked the background' # Do other things like call event handler for whole canvas... else: color = canvas.itemcget(item, 'fill') msg = 'You clicked on item with id %s (%s)' % (item, color) label.configure(text=msg) root = tk.Tk() label = tk.Label(root, anchor='w') canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT) label.pack(side='top', fill='x') canvas.pack(fill='both', expand=True) # Create background rect same size as canvas. bkgr = canvas.create_rectangle(0, 0, WIDTH, HEIGHT, width=0, fill=BKGR_COLOR, tags=BKGR_TAG) # Marked with special tag. canvas.tag_bind(bkgr, '&lt;ButtonPress-1&gt;', on_click) for color in ('red', 'orange', 'yellow', 'green', 'blue', 'violet'): x0 = random.randint(RECT_SIZE, WIDTH-RECT_SIZE) y0 = random.randint(RECT_SIZE, HEIGHT-RECT_SIZE) id = canvas.create_rectangle(x0, y0, x0+RECT_SIZE, y0+RECT_SIZE, outline='black', fill=color) canvas.tag_bind(id, '&lt;ButtonPress-1&gt;', on_click) root.mainloop()
answers question: http://stackoverflow.com/q/50118811
type: Answer

http://stackoverflow.com/comment/87285945
has text: store the buttons in a dictionary if you want to give them names.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50133805

http://stackoverflow.com/q/50206800
has body: I am creating an application manages an interview process. In one interview, a candidate can be interviewed by one or more interviewer and an interviewer can interview one or more candidates. This is similar to a "round table" interview. The simplified version of the models are: class Interviewer(models.Model): interviewer_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False) candidates = models.ManyToManyField('Candidate', through='Interview') class Candidate(models.Model): candidate_id = models.PositiveIntegerField( primary_key=True, blank=False, null=False) first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False class Interview(models.Model): interview_name = models.CharField(max_length=200, blank=True, null=True) candidates = models.ForeignKey( Candidate, on_delete=models.CASCADE, blank=True, null=True, related_name='candidates') interviewers = models.ForeignKey( Interviewer, on_delete=models.CASCADE, blank=True, null=True, related_name='interviewers') In Django admin, for the Interview model, adding an entry for an interview would mean that I would have to create the entry for each candidate and interviewer. This process is cumbersome if there are a lot of candidates and/or interviewers. What I would like to do is to add all candidates and the interviewers for a particular interview. I changed my model to use ModelMultipleChoiceField form instead of the default SelectField for Django uses for Foreign Keys. class InterviewAdminForm(forms.ModelForm): interviewers = forms.ModelMultipleChoiceField( queryset=Interviewer.objects.all(), widget=FilteredSelectMultiple( verbose_name='interviewers', is_stacked=False ) ) candidates = forms.ModelMultipleChoiceField( queryset=Candidate.objects.all(), widget=FilteredSelectMultiple( verbose_name='candidates', is_stacked…
has comment: http://stackoverflow.com/comment/87431333
has title: Saving two or multiple records at the same time with a foreign key relation in Django Admin
score: 0
answer count: 0
tagged with: django
tagged with: django-forms
tagged with: python-3.x
type: Question
type: UnansweredQuestion
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/87431537

http://stackoverflow.com/comment/87284045
type: Comment
comment on: http://stackoverflow.com/a/50132327
type: AnswerComment
has text: No it is not if this is the case. In this case using `with ThreadPoolExecutor()` is a good way of doing this, and it will take care of garbage collecting and shutting down the pool for you.
score: 1

http://stackoverflow.com/q/50159000
has body: Let's say I have values = [0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50] and I want to scale each element by a weight, so values get smaller (or bigger) faster the further they are from the mean. That is, to get «small numbers» (numbers below the average) bigger, and «big numbers» (numbers over the average) smaller. Let's pretend the average is 1, then: scale(values) -&gt; [0.6, 0.7, 0.8, 1, 1.5, 4, 8, 12, 20] Values over the average would decrease faster the further they are (2 to 1.5, but 50 to 20), while values under the average would increase faster the further they are (0.5 to 0.8, but 0.1 to 0.6). I tried searching for «how to normalize data», but such answers scale all values equally. For example scaled = [(i - min(values))/max(values) for i in values] Also, I need to control the weight in which the values are scaled.
tagged with: python
has title: How to scale a list by a weight?
possible better answer: http://stackoverflow.com/a/50159260
has comment: http://stackoverflow.com/comment/87336294
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50159260
accepted answer: http://stackoverflow.com/a/50159132
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50159132
has comment: http://stackoverflow.com/comment/87335843
downvote count: 0
has comment: http://stackoverflow.com/comment/87335766
has comment: http://stackoverflow.com/comment/87337230
has comment: http://stackoverflow.com/comment/87336498
has comment: http://stackoverflow.com/comment/87335763
tagged with: statistics
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87335782

mime-message
type: Tag
tags question: http://stackoverflow.com/q/50200540
tag name: mime-message

http://stackoverflow.com/comment/87500243
comment on: http://stackoverflow.com/a/50224471
score: 0
type: Comment
type: AnswerComment
has text: in this case, my code will just return the index of the first row...

http://stackoverflow.com/comment/87339893
has text: In the output `df1` what `id` does the `straw` value have? Is it also `1`? Or are `mango` & `straw` in a list? Or is something else going on?
type: QuestionComment
comment on: http://stackoverflow.com/q/50160708
type: Comment
score: 0

http://stackoverflow.com/q/50171754
has comment: http://stackoverflow.com/comment/87360894
favorite count: 0
tagged with: linux-kernel
type: AnsweredQuestion
tagged with: linux
accepted answer: http://stackoverflow.com/a/50172010
has body: I'm trying to write a script in python3.6 on linux that takes a user's input (in the form of a URL), then performs the 'whois' terminal command on the input provided. I'm trying to launch it from IDLE. The best I've got is: import os os.system("clear") os.system("gnome-terminal -e 'bash -c \'") w = "" w = (input("Who is your target?" )) os.system("whois " + w) It seems that after taking the input, the gnome terminal doesn't open, and nothing happens. I'm not very experienced in python at the moment and I'm struggling quite a bit with this!
has answer: http://stackoverflow.com/a/50172010
has comment: http://stackoverflow.com/comment/87361083
has title: How do I create a script that will take user input and use it in a terminal command using python 3.6?
type: Question
tagged with: python-3.x
score: 2
upvote count: 2
answer count: 1
downvote count: 0
tagged with: python
tagged with: python-3.6

http://stackoverflow.com/comment/87445531
type: Comment
type: AnswerComment
has text: @SergeBallesta. I am just give an idea or logic on how to solve the problem. It will also help in code readability
score: 0
comment on: http://stackoverflow.com/a/50214305

http://stackoverflow.com/q/50105268
type: Question
linked to: http://stackoverflow.com/q/38380795
downvote count: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50105316
accepted answer: http://stackoverflow.com/a/50105316
has body: When writing data to json from a pandas.Series object using to_json, then reading that data in using pandas.read_json, I receive the following ValueError. import pandas as pd js = pd.Series([1, 2, 3], index=list('abc')).to_json() js # out: '{"a":1,"b":2,"c":3}' pd.read_json(js) # Traceback ... # ValueError: If using all scalar values, you must pass an index Apparently because the json data contains just index:value pairs, the read_json function doesn't know to interpret the keys as indexes. I also tried the following orient option based on the docs, which resulted in a different ValueError. js = pd.Series([1, 2, 3], index=list('abc'), name='mydata').to_json(orient='split') js # out: '{"name":"mydata","index":["a","b","c"],"data":[1,2,3]}' pd.read_json(js, orient='split') # Traceback ... # ValueError: JSON data had unexpected key(s): name My question is: how do I configure Series.to_json to be compatible with pd.read_json? Is this a bug/opportunity to improve the Series default json write/read behavior? Thanks for the help!
tagged with: series
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
has title: Pandas Series writing and reading json data gives ValueError with to_json and read_json
duplicate of: http://stackoverflow.com/q/38380795
favorite count: 0

http://stackoverflow.com/q/50109605
type: UnansweredQuestion
has body: who are yours?...sorry for my english translate but im from Spain, and my english is very bad, sorry. Im trying to make a program for my class of Computational Physical Programmation. I need to study the position and the velocity of 2-phase rocket, changing the % of gas of the first phase(it, obviously, change the % of 2 phase gas,Masa1= mass of 1phase, Masa 2= mass of 2phase). Changing the gas, change the time of fly. I wish to put all data whit odeint like this: from numpy import * #importamos todo lo que from scipy.integrate import odeint #podamos necesitar a lo largo import matplotlib.pyplot as plt #del programa #funciones def funder (M,t,u,D,m0): #funcion para calcular luego '''funcion derivada''' #la integral de la funcion y, v=M[0],M[1] return array([v,u*D/(m0-(D*t))]) #constantes ni=100 #numero de intervalos #cohete de una fase #Datos propuestos en el enunciado para una primera prueba D=13840. #Kg/s cantidad de combustible que se quema por segundo m0=2.85e6 #Kg masa total inicial u=2.46 #km/s velocidad de salida de los gases r=0.05 #proporcion de la masa recipiente mu=0.47*m0 #masa util mc=(m0-mu)/(1+r) #masa combustible t0=mc/D #tiempo que tarda en quemar el cobustible en una etapa #condiciones iniciales y0, v0 =0, 0 #posicion y velocidades iniciales igual ListaPorce=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] #lista de #porcentajes,luego se convertira #en un array Intervalos=[] #lista con los #intervalos de tiempo de los #distintos porcentajes de combustible for i in ListaPorce: #para los i en ListaPorce, haz: Combustible=mc*i #multiplicara los indices por #el combustible #asi sabemos que cantidad de #combustible para cada porcentaje tempo=linspace(0,(Combustible/D),ni) #tempo es el array de tiempos #para cada porcentaje de combustible Intervalos.append(tempo) #añade tempo a la lista #Intervalos, que luego sera un array Duracion=array(Intervalos) #convertimos la lista #Intervalos al array Duracion Porcentaje=array(ListaPorce) #convertimos la lista #ListaPorce al…
tagged with: odeint
tagged with: python
has comment: http://stackoverflow.com/comment/87236610
score: 0
linked to: http://stackoverflow.com/q/13293731
has title: Who can i do this? object too deep for desired array
type: Question
has comment: http://stackoverflow.com/comment/87236527
has comment: http://stackoverflow.com/comment/87236511
has comment: http://stackoverflow.com/comment/87237524
answer count: 0

http://stackoverflow.com/comment/87282660
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50131596
score: 0
has text: If I run the code above (adding in the needed imports and setting the two lists up as a list of numbers, the code seems to work fine. When you say "two huge lists", what exactly do you mean. From the code you've shown, they don't look huge...

http://stackoverflow.com/comment/87324611
type: Comment
has text: I copied your code about 3 times, all returned False
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50153412

http://stackoverflow.com/q/50224640
tagged with: urllib
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87467025
has title: Parse JSON from Bittrex
type: UnansweredQuestion
tagged with: python
has body: I have this code: import urllib2 import json from matplotlib.finance import candlestick2_ohlc import matplotlib.pyplot as plt import matplotlib.ticker as ticker import datetime as datetime import numpy as np import csv l = [] date = [] date_intermediaire = [] response = urllib2.urlopen('https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-ETH&amp;tickInterval=thirtyMin&amp;_=') data = json.load(response) where data['result'][:]['T'] contains the time, data['result'][:]['V'] contains the volume ,data['result'][i]['O'] contains the opens, data['result'][i]['C'] contains the close,data['result'][:]['L'] contains the low, data['result'][:]['H'] contains the high And actually I would like to make easier this defining r like this: r['date'][i] = data['result'][i]['T'] r['open'][i] = data['result'][i]['O'] r['close'][i] = data['result'][i]['C'] r['max'][i] = data['result'][i]['H'] r['min'][i] = data['result'][i]['L'] r['volume'][i] = data['result'][i]['V'] But I don't know how to do this in Python.
favorite count: 0
has answer: http://stackoverflow.com/a/50224738
has answer: http://stackoverflow.com/a/50224745
answer count: 3
has answer: http://stackoverflow.com/a/50224832
score: 1
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
has comment: http://stackoverflow.com/comment/87466921

http://stackoverflow.com/q/50182532
has answer: http://stackoverflow.com/a/50183141
tagged with: python
has body: Just running the application I got the correct results on the QPlainTextEdit area on the screen: But when clicking on the button Start Simulation and recovering the input from it with QPlainTextEdit.toPlainText(), the output goes invalid: def handle_first_input_text(self): textEdit = self.textEditWidget1.toPlainText() print( "%s", textEdit ) Also, when trying to retrieve the Delta δ from the image, this error is throw up: Traceback (most recent call last): File "main.py", line 57, in handle_first_input_text print( "%s", textEdit ) File "F:\Python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u03b4' in position 11: character maps to <undefined> How can I retrieve the input the correctly from the QPlainTextEdit? This is the minimal code for the error, just hit Start Simulation and look for the console output. #! /usr/bin/env python # -*- coding: utf-8 -*- import sys from PyQt5 import QtGui from PyQt5 import QtWidgets from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * def main(): app = QtWidgets.QApplication(sys.argv) programWindow = ProgramWindow() programWindow.show() sys.exit(app.exec_()) class ProgramWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setup_main_window() self.first_input_text() self.set_window_layout() def setup_main_window(self): self.resize( 800, 600 ) self.centralwidget = QWidget() self.setCentralWidget( self.centralwidget ) def first_input_text(self): self.textEditWidget1 = QPlainTextEdit( self ) self.startSimulationButton1 = QPushButton( "Start Simulation" ) self.textEditWidget1.document().setPlainText( " # Writing δ some ç é ã õ") self.startSimulationButton1.clicked.connect( self.handle_first_input_text ) verticalInnerLayout = QVBoxLayout() verticalInnerLayout.addWidget( self.startSimulationButton1 ) horizontalInnerLayout = QHBoxLayout() horizonta…
tagged with: qt
has title: How to correctly get Unicode text input from QPlainTextEdit?
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/40660333
linked to: http://stackoverflow.com/q/27092833
tagged with: pyqt5
duplicate of: http://stackoverflow.com/q/27092833
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50183141
answer count: 2
tagged with: encoding
has answer: http://stackoverflow.com/a/50183542
accepted answer: http://stackoverflow.com/a/50183542

http://stackoverflow.com/comment/87469243
score: 1
comment on: http://stackoverflow.com/a/50218049
type: Comment
type: AnswerComment
has text: Thank you very much, this did indeed solve my problem. I already had each block as a list of strings in my code so this was easily expanded and it worked efficiently on the entire dataset. I am struggling with understanding how zip() works but I'll do some reading there.

http://stackoverflow.com/q/50181095
favorite count: 0
type: Question
has body: I have the following imports import time import os import daemon When I click Code -> Optimize Imports in PyCharm I expect it to follow PEP 8 Imports Conventions (which should result in swapping time and os). But what I get is the following: import time import daemon import os As you can see, PyCharm treats os module as if it was a third party module. This behavior was noticed in 2017.1 and 2017.3 versions of Pycharm. Is this still the case in 2018.1? Or may it be some configuration problem?
score: 3
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90247478
has title: PyCharm treats os like a third party module when optimizing imports
upvote count: 3
answer count: 0
tagged with: pycharm
downvote count: 0
has comment: http://stackoverflow.com/comment/87379586
has comment: http://stackoverflow.com/comment/90200573

http://stackoverflow.com/a/50206065
has comment: http://stackoverflow.com/comment/87430047
has comment: http://stackoverflow.com/comment/87429281
has comment: http://stackoverflow.com/comment/87429942
has comment: http://stackoverflow.com/comment/87429314
has comment: http://stackoverflow.com/comment/87575164
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87430581
accepted answer of: http://stackoverflow.com/q/50205977
has comment: http://stackoverflow.com/comment/87431117
has comment: http://stackoverflow.com/comment/87430030
has comment: http://stackoverflow.com/comment/87430876
downvote count: 0
has comment: http://stackoverflow.com/comment/87430452
has comment: http://stackoverflow.com/comment/87429252
has comment: http://stackoverflow.com/comment/87431070
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87431043
has body: You code fails because in each iteration you read only one line (which can contain host or version but not both, yet you write data into csv. Let's iterate through all the text while matching twoliners: with first line Hostname.. and second line version... \n works as line break for Windows (I hear Mac uses \r not sure). Now since you match twoliners you can grab both router and version from same match object. with open('testfile.txt','r',encoding='utf-8') as input: txt = input.read() pattern = re.compile(r'Hostname (.*)(\r\n?|\n)version (.*)') match=pattern.finditer(txt) for match1 in match: with open('sample5.csv', 'a',newline='') as output: writer = csv.DictWriter(output, fieldnames=HeaderFields) writer.writerow({'Hostname': match1.group(1), 'version': match1.group(3)})
answers question: http://stackoverflow.com/q/50205977
has comment: http://stackoverflow.com/comment/87547686
has comment: http://stackoverflow.com/comment/87429469
has comment: http://stackoverflow.com/comment/87431096
has comment: http://stackoverflow.com/comment/87507410
has comment: http://stackoverflow.com/comment/87430238
type: Answer
has comment: http://stackoverflow.com/comment/87430163

http://stackoverflow.com/comment/115419932
score: 0
comment on: http://stackoverflow.com/q/50133478
type: Comment
type: QuestionComment
has text: Indeed completely broken. I am using `python-lorem` from [here](https://github.com/JarryShaw/lorem)

http://stackoverflow.com/a/50152289
has body: Comprehension will do it: [i &gt; 1 for i in a] Otherwise you can use numpy: a = np.array([-1,-1,0,2]) a &gt; 1 #[False False False True]
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50152243

http://stackoverflow.com/a/50105365
answers question: http://stackoverflow.com/q/50105309
type: Answer
has body: You might want to check out string.split to solve this issue for you: row['team_members'] = row['team_members'].split(', ') This will replace the "team_members" field by an array split over the commas.
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/87461533
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50222032
has text: I just ran your code, "--beer is in the menu" is True

series
tags question: http://stackoverflow.com/q/50105268
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/50197501
tags question: http://stackoverflow.com/q/50165398
tags question: http://stackoverflow.com/q/50189804
tags question: http://stackoverflow.com/q/50208189

http://stackoverflow.com/comment/87268307
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50124994
has text: You only have to save the first time to initially create the file; once it's on disk as long as `Tools > Save all on build` is turned on, it will save automatically from that point forward.
score: 0

http://stackoverflow.com/a/50166061
answers question: http://stackoverflow.com/q/50165911
score: 0
has comment: http://stackoverflow.com/comment/87350231
has comment: http://stackoverflow.com/comment/87350211
has body: IIUC, you can do this all from within pandas, without the datetime module. I'm assuming your starting dataframe looks something like: &gt;&gt;&gt; dataframe1 Dispatch Date Order Date 0 2017-03-02 2017-02-13 1 2017-03-06 2017-02-24 In which case, you can do: # set columns to datetime: dataframe1['Order Date'] = pd.to_datetime(dataframe1['Order Date']) dataframe1['Dispatch Date'] = pd.to_datetime(dataframe1['Dispatch Date']) # Make a new column for the difference in days dataframe1['day_diff'] = dataframe1['Dispatch Date'] - dataframe1['Order Date'] Which outputs: &gt;&gt;&gt; df Dispatch Date Order Date day_diff 0 2017-03-02 2017-02-13 17 days 1 2017-03-06 2017-02-24 10 days Explanation: subtracting two datetime objects in pandas results in a Timedelta object (as in the new column day_diff). If you want it as an integer reprsentation of the number of days, just add dt.days to that last command: dataframe1['day_diff'] = (dataframe1['Dispatch Date'] - dataframe1['Order Date']).dt.days
has comment: http://stackoverflow.com/comment/87351697
type: Answer
has comment: http://stackoverflow.com/comment/87351692

http://stackoverflow.com/q/50178866
upvote count: 3
has comment: http://stackoverflow.com/comment/87437357
downvote count: 0
has title: save checkpoint with Tensorflow
has comment: http://stackoverflow.com/comment/87381269
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/50182819
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50181216
has comment: http://stackoverflow.com/comment/87674402
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87437690
has comment: http://stackoverflow.com/comment/87438251
has body: I have 3 folders for my CNN model which are train_data, val_data, test_data. when I am training my model, I found that the accuracy may vary and sometimes the last epoch does not show the best accuracy. for example, last epoch accuracy is 71% but I found the better accuracy in the earlier epoch. I want to save the checkpoint of that epoch which has higher accuracy and then use that checkpoint to predict my model on test_data I trained my model on train_data and predicted on val_data and save the checkpoint of the model like below: print(&quot;{} Saving checkpoint of model...&quot;. format(datetime.now())) checkpoint_path = os.path.join(checkpoint_dir, 'model_epoch' + str(epoch) + '.ckpt') save_path = saver.save(session, checkpoint_path) and before starting the tf.Session() I have this line: saver = tf.train.Saver() I want to know how can I save the best epoch which has higher accuracy and then use this checkpoint for my test_data?
tagged with: python
has comment: http://stackoverflow.com/comment/87442368
tagged with: tensorflow-estimator
has comment: http://stackoverflow.com/comment/87381618
score: 3
answer count: 2

http://stackoverflow.com/comment/87313704
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50146968
score: 0
has text: sorry wrong traceback..edited the post. but I still get the error. Are you mac or windows or it doesnt matter?

http://stackoverflow.com/comment/87291468
has text: @Isma, 'opis.txt' file has already some lines with text, so I can't just replace it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50136568
score: 0

http://stackoverflow.com/q/50113009
upvote count: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0
tagged with: parsing
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50113468
tagged with: python
has answer: http://stackoverflow.com/a/50113562
has body: The official tensorflow tutorial suggests parsing csv files by using a tf.TextLineReader to read the file line by line and then using tf.decode_csv (source). This does however not work with csv records containing strings with newlines, since this causes a single csv record to be split up by the reader. What is the best way to parse these types of files?
score: 0
answer count: 2
has title: How to parse strings with newlines from a csv file in tensorflow?

http://stackoverflow.com/a/50180401
has body: Here is a solution using Counter from collections import Counter def is_superset(l1, l2): c1, c2 = Counter(l1), Counter(l2) return all(c1[k] &gt;= c2[k] for k in c2)
upvote count: 5
type: Answer
score: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/87378146
has comment: http://stackoverflow.com/comment/87378041
answers question: http://stackoverflow.com/q/50180303
has comment: http://stackoverflow.com/comment/87377988

http://stackoverflow.com/q/50141784
has comment: http://stackoverflow.com/comment/87302029
tagged with: python
has body: In a C program, inlining a function is a fairly intuitive optimization. If the inlined function's body is sufficiently small, you end up saving the jump to the function and creation of the stack frame, and you store the return value wherever the function's result would have been stored, jumping to the end of the inlined function's "body" rather than long-jumping to the return pointer. I'm interested in doing the same thing in Python, converting two python functions into another valid python function where the first got "inlined" into the second. An ideal solution to this might look something like the following: def g(x): return x ** 2 def f(y): return g(y + 3) # ... Becomes ... def inlined_f(y): return (y + 3) ** 2 Clearly, in a language as dynamic as Python, this isn't trivial to do automatically. The best generic solution I have come up with is to use dict to capture the arguments passed to the function, wrap the function body in a one-iteration for loop, use break to jump to the end of the function, and replace uses of arguments with indexes into the argument dictionary. The result looks something like the following: def inlined_f(y): _g = dict(x=y + 3) for ____ in [None]: _g['return'] = _g['x'] ** 2 break _g_return = _g.get('return', None) del _g return _g_return I don't care that it's ugly, but I do care that it doesn't support returns from within loops. E.g.: def g(x): for i in range(x + 1): if i == x: return i ** 2 print("Woops, you shouldn't get here") def inlined_f(y): _g = dict(x=y + 3) for ____ in [None]: for _g['i'] in range(_g['x'] + 1): if _g['i'] == _g['x']: _g['return'] _g['i'] ** 2 break # &lt;-- Doesn't exit function, just innermost loop print("Woops, you shouldn't get here") _g_return = _g.get('return', None) del _g return _g_return What approach could I take to this problem that avoids needing to use break to "jump" out of the inlined function's body? I'd also be open to an overall better, generic approach could I take to inline one Python functi…
has comment: http://stackoverflow.com/comment/87303453
has comment: http://stackoverflow.com/comment/87303368
type: Question
upvote count: 9
score: 9
has answer: http://stackoverflow.com/a/50142522
answer count: 2
tagged with: abstract-syntax-tree
downvote count: 0
accepted answer: http://stackoverflow.com/a/50142003
has comment: http://stackoverflow.com/comment/87302641
has comment: http://stackoverflow.com/comment/87301998
has comment: http://stackoverflow.com/comment/87302208
possible better answer: http://stackoverflow.com/a/50142522
has comment: http://stackoverflow.com/comment/87302852
tagged with: compiler-optimization
favorite count: 0
has comment: http://stackoverflow.com/comment/87303105
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87303423
has answer: http://stackoverflow.com/a/50142003
tagged with: inline
has comment: http://stackoverflow.com/comment/87302954
has title: Inlining Python Function
has comment: http://stackoverflow.com/comment/87303082

http://stackoverflow.com/q/50144074
tagged with: regex
possible better answer: http://stackoverflow.com/a/50144186
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50144186
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50144198
type: AnsweredQuestion
upvote count: 3
score: 3
downvote count: 0
has body: Let's say I have a string : s = "id_john, num847, id_000, num___" I know how to retrieve either of 2 patterns with |: re.findall("id_[a-z]+|num[0-9]+", s) #### ['id_john', 'num847'] # OK I know how to capture a portion only of a match with parenthesis: re.findall("id_([a-z]+)", s) #### ['john'] But I fail when i try to combine those two features, this is my desired output: #### ['john', '847'] Thanks for your help.. (I work with python)
has title: regex: combine capturing group with OR condition
has answer: http://stackoverflow.com/a/50144198

http://stackoverflow.com/comment/87349146
type: AnswerComment
has text: no, I moved the second and third columns, in order to understand my question
comment on: http://stackoverflow.com/a/50165437
score: 0
type: Comment

http://stackoverflow.com/a/50097142
score: 0
answers question: http://stackoverflow.com/q/50097048
type: Answer
has body: You are passing a list as a single argument, you need to expand the list, to unpack the list you can use * myClass(*list())

http://stackoverflow.com/comment/87416513
comment on: http://stackoverflow.com/q/50200002
has text: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profiles', 'crispy_forms', 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', ]
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50204126
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87425440
has body: Why don't you just use the same arguments as the class you want to subclass? import seaborn class CustomJointGrid(seaborn.JointGrid): def __init__(self, x, y, data=None, size=6, ratio=5, space=.2, dropna=True, xlim=None, ylim=None, **kwargs): super().__init__(x, y, data=data, size=size, ratio=ratio, space=space, dropna=dropna, xlim=xlim, ylim=ylim) Else you could set some default yourself, class CustomJointGrid(seaborn.JointGrid): def __init__(self, *args, **kwargs): size = kwargs.get("size", 6) kwargs.update(size=size) super().__init__(*args, **kwargs) # use size here self.someattribute = size*100
has comment: http://stackoverflow.com/comment/87425200
type: Answer
answers question: http://stackoverflow.com/q/50203934
has comment: http://stackoverflow.com/comment/87425587
has comment: http://stackoverflow.com/comment/87425547
has comment: http://stackoverflow.com/comment/87426405
has comment: http://stackoverflow.com/comment/87425289
downvote count: 0

http://stackoverflow.com/a/50106434
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87230945
accepted answer of: http://stackoverflow.com/q/50106240
has comment: http://stackoverflow.com/comment/87231833
answers question: http://stackoverflow.com/q/50106240
type: Answer
has body: The 'USER' environment variable seems not to defined within your image. Define it externally, or make your code resilient to its absence: In your code, use os.getenv('USER', backup_user_name) instead of os.environ['USER'] In your code, use getpass instead of relying on your environment to get the current user. import getpass print getpass.getuser() In docker run, you could add -e USER=$(whoami) or something of that sort In docker-compose, you could add USER: some_user_name under the environ setting for that service.
score: 3
upvote count: 3

http://stackoverflow.com/comment/87396358
type: QuestionComment
comment on: http://stackoverflow.com/q/50189726
score: 0
has text: Oh im sorry ill edit my question right now.
type: Comment

http://stackoverflow.com/comment/87406861
type: Comment
score: 0
type: QuestionComment
has text: Show us what you've tried so far.
comment on: http://stackoverflow.com/q/50194900

http://stackoverflow.com/comment/87333786
comment on: http://stackoverflow.com/q/50157543
type: Comment
type: QuestionComment
has text: You write about `ModuleNotFoundError`. Is there a typo in `utuls.get_original_title_and_name.requests.get` (utuls -> utils)
score: 0

http://stackoverflow.com/a/50134688
answers question: http://stackoverflow.com/q/50131811
has body: train_step is an operation not a tensor, and it has no outputs. Therefore train_step:0 refers to nothing, as it is trying to point to the first output of the operation. Try print( tf.get_default_graph().get_operation_by_name( "train_step" ) )
has comment: http://stackoverflow.com/comment/87289122
accepted answer of: http://stackoverflow.com/q/50131811
type: Answer
has comment: http://stackoverflow.com/comment/87301464
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50222978
has comment: http://stackoverflow.com/comment/87463839
score: 3
linked to: http://stackoverflow.com/q/37039923
has comment: http://stackoverflow.com/comment/87464731
tagged with: matrix
upvote count: 3
has comment: http://stackoverflow.com/comment/87465093
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87466640
has answer: http://stackoverflow.com/a/50223074
has answer: http://stackoverflow.com/a/50223064
answer count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87463742
has comment: http://stackoverflow.com/comment/87464667
tagged with: python
has title: Assembling matrices in python (scipy/numpy)
has body: I was wondering if there is an easy way to assemble matrices along the diagonal in python, adding values if they overlap. Here is a handy diagram I stole from the Matlab forum: https://i.sstatic.net/ZunrZ.jpg Currently, I am trying to implement it to work with a set number of 2x2 matrices, but the end goal is to make the code assemble an arbitrary amount of arbitrary sized matrices(all the same size ofc., max 4x4).
linked to: http://stackoverflow.com/q/21139822

http://stackoverflow.com/q/50164522
has comment: http://stackoverflow.com/comment/87347224
has body: It is a weird question but I wondering if it is possible to build a dict that value contains key in key-value pairs in python. As following, I would like to rewrite the following class SwitchTest by replace duplicated customer, product, animal in value from key-value pair of instance. How can I do that? or more specifically how can I get key's value in value inside a dictionary? class Product(): def __init__(self, para): self.para = para ..... class Animal(): def __init__(self, para): self.para = para .... class Human(): def __init__(self, para): self.para = para .... class SwitchTest(): def __init__(self): instance = {'customer': lambda x: setattr(SwitchTest, 'customer', Human(x)), 'product': lambda x: setattr(self, 'product', Product(x)), 'animal': lambda x: setattr(self, 'animal', Animal(x))}
type: Question
answer count: 2
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87347095
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50164879
has comment: http://stackoverflow.com/comment/87347105
has answer: http://stackoverflow.com/a/50164615
tagged with: python
score: -1
has title: how to get key's value in value in key-value pair dict

scroll
type: Tag
tags question: http://stackoverflow.com/q/50162438
tag name: scroll
tags question: http://stackoverflow.com/q/50222689

http://stackoverflow.com/comment/87268767
comment on: http://stackoverflow.com/a/50118325
has text: this is better and cleaner without mocking.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50165614
has comment: http://stackoverflow.com/comment/87350340
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87350861
has comment: http://stackoverflow.com/comment/87403111
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/87351518
has body: Suppose I have the following pandas data frame: userID dayID feature0 feature1 feature2 feature3 xy1 0 24 15.3 41 43 xy1 1 5 24 34 40 xy1 2 30 7 8 10 gh3 0 50 4 11 12 gh3 1 49 3 59 11 gh3 2 4 9 12 15 ... There are many userID's and each one has 3 days and 4 features per day. What I want to do is for each feature, select 1 of the days at random and then cut down the matrix. So for instance, if feature 0 was day 1, feature 1 used day 0, feature 2 used day 0 and feature 3 used day 2: userID feature0 feature1 feature2 feature3 xy1 5 15.3 41 10 gh3 49 4 11 15 ... And so forth. I've come up with: I thought the this code works but it does not. reduced_features = features.reset_index().groupby('userID').agg(lambda x: np.random.choice(x,1)) But this seems slow. Is there a faster way to do it?
downvote count: 0
has comment: http://stackoverflow.com/comment/87350266
possible better answer: http://stackoverflow.com/a/50167249
favorite count: 0
has answer: http://stackoverflow.com/a/50167249
type: Question
accepted answer: http://stackoverflow.com/a/50176681
score: 8
upvote count: 8
has answer: http://stackoverflow.com/a/50176681
has comment: http://stackoverflow.com/comment/87352288
has comment: http://stackoverflow.com/comment/87351403
has title: Selecting a random value in a pandas data frame by column
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87352086
has comment: http://stackoverflow.com/comment/87350139

http://stackoverflow.com/comment/87579573
comment on: http://stackoverflow.com/q/50202829
type: Comment
type: QuestionComment
score: 0
has text: well i disagree. I stated i created 2 virtual environments and that didn't work. i also tried selecting a python2 interpreter from command pallett and that didn't work either. i was out of options after that.

http://stackoverflow.com/comment/87228076
comment on: http://stackoverflow.com/q/50105249
score: 0
type: QuestionComment
type: Comment
has text: See this lovely [debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) blog for help. Please explain more about where your program is deviating from the expected results.

http://stackoverflow.com/comment/87266715
score: 0
comment on: http://stackoverflow.com/q/50124201
has text: @Aran-Fey Python is a popular language for code golf challenges. There are also circumstances where the size of your source code can matter (micro computers). Day to day, this might be a bad idea, but maybe OP has a legitimate use case for it.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50146978
has answer: http://stackoverflow.com/a/50147246
upvote count: 4
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50147452
possible better answer: http://stackoverflow.com/a/50147452
has body: I have a time series data. But data has discontinuity.(2005-03-02 02:08:00 is missing). I need a new column C such that C(i)=A(i)+B(i)+average, where my average is the average of B up to the discontinuity (02:08:00). average=Data.loc['2005-03-02 02:05:30':'2005-03-02 02:07:30',['B']].mean(axis=0) After discontinuity we have to again recalculate average till next discontinuity average=Data.loc['2005-03-02 02:08:30':'2005-03-02 02:11:00',['B']].mean(axis=0) Input Date,A,B 2005-03-02 02:05:30,1,3 2005-03-02 02:06:00,2,4 2005-03-02 02:06:30,3,5 2005-03-02 02:07:00,4,6 2005-03-02 02:07:30,5,7 2005-03-02 02:08:30,7,9 2005-03-02 02:09:00,7,9 2005-03-02 02:09:30,7,9 2005-03-02 02:10:00,8,12 2005-03-02 02:10:30,9,13 2005-03-02 02:11:00,10,14 Output Date,A,B,C 2005-03-02 02:05:30,1,3,9 2005-03-02 02:06:00,2,4,11 2005-03-02 02:06:30,3,5,13 2005-03-02 02:07:00,4,6,15 2005-03-02 02:07:30,5,7,17 2005-03-02 02:08:30,7,9,28 2005-03-02 02:09:00,7,9,28 2005-03-02 02:09:30,7,9,28 2005-03-02 02:10:00,8,12,32 2005-03-02 02:10:30,9,13,34 2005-03-02 02:11:00,10,14,36 How can I find out discontinuity in my index?. How can I do the entire stuff using pandas?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50147363
accepted answer: http://stackoverflow.com/a/50147363
type: AnsweredQuestion
has title: How to find out discontinuous date time index? How to take average over continuous index?
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
score: 4

http://stackoverflow.com/q/50175564
has comment: http://stackoverflow.com/comment/87381901
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87485397
has body: I upgraded my native python 2.7 to Python 2.7.15 and now all of the native packages that came with my MacOS are gone when I do pip freeze. Is this concerning and if so, what should I do. No time machine backups. I know touching the native python is a no-no but didn't realize the upgrade would delete all packages.
tagged with: python
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87381868
answer count: 0
has comment: http://stackoverflow.com/comment/87485766
has title: Installed Python Upgrade and Deleted My Apple OS Packages
has comment: http://stackoverflow.com/comment/87528569
tagged with: macos
has comment: http://stackoverflow.com/comment/87497539
type: Question

rotation
tags question: http://stackoverflow.com/q/50182691
type: Tag
tag name: rotation

http://stackoverflow.com/comment/87423168
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50202455
has text: There was a modification to mingw called [mingwpy](https://mingwpy.github.io/) that aimed to be compatible with versions of Python that were compiled with Visual Studio. I think it basically worked until Python 3.5+ (where it got trickier)

http://stackoverflow.com/comment/87394542
comment on: http://stackoverflow.com/a/50187397
type: AnswerComment
score: 1
type: Comment
has text: @sushionthefork: It creates a big number from the bytes values. If the byte sequence `s` is composed of <b0, b1, b2, ..., bN>, then the number representing it is b0*256^0+b1*256^1+b2*256^2+...+bN*256^N

http://stackoverflow.com/q/50120877
tagged with: python
has answer: http://stackoverflow.com/a/50292758
has body: I an using pyexcel to read a csv file which contains entries like 1234_5678,,,,,,, This is being read in by pyexcel as 12345678 rather than "1234_5678". Is there a way to force this to be read as a string rather than having the underscores removed. The way I am using pyexcel is with the get_array function pyexcel.get_array(file_content=file_content, file_type="csv")
has title: Pyexcel: do not ignore underscores
has comment: http://stackoverflow.com/comment/87261184
has comment: http://stackoverflow.com/comment/87259383
tagged with: int
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: string
tagged with: pyexcel
type: Question
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/50292758

http://stackoverflow.com/comment/87252804
comment on: http://stackoverflow.com/q/50117703
type: Comment
has text: Sure, this okay? (The actual CSV data has a lot of columns, this is what I read in)
score: 0
type: QuestionComment

http://stackoverflow.com/q/50191861
tagged with: pandas
tagged with: join
has title: Pandas select value in one dataframe, based on value in other df
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87400763
type: Question
upvote count: 2
answer count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50191936
has comment: http://stackoverflow.com/comment/87400690
has comment: http://stackoverflow.com/comment/87400805
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/50191966
has body: df1: GAME PLAY BET 0 (SWE, FIN) DRAW 10 1 (DEN, GER) WIN 20 2 (RUS, CZE) LOSS 30 df2: GAME WIN DRAW LOSS 0 (SWE, FIN) 1.50 2.0 3.25 1 (DEN, GER) 2.00 2.5 2.10 2 (RUS, CZE) 1.05 2.1 10.00 I'd like to create a column "PAYOFF" in df1, for each game. Payoff is computed by fetching the actual odds (WIN/DRAW/LOSS) from df2, by multiplying that value with the "BET" from df1. For instance, for row 1, (SWE,FIN), the PLAY was a DRAW, and I need to use that value to fetch from the DRAW col in df2. I can manage that by joining the 2 df's, and then some ugly del/rename of columns in a number of steps, but surely I'm missing some more elegant way to do that ? TIA, --Tommy

http://stackoverflow.com/q/50217366
answer count: 1
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87458406
tagged with: python
has title: Not able to train a simple Char RNN
has answer: http://stackoverflow.com/a/50219846
score: 0
has body: I have been working on a vanilla char rnn in tensorflow. I am not able it to produce any thing sensible even after training it a couple of hours. The code is tf version of Keras code from Chollet's Deep learning with pythonGithub I tried playing around with hyper params without much success. Chollet mentioned in the book that the model produced good output after 80 epochs. I have able to get anything resonable after 50K+ epochs :( Curious if there is something I missed while converting this code to tensorflow. n_layers = 1 num_units = 128 batch_size = 150 X = tf.placeholder(tf.float32, [None, maxlen, len(unique_chars)], name="Placeholder_X") y = tf.placeholder(tf.int64, [None, len(unique_chars)], name="Placeholder_Y") lstm_cells = [tf.contrib.rnn.BasicLSTMCell(num_units=num_units) for layer in range(n_layers)] multi_cell = tf.contrib.rnn.MultiRNNCell(lstm_cells) outputs, current_state = tf.nn.dynamic_rnn(multi_cell, X, dtype=tf.float32) top_layer_h_state = current_state[-1][1] logits = tf.layers.dense(top_layer_h_state, len(unique_chars), name="softmax") xentropy=tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y) loss = tf.reduce_mean(xentropy, name="loss") optimizer = tf.train.RMSPropOptimizer(learning_rate=0.001) training_op = optimizer.minimize(loss) pred = tf.nn.softmax(logits) init = tf.global_variables_initializer() saver = tf.train.Saver() Sampling Code: with tf.Session() as sess: init.run() saver.restore(sess, model_name) # Output some data start_index = random.randint(0, len(text) - maxlen - 1) generated_text = text[start_index: start_index + maxlen] print("Seed: ", generated_text) final_string = "" sampled = np.zeros((1, maxlen, len(unique_chars))) for i in range(50): for t, char in enumerate(generated_text): sampled[0, t, char_to_idx[char]] = 1. preds_eval = sess.run([pred], feed_dict={X: sampled}) preds=preds_eval[0][0] next_index = sample(preds, 0.5) next_char = unique_chars[next_index] generated_text += next_char final_string += next_char …

http://stackoverflow.com/a/50175055
has body: You need to return When you return from a function, it only returns to the function that called it. So when you return in mathematical_sum(), the value is returned to calculate_mathematical_expression() &amp; you need to return again from this function, like this: if operation == "+": return mathematical_sum(num1,num2) elif operation == "-": return mathematical_difference(num1,num2) elif operation == "*": return mathematical_product(num1,num2) elif operation == "/": return mathematical_division(num1,num2) else: return operation_error(operation) ...otherwise calculate_mathematical_expression() returns None. operation_error() does not work Use and instead of or. Otherwise your condition will always be True Return a boolean, not None. Here, your function always return None Example: def operation_error(operation): return operation != "+" and operation != "-" and operation != "*" and operation != "/" You don't need operation_error() Since you have a condition for each operator, you don't need the operation_error() function, you can directly do this: else: return None ...or even remove the else statement and let calculate_mathematical_expression() automatically return None when reaching its end.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50174965

http://stackoverflow.com/q/50091000
answer count: 1
has comment: http://stackoverflow.com/comment/87206179
type: Question
tagged with: beautifulsoup
has body: I am web scraping a forum. However, the same code scrapes all 15 posts from one page but only 12 posts on the second forum page. This second forum page also has 15 posts. I don't understand why it's not scraping all the posts. first_tr = page_soup.find_all('table' ,{'class' : 'forumline'})[0].select('tr')[2] all_tr = [first_tr] + first_tr.find_next_siblings('tr') I output all_tr and found that it was missing the last three table rows for the second forum page. Is something wrong with my find_next_siblings?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50166753
score: 0
tagged with: siblings
has title: Find_all_siblings is not finding all table row siblings from forum post in Python Beautiful Soup

http://stackoverflow.com/comment/87408987
has text: I just tried that and I get the error: all the input array dimensions except for the concatenation axis must match exactly
comment on: http://stackoverflow.com/q/50195967
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50190252
accepted answer of: http://stackoverflow.com/q/50190131
type: Answer
answers question: http://stackoverflow.com/q/50190131
has body: Add a meta class to the models and set the sort according to your requirement. Ex: class Post(models.Model): title = models.CharField(max_length=255) body = MarkdownxField() tags = models.ManyToManyField(Tag) author = models.CharField(max_length=255, default='Raúl Chirinos') date = models.DateTimeField(auto_now_add=True, blank=True) class Meta: ordering = ['-date'] @property def formatted_markdown(self): return markdownify(self.body) def __str__(self): return self.title
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50145195
upvote count: 1
type: UnansweredQuestion
has body: I am a newbie in Spark . I installed PySpark 2.3.0 on Windows. I am working on a dataset that contains 3 classes : "Positive","Negative","Neutral". I want to apply cross validation using LinearSVC , but for evaluation I want to use the average F1-score for the 2 classes "positive" and "negative" only to evaluate each model. In the following code : I think that , by choosing the "metricName" to be "f1" in the "MulticlassClassificationEvaluator" , the best parameters are chosen based on the average F1-score of the 3 classes .. But as I said before , I want the choice to be based on the average score of 2 classes only. from pyspark.ml.tuning import CrossValidator, ParamGridBuilder from pyspark.ml.classification import LinearSVC from pyspark.ml.evaluation import MulticlassClassificationEvaluator LSVC = LinearSVC() paramGrid = ParamGridBuilder().addGrid(LSVC.maxIter, [10, 100, 1000]).addGrid(LSVC.regParam, [0.01,0.1,10.0,100.0]).build() crossval = CrossValidator(estimator=LSVC, #estimator=pipeline, estimatorParamMaps=paramGrid, evaluator=MulticlassClassificationEvaluator(metricName="f1"), numFolds=2)
favorite count: 0
tagged with: apache-spark-ml
score: 1
tagged with: pyspark
tagged with: python
has title: Pyspark : The evaluation in the cross validation based on a user-defined metric
type: Question
answer count: 0
downvote count: 0
tagged with: apache-spark

http://stackoverflow.com/a/50299214
has body: I'm not exactly certain what "pandas" is - a quick search didn't reveal anything except the game engine Panda3D and the animal itself... As for accessing data external to FreeCAD, this is something I've been exploring myself lately. At the moment, some success has been achieved by starting FreeCAD in server mode and having it watch an excel file, then running python script when it changes. This approach would allow you to parse an Excel file using commonly available python libraries for that purpose. EDIT: Having been informed on just what pandas is, it seems odd you can't make it work with FreeCAD. However, there could be a number of causes: Old version. FreeCAD is undergoing really significant change right now. Ensure you're using the latest stable release (0.17 - Roland), but I'd recommend getting your hands on the latest 0.18-dev release Incorrect python version - FreeCAD currently is built on Py2, though Py3 builds are possible (I run FreeCAD / Py3 on my linux machine). Ensure you've installed pandas appropriately to match the python version FreeCAD depends upon (Py2, most likely). Invalid install - If you know pandas imports and works in the python interpreter itself, try importing and running pandas code from the FreeCAD python console.
answers question: http://stackoverflow.com/q/50107573
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87616737

http://stackoverflow.com/q/50205646
linked to: http://stackoverflow.com/q/31512422
has title: Permission denied with trying to use pip on MAC?
has comment: http://stackoverflow.com/comment/87429109
tagged with: pip
downvote count: 1
possible better answer: http://stackoverflow.com/a/51077112
has answer: http://stackoverflow.com/a/50205707
type: AnsweredQuestion
has body: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/beautifulsoup4-4.6.0.dist-info'Consider using the `--user` option or check the permissions. The error above is the one I get when I try to use the pip command. All I need to do is pip install the requirements.txt to get my program to work. I have python 2.7.1 installed and placed my code where I am able to use python commands. I tried to change permissions by using this command: chmod -R 777 but it did not work. I have homebrew installed on my computer. I also tried to use a virtual environment using this link: http://sourabhbajaj.com/mac-setup/Python/virtualenv.html but it gave me permission issues as well. Is there any suggestions to get rid of this permissions issue and run pip successfully? The sudo command below also doesn't work. sudo pip install -r requirements.txt
tagged with: python-2.7
linked to: http://stackoverflow.com/q/25816674
answer count: 3
has answer: http://stackoverflow.com/a/63786564
tagged with: python
upvote count: 26
tagged with: macos
accepted answer: http://stackoverflow.com/a/50205707
tagged with: permissions
score: 25
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51077112

http://stackoverflow.com/comment/87172708
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50078374
has text: Where/how is that string generated? The problem is there; can you change it?

http://stackoverflow.com/comment/87219692
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50101462
type: AnswerComment
has text: You might consider specifying your date format explicitly using `format='%m/%d/%Y'` in the call to `to_datetime`

http://stackoverflow.com/comment/87275812
type: QuestionComment
has text: Sorry, didn't want to unaccept your answer. It appeared like I didn't accepted it.
type: Comment
comment on: http://stackoverflow.com/q/50101119
score: 0

http://stackoverflow.com/comment/87303209
has text: By "uncharacters", you must mean "non-word and non-space" chars, right? You may match them with `[^\w\s]`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50142104

http://stackoverflow.com/q/50210829
has body: Simple client - server app. #Server use decode import socket s = socket.socket() host = socket.gethostname() port = 12345 s.bind((host,port)) s.listen(5) while True: c,addr = s.accept() print("Got connection from " + str(addr)) ret_val = s.send("Thank you".encode('utf-8')) print ("ret_val={}".format(ret_val)) c.close() Client: #client use decode from socket import gethostname, socket serSocket = socket() server = gethostname() port = 12345 serSocket.connect((server, port)) data = serSocket.recv(1024) msg = data.decode('utf-8') print("Returned Msg from server: &lt;{}&gt;".format(msg)) serSocket.close() when the server tries to send the following exception occurred Traceback (most recent call last): Got connection from ('192.168.177.1', 49755) File "C:/Users/Oren/PycharmProjects/CientServer/ServerSide/Server2.py", line 16, in &lt;module&gt; ret_val = s.send("Thank you".encode('utf-8')) OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied Process finished with exit code 1 As can be seen the client connects the server successfully. But send fails. What is the problem?
type: Question
has comment: http://stackoverflow.com/comment/87443338
has answer: http://stackoverflow.com/a/50216090
has comment: http://stackoverflow.com/comment/87443297
tagged with: sockets
has comment: http://stackoverflow.com/comment/87438691
has title: Python socket.send not working
tagged with: python
accepted answer: http://stackoverflow.com/a/50216090
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87438679
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87444450
has comment: http://stackoverflow.com/comment/87443045

http://stackoverflow.com/q/50077751
linked to: http://stackoverflow.com/q/39070329
downvote count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50078019
upvote count: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87173397
favorite count: 0
type: Question
has title: Python: searching through two data frames and when data matches append to new data frame
answer count: 2
has comment: http://stackoverflow.com/comment/87171967
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87171692
score: -2
has body: I have two data frames and I want to append the 'lat' and 'lon' column values when 'CommonName' column of first data frame matches the 'Name' column of the second data frame to the second data frame. The first data frame is 'AllBusStops' and takes the form: AllBusStops = {'CommonName': ['Cambuslang Road', 'Hillsborough Road'],'lon': [-4.17351, -4.12914], 'lat': [55.82932, 55.85388]} The second data frame is 'SixtyOne' and takes the form: SixtyOne = {'Name': ['Canonbie Street', 'Hillsborough Road']} So in the above example the 'lat', 'lon' values from the AllBusStops dataframe would be appended to the SixtyOne data frame for Hillsborough Road. The code looks like this thus far: for i in range(len(AllBusStops)): for j in range(len(SixtyOne)): if AllBusStops'CommonName'[i] == SixtyOne'Name'[j]: Lat = AllBusStops'Lat'[i] Lon = AllBusStops'Lon'[i] When I execute this I receive the following message: KeyError: 0 During handling of the above exception, another exception occurred
tagged with: python
has answer: http://stackoverflow.com/a/50077827
has comment: http://stackoverflow.com/comment/87171859

http://stackoverflow.com/q/50228625
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87483945
tagged with: python
has comment: http://stackoverflow.com/comment/87475950
has title: Wingdings Font Not Shown in Tkinter on Macbook
has comment: http://stackoverflow.com/comment/87503999
has comment: http://stackoverflow.com/comment/87475998
answer count: 0
tagged with: fonts
score: 1
downvote count: 0
has body: Whenever I run the following snippet (on MacOs 10.13.1 using Python 3.6.1): import tkinter window = tkinter.Tk() open_file = tkinter.Button(window, text="1", font=("Wingdings", 12)) open_file.pack() Instead of showing the following glyph: The program shows this: Is there a way in which I can fix this so that the Wingdings font displays correctly? (Note: The font shows up fine on Windows 10)
has comment: http://stackoverflow.com/comment/88802912
upvote count: 1

http://stackoverflow.com/a/51806337
answers question: http://stackoverflow.com/q/50113683
type: Answer
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90568244
has body: You need to export the environmental variables every time you open a new terminal in that environment. Please note that there are are back quotes on each of the pwd in the command as this might not be showing in the command below. Back quote is the same as the tilde key without pressing the shift key (US keyboard). From tensorflow/models/research/ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
score: 3

http://stackoverflow.com/comment/87202998
type: AnswerComment
has text: You may have to re-install it.
comment on: http://stackoverflow.com/a/50093339
type: Comment
score: 0

http://stackoverflow.com/comment/87427256
type: Comment
type: QuestionComment
has text: It worked! Thank you so much!
comment on: http://stackoverflow.com/q/50204878
score: 1

game-development
type: Tag
tags question: http://stackoverflow.com/q/50075703
tag name: game-development

http://stackoverflow.com/comment/87240426
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50111465
has text: @abarnert Program successfully prints the output in the terminal.
score: 1

http://stackoverflow.com/q/50216691
score: 4
upvote count: 4
answer count: 2
downvote count: 0
has body: I want to run simple MLP Classifier (Scikit learn) with following set of data. Data set consists of 100 files, containing sound signals. Each file has two columns (two signals) and rows (length of the signals). The length of rows (signals) vary from file to file ranges between 70 to 80 values. So the dimensions of file are 70 x 2 to 80 x 2. Each file represent one complete record. The problem I am facing how to train simple MLP with variable length of data, with training and testing set contains 75 and 25 files respectively. One solution is to concatenate all file and make one file i.e. 7500 x 2 and train MLP. But important information of signals is no longer useful in this case.
tagged with: machine-learning
has answer: http://stackoverflow.com/a/70286197
tagged with: scikit-learn
favorite count: 0
type: Question
has title: How to input Scikit learn MLP classifier with variable length of input data.
has answer: http://stackoverflow.com/a/50216874
type: UnansweredQuestion
tagged with: neural-network
tagged with: python

http://stackoverflow.com/comment/87460752
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50219435
has text: pip install pypiwin32
score: 2

http://stackoverflow.com/a/50098053
upvote count: 2
has body: I would say it is a bad practice. There is no reason for doing that. And it breaks an interactive console such as bpython, because __name__ is "__console__". (this has been fixed in v0.18) What usually is done is the opposite: avoid some global code being run when the module is imported, by checking if __name__ == '__main__':. I don't see a reason why some other script must not import the functions of your script, but if you really want to enforce that, define your functions under the if block: if __name__ == '__main__': def func1(): pass def func2(): pass # put main script code here # e.g.: func1() func2() and a script that will try to import your script as a module will just get an empty module, instead of an unexpected sys.exit().
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87217436
answers question: http://stackoverflow.com/q/50097948
has comment: http://stackoverflow.com/comment/87219572

http://stackoverflow.com/a/50218591
accepted answer of: http://stackoverflow.com/q/50218539
type: Answer
answers question: http://stackoverflow.com/q/50218539
downvote count: 0
type: AcceptedAnswer
has body: You're using the wrong function. re_path is an alias for url, so it uses the old regex syntax. If you want to use the new syntax, use path.
score: 5
upvote count: 5

http://stackoverflow.com/comment/87226827
has text: At the final iteration (final figure), you should see only one point (x[9,:]).
type: AnswerComment
comment on: http://stackoverflow.com/a/50104646
score: 0
type: Comment

http://stackoverflow.com/a/50158287
type: Answer
answers question: http://stackoverflow.com/q/50158152
score: 8
has comment: http://stackoverflow.com/comment/87334532
has body: Similarly to what Wen (who beat me to it) proposed, you can use pd.DataFrame.subtract: df1.set_index('ID').subtract(df2.set_index('ID')).reset_index() A B C D ID 'ID1' -0.5 0.1 0.2 2.2 'ID1' -0.3 -0.8 2.3 1.6 'ID2' -0.3 0.5 0.3 0.0 'ID3' 0.5 6.0 4.1 -3.0
downvote count: 0
upvote count: 8

http://stackoverflow.com/comment/87262132
type: QuestionComment
comment on: http://stackoverflow.com/q/50122098
score: 0
has text: In Python lingo, you are actually having a list of lists, or a once-nested list. It's helpful to be precise about this, because there are popular libraries which expose matrix datastructures.
type: Comment

http://stackoverflow.com/q/50103156
tagged with: jupyter-kernel
answer count: 1
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: gateway
has answer: http://stackoverflow.com/a/51524124
tagged with: python
has body: I'm trying to understand how to pass data via POST request method in Jupyter notebook kernel gateway and make a validation of the parameters. I have already made some tests with GET method and It works as expected: import json # GET /get req = json.loads(REQUEST) args = req['args'] if 'name' not in args: print(json.dumps({'name': None})) else: name = args['name'][0] print(json.dumps({'name': name})) So, if I got to http://127.0.0.1:8888/get?name=John I get the desired output of the GET request in json format. But what if I want (after the previous GET validation) also to make a POST request passing a raw body like this and make the correct validation in order to output the value parameters only in case they are filled or not empty/null? {"parameter_1":"5", "parameter_2":"33", "parameter_3":"120" } Thanks in advance for the suggestions.
tagged with: jupyter-notebook
tagged with: post
score: 2
has title: POST request validation on Jupyter kernel gateway
upvote count: 2

http://stackoverflow.com/a/50169189
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50169031
type: Answer
has body: You can achieve this using dictionary comprehension. dict3 = {} # create a new dictionary # iterate dict1 keys, to get value from dict2, which will be used to divide dict 1 values for d in dict1: y = dict2[d] dict3[d] = {k:(v/y) for k, v in dict1[d].items() }
answers question: http://stackoverflow.com/q/50169031
downvote count: 0

http://stackoverflow.com/a/50196135
score: 1
has comment: http://stackoverflow.com/comment/92790034
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50145104
type: Answer
answers question: http://stackoverflow.com/q/50145104
has body: The switch statement is considered harmful. That's probably why Python doesn't have it. The fallthrough behavior is a major source of bugs in C code. It's easy to forget a break; That's why C# disallows it--you'd have to use an explicit goto instead. It's the same in Python's dict of functions approach. You put in a call to the next function. "Explicit is better than implicit". The easiest way to make a dict of functions (with identifier keys) is with a class declaration. class switch: def a(): print('a') switch.b() def b(): print('b') switch.c() def c(): print('c') def d(): switch.e() def e(): print('de') def f(): switch.g() def g(): print('fg') def h(): print('h') def i(): print('i') switch.default() def default(): print('foo') Use it like so. &gt;&gt;&gt; expression = 'a' &gt;&gt;&gt; getattr(switch, expression, 'default')() a b c You can also extract the __dict__ attr if you want an actual dict. &gt;&gt;&gt; switch.__dict__.get('e', 'default')() de You can be similarly explicit with if statements. def switch(case) if case == a: doA() case = b if case == b: doB() case = c if case == c: doC() return if case == d: case = e if case == e: doDE() return if case == f: case = g if case == g: doFG() case = h if case == h: doH() return if case == i: doI() foo() If you're worried about side effects changing the condition or if the conditions are more complex than simple equality and you don't want to repeat them, you can use a helper variable instead of reassigning case. def switch(case): fall = False if case == a: doA() fall = True if fall or case == b: doB() fall = True if fall or case == c: doC() return if case == d: fall = True if fall or case == e: doDE() return if case == f: fall = True if fall or case == g: doFG() fall = True if fall or case == h: doH() return if case == i: doI() foo()
upvote count: 2

http://stackoverflow.com/comment/87372253
type: Comment
has text: @DhanyPSukumaran you can insert this line where you need latest product.
type: AnswerComment
comment on: http://stackoverflow.com/a/50174470
score: 0

http://stackoverflow.com/a/50157441
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50157369
downvote count: 0
score: 4
has body: You can create B as a numpy array and then use the method dot B=np.array([10,11,12]) print(A.dot(B)) #Use A.dot(B).T if you need to keep the original dimension

http://stackoverflow.com/a/50360611
score: 1
upvote count: 1
type: Answer
has body: The easiest way to install PyGObject on windows is with the All-In-One PyGI/PyGObject for Windows Installer https://sourceforge.net/projects/pygobjectwin32/
answers question: http://stackoverflow.com/q/50156741
downvote count: 0

http://stackoverflow.com/comment/87351697
type: AnswerComment
comment on: http://stackoverflow.com/a/50166061
has text: THis is the first row of my dataset
type: Comment
score: 0

http://stackoverflow.com/a/50101615
accepted answer of: http://stackoverflow.com/q/50101483
has comment: http://stackoverflow.com/comment/87224013
type: Answer
has comment: http://stackoverflow.com/comment/87220325
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87220409
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87222849
answers question: http://stackoverflow.com/q/50101483
has body: You can choose to skip rows: You can choose specific line numbers to skip or a quantity of lines to skip. If you use specific row numbers, then pass a list to skiprows. In your case you could use the following to be certain things are read correctly: pd.read_csv("data.csv",header=[0], skiprows=[0]) Data: I used the following data stored in a file called data.csv ,,name, 0, col1, col2, col3, col4, 1, 1, 2, 3, 4, 2, 2, 5, 4, 6 Output: 0 col1 col2 col3 col4 Unnamed: 5 0 1 1 2 3 4 NaN 1 2 2 5 4 6 NaN From the docs: Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. Link to source: Here is a link to the documentation for your reference.

http://stackoverflow.com/comment/87265255
type: QuestionComment
has text: I think this will go nowhere unless you can show me some expected output. I've tried to explain that what you want isn't really possible because dates and strings aren't the same thing, and that imposing your own format on a date is not possible unless you format it to a string.
comment on: http://stackoverflow.com/q/50117750
score: 0
type: Comment

http://stackoverflow.com/comment/87414540
comment on: http://stackoverflow.com/a/50196911
has text: Sounds like you're trying to add a second measurement for the same location:day pair
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87358014
comment on: http://stackoverflow.com/q/50170242
type: QuestionComment
type: Comment
has text: Please add your code so we can help you. Thanks!
score: 0

http://stackoverflow.com/comment/87392795
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50183550
has text: You probably need to install the `numpy` package, see https://pypi.org/project/GDAL/

http://stackoverflow.com/comment/87273409
type: Comment
type: AnswerComment
has text: @jessica Clarified the answer a little bit more.
comment on: http://stackoverflow.com/a/50127710
score: 0

http://stackoverflow.com/a/50148114
score: 0
accepted answer of: http://stackoverflow.com/q/50147459
has body: You only import ''Workbook'' sub-module from openpyxel. Try: from openpyxel import Workbook, drawing # also import drawing namespace [...] sheet.add_image(drawing.image.Image('square_blue.jpg'), colnum_string(col)+str(row)) [...]
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50147459
has comment: http://stackoverflow.com/comment/87377725
has comment: http://stackoverflow.com/comment/87378142
type: Answer

http://stackoverflow.com/comment/87291780
has text: @Ta946 is the noise always at the side of the rectangle and has the same size? Maybe you can find a bounding box for the rectangle + noise and then divide its width by 2 or something
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50111098
score: 0

http://stackoverflow.com/comment/87410395
type: AnswerComment
comment on: http://stackoverflow.com/a/50194820
has text: IDE is not key，IDLE Pycharm Visual Studio are all good，even if Windows notepad，you can use any kind of IDE as you like
type: Comment
score: 0

http://stackoverflow.com/comment/118974530
comment on: http://stackoverflow.com/a/62304225
type: Comment
type: AnswerComment
score: 0
has text: @YuriShatrov Thanks and I have updated the statement `The PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages.` ,

numpy
tags question: http://stackoverflow.com/q/50144283
tags question: http://stackoverflow.com/q/50178361
tags question: http://stackoverflow.com/q/50144430
tags question: http://stackoverflow.com/q/50182860
tags question: http://stackoverflow.com/q/50170744
tags question: http://stackoverflow.com/q/50205937
tags question: http://stackoverflow.com/q/50119819
tags question: http://stackoverflow.com/q/50092018
tags question: http://stackoverflow.com/q/50229849
tags question: http://stackoverflow.com/q/50199997
tags question: http://stackoverflow.com/q/50161345
tags question: http://stackoverflow.com/q/50105249
tags question: http://stackoverflow.com/q/50099960
tags question: http://stackoverflow.com/q/50171718
tags question: http://stackoverflow.com/q/50125525
tags question: http://stackoverflow.com/q/50202622
tags question: http://stackoverflow.com/q/50192719
tags question: http://stackoverflow.com/q/50110099
tags question: http://stackoverflow.com/q/50132042
tags question: http://stackoverflow.com/q/50204698
tags question: http://stackoverflow.com/q/50096846
tags question: http://stackoverflow.com/q/50123028
tags question: http://stackoverflow.com/q/50139993
tags question: http://stackoverflow.com/q/50186393
tags question: http://stackoverflow.com/q/50183540
tags question: http://stackoverflow.com/q/50102719
tags question: http://stackoverflow.com/q/50092665
tags question: http://stackoverflow.com/q/50076262
tags question: http://stackoverflow.com/q/50191826
tags question: http://stackoverflow.com/q/50140227
tags question: http://stackoverflow.com/q/50220638
tags question: http://stackoverflow.com/q/50178530
tags question: http://stackoverflow.com/q/50115816
tags question: http://stackoverflow.com/q/50110619
tags question: http://stackoverflow.com/q/50213967
tags question: http://stackoverflow.com/q/50077308
tags question: http://stackoverflow.com/q/50117751
tags question: http://stackoverflow.com/q/50229388
tags question: http://stackoverflow.com/q/50206986
tags question: http://stackoverflow.com/q/50136919
tags question: http://stackoverflow.com/q/50121980
tags question: http://stackoverflow.com/q/50182502
tags question: http://stackoverflow.com/q/50138988
tags question: http://stackoverflow.com/q/50090052
tags question: http://stackoverflow.com/q/50207924
tags question: http://stackoverflow.com/q/50121597
tags question: http://stackoverflow.com/q/50148845
tags question: http://stackoverflow.com/q/50177774
tags question: http://stackoverflow.com/q/50079194
tags question: http://stackoverflow.com/q/50217834
tags question: http://stackoverflow.com/q/50213733
tags question: http://stackoverflow.com/q/50208943
tags question: http://stackoverflow.com/q/50100246
tags question: http://stackoverflow.com/q/50158216
tags question: http://stackoverflow.com/q/50193883
tags question: http://stackoverflow.com/q/50219994
tags question: http://stackoverflow.com/q/50226821
tags question: http://stackoverflow.com/q/50120736
tags question: http://stackoverflow.com/q/50105560
tags question: http://stackoverflow.com/q/50091342
tags question: http://stackoverflow.com/q/50194752
tags question: http://stackoverflow.com/q/50195187
tags question: http://stackoverflow.com/q/50194742
tags question: http://stackoverflow.com/q/50119207
tags question: http://stackoverflow.com/q/50137367
tags question: http://stackoverflow.com/q/50177805
tags question: http://stackoverflow.com/q/50222055
tags question: http://stackoverflow.com/q/50114546
type: Tag
tags question: http://stackoverflow.com/q/50087548
tags question: http://stackoverflow.com/q/50225801
tags question: http://stackoverflow.com/q/50120247
tags question: http://stackoverflow.com/q/50095730
tags question: http://stackoverflow.com/q/50141450
tags question: http://stackoverflow.com/q/50198743
tags question: http://stackoverflow.com/q/50143825
tags question: http://stackoverflow.com/q/50146362
tags question: http://stackoverflow.com/q/50152311
tags question: http://stackoverflow.com/q/50157754
tags question: http://stackoverflow.com/q/50105629

http://stackoverflow.com/comment/87361083
comment on: http://stackoverflow.com/q/50171754
has text: Sorry if I was unclear, I'd like to take the input the user enters (in the form of a url) and then use the terminal command "whois" to display information about the site, with all of this being completed in a single script.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50178132
answers question: http://stackoverflow.com/q/50178055
upvote count: 2
has body: Use str.split Ex: import pandas as pd df = pd.DataFrame({"a": ["John/Smith"]}) df"a", "b" = df["a"].str.split("/").apply(pd.Series) print(df) Output: a b 0 John Smith
has comment: http://stackoverflow.com/comment/87373651
type: AcceptedAnswer
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50178055
downvote count: 0
has comment: http://stackoverflow.com/comment/87374463

http://stackoverflow.com/comment/87202333
type: Comment
comment on: http://stackoverflow.com/a/50092692
score: 0
type: AnswerComment
has text: I think you will need `modelA.summary()` and `modelB.summary()`. I don't know another way.

http://stackoverflow.com/comment/103768784
type: Comment
score: 0
type: AnswerComment
has text: Update 2019: use options=options instead of chrome_options=options
comment on: http://stackoverflow.com/a/50140554

http://stackoverflow.com/comment/87297095
comment on: http://stackoverflow.com/q/50139032
type: Comment
type: QuestionComment
score: 0
has text: I update the question

http://stackoverflow.com/q/50185399
tagged with: gaussian-process
accepted answer: http://stackoverflow.com/a/50256072
favorite count: 0
has answer: http://stackoverflow.com/a/50256072
upvote count: 25
type: Question
linked to: http://stackoverflow.com/q/43618633
has body: I am using scikit learn for Gaussian process regression (GPR) operation to predict data. My training data are as follows: x_train = np.array([[0,0],[2,2],[3,3]]) #2-D cartesian coordinate points y_train = np.array([[200,250, 155],[321,345,210],[417,445,851]]) #observed output from three different datasources at respective input data points (x_train) The test points (2-D) where mean and variance/standard deviation need to be predicted are: xvalues = np.array([0,1,2,3]) yvalues = np.array([0,1,2,3]) x,y = np.meshgrid(xvalues,yvalues) #Total 16 locations (2-D) positions = np.vstack([x.ravel(), y.ravel()]) x_test = (np.array(positions)).T Now, after running the GPR (GausianProcessRegressor) fit (Here, the product of ConstantKernel and RBF is used as Kernel in GaussianProcessRegressor), mean and variance/standard deviation can be predicted by following the line of code: y_pred_test, sigma = gp.predict(x_test, return_std =True) While printing the predicted mean (y_pred_test) and variance (sigma), I get following output printed in the console: In the predicted values (mean), the 'nested array' with three objects inside the inner array is printed. It can be presumed that the inner arrays are the predicted mean values of each data source at each 2-D test point locations. However, the printed variance contains only a single array with 16 objects (perhaps for 16 test location points). I know that the variance provides an indication of the uncertainty of the estimation. Hence, I was expecting the predicted variance for each data source at each test point. Is my expectation wrong? How can I get the predicted variance for each data source at each test points? Is it due to wrong code?
answer count: 2
has comment: http://stackoverflow.com/comment/87430591
possible better answer: http://stackoverflow.com/a/50244319
tagged with: python
has answer: http://stackoverflow.com/a/50244319
has title: Multiple-output Gaussian Process regression in scikit-learn
score: 25
has comment: http://stackoverflow.com/comment/87429876
type: AnsweredQuestion
tagged with: regression
downvote count: 0
has comment: http://stackoverflow.com/comment/87389181
tagged with: machine-learning
tagged with: scikit-learn

http://stackoverflow.com/q/50139421
has comment: http://stackoverflow.com/comment/87297371
has title: Pandas self-merge blocked missing structure
tagged with: missing-data
has comment: http://stackoverflow.com/comment/87303097
tagged with: python
has comment: http://stackoverflow.com/comment/87297210
accepted answer: http://stackoverflow.com/a/50139656
has body: I have this pandas data frame: from numpy import nan import pandas as pd data = {'A': {0: 1, 1: 2, 2: 1, 3: 2}, 'B': {0: 0.1, 1: 0.5, 2: 0.1, 3: 0.5}, 'C1': {0: 9.0, 1: 9.0, 2: nan, 3: nan}, 'C2': {0: 9.0, 1: 9.0, 2: nan, 3: nan}, 'D1': {0: nan, 1: nan, 2: 6.0, 3: 6.0}, 'D2': {0: nan, 1: nan, 2: 6.0, 3: 6.0}} data = pd.DataFrame(data) The out come is: A B C1 C2 D1 D2 0 1 0.1 9.0 9.0 NaN NaN 1 2 0.5 9.0 9.0 NaN NaN 2 1 0.1 NaN NaN 6.0 6.0 3 2 0.5 NaN NaN 6.0 6.0 Now apparently this data frame can be consolidated, because it is unnecessarily blocked. The expected outcome is: A B C1 C2 D1 D2 0 1 0.1 9.0 9.0 6.0 6.0 1 2 0.5 9.0 9.0 6.0 6.0 In general I'm talking about a data frame that has most of the columns complete, or missing at random, but there exists this type of blocked non-random missing structure in the data frame that can be safely merged. The problem is we do not know in advance which columns are to be aggregated. How do deal with it?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50139656
tagged with: pandas
has comment: http://stackoverflow.com/comment/87297420
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87297247

http://stackoverflow.com/a/50169679
answers question: http://stackoverflow.com/q/50169588
type: Answer
upvote count: 4
has body: Something like that should work: import itertools mylist = [...] [list(v) for k,v in itertools.groupby(mylist, key=lambda x: x[:3])] If input list isn't sorted, than use something like that: import itertools mylist = [...] keyfunc = lambda x:x[:3] mylist = sorted(mylist, key=keyfunc) [list(v) for k,v in itertools.groupby(mylist, key=keyfunc)]
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/50169588
downvote count: 0

http://stackoverflow.com/comment/87422428
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50202701
type: QuestionComment
has text: @StephenRauch `file` isn't actually on the list in Python 3 anymore, since there is no `file` type.

http://stackoverflow.com/comment/87244426
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50112351
has text: @Blckknght I added the test data which my solution fails on the most dramatically
score: 0

http://stackoverflow.com/a/50139132
type: Answer
answers question: http://stackoverflow.com/q/50138405
score: 0
has body: In order to make it easay, I would reuse the variable distances from k_means() function, returning it: def k_means(dataset, k): centroids = init_cent(dataset, k) distances = calc_dist_euclidean(dataset, centroids) cluster_assigning = np.array([dataset[distances == k].mean(axis=0) for k in range(centroids.shape[0])]) return centroids, distances, cluster_assigning Then, you can plot your centroids and data points based on corresponding cluster defining a numpy array colors containing each color and creating a numpy array of colors for each of your data points using colors[distances]: df = pd.read_csv('bristol_vacation_rentals_2016.csv') dataset = df'latitude', 'longitude'.values k = 3 colors = np.array(['r', 'g', 'b']) centroids, distances, cluster_assigning = k_means(dataset, k) plt.subplot(121) plt.scatter(dataset[:, 0], dataset[:, 1], c=colors[distances], s=2) plt.scatter(centroids[:, 0], centroids[:, 1], c=colors, s=50) plt.xlabel('latitude') plt.ylabel('longitude') plt.subplot(122) plt.scatter(dataset[:, 0], dataset[:, 1], c=colors[distances], s=2) plt.scatter(cluster_assigning[:, 0], cluster_assigning[:, 1], c=colors, s=50) plt.xlabel('latitude') plt.ylabel('longitude') plt.show()
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50138405

http://stackoverflow.com/comment/87180793
has text: Possible starting point: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
comment on: http://stackoverflow.com/q/50082370
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50150375
has body: I want to call a method in another class and make changes to the parent class when the button is clicked in Python. To explain; With Tkinter visual programming, I click the button to change the main window and I can not change the properties in the main window with another class method. I get the error message below. Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.5/tkinter/_ init _.py", line 1553, in _ call _ return self.func(*args) TypeError: buton_goster() missing 1 required positional argument: 'event' class Butonol(object): #Button class def __init__(self): ... def buton_goster(self, event ): # Properties kisminda ozellik gosterir Test.countshow = Test.countshow + 1; if(Test.countshow &gt;1): Test.props0.pack_forget() Test.props.pack_forget() ... And here is the Test Class class Test(Frame): countshow = 0 ... def new_Button(self): self.nesne = Butonol() self.but= Button(self.mainFrame,text = self.nesne.text) self.but.bind('&lt;Button-1&gt;',Butonol.buton_goster) self.but.bind('B1-Motion&gt;',self.label_tasi) self.but.pack(side = LEFT,anchor = N) Butonol.butonsay = Butonol.butonsay + 1 Butonol.butonliste.append(self.but)
has title: Calling methods from outside a class in Python - Tkinter events
tagged with: tkinter
type: Question
has answer: http://stackoverflow.com/a/50150522
tagged with: python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87318785
has comment: http://stackoverflow.com/comment/87420908
score: 0

http://stackoverflow.com/a/50180135
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50179822
upvote count: 1
has body: From the link you gave, it seems you don't want the output in a different image variable, given that you know the coordinates of the region you want to process. I'll assume your image processing function to be cv2.blur() so this is how it'll be: image[y:y+height, w:w+width] = cv2.blur(image[y:y+height, w:w+width], (11,11)) Here, x &amp; y are your ROI starting co-ordinates, and height &amp; width are the height, width of the ROI Hope this is what you wanted, or if it's anything different, provide more details in your question.
accepted answer of: http://stackoverflow.com/q/50179822

http://stackoverflow.com/q/50193599
has answer: http://stackoverflow.com/a/50204314
downvote count: 0
has title: pyspark / python 3.6 (TypeError: 'int' object is not subscriptable) list / tuples
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: pyspark
has answer: http://stackoverflow.com/a/50193803
tagged with: python
tagged with: rdd
tagged with: lambda
has body: I have this code in pyspark / python: n --> is a number of itens of new list n = 2 new tuple ( x, y, z ) Where: x --&gt; index y --&gt; list [where variable n is a number of itens of list] z --&gt; value of front value of list I'm doing this code: RDD_Dados = RDD_one.map(lambda x: (x[0], [list(x[i][1]) for i in range(n)], x[i+1][1]) ) Content of RDD_one is: (0, [(0, '5'), (1, '1'), (2, '2'), (3, '4'), (4, '4'), (5, '3.5'), (6, '-2'), (7, '1'), (8, '2'), (9, '0')]) (1, [(1, '1'), (2, '2'), (3, '4'), (4, '4'), (5, '3.5'), (6, '-2'), (7, '1'), (8, '2'), (9, '0')]) (2, [(2, '2'), (3, '4'), (4, '4'), (5, '3.5'), (6, '-2'), (7, '1'), (8, '2'), (9, '0')]) (3, [(3, '4'), (4, '4'), (5, '3.5'), (6, '-2'), (7, '1'), (8, '2'), (9, '0')]) (4, [(4, '4'), (5, '3.5'), (6, '-2'), (7, '1'), (8, '2'), (9, '0')]) (5, [(5, '3.5'), (6, '-2'), (7, '1'), (8, '2'), (9, '0')]) (6, [(6, '-2'), (7, '1'), (8, '2'), (9, '0')]) (7, [(7, '1'), (8, '2'), (9, '0')]) (8, [(8, '2'), (9, '0')]) (9, [(9, '0')]) I would like to get each secound item of each duple and make a new list like this: (0, ['5','1'], '2') (1, ['1','2'], '4') (2, ['2','4'], '4') (3, ['4','4'], '3.5') (4, ['4','3.5'], '-2') (5, ['3.5','-2'], '1') (6, ['-2','1'], '2') (7, ['1','2'], '0') but doesn't work. I have been reciving this error: --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-12-3532f6a9c36a&gt; in &lt;module&gt;( 59 RDD_Dados = RDD_one.map(lambda x: (x[0],[list(x[i][1]) for i in range(n)],x[i+1][1])) File "C:\Spark\spark-2.3.0-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\worker.py", line 229, in main File "C:\Spark\spark-2.3.0-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\worker.py", line 224, in process File "C:\Spark\spark-2.3.0-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\serializers.py", line 372, in dump_stream vs = list(itertools.islice(iterator, batch)) File "&lt;ipython-input-12-3532f6a9c36a&gt;", line 59, in &lt;lambda&gt;…
has comment: http://stackoverflow.com/comment/87405568
score: 2
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/125251040
type: Comment
has text: such a pity that still no better way than to rename
type: AnswerComment
comment on: http://stackoverflow.com/a/50168890
score: 2

http://stackoverflow.com/q/50107615
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79186424
downvote count: 1
has answer: http://stackoverflow.com/a/50124438
has answer: http://stackoverflow.com/a/50107729
tagged with: psycopg2
favorite count: 0
tagged with: runtime-error
tagged with: postgresql
has answer: http://stackoverflow.com/a/79239138
has comment: http://stackoverflow.com/comment/87232714
tagged with: python
has body: I have repeatable tried to create a table MYTABLENAME with SQLAlchemy in Python. I deleted all tables through my SQL client Dbeaver but I am getting an error that the table exists such that Traceback (most recent call last): File "/home/hhh/anaconda3/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/home/hhh/anaconda3/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) psycopg2.ProgrammingError: relation "ix_MYTABLENAME_index" already exists sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "ix_MYTABLENAME_index" already exists [SQL: 'CREATE INDEX "ix_MYTABLENAME_index" ON "MYTABLENAME" (index)'] I succeed in the creation of tables and their insertions with an unique name but the second time I am getting the error despite deleting the tables in Dbeaver. Small example from datetime import date from sqlalchemy import create_engine import numpy as np import pandas as pd def storePandasDF2PSQL(myDF_): #Store results as Pandas Dataframe to PostgreSQL database. # #Example #df=pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D']) #dbName= date.today().strftime("%Y%m%d")+"_TABLE" #engine = create_engine('postgresql://hhh:yourPassword@localhost:1234/hhh') #df.to_sql(dbName, engine) df = myDF_ dbName = date.today().strftime("%Y%m%d")+"_TABLE" engine = create_engine('postgresql://hhh:yourPassword@localhost:1234/hhh') # ERROR: NameError: name 'table' is not defined #table.declarative_base.metadata.drop_all(engine) #Drop all tables #TODO: This step is causing errors because the SQLAlchemy thinks the #TODO: table still exists even though deleted df.to_sql(dbName, engine) What is the proper way to clean up the backend such as some hanging index in order to recreate the table with fresh data? In other words, how to solve the error?
tagged with: sqlalchemy
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/87263473
has title: Python SQLAlchemy: psycopg2.ProgrammingError relation already exists?
score: 0

bokeh
tags question: http://stackoverflow.com/q/50159071
tags question: http://stackoverflow.com/q/50220452
tags question: http://stackoverflow.com/q/50153325
tags question: http://stackoverflow.com/q/50083062
type: Tag
tags question: http://stackoverflow.com/q/50086517
tags question: http://stackoverflow.com/q/50111925
tags question: http://stackoverflow.com/q/50229287
tags question: http://stackoverflow.com/q/50083900
tags question: http://stackoverflow.com/q/50142618
tag name: bokeh
tags question: http://stackoverflow.com/q/50123144
tags question: http://stackoverflow.com/q/50121154
tags question: http://stackoverflow.com/q/50134545
tags question: http://stackoverflow.com/q/50227974
tags question: http://stackoverflow.com/q/50192139

http://stackoverflow.com/comment/87316485
type: Comment
has text: thanks for your answer, but even uncommenting the line, the error is there
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50137181

http://stackoverflow.com/q/50141424
accepted answer: http://stackoverflow.com/a/50142745
has body: I have a problem with freeze_graph function: ValueError: cannot add op with name Conv1/W1/Adam as that name is already used In this line: def export_model(input_node_names, output_node_name): my_freeze_graph.freeze_graph('out/' + MODEL_NAME + '.pbtxt', None, False, 'out/' + MODEL_NAME + '.chkp', output_node_name, "save/restore_all", "save/Const:0", 'out/frozen_' + MODEL_NAME + '.pb', True, "") My model structure: def get_model(input, dropout): with tf.name_scope('Conv1'): input_4D = tf.reshape(input, [-1, HEIGHT, WIDTH, 1]) w1 = tf.Variable(tf.truncated_normal([12, 8, 1, 44], stddev=0.01), name='W1') b1 = tf.Variable(tf.zeros([44]), name='B1') conv1 = tf.nn.conv2d(input_4D, w1, strides=[1, 1, 1, 1], padding='SAME') act1 = tf.nn.relu(conv1 + b1) drop1 = tf.nn.dropout(act1, dropout) max_pool1 = tf.nn.max_pool(drop1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') tf.summary.histogram('weights', w1) tf.summary.histogram('biases', b1) tf.summary.histogram('activations', act1) tf.summary.histogram('dropouts', drop1) with tf.name_scope('Conv2'): w2 = tf.Variable(tf.truncated_normal([6, 4, 44, 44], stddev=0.01), name='W2') b2 = tf.Variable(tf.zeros([44]), name='B2') conv2 = tf.nn.conv2d(max_pool1, w2, strides=[1, 1, 1, 1], padding='SAME') act2 = tf.nn.relu(conv2 + b2) drop2 = tf.nn.dropout(act2, dropout) tf.summary.histogram('weights', w2) tf.summary.histogram('biases', b2) tf.summary.histogram('activations', act2) tf.summary.histogram('dropouts', drop2) conv_shape = drop2.get_shape() count = int(conv_shape[1] * conv_shape[2] * conv_shape[3]) flat_output = tf.reshape(drop2, [-1, count]) with tf.name_scope('FC'): w3 = tf.Variable(tf.truncated_normal([count, NUM_LABELS], stddev=0.01), name='W3') b3 = tf.Variable(tf.zeros([NUM_LABELS]), name='B3') fc = tf.add(tf.matmul(flat_output, w3), b3) tf.summary.histogram('weights', w3) tf.summary.histogram('biases', b3) return fc What did I do wrong? P.S. Tensorflow version is 1.2.1, python version is 3.6.4
has answer: http://stackoverflow.com/a/50142745
has title: cannot add op with name
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/50111531
has answer: http://stackoverflow.com/a/50112159
tagged with: python
has body: I have a piece of code: temp_dir = "/tmp/working" p = subprocess.Popen(["python3", temp_dir + "/tmp.py"]) but I got OSError: [Errno 7] Argument list too long when I run the code in bash of Linux Mint 18. But when I test in Fedora, macOS, FreeBSD, Ubuntu (they have many shell: fish, zsh,...) I don't receive any errors. Even I use print(subprocess.check_call(["python3", temp_dir + "/tmp.py"], shell=True)) , the same error has been reached. The command is really short, and I have no idea why I get that error. I have google hundreds of result, but I can't get the solution of my problem.
has comment: http://stackoverflow.com/comment/116232004
tagged with: python-3.x
linked to: http://stackoverflow.com/q/24788292
answer count: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87240578
downvote count: 1
has title: subprocess.Popen() get OSError: [Errno 7] Argument list too long when run the code in Linux Mint
has answer: http://stackoverflow.com/a/50111828
favorite count: 0
type: Question
score: 1
has comment: http://stackoverflow.com/comment/87240747

http://stackoverflow.com/q/50081196
score: 1
tagged with: python
has title: Encrypted text inputs alongside shift value results outputs plain text using a Caesar cipher
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87178393
tagged with: encryption
downvote count: 0
upvote count: 1
has body: The overall make a script that inputs a line of encrypted text and a distance value and outputs plaintext using a Caesar cipher. I have been working on this for the last couple of days but don't understand what i am doing wrong. I feel I am not taking into account the shift value to decode the encrypted text. text = input("Enter plain text: "); s = input("Shift: "); def caesar(plainText, shift): cipherText = "" for char in plainText: newChar = ord(char) + shift if newChar &gt; 128: newChar = newChar % 128 finalChar = chr(newChar) cipherText += finalChar return cipherText print (caesar(text, int(s))); Ive tested with a series of inputs that are supposed to work but only one seems correct Enter plain text: abcde Shift: 128 abcde This is the only correct Value Enter plain text: EFGHI Shift: 100 )*+,- Value is supposed to abcde Enter plain text: Khoor#Zruog Shift: 3 Nkrru&amp;]uxrj Value is supposed to be Hello World I feel I setup the Shift value incorrect but I am not sure whats wrong exactly.
favorite count: 0
has comment: http://stackoverflow.com/comment/87178839
has comment: http://stackoverflow.com/comment/87178525

http://stackoverflow.com/comment/87420291
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50201797
has text: You are welcome :). You can use `urllib3` or `requests` modules
score: 1

python-keyring
type: Tag
tag name: python-keyring
tags question: http://stackoverflow.com/q/50094328

http://stackoverflow.com/comment/96579116
has text: @u2gilles were you able to find an answer to this? I'm facing the same thing... thanks!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50128663

http://stackoverflow.com/comment/87444981
has text: ...that said, the **immediate** concern is that the shell in which you `source repo.sh` is a completely different shell from the one in which you later call `bitbake -g`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50213786
type: Comment
score: 0

http://stackoverflow.com/q/50087728
has comment: http://stackoverflow.com/comment/92389963
downvote count: 0
tagged with: x-sendfile
tagged with: flask
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/64329074
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87217610
tagged with: python
has body: I am new to python and still learning. I created a small python 3.6 Flask webapp on pythonanwhere and found out that send_file() is not working on pythonanywhere servers. I am actively looking for an alternative to download an excel file directly on the user machine. I also tried Response but it is not giving desired output. I read alot about it online and found that the send_file works fine if we set below wsgi-disable-file-wrapper = True However, i don't know where to set this as i couldn't find uWsgi.ini file where i could update this line. Below are the methods which i tried but they failed, please help SEND_FILE() configuration: ->>> Not running.. output = BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') workbook = writer.book output.seek(0) return send_file(output,attachment_filename="testing.xlsx",as_attachment=True) Output Error: return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size) SystemError: &lt;built-in function uwsgi_sendfile&gt; returned a result with an error set With Response configuration: writer = pd.ExcelWriter("abc.xlsx", engine='xlsxwriter') return Response(writer,mimetype="text/csv",headers={"Content-disposition":"attachment; filename=myplot.csv"}) Output error: Error running WSGI application TypeError: '_XlsxWriter' object is not iterable File "/home/hridesh1987/.virtualenvs/myproject/lib/python3.6/site-packages/werkzeug/wsgi.py", line 870, in __next__return self._next() File "/home/hridesh1987/.virtualenvs/myproject/lib/python3.6/site-packages/werkzeug/wrappers.py", line 83, in _iter_encoded for item in iterable:
score: 6
upvote count: 6
tagged with: pythonanywhere
has title: Alternative of send_file() in flask on Pythonanywhere?
answer count: 2
has answer: http://stackoverflow.com/a/53536043

http://stackoverflow.com/comment/102604015
comment on: http://stackoverflow.com/a/50195155
type: Comment
score: 0
type: AnswerComment
has text: @cs95 The problem with this is that you lose the 'code' column after the `ffill()` and then pandas runs the `bfill()` on all NaNs, regardless of 'code'.

http://stackoverflow.com/a/50170247
has body: I think the contrib accuracy is the problem. https://github.com/tensorflow/tensorflow/issues/9498. It does not reset, so you accuracy is basically the average of all the accuracy to that point. When you reloaded the graph, this running average was reset. So good news, your network is training great.
upvote count: 2
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50169767

http://stackoverflow.com/q/50205233
has comment: http://stackoverflow.com/comment/87427676
type: Question
has comment: http://stackoverflow.com/comment/87427617
tagged with: sqlite
tagged with: python
score: -1
favorite count: 0
tagged with: python-2.7
upvote count: 0
type: UnansweredQuestion
answer count: 1
has body: i want to print the row id of the updated row in the SQL query while True: Conn = sqlite3.connect('database.db', timeout=60) c = Conn.cursor() c.execute("UPDATE row SET value='value' where status='status'") #i want to do something here to the updated row above Conn.commit() Conn.close()
has title: python sqlite3 select updated row value
downvote count: 1
has answer: http://stackoverflow.com/a/50205656

http://stackoverflow.com/q/50130077
type: Question
has title: Displays PY_VAR4 instead of number
duplicate of: http://stackoverflow.com/q/24768455
has answer: http://stackoverflow.com/a/50130237
possible better answer: http://stackoverflow.com/a/50130237
has comment: http://stackoverflow.com/comment/87286050
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/24768455
type: AnsweredQuestion
answer count: 2
downvote count: 2
tagged with: tkinter
upvote count: 1
has answer: http://stackoverflow.com/a/50130121
has body: x = IntVar() x.set(1) def add(): x.set(x.get()+1) I am using this piece of code to update the question number on a tkinter quiz I am making. self.recordNum = Label(self.quizf, text=x) self.recordNum.pack() self.Submit = Button(self.quizf, text = 'submit', command=lambda:[self.confirmAnswer(),add()]) I used lambda so I could have two commands in the same button which I need as self.confirmAnswer runs the if statement to check the answer and the add command activates the first piece of code displayed above. When I run the quiz PY_VAR4 displays instead of a number, thanks for your help! :)
accepted answer: http://stackoverflow.com/a/50130121
favorite count: 0

http://stackoverflow.com/q/50177616
favorite count: 0
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/87372566
has answer: http://stackoverflow.com/a/66799427
has comment: http://stackoverflow.com/comment/101560299
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/98517585
has answer: http://stackoverflow.com/a/65014536
tagged with: python
answer count: 6
has comment: http://stackoverflow.com/comment/107668298
has answer: http://stackoverflow.com/a/76321873
upvote count: 43
score: 43
has answer: http://stackoverflow.com/a/78709292
has body: Is there a way to rename a variable everywhere in your current jupyter notebook file? I.e. let's say my notebook referencing a variable "foo" in multiple functions and locations through my script. Later I decide I want to rename this variable to "bar" for better readability... In xcode, you can highlight and right click to do this. Sort of a smart search/replace command. Would love to be able to do the same thing. Thanks!
has answer: http://stackoverflow.com/a/62360659
downvote count: 0
has title: Renaming a variable everywhere in Jupyter Notebook
has answer: http://stackoverflow.com/a/65416259
linked to: http://stackoverflow.com/q/35119831

http://stackoverflow.com/q/50222628
has body: I'm using sklearn.svm.SVC for classification of 2, 3 and 4 classes with SVM. SVC support as a parameter class_weight which I would like to use because I have heavy class imbalance (around 70% vs 30% for 2 classes). For optimizing the other paramters of the SVM (gamma and C) I'm using RandomizedSearchCV. For param_distributions of RandomizedSearchCV I'm currently using the following distributions: mdl = svc(probability = True, random_state = 1) RandomizedSearchCV(mdl, param_distributions = params, n_iter = 100, random_state = 1) params = {'clf__C': scipy.stats.expon(scale=100), 'clf__gamma': scipy.stats.expon(scale=.1), 'clf__kernel': ['rbf']} what distributions should I add to params for class_weight if I'm using 2, 3 and 4 classes?
answer count: 0
tagged with: machine-learning
tagged with: scikit-learn
type: Question
has comment: http://stackoverflow.com/comment/87463512
has comment: http://stackoverflow.com/comment/87463381
type: UnansweredQuestion
has title: How to optimize weights of SVM with random search?
tagged with: python
has comment: http://stackoverflow.com/comment/87617154
tagged with: svm
score: 0
has comment: http://stackoverflow.com/comment/87463101

http://stackoverflow.com/a/50221781
has comment: http://stackoverflow.com/comment/87611206
upvote count: 1
answers question: http://stackoverflow.com/q/50211629
has comment: http://stackoverflow.com/comment/88015355
type: Answer
has comment: http://stackoverflow.com/comment/87980869
has comment: http://stackoverflow.com/comment/87590467
has comment: http://stackoverflow.com/comment/87667615
score: 1
has body: Most speech recognition evaluations first segment the speech into sentences or utterances. Then you compute the WER by aligning each utterance. This can give you a big speedup because the WER computation is O(n^2).
has comment: http://stackoverflow.com/comment/87685656
downvote count: 0

http://stackoverflow.com/comment/87349127
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50165445
type: AnswerComment
has text: If you don't call `ROOT.mainloop()`, you will have two make sure to implement your own event loop. This would then compete with whatever code comes next. For use with `FuncAnimation` I would heavily recommend to start the tk event loop via `mainloop`, else you run into trouble like the one you had here.

http://stackoverflow.com/q/50120395
tagged with: regex
answer count: 2
has answer: http://stackoverflow.com/a/50120439
has answer: http://stackoverflow.com/a/50120445
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I wrote a simple class that takes an input zip or postal code and either returns that value or zero-pads it out to five digits if it happens to be all-numeric and less than 5 digits long. Why doesn't my code work? import re class ZipOrPostalCode: def __init__(self, data): self.rawData = data def __repr__(self): if re.match(r"^\d{1,4}$", self.rawData): return self.rawData.format("%05d") else: return self.rawData if __name__ == "__main__": z=ZipOrPostalCode("2345") print(z) The output I expect is 02345. It outputs 2345. Running it in the debugger, it is clear that the regular expression didn't match.
has comment: http://stackoverflow.com/comment/87260330
has title: Why doesn't this python regex work?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87258587
tagged with: python

http://stackoverflow.com/comment/87339220
type: QuestionComment
has text: @tdelaney i found it from here, they use https://stackoverflow.com/questions/15594817/f-seek-and-f-tell-to-read-each-line-of-text-file
score: 0
comment on: http://stackoverflow.com/q/50160069
type: Comment

http://stackoverflow.com/comment/87451315
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50216729
score: 0
has text: Socket.IO limits my complex of my algorithim, it has very defined tempate of how the backend should work (with all the disconnected, rooms and studd..), and what I want to do its little bit more complex, Is there a way of sockets in Swift that arent Socket.IO ?

http://stackoverflow.com/comment/87313711
has text: What is the problem you are trying to solve? It sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). That is to say an issue with your proposed solution, rather your actual problem. If we can understand why you want to do this, we may be able to suggest another way to do it.
type: QuestionComment
comment on: http://stackoverflow.com/q/50147760
score: 3
type: Comment

http://stackoverflow.com/q/50184845
linked to: http://stackoverflow.com/q/519633
has answer: http://stackoverflow.com/a/50185189
tagged with: pandas
tagged with: python
has title: Prevent my RAM memory from reaching 100%
score: 4
tagged with: memory
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/87387124
has comment: http://stackoverflow.com/comment/87397444
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87386915
tagged with: ram
downvote count: 0
has body: I have a very simple python script that reads a CSV file and sorts the rows according to the timestamps. However, the file is large enough (16 GB) that its reading uses ram memory completely. When it reaches 100% (i.e. 64 GB RAM memory), my system completely freezes, and I am forced to restart my computer. Here is the code: import pandas as pd from time import time filename = 'AKER_OB.csv' start_ = time() file_ = pd.read_csv(filename) end_ = time() duration = end_ - start_ print("The duration to load that file : {}".format(duration)) file_.to_datetime(df['TimeStamps'], format="%Y-%m-%d %H:%M:%S").sort_values() Head of AKER_OB.csv : TimeStamp,Bid1,BidSize1,Bid2,BidSize2,Bid3,BidSize3,Bid4,BidSize4,Bid5,BidSize5,Bid6,BidSize6,Bid7,BidSize7,Bid8,BidSize8,Bid9,BidSize9,Bid10,BidSize10,Bid11,BidSize11,Bid12,BidSize12,Bid13,BidSize13,Bid14,BidSize14,Bid15,BidSize15,Bid16,BidSize16,Bid17,BidSize17,Bid18,BidSize18,Bid19,BidSize19,Bid20,BidSize20,Ask1,AskSize1,Ask2,AskSize2,Ask3,AskSize3,Ask4,AskSize4,Ask5,AskSize5,Ask6,AskSize6,Ask7,AskSize7,Ask8,AskSize8,Ask9,AskSize9,Ask10,AskSize10,Ask11,AskSize11,Ask12,AskSize12,Ask13,AskSize13,Ask14,AskSize14,Ask15,AskSize15,Ask16,AskSize16,Ask17,AskSize17,Ask18,AskSize18,Ask19,AskSize19,Ask20,AskSize20 2016-10-08 00:00:00,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,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2016-10-08 00:00:01,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,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2016-10-08 00:00:02,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,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2016-10-08 00:00:03,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,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2016-10-08 00:00:04,0,0,0,…
has answer: http://stackoverflow.com/a/50185199
has comment: http://stackoverflow.com/comment/87387491
favorite count: 0

http://stackoverflow.com/a/50219773
has body: First of all, it should be okay to change the number of samples in the nce loss without causing problems for the optimizer. The internal variables stored by some optimizers relate to the historical gradients of the trainable variables in your graph. Secondly, if you do want to reset the state of your optimizer for some reason, the way I do it is by putting the optimizer in a variable scope. Whenever I want to reset it then I run the reset_optimizer op. reset_optimizer = tf.no_op() with tf.variable_scope('optimizer'): train_op = optimizer(learning_rate).minimize(loss) opt_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, "optimizer") if len(opt_vars): # check if optimzer state needs resetting reset_optimizer = variables_initializer(opt_vars))
upvote count: 1
has comment: http://stackoverflow.com/comment/87458101
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50219134
downvote count: 0

http://stackoverflow.com/a/50106184
downvote count: 0
answers question: http://stackoverflow.com/q/50106021
type: Answer
upvote count: 2
score: 2
has body: itertools.cycle will repeat an iterator indefinitely, and itertools.islice takes only the leading portion. pd.Series(list(itertools.islice(itertools.cycle(range(-12,13)), len(df))))

http://stackoverflow.com/comment/87244913
comment on: http://stackoverflow.com/a/50112396
score: 0
has text: Thanks. I am just trying to get famliarized with pandas and practice coding so I can use the data analysis tools.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50104017
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/94342870
accepted answer of: http://stackoverflow.com/q/50101772
has body: This is already discussed in other posts like the one you mentioned (this, or this, or this). As it is explained there, I would try to use dask dataframe to load the data and execute the merge, but depending on your PC you may still not be able to do it. Minimum working example: import dask.dataframe as dd # Read the CSVs df1 = dd.read_csv('data1.csv') df2 = dd.read_csv('data2.csv') # Merge them df = dd.merge(df1, df2, on='Bin_ID').compute() # Save the merged dataframe df.to_csv('merged.csv', index=False)
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50101772
has comment: http://stackoverflow.com/comment/94369736
has comment: http://stackoverflow.com/comment/112059058
has comment: http://stackoverflow.com/comment/94378862

http://stackoverflow.com/q/50199829
answer count: 1
downvote count: 7
tagged with: dataframe
tagged with: python
has body: id|order_id|order_no|order_status|remark|handle_time|create_time|update_time 11237|3942|2018050307542800005985|新建订单||20180503075428|2018/5/3 07:54:28|2018/5/3 07:54:28 11238|3943|2018050307591600005986|新建订单||20180503075916|2018/5/3 07:59:16|2018/5/3 07:59:16 11239|3943|2018050307591600005986|新建订单||20180503082115|2018/5/3 08:21:15|2018/5/3 08:21:15 11240|3943|2018050307591600005986|新建订单||20180503083204|2018/5/3 08:32:04|2018/5/3 08:32:04 11241|3941|2018050308564400005991|新建订单||20180503085644|2018/5/3 08:56:02|2018/5/3 08:56:44 11242|3941|2018050222320800001084|初审成功||20180503085802|2018/5/3 08:58:02|2018/5/3 08:58:02 11243|3941|2018050222320800001084|审核成功||20180503085821|2018/5/3 08:59:21|2018/5/3 08:58:21 11244|3945|2018050309152000005993|新建订单||20180503091520|2018/5/3 09:15:21|2018/5/3 09:15:21 Above is the data from my txt file. It contains order information for stock trades. I want to calculate the time difference for the create_time column for each unique order_id. How do I do this with Pandas? For example order_id 3941, there are three entries. The difference in create_time from the first to the second entry is 2 minutes, and the difference from the 2nd to the 3rd entry is 1 minute. The final output looks like below: order_id,stage1_time,stage2_time,... 3941,2,1,... Sorry for my poor English.
accepted answer: http://stackoverflow.com/a/50204351
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/87420287
has comment: http://stackoverflow.com/comment/87416296
score: -7
has title: how to calculation cost time
favorite count: 0
has answer: http://stackoverflow.com/a/50204351
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87416591
tagged with: pandas

http://stackoverflow.com/q/50226015
upvote count: 1
downvote count: 1
has body: The code is as follow def filee(filename): cpu = "iso.3.6.1.4.1.2021.10.1.3.1 = STRING:" newline = "\n" quotes = '"\n' file = open(filename) lineno = 0 for line in file: lineno += 1 linestriptime = line[line.find("(")+1:line.find(")")] linestripload = (line.strip(cpu + newline + '\n').replace('\"', '')) v = lineno % 2 if v == 0: load = float(linestripload) yield (timestamp, load) else: timestamp = int(linestriptime) listyield = filee("snmpfile.txt") mappedload = {timestamp : load for (timestamp, load) in listyield} print mappedload Simply put, I want to map the timestamp and load yield variables from the generator function together but somehow the print mappedload command always give me an empty dictionary instead. Why does this happen and how can I map the two variables together? EDIT: I've included this line of code, printing the yield value works just fine print ("**************** TRAP LISTYIELD ***************") for (timestamp, load) in listyield: print(timestamp, load) print ("**************** END OF TRAP LISTYIELD ***************") Result **************** TRAP LISTYIELD *************** (201607, 0.62) (203174, 0.55) (203336, 0.55) (203479, 0.51) (203611, 0.51) (203731, 0.51) **************** END OF TRAP LISTYIELD *************** {}
favorite count: 0
tagged with: yield
type: Question
has comment: http://stackoverflow.com/comment/87471636
has comment: http://stackoverflow.com/comment/87470105
has comment: http://stackoverflow.com/comment/87471291
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87469863
tagged with: python
score: 0
tagged with: mapping
has title: Mapping two yield variables from a generator function
has comment: http://stackoverflow.com/comment/87471558
answer count: 0
tagged with: stream

http://stackoverflow.com/comment/87172811
type: QuestionComment
has text: Use `pickle` if you want save Python structures like dictionaries and lists. Or JSON. But why are you using `numpy` and `scipy`?
comment on: http://stackoverflow.com/q/50075877
score: 0
type: Comment

http://stackoverflow.com/a/50090200
type: Answer
has body: This is a function that test if a list has been sorted, as an example with the builtin sorted function. This function takes an keyword argument key which is used on every single element on the list to compute its compare value: &gt;&gt;&gt; sorted([(0,3),(1,2),(2,1),(3,0)]) [(0, 3), (1, 2), (2, 1), (3, 0)] &gt;&gt;&gt; sorted([(0,3),(1,2),(2,1),(3,0)],key=lambda x:x[1]) [(3, 0), (2, 1), (1, 2), (0, 3)] The key keyword in your function is to be able to mimic the behavior of sorted: &gt;&gt;&gt; is_sorted([(0,3),(1,2),(2,1),(3,0)]) True &gt;&gt;&gt; is_sorted([(0,3),(1,2),(2,1),(3,0)],key=lambda x:x[1]) False The default lambda is just there to mimic a default behavior where nothing is changed.
answers question: http://stackoverflow.com/q/50090072
score: 0

http://stackoverflow.com/a/50175399
answers question: http://stackoverflow.com/q/50175318
has body: tk.Tk.__init__(self, dialog_message) This doesn't look right to me. The first positional argument to the Tk constructor is screenName. If you don't want to display your window on a display that's named "This is definitely working", then don't supply that argument. tk.Tk.__init__(self) ... Or, more idiomatically, super().__init__()
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/87367882
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87367931
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50175318
has comment: http://stackoverflow.com/comment/87368050
has comment: http://stackoverflow.com/comment/87367925

http://stackoverflow.com/comment/87268660
type: Comment
has text: Sorry, not sure I understood you correctly. Could you give some code examples?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50125258

execute
tags question: http://stackoverflow.com/q/50075325
tag name: execute
type: Tag

http://stackoverflow.com/comment/87449329
type: Comment
has text: Your understanding is correct, thanks for your answer. But I'm still confused. Of course I can get the best performing model from RandomizedSearchCV by using best_estimator_ and then I could do again a cross-validation and using predict_proba() on this best model but in this cross-validation I should then train the model again just with the best parameters and not using just the best model.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50215921

http://stackoverflow.com/q/50215301
tagged with: python
favorite count: 0
has body: I'm trying to build an object detector with CNN using tensorflow with python framework. I would like to train my model to do just object recognition (classification) at first and then using several convolutional layers of the pretarined model train it to predict bounding boxes. I will need to replace fully connected layers and probably some last convolutional layers. So, for this reason, I would like to know if it is possible to import only weights from tensorflow graph that was used to train object classifier to a newly defined graph that I will train to do object detection. So basically I would like to do something like this: # here I initialize the new graph conv_1=tf.nn.conv2d(in, weights_from_old_graph) conv_2=tf.nn.conv2d(conv_1, weights_from_old_graph) ... conv_n=tf.nn.nnconv2d(conv_n-1,randomly_initialized_weights) fc_1=tf.matmul(conv_n, randomly_initalized_weights)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87447389
linked to: http://stackoverflow.com/q/50017707
accepted answer: http://stackoverflow.com/a/50216044
tagged with: tensorflow
has title: Tensorflow: how to use pretrained weights in new graph?
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50216044
score: 6
has answer: http://stackoverflow.com/a/50219749
possible better answer: http://stackoverflow.com/a/50219749
upvote count: 6
has comment: http://stackoverflow.com/comment/87447920
downvote count: 0

http://stackoverflow.com/a/65688848
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/133477699
answers question: http://stackoverflow.com/q/50083912
score: 4
has body: In the RFC https://www.rfc-editor.org/rfc/rfc7159, it says: JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32 At first glance it does seem that Python isn't really following the spec when you first look at this after all what does it mean to encode something when it remains a Python3 'str' string, however Python is doing some encoding for you nonetheless. Try this: >>> json.dumps({"Japan":"日本"}) '{"Japan": "\\u65e5\\u672c"}' You can see that the Japanese has got converted to unicode escapes, and the resultant string is actually ASCII, even if it's still a Python str. I'm unsure how to get json.dumps() to actually give you utf-8 sequences - for interoperability purposes - if you wanted them, however for all practical purposes this is good enough for most people. The characters are there and will be interpreted correctly. It's easy to get binary with: >>> json.dumps({"Japan":"日本"}).encode("ascii") b'{"Japan": "\\u65e5\\u672c"}' And python does the right thing when loading back in: >>> json.loads(json.dumps({"Japan":"日本"}).encode("ascii")) {'Japan': '日本'} But if you don't bother encoding at all, the loads() still figures out what to do as well when given a str: >>> json.loads(json.dumps({"Japan":"日本"})) {'Japan': '日本'} Python is - as ever - trying to be as helpful as possible in figuring out what you want and doing it, but this is perplexing to people who dig a little deeper, and in spite of loving Python to bits I sympathise with the OP. Whether this kind of 'helpful' behaviour is worth the confusion is a debate that will rage on. Worth noting that if the next thing to be done with the output is writing to a file, then you can just do: pathlib.Path("myfile.json").open("w").write(json_data) Then you don't need it binary because the file is opened in text mode and encoding is done for you.

http://stackoverflow.com/q/50112332
has comment: http://stackoverflow.com/comment/87242322
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/87242160
has answer: http://stackoverflow.com/a/78706048
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50112365
has comment: http://stackoverflow.com/comment/87242470
has body: Lets suppose I have a list of unevaluated querysets: q_list = [a.objects.all(), b.objects.all(),...] I want to evaluate all of them at once in a single database call. I can iterate over the list and evaluate them individually like this: evaluated_q_list = map(list, q_list) But that will make multiple db queries. Is it possible to do this in a single db query using Django ORM?
type: UnansweredQuestion
has title: Evaluate multiple querysets in a single db call
tagged with: python
score: 2
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87242223
tagged with: django-orm
linked to: http://stackoverflow.com/q/431628

http://stackoverflow.com/q/50130307
tagged with: google-prediction
tagged with: google-cloud-platform
has body: I'm using GCP with GCS and GCMLE APIs to train my model and to predict on the cloud. I'm working on the census dataset. And the goal is to predict a profile's income. this is the github link of codes and scripts https://github.com/SofiaAmel/censusTest Actually I am discovering this tool, I'm struggling with prediction, I'm testing with one profile as .json input , the job preiction runs succussfully, but it occurs this error *** ("Failed to load the model due to bad model data. tags: ['serve']\nNo op named HashTableV2 in defined operations.", 1) ps : I'm using TF version 1.4 , if you can help don't hesitate ! Thanks in advance
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87317257
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87315162
has title: ("Failed to load the model due to bad model data. tags: ['serve']\nNo op named HashTableV2 in defined operations.", 1)
type: Question
tagged with: google-cloud-ml
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50148598

http://stackoverflow.com/comment/87224307
comment on: http://stackoverflow.com/q/50102792
type: QuestionComment
has text: Why should the page reload with this code? This code only tries to open an URL. Could you post the output you get from this program and exactly what the expected behavior is?
score: 1
type: Comment

http://stackoverflow.com/q/50168122
has answer: http://stackoverflow.com/a/50199551
has comment: http://stackoverflow.com/comment/87354556
type: Question
tagged with: arrays
tagged with: transpose
has comment: http://stackoverflow.com/comment/87353889
tagged with: python
possible better answer: http://stackoverflow.com/a/50168843
has comment: http://stackoverflow.com/comment/87353723
has answer: http://stackoverflow.com/a/50168843
type: AnsweredQuestion
has body: I have been trying to transpose my table of 2000000+ rows and 300+ columns on a cluster, but it seems that my Python script is getting killed due to lack of memory. I would just like to know if anyone has any suggestions on a more efficient way to store my table data other than using the array, as shown in my code below? import sys Seperator = "\t" m = [] f = open(sys.argv[1], 'r') data = f.read() lines = data.split("\n")[:-1] for line in lines: m.append(line.strip().split("\t")) for i in zip(*m): for j in range(len(i)): if j != len(i): print(i[j] +Seperator) else: print(i[j]) print ("\n") Thanks very much.
score: 0
has comment: http://stackoverflow.com/comment/87354670
has answer: http://stackoverflow.com/a/50169440
answer count: 3
accepted answer: http://stackoverflow.com/a/50199551
has title: More efficient way than zipping arrays for transposing a table in Python?

http://stackoverflow.com/comment/87203722
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50093687
type: Comment
has text: So creating the transpose is the key >.< . I can't believe I didn't realize that. Thank you very much!

http://stackoverflow.com/comment/87804710
type: AnswerComment
comment on: http://stackoverflow.com/a/50344543
score: 0
has text: @mnistic Noise in blue channel of video file is sometimes more awful than in scanned images. And letters' skew can be like this: http://benjaminpercy.com/thrill-me-essays-on-fiction/
type: Comment

http://stackoverflow.com/comment/88632758
type: QuestionComment
comment on: http://stackoverflow.com/q/50126814
score: 0
has text: @Benjamin no I didn't get it
type: Comment

http://stackoverflow.com/q/50143215
tagged with: easy-install
has comment: http://stackoverflow.com/comment/87304992
has comment: http://stackoverflow.com/comment/87305280
type: Question
has answer: http://stackoverflow.com/a/50154802
has comment: http://stackoverflow.com/comment/87304906
tagged with: pip
has title: Small Mac-based post house looking to run a Windows box, but we rely on some Python scripts
tagged with: python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87305778
score: 0
tagged with: windows
has body: You can tell where this is going from the title.. I work at a small post house, and to replace one of our older Mac Pros, we were looking at building a mid-range PC (doesn't need to do much heavy lifting - not worth the price of a new Mac Pro).. The problem is, we have a number of scripts that we use for footage transcoding and media management, and they were coded for our Mac-exclusive environment.. The basic procedure for setting up a new workstation is: Install pip using easy_install Use pip to install: youtube_dl pexpect parsedatetime XlsxWriter Install MacPorts.. Use MacPorts to install ffmpeg, lftp, and ImageMagick. From there, install a couple custom in-house scripts (that rely mostly on the preceding dependencies and python 2.7 (via xcode). I'm NOT going to ask how to adapt this to PC, since that would be way outside the scope of a single question. My question is, without a strong python developer on-site (the custom scripts were written years ago by someone who's no longer with the company), is it even feasible to adapt the install scripts to a PC environment? We have a freelance Python developer that we consult for minor script changes and he wasn't sure (his response was "I would first double check to make sure some of the utilities can even run on windows. I’m not 100% sure they can or not"). Do any of the utilities jump out as something that would not be adaptable to a Windows environment? Thanks very much in advance - I know it's a rather broad question.
tagged with: macports

http://stackoverflow.com/comment/87231941
score: 2
has text: A -1 as a parameter means 'choose the right number to preserve the total array size.'
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50107313

http://stackoverflow.com/a/50102548
has comment: http://stackoverflow.com/comment/87229597
has body: You need to capture the current value, as the lambda closure will always only close over names, not their values. So a simple lambda i=i: ... should do the trick.
type: Answer
has comment: http://stackoverflow.com/comment/87222765
accepted answer of: http://stackoverflow.com/q/50102452
answers question: http://stackoverflow.com/q/50102452
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87836282
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50128924
has text: ElementaryOS? Im not familiar with ElementOS. Did you install python-dev and build essentials?

ssh
tags question: http://stackoverflow.com/q/50174660
tags question: http://stackoverflow.com/q/50148070
type: Tag
tags question: http://stackoverflow.com/q/50142626
tag name: ssh

http://stackoverflow.com/q/50185419
score: 1
upvote count: 1
has title: Picture encoding and decoding with python
tagged with: image-processing
favorite count: 0
type: Question
tagged with: python-imaging-library
tagged with: encode
type: UnansweredQuestion
has body: First, I got three integer p1, p2, p3. Then for each pixel, I got r, g, b value and changed it to r * (3 ^ p1) % 256, g * (3 ^ p2) % 256, b * (3 ^ p3) % 256. That was my encoding and to decode this, for each pixel in encoded picture, I got r, g, b value and changed it to r * (3 ^ key1) % 256, g * (3 ^ key2) % 256, b * (3 ^ key3) % 256 where each key is 64 - corresponding p. I think this should work since 3 ^ 64 is identical with 1 in mod 256. Is my idea wrong or is there any problem with my algorithm? This is my encoding algorithm : from PIL import Image a = Image.open("up.jpg") rgb_a = a.convert('RGB') b = Image.new("RGB", a.size) p1, p2, p3 = map(int, input().split()) x = 3 ** p1 y = 3 ** p2 z = 3 ** p3 for i in range(a.size[0]): for j in range(a.size[1]): r2, g2, b2 = rgb_a.getpixel((i, j)) r2 *= (x % 256) g2 *= (y % 256) b2 *= (z % 256) r2 = r2 % 256 g2 = g2 % 256 b2 = b2 % 256 b.putpixel((i, j), (r2, g2, b2)) b.save("changer.jpg") print("key 1 is", 64-p1) print("key 2 is", 64-p2) print("key 3 is", 64-p3) And this is my decoding algorithm : from PIL import Image a = Image.open("changer.jpg") rgb_a = a.convert('RGB') b = Image.new("RGB", a.size) key1, key2, key3 = map(int, input().split()) x = 3 ** key1 y = 3 ** key2 z = 3 ** key3 for i in range(a.size[0]): for j in range(a.size[1]): r2, g2, b2 = rgb_a.getpixel((i, j)) r2 *= (x % 256) g2 *= (y % 256) b2 *= (z % 256) r2 = r2 % 256 g2 = g2 % 256 b2 = b2 % 256 b.putpixel((i, j), (r2, g2, b2)) b.save("comeback.jpg")
tagged with: python
tagged with: decode
has comment: http://stackoverflow.com/comment/99580494
has comment: http://stackoverflow.com/comment/87394284
downvote count: 0
answer count: 0

http://stackoverflow.com/q/50197501
tagged with: if-statement
has answer: http://stackoverflow.com/a/50197611
has body: I am trying to obtain a final 'process' array by filtering the raw 'hitdt' array for '-1'; the column that contains -1 in a particular row in hitdt would determine the values of that row in 'process'. I am using if statements in what I suspect a very laborious way, but could not find working methods. Currently, running def frame() does not return any errors, but when I check the resulting 'process' array, new columns remain NaN. 'hitdt' is the input data frame with 4 column series (hitdt['t1'] to hitdt['t4']). 'process' is an empty output dataframe. previous appending of data into hitdt series columns not involving 'if' statements were fine. Is there a way to determine which column of a certain row in a data frame == a value, then apply statements to that row only, and iterate through all rows? def frame(): global hitdt, process #v1 for i, row in hitdt.iterrows(): if -1 == i in hitdt['t3']: process['tau1'] = hitdt['t2']-hitdt['t1'] process['tau2'] = hitdt['t4']-hitdt['t1'] process['xx'] = geom['x2'] process['yy'] = geom['y2'] process['rho1'] = sqrt(square(geom['x2']-geom['x1']) + square(geom['y2']-geom['y1'])) process['alpha'] = 2.357067 elif -1 == i in hitdt['t4']: process['tau1'] = hitdt['t3']-hitdt['t2'] process['tau2'] = hitdt['t1']-hitdt['t2'] process['xx'] = geom['x3'] process['yy'] = geom['y3'] process['rho1'] = sqrt(square(x3-x2) + square(y3-y2)) process['alpha'] = 0.749619 elif -1 == i in hitdt['t1']: process['tau1'] = hitdt['t4']-hitdt['t3'] process['tau2'] = hitdt['t2']-hitdt['t3'] process['xx'] = geom['x4'] process['yy'] = geom['y4'] process['rho1'] = sqrt(square(x3-x4) + square(y3-y4)) process['alpha'] = -0.800233 elif -1 == i in hitdt['t2']: process['tau1'] = hitdt['t1']-hitdt['t4'] process['tau2'] = hitdt['t3']-hitdt['t4'] process['xx'] = geom['x1'] process['yy'] = geom['y1'] process['rho1'] = sqrt(square(geom['x1']-geom['x4']) + square(geom['y1']-geom['y4'])) process['alpha'] = -1.906772 ... [In]: process [Out]: jd frac tau1 tau2 rho1 xx yy alpha hit…
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
has title: Iterating if statements of columns through rows of Python dataframe
answer count: 1
accepted answer: http://stackoverflow.com/a/50197611
tagged with: loops
tagged with: series
type: Question

http://stackoverflow.com/comment/87330825
score: 0
has text: Exactly. This is exactly what I was trying to do. Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/50125564
type: Comment

http://stackoverflow.com/comment/87363922
type: Comment
score: 0
type: AnswerComment
has text: That will work but say for feature F1 at time t1 weight on layer 1 will be w1. For the same feature F1 (now it's flattened, so its I'd will be higher) say f21 at time t2 the weight at layer 1 will be different w21. So learning of features won't be good. But your call. Let us know how it goes.
comment on: http://stackoverflow.com/a/50161614

http://stackoverflow.com/comment/87422384
comment on: http://stackoverflow.com/q/50202010
type: Comment
type: QuestionComment
score: 0
has text: Do you want to replace the tab in the value of `x`, or in the source code itself?

http://stackoverflow.com/q/50212122
has comment: http://stackoverflow.com/comment/87442294
tagged with: soap
tagged with: python
has answer: http://stackoverflow.com/a/50212557
has body: I have some SOAP responses saved in a file which I would like to parse, Part of example file: &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;soapenv:Body&gt; &lt;ns0:GetList_Operation_0Response xmlns:ns0="urn:COMPANY:TEST:Assets" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;ns0:getListValues&gt; &lt;ns0:Status&gt;New&lt;/ns0:Status&gt; &lt;ns0:FormType&gt;Support Group&lt;/ns0:FormType&gt; &lt;ns0:PersonRole&gt;Supported by&lt;/ns0:PersonRole&gt; &lt;ns0:FullName&gt;Data Centre&lt;/ns0:FullName&gt; &lt;ns0:PeopleGroupFormEntryID&gt;SG0003&lt;/ns0:PeopleGroupFormEntryID&gt; &lt;ns0:PeopleGroupInstanceID&gt;ASDAWDASDWADSDWSDWDS&lt;/ns0:PeopleGroupInstanceID&gt; &lt;ns0:AssetClassId&gt;UPS&lt;/ns0:AssetClassId&gt; &lt;ns0:AssetInstanceId&gt;ASDAWDDAWSDWADS66666&lt;/ns0:AssetInstanceId&gt; &lt;/ns0:getListValues&gt; &lt;ns0:getListValues&gt; &lt;ns0:Status&gt;New&lt;/ns0:Status&gt; &lt;ns0:FormType&gt;Support Group&lt;/ns0:FormType&gt; &lt;ns0:PersonRole&gt;Supported by&lt;/ns0:PersonRole&gt; &lt;ns0:FullName&gt;Unix&lt;/ns0:FullName&gt; &lt;ns0:PeopleGroupFormEntryID&gt;SG0004&lt;/ns0:PeopleGroupFormEntryID&gt; &lt;ns0:PeopleGroupInstanceID&gt;ASDAWDASDWADSDWSDWQQ&lt;/ns0:PeopleGroupInstanceID&gt; &lt;ns0:AssetClassId&gt;COMPUTERSYSTEM&lt;/ns0:AssetClassId&gt; &lt;ns0:AssetInstanceId&gt;ASDAWDDAWSDWADS55555&lt;/ns0:AssetInstanceId&gt; &lt;/ns0:getListValues&gt; &lt;/ns0:GetList_Operation_0Response&gt; &lt;/soapenv:Body&gt; I would like to get (FullName &amp; AssetInstanceId): Data Centre;ASDAWDDAWSDWADS66666 Unix;ASDAWDDAWSDWADS55555 Could you suggest the best method to do that? Whenever I try to do that with ElementTree I get error of "SyntaxError: expected path separator (:)" Probably because of ns0: annex in beginning of ever…
score: 0
has comment: http://stackoverflow.com/comment/87442174
answer count: 1
has comment: http://stackoverflow.com/comment/87441838
has comment: http://stackoverflow.com/comment/87446642
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
type: Question
has comment: http://stackoverflow.com/comment/87442630
has comment: http://stackoverflow.com/comment/87442207
has title: How to parse SOAP XML with Python
has comment: http://stackoverflow.com/comment/87442560
type: UnansweredQuestion

http://stackoverflow.com/comment/87469858
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50225646
has text: Hmm... it didn't work. the request_body is indeed Json format, but I need to set "application/specified-content-type-xxx" because of API. I set "application/specified-content-type-xxx" in my header, but it didn't work too. I got 500 error.
score: 0

http://stackoverflow.com/a/65219000
type: Answer
downvote count: 0
has body: What I find easier in many scenarios is: import numpy as np import matplotlib.pyplot as plt f, ax = plt.subplots(2, 2) # make 1d for easier access ax = np.ravel(ax) for i in range(4): ax[i].plot([0,1], [0, 1], c=f"C{i}") # reshape to initial dimensions ax = np.reshape(ax, (2, 2))
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50180981

http://stackoverflow.com/comment/87459504
type: QuestionComment
comment on: http://stackoverflow.com/q/50220638
has text: I learned it is a good idea to vectorize this problem. I used a lot of Fortran, which deeply affects my coding style, sigh
score: 0
type: Comment

treeview
tags question: http://stackoverflow.com/q/50077698
tags question: http://stackoverflow.com/q/50201727
tags question: http://stackoverflow.com/q/50227854
tags question: http://stackoverflow.com/q/50090526
tag name: treeview
type: Tag
tags question: http://stackoverflow.com/q/50227723

http://stackoverflow.com/q/50116204
upvote count: 1
has title: TemplateDoesNotExist when trying to override template name in detail view
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50116235
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87249920
has body: I am following django 2.0 tutorial "2.6.2 Use generic views: Less code is better" and try to convert functions views to class views. It throws such an error: TemplateDoesNotExist at /polls/1/results/ polls/question_detail.html Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/results/ Django Version: 2.0.4 I checked the code with the official materials class ResultsView(generic.DetailView): model = Question template = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): #Redisplay the question voting form return render(request, 'polls/detail.html', { 'question':question, 'error_message':"You did'nt select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) The errors occurs when I attempt to submit the vote: The polls/detail.html template works properly when come with the functions views: {{ question.question_text }} {% if error_message %} {{ error_message }} {% endif %} {% csrf_token %} {% for choice in question.choice_set.all %} {{ choice.choice_text }} {% endfor %} What's the problem with my code?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50116235
has comment: http://stackoverflow.com/comment/87251306
has comment: http://stackoverflow.com/comment/87249820
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50113683
accepted answer: http://stackoverflow.com/a/57745095
has comment: http://stackoverflow.com/comment/87244565
upvote count: 29
has answer: http://stackoverflow.com/a/57745095
has comment: http://stackoverflow.com/comment/87284601
score: 28
has answer: http://stackoverflow.com/a/58625856
has comment: http://stackoverflow.com/comment/87297049
has comment: http://stackoverflow.com/comment/87244666
has answer: http://stackoverflow.com/a/50148096
possible better answer: http://stackoverflow.com/a/55285649
has comment: http://stackoverflow.com/comment/87245494
has comment: http://stackoverflow.com/comment/87314231
has answer: http://stackoverflow.com/a/51806337
has answer: http://stackoverflow.com/a/55285649
has answer: http://stackoverflow.com/a/57332168
downvote count: 1
favorite count: 0
has title: ModuleNotFoundError: No module named 'object_detection'
type: Question
has body: i try to train.py in object_detection in under git url https://github.com/tensorflow/models/tree/master/research/object_detection However, the following error occurs. ModuleNotFoundError: No module named 'object_detection' So I tried to solve the problem by writing the following code. import sys sys.path.append('/home/user/Documents/imgmlreport/inception/models/research/object_detection') from object_detection.builders import dataset_builder This problem has not been solved yet. The directory structure is shown below. ~/object_detection/train.py ~/object_detection/builders/dataset_bulider.py and here is full error massage /home/user/anaconda3/lib/python3.6/site-packages/h5py/init.py:34: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters Traceback (most recent call last): File "train.py", line 52, in import trainer File"/home/user/Documents/imgmlreport/inception/models/research/object_detection/trainer.py", line 26, in from object_detection.builders import optimizer_builder ModuleNotFoundError: No module named 'object_detection' how can i import modules?
answer count: 8
has answer: http://stackoverflow.com/a/66325683
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87244824
has answer: http://stackoverflow.com/a/72315148
has comment: http://stackoverflow.com/comment/87244719
tagged with: python

http://stackoverflow.com/q/50091553
tagged with: python-internals
type: Question
has title: python generators garbage collection
possible better answer: http://stackoverflow.com/a/50091650
has answer: http://stackoverflow.com/a/50091650
tagged with: python
linked to: http://stackoverflow.com/q/15490127
upvote count: 29
score: 29
tagged with: generator
has body: I think my question is related to this, but not exactly similar. Consider this code: def countdown(n): try: while n &gt; 0: yield n n -= 1 finally: print('In the finally block') def main(): for n in countdown(10): if n == 5: break print('Counting... ', n) print('Finished counting') main() The output of this code is: Counting... 10 Counting... 9 Counting... 8 Counting... 7 Counting... 6 In the finally block Finished counting Is it guaranteed that the line "In the finally block" is going to be printed before "Finished counting"? Or is this because of cPython implementation detail that an object will be garbage collected when the reference count reaches 0. Also I am curious on how finally block of the countdown generator is executed? e.g. if I change the code of main to def main(): c = countdown(10) for n in c: if n == 5: break print('Counting... ', n) print('Finished counting') then I do see Finished counting printed before In the finally block. How does the garbage collector directly go to the finally block? I think I have always taken try/except/finally on its face value, but thinking in the context of generators is making me think twice about it.
accepted answer: http://stackoverflow.com/a/50091605
answer count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50091605
downvote count: 0
has comment: http://stackoverflow.com/comment/87199349
favorite count: 0

http://stackoverflow.com/q/50195402
has answer: http://stackoverflow.com/a/56728642
has comment: http://stackoverflow.com/comment/87407892
type: AnsweredQuestion
tagged with: ipython
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50195527
answer count: 2
has comment: http://stackoverflow.com/comment/87407963
score: 5
has body: How can I get something like Spyder's runfile function in IPython? (I'm using IPython v. 4.1.2 under Python 2.7.9.)
has answer: http://stackoverflow.com/a/50195527
upvote count: 5
linked to: http://stackoverflow.com/q/11744181
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/56728642
has title: Equivalent of Spyder's runfile for IPython?

http://stackoverflow.com/comment/134916000
has text: small thing. workspaceRoot has been deprecated, use workspaceFolder instead https://code.visualstudio.com/docs/editor/variables-reference#_why-isnt-workspaceroot-documented
score: 0
comment on: http://stackoverflow.com/a/62304225
type: Comment
type: AnswerComment

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/50155464
tag name: python-packaging

http://stackoverflow.com/comment/89300407
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51131957
has text: As a further clarification: the `fileObject` argument shown in the `_test_raise_exception` callback is an instance of [MFileObject](https://help.autodesk.com/view/MAYAUL/2017/ENU/?guid=__py_ref_class_open_maya_1_1_m_file_object_html). You can use the methods of it to resolve to an on-disk filepath and check if it exists or not. Do not rely on `MFileObject.exists()` method as it seems to always return True.

http://stackoverflow.com/q/50089395
upvote count: 0
downvote count: 2
answer count: 1
has title: Pythonic way of Python subclasses
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50089554
accepted answer: http://stackoverflow.com/a/50089554
tagged with: python-3.x
score: -2
tagged with: python
has body: I would like to organize my code in a way that allows me to define methods that can be categorized based on their purpose. My solutions uses subclasses in the following way: import matplotlib.pyplot as plt class Portfolio: def __init__(self): self.x = [1,2,3] self.y = [4,6,2] class Plotting: def red(x_value,y_value): plt.scatter(x=x_value,y=y_value,color="red") plt.show() def green(x_value,y_value): plt.scatter(x=x_value,y=y_value,color="green") plt.show() class Analysis: def min_max_x(x_value): print([min(x_value),max(x_value)]) def min_max_y(y_value): print([min(y_value), max(y_value)]) # Creates Portfolio object pf = Portfolio() # Plotting pf.Plotting.red(x_value=pf.x,y_value=pf.y) pf.Plotting.green(x_value=pf.x,y_value=pf.y) # Analysis pf.Analysis.min_max_x(x_value=pf.x) pf.Analysis.min_max_y(y_value=pf.y) Even though this works, I am not really satisfied for the following reasons: I have to pass an argument to the method (e.g. 'pf.x'). This seems to be not very pythonic since I am calling the method from 'pf'. Thus I basically access 'pf' twice. My actual code is much longer and this approach would require me to write every line of code in the 'Portfolio' class and thus in one single file. Way too difficult to navigate. So, my very question is: How can we construct a class with methods that are organized in a thematic way (e.g. Plotting, Analysis etc.) like in my example but without having to pass in arguments. Thanks a lot.
tagged with: class
type: AnsweredQuestion
tagged with: oop
tagged with: inner-classes

http://stackoverflow.com/comment/87420095
has text: no problem, but this isn't just for python, this aplies to every language.. imagine that your first `if` and `elif` was a very much complex tast or condition to evaluate, you would go for all of them just for telling that he input was wrong at the end
type: AnswerComment
comment on: http://stackoverflow.com/a/50088568
score: 0
type: Comment

http://stackoverflow.com/comment/87846534
type: AnswerComment
has text: I accepted this answer as it's cleaner, but I have to give it to Ajax1234's answer for actually accomplishing the same purpose with decorators and with more gory details around the dunder methods, this was a close call.
comment on: http://stackoverflow.com/a/50195664
type: Comment
score: 0

http://stackoverflow.com/q/50165258
type: Question
has title: Explain python unstack() simply
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50165510
tagged with: python
linked to: http://stackoverflow.com/q/49482356
downvote count: 0
has comment: http://stackoverflow.com/comment/87348454
upvote count: 1
tagged with: pivot-table
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87349449
has body: I am trying to annotate my python code before I rewrite it to avoid unstack() because of an error. Im stumped when it comes to explaining unstack to myself, even after reading the docs and seeing the output. Can someone explain what it does without using phrases like "pivot a level"? Definition from docs: Pivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels. If the index is not a MultiIndex, the output will be a Series (the analogue of stack when the columns are not a MultiIndex). The level involved will automatically get sorted. Here is the code Im attempting to annotate: import numpy as np import pandas as pd from numpy.core.defchararray import add d = {'vote': [100, 50,1,23,55,67,89,44], 'vote2': [10, 2,18,26,77,99,9,40], 'ballot1': ['a','b','a','a','b','a','c','c'], 'voteId':[1,2,3,4,5,'aaa',7,'NaN']} df1=pd.DataFrame(d) ####################################################################### print(df1) #Set the DataFrame index (row labels) using columns voteId and ballot1 s=df1[:10].set_index(['voteId','ballot1'],verify_integrity=True) print(s) #unstack (default -1). ????? # s=s.unstack() # s.columns=s.columns.map('(ballot1={0[1]}){0[0]}'.format) # dflw=pd.DataFrame(s) # print(df1) # print(dflw)
favorite count: 0

http://stackoverflow.com/comment/87350946
comment on: http://stackoverflow.com/a/50166539
type: Comment
type: AnswerComment
has text: yep I got confused, I meant dnrm2 (anyway, it's just a dummy example) Is the "anyfloat is double" a costly overhead?
score: 0

http://stackoverflow.com/comment/87266430
has text: @Y.Luo This is I think in essence what I want, but a Dense layer wont add the bias element-wise, as with increasing units, the Dense layer adds the bias to all combinations of inputs. Besides, I do not want the multiplication weights 'W' from a normal Dense layer. I tried unsuccesfully to implement it that way, but the permutations of the inputs and the multiplicative matrix W of the Dense layer made it impossible...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50120251
type: QuestionComment

http://stackoverflow.com/a/50225942
score: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/50225869
has comment: http://stackoverflow.com/comment/87469618
type: AcceptedAnswer
has body: numpy.array and numpy.arange are written in C. You can tell because they say "built-in" when you look at them: &gt;&gt;&gt; numpy.array &lt;built-in function array&gt; &gt;&gt;&gt; numpy.arange &lt;built-in function arange&gt; That means there's no def statement. Instead, we look at what module they come from: &gt;&gt;&gt; numpy.array.__module__ 'numpy.core.multiarray' &gt;&gt;&gt; numpy.arange.__module__ 'numpy.core.multiarray' navigate to the corresponding source file, and take a look at the array controlling the module's exported functions: {"array", (PyCFunction)_array_fromobject, METH_VARARGS|METH_KEYWORDS, NULL}, ... {"arange", (PyCFunction)array_arange, METH_VARARGS|METH_KEYWORDS, NULL}, numpy.array and numpy.arange correspond to _array_fromobject and array_arange in that file. That's not where all the work happens, though. You'll need to keep digging to find all the relevant code.
upvote count: 10
answers question: http://stackoverflow.com/q/50225869
downvote count: 1
has comment: http://stackoverflow.com/comment/87470191

http://stackoverflow.com/comment/87463888
comment on: http://stackoverflow.com/a/50215456
type: AnswerComment
has text: so we don't need to delete the attributes like `conv0.weight`? Thats what I was suggested on pytorch forum but seemed odd to me...I guess I just need to make sure the right variables are inserted in the computation tree for backwards computations to be done right, correct? What I had in mind was having 3 networks, 2 the real nets Im combining and the 3rd just as a place holder. The placeholder set to `eval()` and the untrained net also set to eval. But the other not set to eval. Then the placeholder net would hold the combination for the forward coputations to be done right.
score: 0
type: Comment

http://stackoverflow.com/a/50121602
has comment: http://stackoverflow.com/comment/87261347
type: Answer
has body: You can mark your tests and run only those with some mark. For example: import pytest @pytest.mark.runstresstests def test_stress_something(): pass @pytest.mark.logperfdata def test_something_quick(): pass ... If you only want to run stress tests: pytest -m runstresstests Full documentation at https://docs.pytest.org/en/latest/example/markers.html
score: 0
has comment: http://stackoverflow.com/comment/87261053
answers question: http://stackoverflow.com/q/50121464
has comment: http://stackoverflow.com/comment/87261461

http://stackoverflow.com/comment/87453205
comment on: http://stackoverflow.com/a/50159122
type: AnswerComment
score: 1
type: Comment
has text: I would upvote your answer, but I have no basis for evaluating it.

http://stackoverflow.com/comment/87200400
comment on: http://stackoverflow.com/q/50091475
type: Comment
has text: Another possibility is that the actual parsing, grouping, etc. work you're doing really does take hours to run. If so, just using Pandas for looping but still doing the work itself the same way will only knock off a few seconds of time, but if you can rewrite the slow part of the work in terms of Pandas operations, that could knock off hours. But anyway, the first step is to try to get some profiling information (or at least out-of-line benchmarking simulations) to see what part you need to focus on.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87337274
type: Comment
comment on: http://stackoverflow.com/q/50159682
score: 2
has text: Welcome to StackOverflow. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Also, please, format your code correctly, don't add irrelevant tags (java), don't paste links to external images containing screenshots of text.
type: QuestionComment

http://stackoverflow.com/a/50126611
has comment: http://stackoverflow.com/comment/87308499
has comment: http://stackoverflow.com/comment/87339192
accepted answer of: http://stackoverflow.com/q/50126263
has comment: http://stackoverflow.com/comment/87348128
answers question: http://stackoverflow.com/q/50126263
type: AcceptedAnswer
type: Answer
score: 0
has body: I'm not sure I fully understand the question, but certainly each individual piece is quite simple to accomplish in Python. By using the sum() function with the trigonometric functions provided in the math module together in a list comprehension, it should be relatively simple to accomplish. For the example you give, from math import * iters = [1, 2] summation = sum(cos(2*x) for x in iters) , should do the trick. Also, I'd recommend being more thorough in your questions in the future. It is frowned upon to ask questions with no evidence of having attempted the problem already.

http://stackoverflow.com/comment/87476305
has text: You can read about Caesar/shift cipher here: https://en.wikipedia.org/wiki/Caesar_cipher
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50229420
score: 1

http://stackoverflow.com/comment/87237828
score: 0
has text: I got it from running a portfolio optimization on a bunch of assets, but that is a ton of code I didn't want to post and it didn't seem relevant.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50110269

http://stackoverflow.com/comment/103246437
has text: @alexHall The closure is the gen_val_fn, the enclosed variable is inst.
comment on: http://stackoverflow.com/q/50163080
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50219187
answers question: http://stackoverflow.com/q/50196129
score: 0
accepted answer of: http://stackoverflow.com/q/50196129
has body: You can solve this problem using the tf.sparse_retain() op: st = ... # A `tf.SparseTensor` object. # Compute a vector of booleans indicating which values of `st` should be dropped # (if False) or retained (if True) is_nonzero = tf.not_equal(st.values, 0) # `tf.sparse_retain()` computes a new `tf.SparseTensor` with the specified values # retained in the output. st_without_zeros = tf.sparse_retain(st, is_nonzero)
type: Answer
type: AcceptedAnswer

pytorch
tags question: http://stackoverflow.com/q/50175711
tags question: http://stackoverflow.com/q/50196608
tags question: http://stackoverflow.com/q/50149376
tags question: http://stackoverflow.com/q/50079735
tags question: http://stackoverflow.com/q/50090821
tags question: http://stackoverflow.com/q/50144597
tags question: http://stackoverflow.com/q/50124712
tags question: http://stackoverflow.com/q/50176137
tags question: http://stackoverflow.com/q/50229857
tags question: http://stackoverflow.com/q/50185227
tags question: http://stackoverflow.com/q/50195080
tags question: http://stackoverflow.com/q/50090714
tags question: http://stackoverflow.com/q/50170011
tags question: http://stackoverflow.com/q/50087252
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/50196212

http://stackoverflow.com/a/50138442
has comment: http://stackoverflow.com/comment/87295661
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50138323
has body: A series (pd.Series) object is one-dimensional. It consists of an array-like container of items together with an index. Therefore, like any one-dimensional array, only one index is permitted. For the minimum value of a series, use s1.min(). The syntax x.iloc[:, 0].min() is used where x is a dataframe (pd.DataFrame). In other words, it is used to calculate the minimum of the first column across all rows.
has comment: http://stackoverflow.com/comment/87295756
type: Answer
accepted answer of: http://stackoverflow.com/q/50138323
score: 2

http://stackoverflow.com/comment/87369389
type: AnswerComment
comment on: http://stackoverflow.com/a/50176130
has text: Actually removing `eyes_black` would still give you the information that the eyes are black. Like the example of the documentation, if a row is all 0, then it is `a`
score: 2
type: Comment

http://stackoverflow.com/q/50205103
upvote count: 1
downvote count: 1
tagged with: dictionary
has answer: http://stackoverflow.com/a/50205158
accepted answer: http://stackoverflow.com/a/50205158
favorite count: 0
has title: How do I add specific elements of a list of lists in Python?
type: AnsweredQuestion
score: 0
tagged with: list
has body: So I want to add the 3rd value of the elements in a list of lists if the first and second values are equal. And if not, I want the non-equal ones to be added to my sum list. first=[[1,1,5],[2,3,7],[3,5,2],[4,4,6]] second=[[1,1,3],[4,2,4],[2,3,2]] sum=[] for i in ((first)): for j in ((second)): if i[0]==j[0] and i[1]==j[1]: sum.append([i[0],j[1],i[2]+j[2]]) print(sum) so this gives me [[1, 1, 8], [2, 3, 9]] but I want [3,5,2],[4,4,6],[4,2,4] in my sum list too. How do I do this in python?
tagged with: python
possible better answer: http://stackoverflow.com/a/50205435
has answer: http://stackoverflow.com/a/50205435
type: Question
tagged with: python-3.x
answer count: 2

http://stackoverflow.com/q/50220863
has answer: http://stackoverflow.com/a/50220959
tagged with: python
type: Question
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50220959
upvote count: 1
has body: I'm working on my school project and I'm struggling at the very end of my code. The last line which suppose to check if the graph is semi-eulerian isn't working and I'm out of ideas how to fix it. I'm a beginner at Python, hope to see some good advice :) graph = { "1" : set(["2", "6"]), "2" : set(["1", "6", "7", "3"]), "3" : set(["2","7","4", "5"]), "4" : set(["3", "5"]), "5" : set(["3","4", "7", "6"]), "6" : set(["1","2", "7", "5"]), "7" : set(["2", "3", "5"]), } def path(x, node, visited): if node not in visited: visited.append(node) for n in x[node]: path(x,n, visited) return visited visited = path(graph,"1", []) print("Graph path: ", visited) values = list(map(len, graf.values())) print(values) if all(map(lambda x: x % 2 == 0, values)): print("Eulerian") else list(filter(lambda x: x % 2 == 1, values)) &gt;= 2: print("Semi-eulerian")
favorite count: 0
tagged with: graph
has title: Finding if given graph is eulerian or semi-eulerian

http://stackoverflow.com/q/50228781
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/50230158
tagged with: python
has body: Wrote this code to download h1,h2 and h3 headers and write to a pandas frame along with a list of urls but it gives error as unpacking error expected 3 values. def url_corrector(url): if not str(url).startswith('http'): return "https://"+str(url) else: return str(url) def header_agg(url): h1_list = [] h2_list = [] h3_list = [] p = requests.get(url_corrector(url),proxies = proxy_data,verify=False) soup = BeautifulSoup(p.text,'lxml') for tag in soup.find_all('h1'): h1_list.append(tag.text) for tag in soup.find_all('h2'): h2_list.append(tag.text) for tag in soup.find_all('h3'): h3_list.append(tag.text) return h1_list, h2_list, h3_list headers_frame = url_list.copy() headers_frame['H1'],headers_frame['H2'],headers_frame['H3'] = headers_frame.url.map(lambda x: header_agg(x)) Any help on how to do it? Getting this error: ValueError: too many values to unpack (expected 3)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50229370
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50230158
has title: Writing scraped headers from webpages to pandas frame
has answer: http://stackoverflow.com/a/50228890
possible better answer: http://stackoverflow.com/a/50229370

http://stackoverflow.com/comment/87403175
score: 0
comment on: http://stackoverflow.com/a/50192991
type: Comment
type: AnswerComment
has text: the string format is actually in "MM/DD/YYYY" so i adjusted that in the code you gave to "%m/%d/%Y", but after run it I get: " ValueError: time data 'Appointment Date' does not match format '%m/%d/%Y' "?

http://stackoverflow.com/comment/87352194
type: Comment
type: QuestionComment
has text: Yes, the statement is accurate. When doing an assignment, Python never implicitly assigns a copy of the right-hand side to the left. You must do this explicitly.
comment on: http://stackoverflow.com/q/50167261
score: 0

http://stackoverflow.com/comment/87299670
type: QuestionComment
comment on: http://stackoverflow.com/q/50140676
score: 2
has text: Along with the input, what do you expect `A` to look like? (In general, your answer will consist of parsing the input and producing an appropriate value. How you do that depends on what exactly `v` looks like and what you actually want to do with the parsed result.)
type: Comment

http://stackoverflow.com/comment/87346532
score: 0
has text: Python 2.7. Thanks!
type: QuestionComment
comment on: http://stackoverflow.com/q/50164258
type: Comment

http://stackoverflow.com/a/51011679
answers question: http://stackoverflow.com/q/50225297
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/100471047
accepted answer of: http://stackoverflow.com/q/50225297
type: Answer
score: 2
upvote count: 2
has body: You can also modify wagtail's icon font. Then you don't have to touch any of the code. The font file is at https://github.com/wagtail/wagtail/blob/8e0b2f6d1da6c18ad1aaaa8366f02e6c8cf76027/wagtail/admin/static_src/wagtailadmin/fonts/wagtail-icomoon.json I used a slightly modified version of the instructions at https://github.com/wagtail/wagtail/wiki/Adding-new-icon go to https://icomoon.io/app/ hamburger menu -> Manage project -> Import project open the font Rename 'Untitled Project 1' to 'Wagtail' click 'Load' switch to the edit tool and select the bird icon (there are two of them. The one you want will be named uni56) Click replace and choose an svg to replace it with. (I just downloaded one from the icomoon library) From the hamburger menu next to Wagtail, 'select all', then 'Generate font' Unpack the zip file, and copy the contents of the 'fonts' folder to static/wagtailadmin/fonts/ in any of your apps as long as your app comes before wagtail.admin in INSTALLED_APPS it will use your modified font instead modified icon
downvote count: 0

html-parsing
tags question: http://stackoverflow.com/q/50198050
tags question: http://stackoverflow.com/q/50177007
tags question: http://stackoverflow.com/q/50176051
tag name: html-parsing
type: Tag

http://stackoverflow.com/comment/87257094
type: QuestionComment
has text: this works but I need the relative one cause I have to hand it in
comment on: http://stackoverflow.com/q/50119792
score: 0
type: Comment

http://stackoverflow.com/a/50211918
upvote count: 1
has body: This is generally known as a stampeding or thundering herd problem. All of a sudden a ton of clients want something, and then activity goes back to nothing. There are different ways of coping with that. If you have some intermediary between the client and the server, e.g. a load balancer, you can use that to spread the load around and perhaps even use it to spin up new server instances as needed. In the case of a direct client-MySQL connection that typically isn't an option. Perhaps you can switch to read-only replicated slaves, which can more easily absorb the impact (i.e. scale horizontally). Or you get a bigger server which has a better peak-load performance. Of course, if 99% of the time there's no load whatsoever, these solutions aren't very cost-effective. The cheap solution is to avoid all clients stampeding towards the server at the same time. Either offset each client individually (e.g. schedule their cron job for 0 * * * *, 5 * * * *, 10 * * * * etc.), or simply delay each client by a random amount each time (sleep(randint(0, 360)) in Python, sleep $((RANDOM % 360)) &amp;&amp; ... in bash).
answers question: http://stackoverflow.com/q/50187126
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/comment/87391849
type: AnswerComment
has text: @Kasramvd Do you mean that the `1`s not at the very end also should be considered? If so, I thought the loop that the OP gave considers only the `1`s at the very end of the array.
comment on: http://stackoverflow.com/a/50187372
type: Comment
score: 0

http://stackoverflow.com/a/50198282
has body: You can avoid passing the ID in the URL with a POST request. Supply the ID and some kind of "action" verb, e.g. action=delete in the body of the request. That's not considered RESTful though, partly because the HTTP DELETE and PUT verbs perfectly describes the requested operations, but also because POST is considered a non-idempotent method, meaning that the server state will change with each successful request. Being idempotent, duplicate DELETE/PUT (and GET for that matter) requests will leave the server in the same state. It's not a major hassle to have a second route and view to implement the REST API so it's best to leave it as it is.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50196721
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50196721
score: 1
type: Answer

http://stackoverflow.com/q/50104344
tagged with: deep-learning
score: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51252920
has title: tensorflow input pipeline & performance - images
tagged with: python
tagged with: pipeline
has body: Best, system properties: windows 10 intel core i7-6820HQ CPU | 2.70GHZ 8CPUs 16GB ram 64bit NVIDIA Quadro M1000M approx. total memory: 10093 MB Display memory (VRAM): 2019 MB Shared Memory: 8073 MB Tensorflow 1.8 Python 3.5.2 images (i've 36k images): train: 3000 x (720x1280x3) valid: 500 x (720x1280x3) test : 500 x (720x1280x3) My story &amp; strugles First of all, I would like to say that I really like machine learning, specially neural networks. But most of the time, when I'm working with Tensorflow, I've the feeling that it is backstabbing me the entirely time. (like for example, the speed of those releases... (1.8 :O )) &amp; Sometimes I even don't know any more if I'm doing it right or wrong? (Or can I do it better?) Therefore, my main question is: How do you create a proper input pipeline! preferable with tensorflow gpu Because come one, it should be easy as $*%€k no? Especially, can't you cover 90% of all the input pipelines into 1, 2 or 3 template pipelines? (I think it is +/- possible, (a giant image with a cat is still an image | matrix)) and if it is possible, why can't we have an optimized template/base for it? as you would have noticed, I've provided my system properties and info about the data which I'm using. My goals are: Create a GAN-network (GPU)(doesn't have to be a gan for this question) Use the TF-estimator api (with custom features) Use TF-records ! Use TF-dataset ! But Unfortunately, most of the time, I'll receive errors like for example that I'm out of memory :'( And the more I look things up, the more I start to hesitate... Step 1: create TF-records In my first step, I create a tf-record (train). And as you can see, I loop over the images (from a certain folder) and write all the data into 1 tf-record. # Helper-function for wrapping an integer so it can be saved to the TFRecords file def wrap_int64(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) # Helper-function for wrapping raw bytes so they can be saved to t…

http://stackoverflow.com/a/50141800
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87301805
has body: You have to use bracket notation in order to add elements to dictionary. totaldict = {} for i in range (1,201): ........................ totaldict[count] = studno
type: Answer
answers question: http://stackoverflow.com/q/50141770
has comment: http://stackoverflow.com/comment/87302067
accepted answer of: http://stackoverflow.com/q/50141770
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/102946198
score: 0
comment on: http://stackoverflow.com/a/50212424
has text: @JuneWang Hi, when you try to reuse the layer one of your dimensions changed from 16 to 32. Check the inputs to the shared layer and make sure the dimensions are the same.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/66240707
answers question: http://stackoverflow.com/q/50203379
has comment: http://stackoverflow.com/comment/118631483
type: Answer
upvote count: 2
score: 2
downvote count: 0
has body: for me using virtualenv solved the problem create virtual environment by python3 -m virtualenv venv then install cryptography pip install cryptography

http://stackoverflow.com/q/50182427
score: 0
tagged with: windows
tagged with: multimedia
has answer: http://stackoverflow.com/a/50182462
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I need to play several videos (with the relative audios) under a python script because I need to insert specific pauses between them and triggers (for a neuropsychological experiment). I tried many examples on the internet to implement the media player, like this one from here, but I didn`t manage to compile the library MPlayer. Finally I just need to have videos controlled by python, either using an external program or not. The critical part is to find a way to implement playvideo() in the following code for pairs in Videos_paired_to_play: video1,video2 = pairs send_trigger(triggerType1) playvideo(video1[1] ) make_a_pause(2) playvideo(video2[1]) send_trigger(triggerType2) make_a_pause(20) Ideally, I would need a way to play videos without destroying the window after having played them. Thanks!
has title: Play videos (with audio) under Python

http://stackoverflow.com/a/50090883
answers question: http://stackoverflow.com/q/50090868
has comment: http://stackoverflow.com/comment/87215878
has comment: http://stackoverflow.com/comment/87215914
upvote count: 8
has body: There is a syntax problem: an assignment is a statement, and the body of a lambda can only have expressions. Python's syntax is designed this way1. Check it out at https://docs.python.org/3/reference/grammar.html. There is also a semantics problem: what does each statement return? I don't think there is interest in changing this, as lambdas are meant for very simple and short code. Moreover, a statement would allow sequences of statements as well, and that's not desirable for lambdas. It could be also fixed by selectively allowing certain statements in the lambda body, and specifying the semantics (e.g. an assignment returns None, or returns the assigned value; the latter makes more sense to me). But what's the benefit? Lambdas and functions are interchangeable. If you really have a use-case for a particular statement in the body of a lambda, you can define a function that executes it, and your specific problem is solved. Perhaps you can create a syntactic macro to allow that with MacroPy3 (I'm just guessing, as I'm a fan of the project, but still I haven't had the time to dive in it). For example MacroPy would allow you to define a macro that transforms f[_ * _] into lambda a, b: a * b, so it should not be impossible to define the syntax for a lambda that calls a function you defined. 1 A good reason to not change it is that it would cripple the syntax, because a lambda can be in places where expressions can be. And statements should not. But that's a very subjective remark of my own.
type: Answer
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/87198615

http://stackoverflow.com/comment/128616558
score: 0
type: AnswerComment
has text: @undetectedSelenium it is there pls check again.
comment on: http://stackoverflow.com/a/50183293
type: Comment

http://stackoverflow.com/comment/87412988
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50197181
has text: For multiple points you could create a function `add_point` that takes the current `axes` as an argument, and plot with `ax.imshow`. The linked example does this for 2 points. If you're concerned with the number of point to be plotted (for instance if your output is a .pdf), you could consider [rasterising](https://matplotlib.org/examples/misc/rasterization_demo.html) your plot.
score: 0

http://stackoverflow.com/q/50187932
has answer: http://stackoverflow.com/a/50187951
has answer: http://stackoverflow.com/a/50187968
accepted answer: http://stackoverflow.com/a/50187951
possible better answer: http://stackoverflow.com/a/53526442
has body: I am new to Python pandas library and using data frames. I am using Jupyter. I kind of lost with this syntax. I want to loop through rows and set new value to column new_value. I thought I would do it like this, but it raises an error. df_merged['new_value'] = 0 for i, row in df_merged.iterrows(): df_merged['new_value'][i] = i I also tried to do a calculation like: df_merged['new_value'][i] = df_merged['move_%'] * df_merged['value'] But it doesnt work. I am getting this error: /usr/lib/python3.4/site-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas- docs/stable/indexing.html#indexing-view-versus-copy after removing the cwd from sys.path. What I am doing wrong here? Thanks.
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50188003
has answer: http://stackoverflow.com/a/53526442
has answer: http://stackoverflow.com/a/50187966
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has title: Changing value in data frame column in a loop python
linked to: http://stackoverflow.com/q/20625582
favorite count: 0
answer count: 5
type: Question
score: 5
upvote count: 5

http://stackoverflow.com/a/66950791
type: Answer
score: 0
has body: This should do it: import tensorflow as tf from google.colab import files # Specify export directory and use tensorflow to save your_model export_dir = './saved_model' tf.saved_model.save(your_model, export_dir=export_dir) Note that the export directory contains several files, but if you only want to download the .pb file the following should do it. # Download the model files.download(export_dir + '/saved_model.pb')
answers question: http://stackoverflow.com/q/50166987

http://stackoverflow.com/q/50082441
tagged with: performance
has title: Improve performance filtering on object column with dates
accepted answer: http://stackoverflow.com/a/50082568
tagged with: datetime
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/17978092
has body: Working on the NYC car crash dataset. The current csv has data from 2012 and I wanted to extract out the 2017 values. Thing is DATE is an object dtype and trying something like this ended up taking too long data = data[(pd.to_datetime((data['DATE'])).dt.year == 2017)] Here is how a sample of the data looks Does anyone possibly know of a faster or more efficient way? Thank you.
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50082568
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/50165749
type: Answer
has body: To texture your text, you can first render the text in white, then blit the texture onto it and pass pygame.BLEND_RGB_MULT as the special_flags argument to use the multiply blend mode. The texture will appear only on the opaque parts of the text surface. Also, make sure that your texture is bigger than the text surface, otherwise some parts of the text will remain unaffected. import pygame as pg pg.init() screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() BG_COLOR = pg.Color('gray32') FONT = pg.font.Font(None, 50) # I create a grid texture for demonstration purposes here. # Just load your image with pygame.image.load instead. texture = pg.Surface((200, 100)) texture.fill((200, 100, 0)) for x in range(0, 201, 5): pg.draw.line(texture, (0, 0, 0), (x, 0), (x, 200)) for y in range(0, 101, 5): pg.draw.line(texture, (0, 0, 0), (0, y), (200, y)) # Render the text and use pure white as the color. text_surface = FONT.render('Hello world!', True, (255, 255, 255)) # Now blit the texture onto the text surface and pass BLEND_RGB_MULT as # the special_flags argument, so that only the opaque parts are affected. text_surface.blit(texture, (0, 0), special_flags=pg.BLEND_RGB_MULT) done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True screen.fill(BG_COLOR) screen.blit(texture, (50, 50)) screen.blit(text_surface, (50, 170)) pg.display.flip() clock.tick(30) pg.quit() Here's the animated version. You have to load the separate frames of the animation and do the same as above for each frame. Put the resulting surfaces into a list and then play them back in the main loop. import pygame as pg pg.init() screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() BG_COLOR = pg.Color('gray32') FONT = pg.font.Font(None, 50) # I create a grid texture for demonstration purposes here. # Just load your image with pygame.image.load instead. texture = pg.Surface((200, 100)) texture.fill((200, 100, 0)) for x in range(0, 201, 5): pg.draw.line(…
accepted answer of: http://stackoverflow.com/q/50165177
has comment: http://stackoverflow.com/comment/87661859
score: 5
has comment: http://stackoverflow.com/comment/87371969
downvote count: 0
has comment: http://stackoverflow.com/comment/87659647
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50165177
has comment: http://stackoverflow.com/comment/87397611
upvote count: 5

http://stackoverflow.com/q/50156001
tagged with: dataset
type: Question
tagged with: performance
has title: efficiently check two conditions on a dataset in python
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/87329726
has answer: http://stackoverflow.com/a/50156014
has comment: http://stackoverflow.com/comment/87329696
score: 0
has body: I want to find the number of rows in a dataset which satisfy two conditions: counter = len(train[(train['tag'] == label) &amp; (train['word'] == word)]) but it takes a long time to compute it based on the volume of data I have and number of times I want to perform it. Is there any other faster way? update: @jezrael solution, nearly tripled its speed, but still takes too long. it is the more completed code! for index, row in tqdm(test.iterrows()): word = row['word'] for label in labels: temp1 = train.eval('tag == @label and word == @word').sum()/labelDict[label] temp2 = train.eval('tag == @label and tag1 == @LastLable').sum()/labelDict[label] temp = temp1 * temp2 if max &gt; temp: max = temp bestLabel = label
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/50077107
tagged with: apache-spark
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50077375
has answer: http://stackoverflow.com/a/50077375
has body: I need to calculate Standard deviation row wise assuming that I already have a column with calculated mean per row.I tried this SD= (reduce(sqrt((add, (abs(col(x)-col("mean"))**2 for x in df.columns[3:])) / n))).alias("SD") dfS = df.withColumn("SD",SD) dfS.select("stddev").show() but I got the following error AttributeError: 'builtin_function_or_method' object has no attribute '_get_object_id'
possible better answer: http://stackoverflow.com/a/71989959
tagged with: python
has title: Spark Calculate Standard deviation row wise
score: -1
has answer: http://stackoverflow.com/a/71989959
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/50115840
upvote count: 1
has comment: http://stackoverflow.com/comment/87256465
score: 1
has comment: http://stackoverflow.com/comment/87254981
answer count: 1
tagged with: database-design
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87255931
has answer: http://stackoverflow.com/a/50116214
accepted answer: http://stackoverflow.com/a/50116214
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Autofill Django model fields when create instance of another model
has comment: http://stackoverflow.com/comment/87256162
downvote count: 0
has body: I have three models Student, Question and StudentAndQuestion class Student(models.Model): class Meta: verbose_name_plural = "Students" name = models.CharField(max_length=150) surname = models.CharField(max_length=150) code = models.CharField(max_length=10) # group = models.ForeignKey(Group,on_delete=models.CASCADE) points = models.IntegerField(default=0) class Question(models.Model): class Meta: verbose_name_plural = "Questions" text = models.CharField(max_length=1500) variants = models.CharField(max_length=1500) theme = models.OneToOneField(Theme, on_delete=models.CASCADE) anwser = models.CharField(max_length=1500) class StudentAndQuestion(models.Model): question = models.OneToOneField(Question,on_delete=models.CASCADE) student = models.OneToOneField(Student,on_delete=models.CASCADE) is_learned = models.BooleanField(default=0) points = models.IntegerField(default=0) I want Django make fill into StudentAndQuestion when i create new instance of students (for example create rows for all Questions and set points to zero) and when i create new instance of Question add it to all old students

http://stackoverflow.com/comment/87304529
score: 0
comment on: http://stackoverflow.com/a/50136004
type: Comment
has text: Now that I know what you're trying to achieve, I could advise you to use Jinja. http://jinja.pocoo.org
type: AnswerComment

http://stackoverflow.com/comment/87373516
score: 0
type: Comment
type: QuestionComment
has text: BubbleSort it's not porformance, but why multiprocessing is slower than sigle thread ?
comment on: http://stackoverflow.com/q/50177644

http://stackoverflow.com/q/50196294
has title: Django - Pass Foreign Key to Second Model
accepted answer: http://stackoverflow.com/a/50196415
type: AnsweredQuestion
has body: I'm trying to create a fairly simply input view for a django webapp. I have the following simply models set up. At the end I've included the traceback as well. The question is how do I create an object in the CreateView class and pass the foreign key of the parent object? #models.py #imports... class Client(models.Model): client_id = models.AutoField( primary_key=True) class Item(models.Model): client = models.ForeignKey( Client, on_delete=models.CASCADE) item_id = models.AutoField( primary_key=True) The idea is to have a list of unique clients and then each client can have a list of unique items. The items are linked to the client. #views.py #imports... class ItemCreate(CreateView): model = Item fields = [ #list of fields ] def form_valid(self, form): form.instance.client_id = self.request.client.client_id return super(PermCreate, self).form_valid(form) Given these two class models, I'm trying to CreateView that will create a new Item and have it attached to the respective Client. I have a ListView that will iterate through Items for a given Client. The ListView has a link to the CreateView (Add New Item). I am not having a problem with the pk's in the views or even getting to the CreateView. I can't get the CreateView to save the object. I get an error that says... 'WSGIRequest' object has no attribute 'client' The code above is derived from this question. I've tried several iterations of the argument to set form.instance.client_id but a request is likely the wrong call. The examples given are using user calls not per se the table foreign key information. I've also tried this (using the primary keys for my models) and I've tired accessing the URL pk from the template tags - but figured if I can't access them in the the views object that getting from the template would be more difficult. Traceback File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/anaconda3/lib/python3.6/site-packages…
has answer: http://stackoverflow.com/a/50196415
tagged with: python
has comment: http://stackoverflow.com/comment/87418857
has comment: http://stackoverflow.com/comment/87410026
type: Question
has comment: http://stackoverflow.com/comment/87409930
tagged with: python-3.x
linked to: http://stackoverflow.com/q/10382838
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/13309479
tagged with: django

http://stackoverflow.com/q/50223742
answer count: 5
possible better answer: http://stackoverflow.com/a/50223821
accepted answer: http://stackoverflow.com/a/50224011
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50224011
type: AnsweredQuestion
upvote count: 3
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50223821
tagged with: string
has answer: http://stackoverflow.com/a/50223806
has answer: http://stackoverflow.com/a/50223978
has body: I have the following examples: Tortillas Bolsa 2a 1kg 4118 Tortillinas 50p 1 31Kg TAB TR 46113 Bollos BK 4in 36p 1635g SL 131 Super Pan Bco Ajonjoli 680g SP WON 100 Pan Blanco Bimbo Rendidor 567g BIM 49973 Gansito ME 5p 250g MTA MLA 49860 Where I want to keep everything before the number but I also don't want the two uppercase letter word example: ME, BK. I'm using ^((\D*).*?) [^A-Z]{2,3} The expected result should be Tortillas Bolsa Tortillinas Bollos Super Pan Bco Ajonjoli Pan Blanco Bimbo Rendidor Gansito With the regex I'm using I'm still getting the two capital letter words Bollos BK and Gansito ME
favorite count: 0
type: Question
has title: regex two group matches everything until pattern
tagged with: split
has answer: http://stackoverflow.com/a/50223835

http://stackoverflow.com/comment/87268035
comment on: http://stackoverflow.com/q/50124816
score: 0
has text: If you want to handle duplicate keys by, e.g., keeping a set of all values, the idea is the same; just use `defaultdict(set)`, and `token_dictionary[token].add(in_both[token])`. Or, if you prefer, use a plain dict and do `token_dictionary.setdefault(token, set()).add(in_both[token])`. (The difference is that when you're looking things up later, `defaultdict` will give you an empty set for unknown keys, but a regular dict that you built with `setdefault` will give you `KeyError`s.)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87270134
comment on: http://stackoverflow.com/q/50125979
type: QuestionComment
has text: "An n-1 number" sounds to me like nonsense. I think you mean that n is the first command line argument to your program, and L is the second command line argument. Then your task is to produce all L-length combinations of integers between 0 and n-1 (inclusive). Is that right?
type: Comment
score: 0

http://stackoverflow.com/q/50162274
has body: In this example I am assigning a variable (hsname) the school that is selected when sending the form: I then use this value in python (with flask) and to get it I use the following (in a separated .py file): hsname = request.form.get("hsname") The previous is working fine. In a similar way, I want to assign to a variable the name of the button that the user is clicking (b1 or b2). The following is not working as there is not variable that records the button that the user clicks. b1 b2 How can I do it? I know I could use a radio button here but aesthetically I would rather use a normal button. I know I can use the onclick method but what should I write inside so that it stores a variable that is directly sent to flask?
score: 2
type: AnsweredQuestion
answer count: 3
tagged with: http://stackoverflow.com/tag/html
tagged with: forms
has title: Getting button name as input
has answer: http://stackoverflow.com/a/50162640
type: Question
has answer: http://stackoverflow.com/a/50162646
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50162701
tagged with: python
possible better answer: http://stackoverflow.com/a/50162640
tagged with: flask
has answer: http://stackoverflow.com/a/50162701
favorite count: 0

http://stackoverflow.com/q/50205782
has body: I am trying to execute the following code from https://pypi.org/project/pygmsh/ import pygmsh import numpy as np geom = pygmsh.built_in.Geometry() # Draw a cross. poly = geom.add_polygon([ [ 0.0, 0.5, 0.0], [-0.1, 0.1, 0.0], [-0.5, 0.0, 0.0], [-0.1, -0.1, 0.0], [ 0.0, -0.5, 0.0], [ 0.1, -0.1, 0.0], [ 0.5, 0.0, 0.0], [ 0.1, 0.1, 0.0] ], lcar=0.05 ) axis = [0, 0, 1] geom.extrude( poly, translation_axis=axis, rotation_axis=axis, point_on_axis=[0, 0, 0], angle=2.0 / 6.0 * np.pi ) points, cells, point_data, cell_data, field_data =pygmsh.generate_mesh(geom) I'm getting the following error: Traceback (most recent call last): File "C:/Users/200498/PycharmProjects/untitled/venv/test_builtin.py", line 30, in points, cells, point_data, cell_data, field_data =pygmsh.generate_mesh(geom) File "C:\ProgramData\Anaconda3\lib\site-packages\pygmsh\helpers.py", line 117, in generate_mesh gmsh_major_version = get_gmsh_major_version(gmsh_executable) File "C:\ProgramData\Anaconda3\lib\site-packages\pygmsh\helpers.py", line 81, in get_gmsh_major_version stderr=subprocess.STDOUT File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 336, in check_output **kwargs).stdout File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 403, in run with Popen(*popenargs, **kwargs) as process: File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 709, in init restore_signals, start_new_session) File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified: especificado How can I fix that?
tagged with: mesh
tagged with: finite-element-analysis
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: FileNotFoundError: [WinError 2]
has answer: http://stackoverflow.com/a/55735811

http://stackoverflow.com/q/50088010
upvote count: 1
has comment: http://stackoverflow.com/comment/87191886
downvote count: 1
favorite count: 0
type: Question
tagged with: control-flow
has answer: http://stackoverflow.com/a/50089139
type: UnansweredQuestion
tagged with: python
score: 0
has title: Return possible permutations for given array
has body: For a given list with string digits, I want to return the different string numbers that can be generated using all the elements in the list (so if there are 5 elements, the number should consist of 5 digits). The task is to return the possible permutations, the smallest permutation and the maximum permutation in a list. answer should be converted to integers If '0' is present in the input, it will produce string numbers with leading zeroes, this is not taken into account when they are converted to integers. This is my code now: from itertools import permutations def proc_arr(arr): lst = [] # define new list list_of_tuples = list(permutations(arr, len(arr))) # now they are tuples in a list # convert to integers in list separator = [map(str,x) for x in list_of_tuples] together = [int(''.join(s)) for s in separator] # append to new list and return the len of possible combinations, min and max value lst.append(len(together)) lst.append(min(together)) lst.append(max(together)) #print(lst) return lst proc_arr(['1','2','2','3','2','3']) However, I don't understand why I do don't get the right amount of permutations. input: proc_arr(['1', '2', '2', '3', '2', '3']) output: [60, 122233, 332221] and I get [720, 122233, 332221] another example of input &amp; output input: proc_arr(['1','2','3','0','5','1','1','3']) output: [3360, 1112335, 53321110]
answer count: 1

http://stackoverflow.com/q/50206539
has body: I have created a geoDataFrame using, and would like to create a Folium Map, plotting the population eat for each country. Do I have to create the Json file, or I can directly use the geoDataFrame file? import folium import fiona import geopandas as gpd world = fiona.open(gpd.datasets.get_path('naturalearth_lowres')) world = gpd.GeoDataFrame.from_features([feature for feature in world]) world = world[(world.pop_est &gt; 0) &amp; (world.name != "Antarctica")] I used folium.map and geojson function, but it failed to create correct JSON files. Thanks for the help!
downvote count: 0
has answer: http://stackoverflow.com/a/60954599
favorite count: 0
type: Question
tagged with: geopandas
tagged with: http://stackoverflow.com/tag/json
tagged with: geospatial
possible better answer: http://stackoverflow.com/a/60954599
tagged with: python
accepted answer: http://stackoverflow.com/a/50228588
has comment: http://stackoverflow.com/comment/87474259
score: 4
tagged with: folium
has answer: http://stackoverflow.com/a/50228588
upvote count: 4
has title: How to generate Folium map using GeoDataFrame?
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/112577915
type: AnswerComment
has text: However it's still broken if you assign anything to the slot using the dataclasses API.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/63658478

http://stackoverflow.com/comment/87346951
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50162494
has text: 1) `'0'*(6-len(d))+d` is a poor man's `d.zfill(6)`. 2) Why define `fill_stamps` with `*args` if you're gonna unpack it into `a, b = args` in the very next line? Just make two parameters instead. 3) What the heck is that `max_v = ...` monstrosity? You can simplify that to `max_v = max(int(''.join(re.findall('\d+', x))) for x in a)`. One would think you would get _better_ at writing one-liners, but it looks like you're just making them more and more convoluted as time goes on?

http://stackoverflow.com/q/50217926
accepted answer: http://stackoverflow.com/a/50218534
has answer: http://stackoverflow.com/a/50217987
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87455401
has comment: http://stackoverflow.com/comment/87452804
has comment: http://stackoverflow.com/comment/87453958
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50218534
has title: python unicode string in regexes
has body: I have an unicode encoded (with BOM) source file and some string that contains unicode symbols. I want to replace all characters that not belong to a defined character set with an underscore. # coding: utf-8 import os import sys import re t = " [°] \n € dsf $ ¬ 1 Ä 2 t3¥4Ú"; print re.sub(r'[^A-Za-z0-9 !#%&amp;()*+,-./:;&lt;=&gt;?[\]^_{|}~"\'\\]', '_', t, flags=re.UNICODE) output: ____ [__] _ ___ dsf _ __ 1 __ 2 t3__4__ expected: _ [_] _ _ dsf _ _ 1 _ 2 t3_4_ But each character is replaced by a number of its underscores that may be equal to the bytes in its unicode representation. Maybe an additional problem: In the actual problem the strings is read from a unicode file by another python module and I do not know if it handles the unicodeness correctly. So may be the string variable is marked as ascii but contains unicode sequences.
tagged with: unicode
type: Question
possible better answer: http://stackoverflow.com/a/50217987

http://stackoverflow.com/a/55070628
upvote count: 1
has body: using easy_install fancyimpute instead of pip install fancyimpute worked for me
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50217492
type: Answer

http://stackoverflow.com/a/50177925
has body: Since you are using Python 3, you can simply raise the APIException: try: do_stuff() except KeyError as exc: raise APIException() from exc Then in your exception handler, if exc is the APIException, you can access the original exception with exc.__context__. def exception_handler(exc): logger.log(exc.__context__) return Response({"message": "try again sam"}, status_code=400) The from exc is not actually needed to be able to access __context__, but it makes it clear that the KeyError was converted to APIException, rather than APIException being raised during the handling of KeyError. See the exception docs for more info.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50175875

http://stackoverflow.com/q/50126523
answer count: 3
has comment: http://stackoverflow.com/comment/87271105
tagged with: python
has comment: http://stackoverflow.com/comment/87271220
has comment: http://stackoverflow.com/comment/87271076
favorite count: 0
has comment: http://stackoverflow.com/comment/87271159
has comment: http://stackoverflow.com/comment/87274822
has title: Docker container/image running but there is no port number
has comment: http://stackoverflow.com/comment/87271120
upvote count: 8
score: 8
type: Question
possible better answer: http://stackoverflow.com/a/50126629
has answer: http://stackoverflow.com/a/50127627
downvote count: 0
has answer: http://stackoverflow.com/a/50126629
has comment: http://stackoverflow.com/comment/87271131
has comment: http://stackoverflow.com/comment/87271662
tagged with: dockerfile
tagged with: docker
has body: I am trying to get a django project that I have built to run on docker and create an image and container for my project so that I can push it to my dockerhub profile. Now I have everything set up and I've created the initial image of my project. However, when I run it I am not getting any port number attached to the container. I need this to test and see if the container is actually working. Here is what I have: Successfully built a047506ef54b Successfully tagged test_1:latest (MySplit) omars-mbp:mysplit omarjandali$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE test_1 latest a047506ef54b 14 seconds ago 810MB (MySplit) omars-mbp:mysplit omarjandali$ docker run --name testing_first -d -p 8000:80 test_1 01cc8173abfae1b11fc165be3d900ee0efd380dadd686c6b1cf4ea5363d269fb (MySplit) omars-mbp:mysplit omarjandali$ docker container ls -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 01cc8173abfa test_1 "python manage.py ru…" 13 seconds ago Exited (1) 11 seconds ago testing_first (MySplit) omars-mbp:mysplit omarjandali$ Successfully built a047506ef54b You can see there is no port number so I don't know how to access the container through my local machine on my web browser. dockerfile: FROM python:3 WORKDIR tab/ COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0"]
has comment: http://stackoverflow.com/comment/87271080
accepted answer: http://stackoverflow.com/a/50126665
has comment: http://stackoverflow.com/comment/87271698
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50126665

http://stackoverflow.com/q/50161140
has title: How to plot a time series array, with confidence intervals displayed, in python?
answer count: 2
downvote count: 0
tagged with: seaborn
score: 18
tagged with: python
tagged with: plot
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50177632
accepted answer: http://stackoverflow.com/a/50177632
tagged with: confidence-interval
tagged with: matplotlib
upvote count: 18
has answer: http://stackoverflow.com/a/51596880
possible better answer: http://stackoverflow.com/a/51596880
type: Question
has body: I have some time series which slowly increases, but over a short period of time they are very wavy. For example, the time series could look like: [10 + np.random.rand() for i in range(100)] + [12 + np.random.rand() for i in range(100)] + [14 + np.random.rand() for i in range(100)] I would like to plot the time series with a focus on the general trend, not on the small waves. Is there a way to plot the mean over a period of time surrounded with a stripe indicating the waves (the stripe should represent the confidence interval, where the data point could be in that moment)? A simple plot would look like this: The plot which I would like, with confidence intervals would look like this: Is there an elegant way to do it in Python?

http://stackoverflow.com/q/50208955
has title: Chatbot Sqlite3 error on Digital Ocean server
tagged with: sqlite
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have been building a Chatbot on which running perfectly on my local PC and also on Amazon web serve, but I want to implemented these chatbot on Digital ocean server since my website is running on Digital ocean's server. I am getting these Sqlite error [pythondemo@panel Chatbot]$ python3.6 chatbot.py Traceback (most recent call last): File "chatbot.py", line 8, in &lt;module&gt; from sqlite3 import dbapi2 as sqlite File "/home/pythondemo/.local/lib/python3.6/sqlite3/__init__.py", line 23, in &lt;module&gt; from sqlite3.dbapi2 import * File "/home/pythondemo/.local/lib/python3.6/sqlite3/dbapi2.py", line 50, in &lt;module&gt; version_info = tuple([int(x) for x in version.split(".")]) NameError: name 'version' is not defined These is the code which i am trying to run: import os import sys import datetime from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import random from sqlite3 import dbapi2 as sqlite bot = ChatBot('Bot') bot.set_trainer(ListTrainer) for files in os.listdir('C:/Users/OMI/Desktop/chatterbot-corpus-master/chatterbot_corpus/data/english/'): data = open('C:/Users/OMI/Desktop/chatterbot-corpus-master/chatterbot_corpus/data/english/' + files, 'r').readlines() bot.train(data) t=datetime.datetime.now().hour start_greeting = ('hello', 'hi', 'welcome', 'hey') end_greeting = ('bye', 'cya', 'goodbye') random_start_greeting = random.choice(start_greeting) random_end_greeting = random.choice(end_greeting) message = ' '.join(word for word in sys.argv) message = message.replace("chatbot.py ","") if message.strip() in start_greeting: reply = random_start_greeting print(reply.strip()) if (t &lt;= 12 and t &gt;= 5): print("Welcome! Good Morning.") elif (t &lt; 17 and t &gt; 12): print("Welcome! Good Afternoon.") elif (t &lt; 20 and t &gt;= 17): print("Welcome! Good Evening.") elif (t &lt; 23 and t &gt;= 20): print("Welcome! Hope you had a great day.") elif message.strip() in end_greeting: reply = random_end_greeting print(reply) else: reply = …
tagged with: digital-ocean
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/50131539
favorite count: 0
answer count: 3
score: 1
tagged with: findall
tagged with: regex
has answer: http://stackoverflow.com/a/50143472
tagged with: ignore-case
type: Question
has answer: http://stackoverflow.com/a/50131943
type: UnansweredQuestion
has title: how to find uppercase and smallCase using regex -re.findall in python
has body: I have a code that search for expressions and highlight the matching word . I need to find the match regardless if its upper or lower cases i need the search to ignore the case sensitive . code: RepX='&lt;u&gt;&lt;b style="color:#FF0000"&gt;'+x+'&lt;/b&gt;&lt;/u&gt;' for counter , myLine in enumerate(filename): #added self.textEdit_PDFpreview.clear() thematch=re.sub(x,RepX,TextString) thematchFilt=re.findall(x,TextString,re.M|re.IGNORECASE) example the searched word : charles the existing word is Charles the system will not find the searched word unless i wrote Charles.
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50131931

http://stackoverflow.com/comment/87413126
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50198094
type: QuestionComment
has text: Hi! I'd consider https://stats.stackexchange.com/ for this (not a coding question). In a nutshell, one-hot encoding would apply to your model _features_ (those that you base your prediction on), not on the predicted label. Also, `Gender_Male` = `Gender` = 1 - `Gender_Female`, so it'd be redundant to keep more than one of them, as they are all equivalent (carry the very same information)

http://stackoverflow.com/comment/87246005
type: QuestionComment
score: 0
has text: @PM2Ring yup that can eliminate few code sure !
comment on: http://stackoverflow.com/q/50114208
type: Comment

http://stackoverflow.com/comment/87412959
type: Comment
type: AnswerComment
has text: i get a error: file.write(words) TypeError: write() argument must be str, not list.. i changed file.writelines too - it runs but nothing gets written to the file.
comment on: http://stackoverflow.com/a/50198000
score: 0

http://stackoverflow.com/q/50140639
type: Question
has title: NameError in a Function (python 3.6)
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50140664
linked to: http://stackoverflow.com/q/8369219
has comment: http://stackoverflow.com/comment/87299546
tagged with: python
has comment: http://stackoverflow.com/comment/87299517
has comment: http://stackoverflow.com/comment/87299555
has body: I need to define a function that opens a text file, reads it, then loads the entire file into a string. This is what I have so far: def encrypt_file(filename): open_file = open(filename, 'r') file_content = filename.read() filename.close() encrypt_file(filename) user_input = input('enter file name: ') This is the error I get: encrypt_file(filename) NameError: name 'filename' is not defined What am I doing wrong here?
has answer: http://stackoverflow.com/a/50140658
score: 0
has answer: http://stackoverflow.com/a/50140708
answer count: 3
upvote count: 1
type: UnansweredQuestion
tagged with: function
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87395643
type: AnswerComment
has text: I think the output will be as a list of lists and not a single one
comment on: http://stackoverflow.com/a/50189391
score: 0
type: Comment

http://stackoverflow.com/comment/87212355
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50097648
has text: Can you edit your message to add more details on your problem?

http://stackoverflow.com/comment/87413898
comment on: http://stackoverflow.com/a/50198446
type: Comment
has text: @JörgWMittag: I think you're imagining a lot more flexibility than I am. I'm just imagining the virtual part can be at the end.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87340153
score: 0
has text: convert `{'a': 1, 'b': {'c': 1, 'd': 2, 'e': 3}, 'f': 4}` to `{'a': 1, 'c': 1, 'd': 2, 'e': 3, 'f': 4}` before loading into Pandas, you can try it first
type: QuestionComment
comment on: http://stackoverflow.com/q/50161070
type: Comment

http://stackoverflow.com/q/50218517
tagged with: python
accepted answer: http://stackoverflow.com/a/50219358
type: Question
has answer: http://stackoverflow.com/a/50219358
has title: How to replace a string containing [] in python
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/50219471
has body: Please excuse me if my question is too basic since I am new to python. I have a string as follows. Data=['A', 'B', 'C', 'X [7:0] Y', '[3:0] K' ] I want to change it to the following format. Data=['A', 'B', 'C', 'Y X [7:0]', 'K [3:0]'] Is there any way in python to do it.
has answer: http://stackoverflow.com/a/50219471
has comment: http://stackoverflow.com/comment/87454017
downvote count: 3
upvote count: 1
tagged with: string
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87453956
has comment: http://stackoverflow.com/comment/87454221
score: -2

http://stackoverflow.com/a/50152659
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87323947
has comment: http://stackoverflow.com/comment/87323865
answers question: http://stackoverflow.com/q/50152386
type: Answer
has body: In the documentation of CountVectorizer, it is provided that default token_pattern takes tokens of 2 or more alphanumeric characters. If you want to change this, pass your own regex In your case, add token_pattern = "^[a-zA-Z]{3,7}$" to the options of CountVectorizer Edit The regex that should be used is [a-zA-Z]{3,7}. See Example below - doc1 = ["Elon Musk is genius", "Are you mad", "Constitutional Ammendments in Indian Parliament",\ "Constitutional Ammendments in Indian Assembly", "House of Cards", "Indian House"] from sklearn.feature_extraction.text import CountVectorizer regex1 = '[a-zA-Z]{3,7}' vectorizer = CountVectorizer(analyzer='word', stop_words = 'english', token_pattern = regex1) vectorizer1 = vectorizer.fit_transform(doc1) vectorizer.vocabulary_ Results - {u'ammendm': 0, u'assembl': 1, u'cards': 2, u'constit': 3, u'elon': 4, u'ent': 5, u'ents': 6, u'genius': 7, u'house': 8, u'indian': 9, u'mad': 10, u'musk': 11, u'parliam': 12, u'utional': 13}
score: 2

http://stackoverflow.com/q/50172034
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/34345605
favorite count: 0
has body: Sorry fro my englihs. I use pyDryve for google drive api. And i want move files from one folder to another, use for this multythreading. pool = ThreadPoolExecutor(max_workers=2) # i have list of file for file in date_val: pool.submit(self.start_rename_move_process, file) def start_rename_move_process(self, file): try: print(file['title']) # Retrieve the existing parents to remove move_file = thread_drive.g_drive.auth.service.files().get(fileId=file['id'], fields='parents').execute() previous_parents = ",".join([parent["id"] for parent in move_file.get('parents')]) # Move the file to the new folder thread_drive.g_drive.auth.service.files().update(fileId=file['id'], addParents=MOVE_FOLDER_ID, removeParents=previous_parents, fields='id, parents').execute() except BaseException as e: print(e) i have error: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2217) My question: Why in one thread all works fine, but if i do 2 thread i have error [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2217)
has comment: http://stackoverflow.com/comment/87365231
type: Question
tagged with: google-drive-api
upvote count: 2
tagged with: pydrive
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/55282616
score: 2
has title: Google drive multythreading move files PYTHON
has comment: http://stackoverflow.com/comment/87365631

http://stackoverflow.com/q/50130706
type: AnsweredQuestion
has title: How do I read dependencies from requires.txt of a Python package
answer count: 3
has comment: http://stackoverflow.com/comment/87279767
has comment: http://stackoverflow.com/comment/87396532
has body: I need the dependencies because I want to add these to my RPM meta-data. To build I use: python setup.py bdist_rpm When I build the package cryptography-2.2.2 it creates a file /src/cryptography.egg-info/requires.txt It contains: idna&gt;=2.1 asn1crypto&gt;=0.21.0 six&gt;=1.4.1 [:platform_python_implementation != 'PyPy'] cffi&gt;=1.7 [:python_version &lt; '3'] enum34 ipaddress How can I read all dependencies, evaluating the expression between []? I'm using Python 2.7 (don't ask) I need the following output: idna&gt;=2.1 asn1crypto&gt;=0.21.0 six&gt;=1.4.1 cffi&gt;=1.7 enum34 ipaddress I want to omit other sections like [doc], [test] etcetera.
downvote count: 0
has comment: http://stackoverflow.com/comment/87279222
has answer: http://stackoverflow.com/a/50193639
favorite count: 0
accepted answer: http://stackoverflow.com/a/50193639
type: Question
has comment: http://stackoverflow.com/comment/87391066
has comment: http://stackoverflow.com/comment/87279935
has answer: http://stackoverflow.com/a/50194503
tagged with: python
has answer: http://stackoverflow.com/a/50190190
possible better answer: http://stackoverflow.com/a/50190190
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87279151

http://stackoverflow.com/a/50438590
has body: Add the following at the start- from gevent import monkey monkey.patch_all()
type: Answer
answers question: http://stackoverflow.com/q/50218830
score: 0

http://stackoverflow.com/a/50075662
score: 1
has comment: http://stackoverflow.com/comment/87167497
has body: You have to declare global variable within function: var = 0 def func(): global var var += 1 Edit Pay attention to comments: more generally within non-global scope
accepted answer of: http://stackoverflow.com/q/50075613
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50075613
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/comment/87461752
score: 0
type: Comment
type: QuestionComment
has text: Thanks Joel, I don't know how long it takes to run each of the operations, I just know that the whole script takes well more than an hour...
comment on: http://stackoverflow.com/q/50221779

http://stackoverflow.com/q/50209797
answer count: 0
has comment: http://stackoverflow.com/comment/87465135
tagged with: wxpython
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/87437059
has title: Using wx.html2, there are some strange points when using button tag
has body: import wx.html2 import re import os import cx_Oracle class Main(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, style=wx.DEFAULT_FRAME_STYLE) self.MainHtml2WebView = wx.html2.WebView.New(self, size=(0, 0), backend=wx.html2.WebViewBackendIE) self.MainFirstPage() def MainFirstPage(self): self.FirstPage = """ TITLE """ self.Department() self.MainHtml2WebView.SetPage(self.FirstPage.format(nextpage=re.sub(r'\s+', " ", self.DepartmentChoie)), "") def Department(self): self.DepartmentChoie = """ TITLE2 """ self.obgy() self.MainHtml2WebView.SetPage(self.DepartmentChoie.format(obgypage=re.sub(r'\s+', " ", self.obgychoice)), "") def obgy(self): self.obgychoice = """ TITLE2 """ if __name__ == '__main__': app = wx.App() fream = Main() fream.Show(True) app.MainLoop() My code is simple html like above using wx.html2. I'm using the input button tag to open the next page. Serious here? I found something strange. The first is that when you load the page, you can not load the page if you use a comma in all the html, and the second you have to make all the html code in one line with the regular expression. I do not know why the comma is allowed, but this only worked onclick = "location.href = ''" function. The first page can load self.DepartmentChoie html using onclick = "location.href = '{nextpage}'" Second page onclick = "location.href = '{obgypage}'" can not be called. This is because the onclick = "location.href = ''" function has a comma. There is no word. I've tried countless ways, but I could only load the first page with the onclick = "location.href = ''" function. Another way I would like to know how to load the self.FirstPage -> self.DepartmentChoie -> self.obgychoice page using the button. Other modules are also good. Other ways are also good. I really need help
score: 0

http://stackoverflow.com/q/50181359
score: 1
upvote count: 3
downvote count: 2
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: UPDATE: Added the pattern required as asked I have 2 lists and the expected output is different than the last time Numberset1 = [10,11,12] Numberset2 = [1,2,3,4,5] and i want to display output by manipulating the lists, the expected output is 10 1 1 10 1 2 10 1 3 10 1 4 10 1 5 10 2 2 10 2 3 10 2 4 10 2 5 10 2 1 10 3 3 10 3 4 10 3 5 10 3 1 10 3 2 10 4 4 10 4 5 10 4 1 10 4 2 10 4 3 10 5 5 10 5 1 10 5 2 10 5 3 10 5 4 11 2 2 11 2 3 11 2 4 11 2 5 11 2 1 11 3 3 11 3 4 11 3 5 11 3 1 11 3 2 11 4 4 11 4 5 11 4 1 11 4 2 11 4 3 11 5 5 11 5 1 11 5 2 11 5 3 11 5 4 11 5 1 11 1 1 11 1 2 11 1 3 11 1 4 11 1 5 12 3 3 12 3 4 12 3 5 12 3 1 12 3 2 12 4 4 12 4 5 12 4 1 12 4 2 12 4 3 12 4 4 12 4 5 12 5 5 12 5 1 12 5 2 12 5 3 12 1 1 12 1 2 12 1 3 12 1 4 12 1 5 12 2 2 12 2 3 12 2 4 12 2 5 12 2 1 The code i have tried is as follows, this was suggested in previous question and i tried using it for the next level of looping but i could not get the desired output Numberset1 = [10,11,12] Numberset2 = [1,2,3,4,5] from itertools import cycle, islice it = cycle(Numberset2) for i in Numberset1: for a in Numberset2: for j in islice(it, len(Numberset2)): print(i, a,j) skipped1 = next(it) skipped1 = next(it) The output i am getting is 10 1 1 10 1 2 10 1 3 10 1 4 10 1 5 10 2 2 10 2 3 10 2 4 10 2 5 10 2 1 10 3 3 10 3 4 10 3 5 10 3 1 10 3 2 10 4 4 10 4 5 10 4 1 10 4 2 10 4 3 10 5 5 10 5 1 10 5 2 10 5 3 10 5 4 11 1 2 11 1 3 11 1 4 11 1 5 11 1 1 11 2 3 11 2 4 11 2 5 11 2 1 11 2 2 11 3 4 11 3 5 11 3 1 11 3 2 11 3 3 11 4 5 11 4 1 11 4 2 11 4 3 11 4 4 11 5 1 11 5 2 11 5 3 11 5 4 11 5 5 12 1 3 12 1 4 12 1 5 12 1 1 12 1 2 12 2 4 12 2 5 12 2 1 12 2 2 12 2 3 12 3 5 12 3 1 12 3 2 12 3 3 12 3 4 12 4 1 12 4 2 12 4 3 12 4 4 12 4 5 12 5 2 12 5 3 12 5 4 12 5 5 12 5 1 Please note the change when the number 11 starts in the first column than the expected output How can we use cycle and islice for multiple levels Pattern: The first column should be in order of numbers in Numberset1, the second column for first number in Nu…
has answer: http://stackoverflow.com/a/50181564
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/87380662
has title: islice and cycle with multiple levels
has comment: http://stackoverflow.com/comment/87389459
tagged with: python
accepted answer: http://stackoverflow.com/a/50181564
type: AnsweredQuestion

http://stackoverflow.com/comment/87268531
has text: @juanpa.arrivillaga That is only true in CPython 2. In Python 3 and in both versions of PyPy, `range` only allocates a small constant-space object.
comment on: http://stackoverflow.com/q/50124621
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87217060
type: Comment
type: QuestionComment
score: 0
has text: @pissall I added it
comment on: http://stackoverflow.com/q/50099922

http://stackoverflow.com/a/50203813
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50203743
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50203743
has body: Here is one way using groupby and checking the type of the items. from itertools import groupby lst = ['a',3,4,'b',6,'c',5,1] nlst = [''.join(i) if c == str else int(''.join(map(str,i))) for c, i in groupby(lst, key=type)] print(nlst) Returns: ['a', 34, 'b', 6, 'c', 51] Short explanation: The groupby will create these items (the lists are actually returned as generators, but that's not important for now) [(str, ['a']), (int, [3, 4]), (str, ['b']), (int, [6]), (str, ['c']), (int, [5, 1])] We then either perform a str.join() if str or we map int to str, perform a str.join() and back to int again for int. Note: that lst = ['a','b',3,4,'b',6,'c',5,1] # added a 'b' would return: ['ab', 34, 'b', 6, 'c', 51] If that is not desirable you could rewrite the function and this might even make it easier to understand like this: lst = ['a','b',3,4,'b',6,'c',5,1] nlst = [] for c, i in groupby(lst, key=type): if c == int: nlst.append(int(''.join(map(str,i)))) elif c == str: nlst.extend(i) # If type is not int or str, we skip! else: pass print(nlst) Returning: ['a', 'b', 34, 'b', 6, 'c', 51] Further reading: If you have trouble understanding this solution I'd say you could read more about: Python str.join() joining strings Python map converting from one type to another Python types str, int, list.. List comprehensions compact for loops [i for i in list] Itertools groupby (key function here)
type: Answer

http://stackoverflow.com/q/50115873
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87248861
downvote count: 8
has comment: http://stackoverflow.com/comment/87248851
has body: Can someone show me an example of a system where when you answer a question right it gives you one point and at the end of the quiz it gives me a total of how much I got right? This is the code I have so far: def QuestionSet1(): print("Challenge level 1 has being selected.") print("Can you translate these words into french?") a=input('Q1. Hello! :') if 'Bonjour' in a: score = score + 1 print('Correct!') elif 'bonjour'in a: score = score + 1 print('Correct!') else: print('Wrong! '+'Its Bonjour') print('You have finished and scored', score, 'out of 10')
tagged with: python
has title: How do I create a scoring system in Python?
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87250004
has comment: http://stackoverflow.com/comment/87248859
has comment: http://stackoverflow.com/comment/87249082
has comment: http://stackoverflow.com/comment/87249058
has answer: http://stackoverflow.com/a/50116123
accepted answer: http://stackoverflow.com/a/50116123
answer count: 1
has comment: http://stackoverflow.com/comment/87249115
score: -6
favorite count: 0
type: Question

http://stackoverflow.com/comment/87550759
type: QuestionComment
comment on: http://stackoverflow.com/q/50206574
has text: Were you able to get it working. I tried your code with my own dataset( i had to change the loss function though) and it works fine.
score: 0
type: Comment

http://stackoverflow.com/comment/87293428
has text: If you're coming from another language it can be hard to get used to Python's data model. You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. For a shorter and slightly different take on this topic see [Other languages have "variables", Python has "names"](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50136493
type: Comment

http://stackoverflow.com/comment/87361298
comment on: http://stackoverflow.com/q/50171771
score: 0
type: Comment
type: QuestionComment
has text: is it always in the format `test-patternX.zip`?

http://stackoverflow.com/comment/87311418
type: Comment
comment on: http://stackoverflow.com/a/50145421
type: AnswerComment
has text: @user2125827 as far as i can see second command should be as follows: `rpm -qpR yum-3.2.29-60.0.1.el6.noarch` since you've allready have properly formated package name
score: 0

http://stackoverflow.com/comment/87460792
has text: What is `tqdm`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50221512
type: Comment

http://stackoverflow.com/comment/87490543
type: AnswerComment
has text: I'm curious: see my edit, do your timings show the same improvement?
type: Comment
comment on: http://stackoverflow.com/a/50210508
score: 0

http://stackoverflow.com/q/50162521
type: Question
upvote count: 4
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50189551
tagged with: python
has comment: http://stackoverflow.com/comment/87395345
linked to: http://stackoverflow.com/q/36969991
linked to: http://stackoverflow.com/q/46829761
has comment: http://stackoverflow.com/comment/87395916
has comment: http://stackoverflow.com/comment/87395801
score: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50189551
has title: Folium heatmap not displaying in Jupiter notebook in Internet Explorer
has comment: http://stackoverflow.com/comment/87389957
tagged with: folium
has comment: http://stackoverflow.com/comment/87386982
tagged with: jupyter-notebook
has body: I am trying to plot a heatmap similar to the one from https://alysivji.github.io/getting-started-with-folium.html. The output should look something like this picture but for the area of the North Sea. However when I try to plot the colorfull dots over the map, Jupyter notebooks output is blank. This my code: import folium from folium import plugins import pandas as pd import matplotlib.pyplot as plt import seaborn as sns m = folium.Map([52.5, 2], zoom_start=5.5) m Gives me this, which is what I want: Now I want to add 10 dots to the map, my data and code is the following: divvyStations =df = pd.DataFrame({'Xpos': Xpos1[0], 'Ypos': Ypos1[0],'Density': Density}) print(divvyStations) OUT: Density Xpos Ypos 0 1 -3.758242 50.099575 1 1 -3.780331 50.110645 2 1 -3.740984 50.113747 3 1 -3.802421 50.121719 4 1 -3.763073 50.124821 5 1 -3.723726 50.127922 6 1 -3.824510 50.132793 7 1 -3.785162 50.135895 8 1 -3.745815 50.138992 9 1 -3.706468 50.142094 And then I try to plot the points: for index, row in divvyStations.iterrows(): folium.CircleMarker([row['Ypos'],row['Xpos']], radius=15, #popup=row['Density'], fill_color="#3db7e4", # divvy color ).add_to(m) m Which gives me this nice screen: Why is there no map? I already checked questions: Folium map not displaying, Python Folium Map Not Displaying Thanks in advance!
favorite count: 0

http://stackoverflow.com/comment/87452663
type: QuestionComment
comment on: http://stackoverflow.com/q/50217834
has text: import numpy as np, of course.... then ... np.random.randint(0, 10, size=(5, 10))
type: Comment
score: 0

http://stackoverflow.com/q/50152311
has comment: http://stackoverflow.com/comment/87323006
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87323119
has comment: http://stackoverflow.com/comment/87383439
tagged with: numpy
answer count: 0
downvote count: 0
tagged with: machine-learning
score: 1
upvote count: 1
favorite count: 0
has body: I am following this tutorial about data augmentation for this dataset about facial key-points detection (identified by (x,y) target coordinates). I want to flip images horizontally, so also some targets need to be swapped in this way: left_eye_center_x ---------&gt;&gt; right_eye_center_x left_eye_center_y ---------&gt;&gt; right_eye_center_y left_eye_inner_corner_x ---------&gt;&gt; right_eye_inner_corner_x left_eye_inner_corner_y ---------&gt;&gt; right_eye_inner_corner_y ... The image flipping and the coordinates reordering seem fine when printing, but not when plotting. code: # target indices to swap flip_indices = [(0, 2), (1, 3),(4, 8), (5, 9), (6, 10), (7, 11), (12, 16), (13, 17), (14, 18), (15, 19),(22, 24), (23, 25)] # permutation that represents the target coordinates reordering permutation = [2, 3, 0, 1, 8, 9, 10, 11, 4, 5, 6, 7 ,16, 17, 18, 19, 12, 13, 14, 15, 20, 21, 24, 25, 22, 23, 26, 27, 28, 29] X_train_flipped = np.flip(X_train, axis=2) # flips images horizontally Y_train_flipped = np.copy(Y_train)[:,permutation] # flips targets according to permutation print (Y_train[1,permutation] == Y_train_flipped[1]) # permutation seems successful fig = plt.figure(figsize=(10, 10)) # original image, original targets ax = fig.add_subplot(1, 3, 1, xticks=[], yticks=[]) plot_sample(X_train[1], Y_train[1], ax) # flipped image, original targets ax = fig.add_subplot(1, 3, 2, xticks=[], yticks=[]) plot_sample(X_train_flipped[1], Y_train[1], ax) # flipped image, flipped targets ax = fig.add_subplot(1, 3, 3, xticks=[], yticks=[]) plot_sample(X_train_flipped[1], Y_train_flipped[1], ax) Output: [ True True ... True True] The third picture should have the targets correctly positioned. The function plot_sample() is defined in the tutorial like this: def plot_sample(x, y, axis): img = x.reshape(96, 96) axis.imshow(img, cmap='gray') axis.scatter(y[0::2] * 48 + 48, y[1::2] * 48 + 48, marker='x', s=10)
type: Question
has title: Python: flipping images horizontally and reordering targets
tagged with: matplotlib

http://stackoverflow.com/a/50105050
answers question: http://stackoverflow.com/q/50104938
has body: Remember in python, strings are immutable. So you can't change them. (I am guessing by 'I can't keep the change to a variable', you were expecting the global test_variable to change as well. You are essentially assigning names. This talk is a good place to start to understand some core python concepts: https://www.youtube.com/watch?v=_AEJHKGk9ns
has comment: http://stackoverflow.com/comment/87227462
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87227536

http://stackoverflow.com/comment/87450249
type: QuestionComment
comment on: http://stackoverflow.com/q/50216573
score: 0
has text: @Arount its True , first he need to take the time to Write his question and try to create a script for try to solve his problem , if he can't he will ask his question here but by writing it
type: Comment

http://stackoverflow.com/a/50158533
has body: I found the problem, this is because my module name is not the folder name, thats why it doesnt work.
type: Answer
answers question: http://stackoverflow.com/q/50137368
score: 0

http://stackoverflow.com/comment/87201899
score: 0
has text: How about you convert the code like this? `i = i.strip('\n')` or `r.append(str(i.strip('\n')`
comment on: http://stackoverflow.com/q/50092618
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87480435
has text: but if one of my values have `"` in it? it will change it.
score: 0
comment on: http://stackoverflow.com/a/50231436
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50106530
type: AnsweredQuestion
has title: Pyserial runtime error with cx_Freeze
tagged with: python
accepted answer: http://stackoverflow.com/a/50113376
has answer: http://stackoverflow.com/a/50113376
score: 0
has body: I am trying to make an executable using cx_Freeze on a Raspberry Pi 3. The code all compiles without issue, but i get a runtime error: import serial File "/home/pi/.virtualenvs/cv/local/lib/python2.7/site-packages/serial/__init__.py, line 12 in &lt;module&gt; standard_library.install_aliases() File "/home/pi/.virtualenvs/cv/local/lib/python2.7/site-packages/future/standard_library/__init__.py", line 487, in install_aliases from future.moves.test import support File "/usr/lib/python2.7/test/test_support.py", line 642, in &lt;module&gt; character.encode(sys.getfilesystemencoding())\ TypeError: encode() argument 1 must be string, not None The code works fine when run from the source. The error only shows when running the compiled version. Anyone got any ideas? Thanks in advance.
tagged with: pyserial
answer count: 1
tagged with: raspberry-pi3
type: Question
tagged with: cx-freeze

http://stackoverflow.com/comment/87212387
comment on: http://stackoverflow.com/q/50097704
has text: @Aran-Fey I reopened the question because answers in that duplicate haven't answered OP's questions completely. Please let me now if you could find a proper duplicate, I couldn't find any.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50156428
has body: From the documentation on tracemalloc: The tracemalloc module is a debug tool to trace memory blocks allocated by Python. In other words, memory not allocated by the python interpreter is not seen by tracemalloc. This would include anything not done by PyMalloc at the C-API level, including all standard libc malloc calls by native code used via extensions, or extension code using malloc directly. Whether that is the case here is impossible to tell for certain without code to reproduce. You can try running the native code part outside of python through, for example, valgrind, to detect memory leaks in the native code. If there is cython code doing malloc, that could be switched to PyMalloc to have it traced.
has comment: http://stackoverflow.com/comment/87349334
type: Answer
answers question: http://stackoverflow.com/q/50148554
has comment: http://stackoverflow.com/comment/87350659
accepted answer of: http://stackoverflow.com/q/50148554
type: AcceptedAnswer
score: 14
upvote count: 14
downvote count: 0

http://stackoverflow.com/q/50178161
has body: I recently tried to automate a windows application using a pywinauto since it enables automation with using python. I just started it and encountered a problem which hinders me to continue. I get this error whenever I try to find the relevant element: Traceback (most recent call last): File "test.py", line 14, in &lt;module&gt; app.findwindows.find_elements().click_input() File "C:\Users\Bar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pywinauto\application.py", line 173, in __call__ format(self.criteria[-1]['best_match'])) AttributeError: WindowSpecification class has no 'find_elements' method This is my code: from pywinauto.application import Application import pywinauto import time app = Application(backend='uia').start(r"C:\Program Files\Intellech\Analyzer\Suite.exe") time.sleep(3) app.findwindows.find_windows(auto_id='btQuick').click_input() Can you help me to find out the reason of this error?
upvote count: 2
tagged with: automation
answer count: 1
downvote count: 0
tagged with: pywinauto
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50178311
tagged with: element
tagged with: python
tagged with: ui-automation
accepted answer: http://stackoverflow.com/a/50178311
favorite count: 0
type: Question
has title: Find Elements issue on the pywinauto

http://stackoverflow.com/comment/87194063
type: AnswerComment
type: Comment
has text: Great thanks Stuart! The first method worked, so now just cleaning up the data a bit for usage. Just so I'm understanding the data types: `weather_list = pd.read_html(url, header = 0) weather_list = weather_list[4]` - the pd.read_html returns an indexed list of the available lists at the URL, and weather_list[4] gets the index 4 table and puts it to a pandas dataframe?
score: 0
comment on: http://stackoverflow.com/a/50082493

http://stackoverflow.com/comment/87285507
score: 1
type: Comment
has text: Hard to say without a [mcve]. But the error message says that `writer.writerow` could not write a bullet (• or `'\u2022'`) because it uses a cp949 encoding. Is it a plain file or a console? Solutions will be different in Windows...
type: QuestionComment
comment on: http://stackoverflow.com/q/50132242

http://stackoverflow.com/comment/94737933
score: 0
type: Comment
has text: If it worked for you then mark it as right answer buddy, I'll be thankful @AustinCopeland
type: AnswerComment
comment on: http://stackoverflow.com/a/52174245

http://stackoverflow.com/comment/87388533
score: 0
comment on: http://stackoverflow.com/a/50185297
has text: @TerryA it's honestly a very cool trick, and I'm surprised you're getting heat for it. Adding strings, and then making it a statement that can be evaluated. Top notch! I think the stigma comes from people worried that it's hard to work with corrupt user input, or hard to debug, or that there must be a way around it (to change your code, but you can't change this code. It is a clear and defined goal.) Anyway, good answer! +1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87260503
type: AnswerComment
comment on: http://stackoverflow.com/a/50117390
has text: The way you are writing your program, you are basically using it as a module. You will have to import any modules (including built-in modules) if you want to use them in your program. So, if you wanted to use this program in another program, you would need to add `import nintetynine` at the top of the file. Python is not 'compiled', so you just need to import your module each time you use your program.
score: 0
type: Comment

http://stackoverflow.com/a/50076937
has comment: http://stackoverflow.com/comment/87221903
answers question: http://stackoverflow.com/q/50076791
score: 2
has comment: http://stackoverflow.com/comment/87170477
has body: Something like this in Python 3 may work: import statistics with open('10year-gdp.txt') as f: items = [] for line in f.readlines(): line = line.strip() if line.isdigit(): items.append(float(line)) else: print('{0}: {1}'.format(line, statistics.mean(items))) items = []
downvote count: 0
has comment: http://stackoverflow.com/comment/87170505
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/87171424
has comment: http://stackoverflow.com/comment/87254028
has comment: http://stackoverflow.com/comment/87171385
has comment: http://stackoverflow.com/comment/87171497
has comment: http://stackoverflow.com/comment/87170489
has comment: http://stackoverflow.com/comment/87170516

http://stackoverflow.com/q/50217893
linked to: http://stackoverflow.com/q/3787908
has title: Python: efficient way to find indexes of differences in strings
downvote count: 0
answer count: 1
has body: I have a large amount of DNA sequences formatted in a text file like this: // BLOCK_1 AATTCAT AGTTCAT AATTCGT // BLOCK_2 AGAGGA AGAGGA AGAGGA Each line in a block corresponds to one sample. The real dataset has 120 characters per sequence line, 250 samples/lines per 'block' and a total of roughly 10000 such blocks. I now need to remove those positions in each block that are the same in all samples. The desired output looks like this: // BLOCK_1 AA GA AG // BLOCK_2 Getting rid of those blocks where all sequences are the same was quickly done by creating a list of hashes for each line and following this on SO: Python: determine if all items of a list are the same item. However, I'm now struggling to find a way to efficiently find the positions in those strings where at least one of them differs.
favorite count: 0
type: Question
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50218049
accepted answer: http://stackoverflow.com/a/50218049
tagged with: python
upvote count: 2

http://stackoverflow.com/a/50140758
has comment: http://stackoverflow.com/comment/87300013
has comment: http://stackoverflow.com/comment/87306708
downvote count: 0
has body: In order to do this you would either need to use a datatype that's size can be mutated as I did in my other answer or you could also figure out how many images you have before defining the array. (As suggested by @P.Camilleri) Here's an example of that: # Count nuber of images idx_count = 0 for item in dataset: idx_count += len(item['data']) # Create an empty numpy array that's Nx3x3 images = np.empty((count, 3, 3)) # Populate numpy array with images idx = 0 for item in dataset: for row in item["data"]: images[idx] = row["sub_data"] idx += 1 print(images) This has the advantage that you only allocate the space once, as apposed to using a python list where it's first added to the list then copied to a numpy array. However, this is at the cost of having to iterate over the data twice. (Note: Two separate answers so they can be rated separately as I'm not sure which solution is better.)
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50139993
score: 2

http://stackoverflow.com/a/50165027
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50164915
has comment: http://stackoverflow.com/comment/87348308
has comment: http://stackoverflow.com/comment/87348289
has comment: http://stackoverflow.com/comment/87348067
answers question: http://stackoverflow.com/q/50164915
downvote count: 0
has comment: http://stackoverflow.com/comment/87348489
type: Answer
upvote count: 1
has body: I believe the issue could be that "soup.select" always starts from the beginning of your XML, and thus in your second soup.select you are finding all instances of tr. In this following snipped I've replaced the second soup.select with x.select - that will then only do the select from the "x" node rather than from the beginning. for x in soup.select('table'): for tr in x.select('tr'):
has comment: http://stackoverflow.com/comment/87348395
has comment: http://stackoverflow.com/comment/87348335
score: 1

http://stackoverflow.com/q/50183126
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87384376
type: UnansweredQuestion
score: 1
tagged with: dataframe
tagged with: python
tagged with: lambda
has answer: http://stackoverflow.com/a/50183282
tagged with: pandas
has body: I have a relatively big dataframe that looks like this: (I have uploaded the csv file here - ufile.io/526t4) value 0 [[1,92,"D"],[93,93,"C"],[94,113,"S"],[114,120,"C"],[121,181,"S"],[182,187,"C"],[188,292,"S"],[319,319,"S"],[320,353,"C"],[354,393,"D"]] 1 [[18,23,"D"],[24,27,"C"],[28,186,"S"],[187,198,"C"],[199,246,"S"]] 2 [[18,23,"D"],[24,27,"C"],[28,186,"S"],[187,198,"C"],[199,246,"S"]] 3 20,79,"D" ... 12352 [[25,36,"S"],[37,89,"C"],[90,115,"S"]] 12353 [[1,16,"D"],[17,407,"C"],[408,416,"D"]] 12354 [[16,21,"D"],[22,108,"C"],[109,123,"D"],[124,164,"C"],[165,421,"S"]] 12355 rows × 1 columns And I want to create a new column with the sum of all "D" occurrences using the first row as an example: x = [[1,92,"D"],[93,93,"C"],[94,113,"S"],[114,120,"C"][121,181,"S"],182,187,"C"],[188,292,"S"],[319,319,"S"],[320,353,"C"],[354,393,"D"]] new_colum_D = (sum([y[1]-y[0] for y in x if y[2]=="D"])) # applied for all rows the new_colum_D = first row value would be 130 I have tried the following: df['Column_D']=df["value"].apply(lambda x:sum([y[1]-y[0] for y in x if y[2]=="D"])) but I get the following message: IndexError: string index out of range IndexError Traceback (most recent call last) &lt;ipython-input-7-f7f23d42d4e5&gt; in &lt;module&gt;() ----&gt; 1 df['sum']=df["value"].apply(lambda x:sum([y[1]-y[0] for y in x if y[2]=="D"])) ~\AppData\Local\conda\conda\envs\my_root\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds) 2549 else: 2550 values = self.asobject -&gt; 2551 mapped = lib.map_infer(values, f, convert=convert_dtype) 2552 2553 if len(mapped) and isinstance(mapped[0], Series): pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer() &lt;ipython-input-7-f7f23d42d4e5&gt; in &lt;lambda&gt;(x) ----&gt; 1 df['sum']=df["value"].apply(lambda x:sum([y[1]-y[0] for y in x if y[2]=="D"])) &lt;ipython-input-7-f7f23d42d4e5&gt; in &lt;listcomp&gt;(.0) ----&gt; 1 df['sum']=df["value"].apply(lambda x:sum([y[1]-y[0] for y in x if y[2]=="D…
has title: Create a new column with the sum of occurrences from a existing column containing nested lists
has comment: http://stackoverflow.com/comment/87383803
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/50216345
has comment: http://stackoverflow.com/comment/87449680
has comment: http://stackoverflow.com/comment/87449485
has comment: http://stackoverflow.com/comment/87449762
has title: Extracting data from large text file using Python
tagged with: python
score: -1
tagged with: full-text-search
has comment: http://stackoverflow.com/comment/87449900
has body: For a project, I need to extract data from different sources. One of these sources is a large (.txt) file (~750 Mb). I've tried the common parsing techniques, but the file is too large and it takes too much time. A solution I found here, is to build a full-text index by using the Whoosh library. I'm new to python, and new to full-text search. Do you have any idea of how to open the file in a reasonable time and how to design a schema? My file has the following structure FIELD NO % something that I want to extract % FIELD NOT-INTERESTING % something not interesting % FIELD TP % something I want to extract %
tagged with: whoosh
tagged with: extract
has comment: http://stackoverflow.com/comment/87449730
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: bigdata
has answer: http://stackoverflow.com/a/50216468
has comment: http://stackoverflow.com/comment/87449840
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87449805

http://stackoverflow.com/a/50203888
score: 4
upvote count: 4
has body: Instead of anchoring the regex at the beginning of the string, utilize boundary checking: import re s = 'Everyday HOLDS the poSSibility Of A Miracle' new_s = ' '.join(re.findall(r'\b[A-Z][a-z]+|\b[A-Z]\b', s)) Output: 'Everyday Of A Miracle'
answers question: http://stackoverflow.com/q/50203857
downvote count: 0
type: Answer

http://stackoverflow.com/q/50222032
has comment: http://stackoverflow.com/comment/87461632
has title: in search giving false when expecting true
tagged with: python
has body: I am trying to run the below Python and expect the last item to prove true. I am searching for beer to see if it exists in the menu, but I am getting false. What am I missing here? # [] print 3 tests, with description text, testing the menu variable for 'pizza', 'soup' and 'dessert' menu = "salad, pasta, sandwich, pizza, drinks, dessert, soda, beer" print("pizza is in the menu =", 'pizza' in menu) print("soup is in the menu =", 'soup' in menu) print("dessert is in the menu = ", 'dessert' in menu) print("beer is in the menue = ", 'beer' in menu) #now asking for a user to search an item menu_ask = input("Type an item to see if it is in the menu: ") print(menu_ask,"is in the menu = ", 'menu_ask'.lower() in menu.lower()) My output is as follows pizza is in the menu = True soup is in the menu = False dessert is in the menu = True beer is in the menue = True Type an item to see if it is in the menu: beer beer is in the menu = False Why is the last item not True? And how do I get it to be True?
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87461533
has comment: http://stackoverflow.com/comment/87461526
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50222133
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87461639
has comment: http://stackoverflow.com/comment/87462164
has answer: http://stackoverflow.com/a/50222133
score: -2

http://stackoverflow.com/comment/87315091
type: Comment
score: 0
type: AnswerComment
has text: Thanks! This is really simple! Just wondering, though. Why doesn't it work when I write it out the way I did?
comment on: http://stackoverflow.com/a/50148409

http://stackoverflow.com/a/50159122
has body: The dense part of DNNLinearCombinedClassifier is exactly the same as a regular DNNClassifier.
answers question: http://stackoverflow.com/q/50158974
has comment: http://stackoverflow.com/comment/87453205
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50158974
score: 0

http://stackoverflow.com/q/50174393
score: 1
has answer: http://stackoverflow.com/a/50174540
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I am in a ListView that is named PortfolioView. I am trying to retrieve all the items that a user has entered into the model, which is named "Prospect". To do this, I try the following: def get_context_data(self, **kwargs): Prospect.objects.all().filter(owner__username=self.request.user) context = MakeGraphs(Prospect.psuccess, Prospect.hc_type) return super(PortfolioView, self).get_context_data(**context) However, when I run the function MakeGraphs I get an error saying that the operation cannot be ran on a Deferred Attribute. I don't understand why it is getting returned as a Deferred Attribute. Suggestions? Edit: For clarity, here is an approximation of what I am doing in the MakeGraphs function: def MakeGraphs(psuccess, hctype): #This isn't what I am really doing, but this should give you a flavor for it... newoutput1 = [] newoutput1 = [] for i in range(len(psuccess)): newoutput1.append(psuccess[i]**2 + hctype[i]) newoutput2.append(psuccess[i]***3 + hctype[i]**2) aaa = sum(newoutput1) bbb = sum(newoutput2) return {'aaa':aaa, 'bbb':bbb} So, It takes in a list for both variables, and returns a single value for each of the returned variables. Edit 2: When I use the query: def get_context_data(self, *args, **kwargs): a = Prospect.objects.filter(owner=self.request.user).first() I get the values for the first record where owner=user, as expected. However, I would like to get all the values of psuccess and hc_type... if I try this: def get_context_data(self, *args, **kwargs): a = Prospect.objects.filter(owner=self.request.user) I get a 'QuerySet' object has no attribute 'psuccess' error... Edit 3: For attributes that have a single value returned, or where you have multiple attributes returned, and you can use them one at a time instead of all at once, the answer marked as the solution will work. However, if you need all of the values for each attribute in the form of a list you should use this for the query: yourvar = list(MyModel.objects.filter(owner=self.request.user)…
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50174540
has title: Django, Deferred Attribute Error

http://stackoverflow.com/comment/87278634
comment on: http://stackoverflow.com/a/50130121
score: 0
has text: You're welcome. :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87324158
score: 2
has text: What have you tried so far?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50153281

http://stackoverflow.com/comment/87253101
has text: Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50117875

http://stackoverflow.com/comment/87173021
has text: From your code it looks like you're trying to keep **two** different sums, `sumNSal` and `sumNSalR`, not one as you state. Also, while `row[6]` is the seventh column, `row[4]` is not the fourth.
comment on: http://stackoverflow.com/q/50078269
score: 1
type: Comment
type: QuestionComment

windows-server-2008-r2
tag name: windows-server-2008-r2
type: Tag
tags question: http://stackoverflow.com/q/50153341

http://stackoverflow.com/q/50214360
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: python
tagged with: macos-sierra
has answer: http://stackoverflow.com/a/50214529
score: 2
favorite count: 0
type: Question
has body: I am trying to uninstall a package installed on MacOS Sierra with pip. pip uninstall -y altgraph I've got an error: Error[('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/altgraph/ObjectGraph.py', '/private/tmp/pip-uninstall-0Bm0Kc/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/altgraph/ObjectGraph.py', "[Errno 1] Operation not permitted: ... I tried run it with sudo but got the same error. How can I fix it and uninstall the package ?
has title: "Operation not permitted" error while trying pip uninstall on Mac
upvote count: 2

http://stackoverflow.com/q/50210555
score: 0
tagged with: pandas
answer count: 1
tagged with: dataframe
linked to: http://stackoverflow.com/q/27965295
type: Question
accepted answer: http://stackoverflow.com/a/50210709
has answer: http://stackoverflow.com/a/50210709
linked to: http://stackoverflow.com/q/26921943
tagged with: set-intersection
tagged with: python
has title: Python Pandas - drop rows based on columns of 2 dataframes
has body: I have 2 dataframes with a column called frames. The dataframes are about data extracted from 2 videos recorded at the same time of two participants. The data lacks some frames (different per video) due to failed tracking. I want to take an intersection based on the frame integer value df['frame']. A similar question is posted here: Pandas - intersection of two data frames based on column entries , but the accepted answer is a join, not an intersection. Example data import pandas as pd df1 = pd.DataFrame(data={'frame': [1, 2, 3]}) df2 = pd.DataFrame(data={'frame': [2, 3, 4]}) Desired output Removed rows not in union of df1['frame'] and df2['frame'] >>> print(df1) frame 1 2 2 3 >>> print(df2) frame 0 2 1 3 (I can reset the index after I'm done processing with df1.reset_index(drop=True)) Tried I thought of first getting the intersection of the frames column of both dataframes with: df1_idx = df1['frame'] df2_idx = df2['frame'] intersection_idx = df1_idx.intersection(df2_idx) Error: File "/*python_path*/site-packages/pandas/core/generic.py", line 3081, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'intersection' After getting the frame indexes that are in both dataframes, I was thinking of doing something like (mentioned in: dropping rows from dataframe based on a "not in" condition): df1 = df1.drop(df[~df['frame'].isin(intersection_idx)]) System Python 3.6.5 with pandas 0.22.0 installed with Anaconda.
type: AnsweredQuestion

http://stackoverflow.com/comment/87477922
comment on: http://stackoverflow.com/q/50229873
score: 0
type: Comment
has text: @MazelTov nothing after `Attaching to mein-dach-web_web_1`. Seems like it just hangs. `docker exec <container id> ps` outputs: PID TTY TIME CMD 1 ? 00:00:00 python 51 ? 00:00:02 python 99 ? 00:00:00 ps
type: QuestionComment

http://stackoverflow.com/comment/87403922
score: 0
comment on: http://stackoverflow.com/q/50192981
type: Comment
has text: @juanpa.arrivillaga that's really interesting. When I timed it, reduce seemed to be faster every time. I guess I should probably do it at a larger scale before making assumptions
type: QuestionComment

http://stackoverflow.com/a/54701823
type: Answer
accepted answer of: http://stackoverflow.com/q/50126814
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50126814
has body: This is due to Debian 9 using OpenSSL 1.1.0., However, OpenSSL 1.1.0 support in the SSL module was only added to Python 2.7.13, 3.5.3 and 3.6+ Thus, it makes the python under those versions cannot be correctly linked to ssl library. Issues https://github.com/pyenv/pyenv/issues/945 So you have to manually add those libraries when you are compiling them. My suggestion Since your system is already compiled with the default python, unintentionally compiled different version of python into global executable may cause many hidden problems, especially some commands used behind on system-default python. So why not you use pyenv, to control those version of pythons? pyenv is like a python-version control programs, it uses shims, through a process called rehashing, pyenv maintains shims in that directory to match every Python command across every installed version of python, pip, and so on. For more documents, please reading: https://github.com/pyenv/pyenv. To install pyenv, please following the provided reference. Solution After many hours struggling, I finally found a solution to perfectly solve those version of pythons confliction problems, copy and paste the following script to a new file, and make it executable, then you can compile and install those pythons. While if you want to install them in other way, say, without using pyenv, please change the last second line commands to fit your needs. #!/bin/bash -e # Note: it is a script to solve Ubuntu 18.04 LTS # different version of pythons compiling # header confliction problems # # The idea is got from @JustAnotherArivist # From URL: https://github.com/pyenv/pyenv/issues/945 # # The script used in here is with slightly modifications # to fit many different SSL header versions # First under your home directory make OpenSSL library # and extract useful package mkdir ~/libssl1.0-dev cd ~/libssl1.0-dev apt-get download libssl1.0-dev ar x libssl1.0-dev* data.tar.xz tar -xf data.tar.xz --strip-components=2 # Second, specifically…

http://stackoverflow.com/q/50121569
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87264161
answer count: 2
accepted answer: http://stackoverflow.com/a/50123032
tagged with: homebrew
has title: How to use Homebrew to upgrade to a specific Python version?
downvote count: 0
has answer: http://stackoverflow.com/a/50123032
tagged with: macos
has answer: http://stackoverflow.com/a/50121657
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/3987683
has body: I've been using Homebrew to install various packages on my Mac. Currently I have Python 2.7.13 installed via Homebrew but I'd like to upgrade to Python 3.5.x, not 3.6 which is brew's current default. At first, I just tried upgrading to Python 3: brew install python3 Brew said "python 2.7.13 is already installed. To upgrade to 3.6.5, run brew upgrade python" which isn't the version I want. I then tried to search to see what versions of Python brew has available: brew search python Now Homebrew tells me, "If you meant "python" specifically: It was migrated from caskroom/cask to homebrew/core." I then looked at homebrew-core on Github but it doesn't appear to provide any instructions on how to do what I want to do. Does anyone know how to now display a list of Python versions that one can install using Homebrew and what command to use to install a specific version?
possible better answer: http://stackoverflow.com/a/50121657
score: 6
tagged with: python
upvote count: 6

http://stackoverflow.com/comment/87377681
comment on: http://stackoverflow.com/q/50180242
type: Comment
has text: Possible duplicate of [Sorting list based on values from another list?](https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list)
score: 0
type: QuestionComment

http://stackoverflow.com/a/50121657
answers question: http://stackoverflow.com/q/50121569
has comment: http://stackoverflow.com/comment/87261855
has comment: http://stackoverflow.com/comment/87263887
type: Answer
downvote count: 4
has body: To see the version of python use python --version, and for upgrade use sudo apt-get upgrade python. I used this, and it's worked
upvote count: 0
score: -4

http://stackoverflow.com/comment/87321500
comment on: http://stackoverflow.com/a/50150359
type: AnswerComment
has text: @YQ.Wang, you can see in "SID_LIST" there is two different "SID_DESC", one is for your jdbc/odbc/dsn connection and another for external program connect, even I have not used. But anyway that is not going to disturb you. if you like my answer then please accept the answer. Thanks :)
score: 0
type: Comment

http://stackoverflow.com/comment/87437263
type: Comment
comment on: http://stackoverflow.com/q/50210174
type: QuestionComment
score: 0
has text: This can be dangerous if people run you code on their machines where this change has not been made.

http://stackoverflow.com/a/50177026
answers question: http://stackoverflow.com/q/50176916
type: Answer
accepted answer of: http://stackoverflow.com/q/50176916
has comment: http://stackoverflow.com/comment/87371231
upvote count: 4
has comment: http://stackoverflow.com/comment/87371214
type: AcceptedAnswer
downvote count: 0
score: 4
has body: You can use regular expressions here: matches = [','.join(re.findall(r'(alid=\d+|vhpn=\d+)', i)) for i in myList] Output: ['alid=65535,vhpn=65535', 'alid=65535,vhpn=65535', 'alid=65535,vhpn=65535'] Regex explanation: ( // matching group 1 alid=\d+ // matches alid= followed by 1 or more digits | // OR vhpn=\d+ // matches vhpn= followed by 1 or more digits ) // end of matching group 1 A solution not using regex: matches = [] for s in myList: options = s.split(',') found = [] for option in options: if option[:option.find('=')] in {'alid', 'vhpn'}: found.append(option) matches.append(','.join(found)) print(matches) Output: ['alid=65535,vhpn=65535', 'alid=65535,vhpn=65535', 'alid=65535,vhpn=65535']

http://stackoverflow.com/q/50078277
type: AnsweredQuestion
upvote count: 0
tagged with: matplotlib
downvote count: 2
has body: I wonder if there is a possibility to set the color of a histgram, which is filled in a for loop, at the end of this process like: import numpy as np import matplotlib.pylot as plt x=np.array([[1,1,3,4],[1,4,5,6],[1,4,4,6]]) plt.figure() for i in range(3): plt.hist(x[i]) plt.show() Maybe some comand before the plt.show() ?
favorite count: 0
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50079986
possible better answer: http://stackoverflow.com/a/50080345
type: Question
has answer: http://stackoverflow.com/a/50079986
has answer: http://stackoverflow.com/a/50080345
answer count: 2
tagged with: python
score: -2
has title: Python: Matplotlib - Set colorspace at the end of loop plotting

http://stackoverflow.com/comment/87212833
score: 0
comment on: http://stackoverflow.com/q/50098066
has text: Can you try to be more specific in what you exactly don't understand on X array structure?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50121464
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: pytest
has body: I have a lot of tests that take a long time to run. Luckily, the time these tests take is evenly distributed among tests for several subsystems of my project. I'm using IPython's pytest magic commands. I'd like to be able to just say things like pytest potato_peeler --donttesti18n --runstresstests or pytest garlic_squeezer --donttestsmell --logperfdata but I can't add the garlic_squeezer and potato_peeler options the same way I do logperfdata et al because parser.addoption gets upset if the option name doesn't start with a --. I know this seems like a tiny inconvenience, but I have a ton of people running these tests several times a day and I'd like the way they're invoked to make as much sense as possible, by emulating how you issue commands on a command line (command, thing you want to run the command on, then --flags.) Is there a way have non-dashed options? (that doesn't involve writing a full-blown pytest plugin that overrides the option parsing?) I was hoping to use the pytest_commandline_parse hook but you can't use that hook in a conftest.py, you have to write a full-blown plugin.
score: 1
has title: Add a pytest option that doesn't have dashes?
tagged with: python
has answer: http://stackoverflow.com/a/50121602
type: UnansweredQuestion

http://stackoverflow.com/comment/87423930
score: 0
comment on: http://stackoverflow.com/a/50186227
has text: I'll check through some of this tomorrow when I'm there. Thanks for all of your help!
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50134528
tagged with: python
tagged with: inspect
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87287228
accepted answer: http://stackoverflow.com/a/50134712
has comment: http://stackoverflow.com/comment/87287710
tagged with: introspection
has title: Python function introspection: what members of a class passed as argument are mentioned inside it?
upvote count: 3
has answer: http://stackoverflow.com/a/50134712
has body: Say that I have a function like the following: def eggs(a,b,c): if c.foo: return a + b.bar else: return c.spam I'd like to have a higher order function capable of introspecting the function passed and retrieve what members of an argument are mentioned inside the code via the dot syntax, with the following behavior: &gt;&gt;&gt; member_inspector(eggs, 'c') ('foo','spam') &gt;&gt;&gt; member_inspector(eggs, 'b') ('bar') &gt;&gt;&gt; member_inspector(eggs, 'a') () Can this be done? How?
has comment: http://stackoverflow.com/comment/87287454
answer count: 1
tagged with: higher-order-functions
downvote count: 0
has comment: http://stackoverflow.com/comment/87290398
has comment: http://stackoverflow.com/comment/87287407
favorite count: 0
has comment: http://stackoverflow.com/comment/87287145
type: Question
has comment: http://stackoverflow.com/comment/87286964
tagged with: function

http://stackoverflow.com/a/50207206
answers question: http://stackoverflow.com/q/50206730
has comment: http://stackoverflow.com/comment/103769553
score: 8
accepted answer of: http://stackoverflow.com/q/50206730
has comment: http://stackoverflow.com/comment/103769682
has comment: http://stackoverflow.com/comment/111464003
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/98106238
has comment: http://stackoverflow.com/comment/111417517
has comment: http://stackoverflow.com/comment/98107893
has comment: http://stackoverflow.com/comment/138708830
has comment: http://stackoverflow.com/comment/105194220
has comment: http://stackoverflow.com/comment/103768478
upvote count: 8
type: Answer
has body: Dask doesn't currently support this, but you can compute the length on the fly: len(df) == 0 len(df.index) == 0 # Likely to be faster

http://stackoverflow.com/comment/87299078
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50140021
type: Comment
has text: sorry about that! the second issuance date in my actual df is 3/31/2019

http://stackoverflow.com/comment/87214208
has text: `scatter` seems to add new points to the existing plot. You probably need to clear or recreate it each time after saving it.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50098388

animation
tags question: http://stackoverflow.com/q/50159373
tags question: http://stackoverflow.com/q/50079363
type: Tag
tag name: animation

http://stackoverflow.com/comment/87331273
comment on: http://stackoverflow.com/a/50156139
type: Comment
has text: @Iwanttoknow That is another question, if my answer helps you do not forget to mark it as correct, if you do not know how to do it, review the [tour], that is the best way to thank. Create another question and I will be happy to follow you helping.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50203860
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50203926
favorite count: 0
type: Question
has body: I am using a Python dictionary to read DNA bases into codons however want the program to recognise if nonsense is inputted into this. Currently all that happens is there is a key error when using something like "codon += cod[F[x]]" Is there a way to search the string of bases (AGCTATATCAT) (for example) for strings not found in the dictionary? For example if other characters that aren't ACGT were in it how would I detect this? Thanks
has comment: http://stackoverflow.com/comment/87424725
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50203959
accepted answer: http://stackoverflow.com/a/50203926
possible better answer: http://stackoverflow.com/a/50203959
has title: How to recognise that the dictionary has no known value for the input provided and not just cause error (KeyError) Python 3.6
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/87182761
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50083493
has text: What exactly are you asking here? If you have a single-value list `lst=[5]`, and you index it with `lst[4]`, that's going to be an `IndexError`, because there aren't that many values.

http://stackoverflow.com/comment/87324913
comment on: http://stackoverflow.com/a/50149522
has text: I have updated the question when i am doing that i am getting "NONE".when i am printing the file_name,it is printing the file_name. am i missing anything there?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50205877
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87429167
answer count: 0
tagged with: widget
score: 1
has body: I have a sizeable piece of text contained in a Python Tkinter Text widget. I need to colour the background of each letter in the text, individually, depending on another variable. I do this by adding tags with tag_add. The problem is that the widget responsiveness slows down significantly when all the tags are added. Without the tags everything runs fluently. What can I do? This is a minimal example of the code: from Tkinter import * import tkMessageBox import Tkinter as ttk import tkFileDialog import csv import ttk from ttk import * root = Tk() root.minsize(width=1280, height=600) root.maxsize(width=1280, height=600) w, h = root.winfo_screenwidth(), root.winfo_screenheight() x = (w/2) - 640 y = (h/2) - 300 root.geometry('%dx%d+%d+%d' % (1200, 640, x, y-80)) #Horizontal (x) Scroll bar xscrollbar = Scrollbar(orient=HORIZONTAL) xscrollbar.pack(side=BOTTOM, fill=X) #Vertical (y) Scroll Bar yscrollbar = Scrollbar() yscrollbar.pack(side=RIGHT, fill=Y) MSA_text1 = Text(height=30, width=150, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) MSA_text1.pack() MSA_text1.configure(wrap="none", font="TkFixedFont") MSA_text1.place(x=105,y=0) #Configure the scrollbars xscrollbar.config(command=MSA_text1.xview) yscrollbar.config(command=MSA_text1.yview) for number2 in range(1,20): MSA_text1.insert(END, "SPAELHSFTHCGQTALTLQGATTTEASNILRSCHACRGGNPQHQMPRGHIRRGLLPNHIWQGDITHFKYKNTLYRLHVWVDTFSGAISATQKRKETSSEAISSLLQAIAHLGKPSYINTDNGPAYISQDFLNMCTSLAIRHTTHVPYNPTSSGLVERSNGILKTLLYKYFTDKPDLPMDNALSIALWTINHLNVLTNCHKTRWQLHHSPRLQPIPETRSLSNKQTHWYYFKLPGLNSRQWKGPQEALQEAAGAALIPVSASSAQWIPWRLLKRAACPRPVGGPADPKEKDLQHHG" +"\n") for number in range(0,295): MSA_text1.tag_add(number, str(number2)+"."+str(number), str(number2)+"."+str(number+1)) MSA_text1.tag_config(number, background="red", foreground="black") MSA_text1.configure(state="disabled") mainloop()
tagged with: user-interface
has title: Python Tkinter Text widget extremely slow when adding multiple tags by tag_add()
has comment: http://stackoverflow.com/comment/87428952
tagged with: textbox
favorite count: 0
type: Question
tagged with: tkinter
type: UnansweredQuestion

http://stackoverflow.com/q/50091372
accepted answer: http://stackoverflow.com/a/50092195
favorite count: 0
type: Question
tagged with: python
tagged with: pygame
tagged with: draw
type: AnsweredQuestion
score: 2
upvote count: 2
has body: I've got this code: import pygame, sys from pygame.locals import * pygame.init() WHITE = (255,255,255) class setup(): def set_resolution(x, y): global surf global screen surf = pygame.Surface((x,y)) screen = pygame.display.set_mode((x,y)) pygame.display.set_caption("Lewis' Game") pygame.draw.rect(screen, WHITE,(200,150,150,50)) def menu(): pass setup.set_resolution(1024,768) setup.menu() while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() For some reason, the pygame.draw.rect(screen, WHITE,(200,150,150,50)) at the end of the setup function doesn't actually appear unless I show the desktop and them tab back in. I'm not sure why this is happening as it's never happened before. I should mention that I'm still learning pygame, and this code is just for practice. Many thanks in advance.
has comment: http://stackoverflow.com/comment/87201138
linked to: http://stackoverflow.com/q/29314987
has title: Pygame Rectangle Doesn't Appear Unless I Tab-out and Back In
answer count: 1
has comment: http://stackoverflow.com/comment/87199064
has answer: http://stackoverflow.com/a/50092195
downvote count: 0

http://stackoverflow.com/q/50161880
has comment: http://stackoverflow.com/comment/87345170
has answer: http://stackoverflow.com/a/50161980
has body: I m writing a bot that create a message, and for each reaction from users it should modify the message and add the user to the embed message, is there any way to do it?
favorite count: 0
type: Question
tagged with: discord.py
possible better answer: http://stackoverflow.com/a/50171795
score: -2
has answer: http://stackoverflow.com/a/50171795
tagged with: python
accepted answer: http://stackoverflow.com/a/50161980
has title: Python Discordpy Is there a way to modify a message embed?
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 2

http://stackoverflow.com/a/77953011
answers question: http://stackoverflow.com/q/50077562
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50077562
type: AcceptedAnswer
type: Answer
has body: From the Decision Trees documentation: scikit-learn uses an optimized version of the CART algorithm The CART algorithm is described by Breiman et al. in the book with the same title, that is Classification and Regression Trees. In CART, the authors describe how they experimented with numerous criteria for stopping early while growing the decision tree. Eventually they discovered what is now known as Minimal-Cost-Complexity Pruning (MCCP): rather than using ad-hoc stopping criteria, grow a large tree and then prune it back, using cross-validation to compare various subtrees considered by the algorithm. MCCP is described in detail in chapter 3 of CART, and a brief summary is available in the Decision Tree documentation. Now that we know that the sklearn.DecisionTreeClassifier implements the CART algorithm, we know many things. For one, with the default settings, unless the max_depth parameter is provided, the tree is expanded completely. More precisely, as mentioned in the documentation for DecisionTreeClassifier.max_depth: max_depth: int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. This answers your first question of why node #6 was split: node #6 was not pure, as defined by the Gini Index function, and therefore it was split into node #8, a pure node, and node #7. Following this logic, your next question seems quite reasonable: But the odd thing is, the 1 versicolor still in there still gets misclassified, since both the nodes end up having the class of virginica anyway. Why is it doing this? That is, why was Node #7 not expanded? A key detail is that your tree has depth 3 only because you passed max_depth=3 to the constructor. In other words, you explicitly constrained DecisionTreeClassifier from expanding node #7. If you remove the constraint, you get the following tree from your code: At first glance, I thought that this would solve the prob…
score: 2
downvote count: 0

http://stackoverflow.com/a/50140438
type: Answer
answers question: http://stackoverflow.com/q/50140131
has body: This can also be solved using indexing and fillna. df.loc[(df['A'] &gt; df['B']) &amp;(df['B'] &gt; df['C']), 'New_Col'] = 1 df.loc[(df['A'] &lt; df['B']) &amp;(df['B'] &lt; df['C']), 'New_Col'] = 2 df['New_Col'] = df['New_Col'].fillna(3) The first chunk of code is read like so: locate where A > B and B > C, if both of these conditions are true, set the column 'New_Col' equal to 1. The second chunk can be interpreted in the same way. If both the first and second chunk do no return a 1 or 2, then they will appear as null. Use the fillna() function to fill those nulls with a 3. This will produce the following dataframe:
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50175944
has body: Have you tried using cmd line as an administrator to run below, pip install virtualenv virtualenv comes with a copy of pip which gets copied into every new environment you create so virtualenv is all that is requried. You can try installing virtualenv separately as a standalone package. Which is actually easier for windows users. See https://virtualenv.pypa.io/en/stable/ for instructions.
answers question: http://stackoverflow.com/q/50175733
type: Answer
score: 0

http://stackoverflow.com/comment/127372539
type: AnswerComment
comment on: http://stackoverflow.com/a/50953014
has text: @AlessandroDentella Could you elaborate on this, please? Where is this config set? I too have lost a lot of time on this :/
type: Comment
score: 0

http://stackoverflow.com/q/50134013
tagged with: python
type: UnansweredQuestion
answer count: 1
score: 2
has body: I am trying to figure out where are my anaconda kernels in my mac, since applications report different things. If I run: jupyter kernelspec list I get: Available kernels: python2 /Users/user/anaconda/share/jupyter/kernels/python2 However, when I open Jupiter notebook, I can see and use: [I 07:47:21.394 NotebookApp] [nb_conda_kernels] enabled, 4 kernels found Here are some screenshots: How can I remove all of those envs and leave only conda root? Thanks
has comment: http://stackoverflow.com/comment/87339328
has title: locating and removing hidden kernels in jupyter notebook
has answer: http://stackoverflow.com/a/55120924
tagged with: kernel
tagged with: jupyter-notebook
favorite count: 0
has comment: http://stackoverflow.com/comment/96983333
type: Question
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87271217
type: QuestionComment
has text: Actually, I only get the temporary hang when I run your code from PyCharm.
score: 1
comment on: http://stackoverflow.com/q/50120769
type: Comment

restore
tag name: restore
tags question: http://stackoverflow.com/q/50136375
type: Tag

http://stackoverflow.com/comment/115423778
type: Comment
comment on: http://stackoverflow.com/a/65287165
score: 0
type: AnswerComment
has text: This should be a comment, not an answer.

http://stackoverflow.com/q/50225919
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50225968
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50225968
tagged with: python
type: AnsweredQuestion
score: 0
has title: How to handle irregular format from CSV using Pandas
tagged with: pandas
has body: I have been trying different ways to handle date time in Pandas from CSV. I have 3 columns in csv file: kickoffDate kickoffTime time The first two columns are well formatted. But the format of third column "time" is mixed up.. some represents as time, some represent as date time. For example: 12:00:00 AM 1/1/1900 9:04:00 PM How do I make same format using pandas? Second thing is that I want to add all three columns to get a event time. For example: kickoffDate =['8/6/2017','8/6/2017','8/6/2017'] kickoffTime =['15:00:00','15:00:00','15:00:00'] time =['51:48:00','86:05:00','10:04']` time in this case is mm:ss:00 format. i want to combine those three column to create a new column so called eventdatetime: eventdatetime = [06-08-2017 15:51:48, 06-08-2017 16:26:05,06-08-2017 15:10:04]` How can i do this? I am able to combine the first two by using following formula: DateTime1 = data['kickoffDate']+' '+ data ['kickoffTime'] The original csv file can be downloaded from below link: https://drive.google.com/open?id=1JL65x7nq2m6zk4qnaRUDKL894aEdXW_B
linked to: http://stackoverflow.com/q/50225050

http://stackoverflow.com/comment/87279621
has text: But when I do this,error occured. The code is there: https://paste.ubuntu.com/p/kkTWdn87hv/
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50130315

http://stackoverflow.com/comment/87449017
score: 0
comment on: http://stackoverflow.com/a/50216016
has text: I know that its much easier and faster, our teacher asked us to come up with an alternative way of doing it and this is the closest I got so far.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87367102
comment on: http://stackoverflow.com/q/50175035
score: 0
has text: Also note a missing `%`: `%Y-%m-%dT%H:%M:%Sz` should be `%Y-%m-%dT%H:%M:%S%z`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87422150
type: AnswerComment
comment on: http://stackoverflow.com/a/50110116
has text: Np, welcome to Stack Overflow! It can be a prickly place sometimes but it is a great source for answering questions. As long as you put thought into your questions (which you have), I'm sure you'll do fine.
score: 0
type: Comment

http://stackoverflow.com/q/50174656
tagged with: deep-learning
has answer: http://stackoverflow.com/a/50175812
score: 0
has answer: http://stackoverflow.com/a/50179328
tagged with: tensorflow
linked to: http://stackoverflow.com/q/33712178
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/46291253
has comment: http://stackoverflow.com/comment/87374674
type: UnansweredQuestion
has body: Contextualization I am building a neural network for multi label classification: Identifying labels in an image (what clothes a person is wearing, its color,etc..). I wanted to use pure tensorflow (instead of APIs like kears) in order to have more flexibility over my metrics. P.S: The data used for this tensorflow model was tested with a Keras built model and didn't produce the issues that I am going to expose here. Data My input data are (X,Y): X is of shape (1814,204,204,3) and Y is of shape (1814,39). So basically X are the set of images and Y are the labels associated to each images which will be used for the supervised learning process. There are 39 labels in total, so for every image of size (1,204,204,3) we associate a vector of shape (1,39) : the 39 values can be 0 or 1. 1,if the corresponding label is identified in that image , O else. Many labels can be identified at the same time, which means that we are not using one hot encoding and it is not a multi-class classification situation! PS:I already normalized my data in order to be fitted in [0,1] What I have done 1. First thing I have done is buidling the abstract version of my classifier(which is a CNN): here is the structure of my CNN: # Convolutional Layer 1 # Dropout layer 1 # Convolutional Layer 2 # Pooling Layer 2 # Dense layer 3 # Dropout layer 3 # Dense layer 4 for a given dataset of size (?,204,204,3): here is the flow of the data through the different layers: conv1 OUTPUT shape: (?, 204, 204, 32) drop1 OUTPUT shape: (?, 204, 204, 32) conv2 OUTPUT shape: (?, 204, 204, 32) pool2 OUTPUT shape: (?, 102, 102, 32) dense3 OUTPUT shape: (?, 512) drop3 OUTPUT shape: (?, 512) dense4 OUTPUT shape: (?, 39) Here is the code for building the structure of the CNN def create_model(X,Y): # Convolutional Layer #1 conv1 = tf.layers.conv2d( inputs=X, filters=32, kernel_size=[3, 3], padding="same", activation=tf.nn.relu) print('conv1 OUTPUT shape: ',conv1.shape) # Dropout layer #1 dropout1 = tf.layers.dropout( inputs…
has comment: http://stackoverflow.com/comment/87368942
tagged with: machine-learning
linked to: http://stackoverflow.com/q/37312421
tagged with: python
has title: Multi label classification with TENSORFLOW---NaN in COST and Weights
linked to: http://stackoverflow.com/q/34240703
tagged with: conv-neural-network

http://stackoverflow.com/comment/87456458
comment on: http://stackoverflow.com/q/50219683
type: Comment
type: QuestionComment
score: 0
has text: @TomWojcik I tried to put it after like "else: return false" but it did not work

http://stackoverflow.com/comment/87452768
score: 1
type: Comment
has text: @HarvIpan Yes, I think so, you have to set up gridspec to meet your exact needs. This was a shortcut using subplot. Look at matploblib [`Customizing Location of Subplot Using GridSpec`](https://matplotlib.org/users/gridspec.html)
type: AnswerComment
comment on: http://stackoverflow.com/a/50217671

http://stackoverflow.com/q/50123315
type: Question
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87265139
tagged with: python
has answer: http://stackoverflow.com/a/50135930
upvote count: 6
score: 2
has comment: http://stackoverflow.com/comment/87265748
downvote count: 4
has comment: http://stackoverflow.com/comment/87265137
answer count: 1
has body: So you know how when you use Notepad (on Windows), for example, and you want to open an old file? You click file, then open, then a file dialog opens ups and you can select the file you want, and the program will display its contents. Basically, I want to make a button in Python that can do that exact thing. Here's my function for the button- def UploadAction(): #What to do when the Upload button is pressed from tkinter import filedialog When I click on the button assigned to this action, nothing happens, no errors, no crash, just nothing.
has comment: http://stackoverflow.com/comment/87265485
favorite count: 0
has title: How do I create an Import File Button with Tkinter?

http://stackoverflow.com/q/50092490
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87236136
has body: I have searched a lot but there is no explanation on how SciPy calculates the p-value for the correlation coefficient and why it is unreliable (started by SciPy on the function page) for data sets smaller than 500.
tagged with: p-value
has title: How SciPy calculates the p-value in pearsonr() function?
has answer: http://stackoverflow.com/a/50109254
tagged with: python
accepted answer: http://stackoverflow.com/a/50109254
score: 4
upvote count: 4
type: Question
downvote count: 0
answer count: 1
tagged with: scipy

http://stackoverflow.com/comment/87179725
type: Comment
type: QuestionComment
has text: Don't use `lambda`. Have the button call a command. Put any logic you want in that command.
comment on: http://stackoverflow.com/q/50078791
score: 0

http://stackoverflow.com/a/50175969
score: 0
answers question: http://stackoverflow.com/q/50172447
type: Answer
has body: This should work on UNIX: import os, pwd uid = os.stat("/path/to/file").st_uid print pwd.getpwuid(uid).pw_name

http://stackoverflow.com/a/50223715
downvote count: 0
type: Answer
has body: It really seems to be the case pointed by @jwodder: X-Subject-Token is not part of the JSON, but one of the HTTP headers. When you make an HTTP request, the response comes with a body and a series of headers. The headers are important for the server and the browser properly communicate; the body is the info we usually want. Since headers are generally (but not always) relevant only for the server and browser, curl by default gives us only the body. Here I'll use some random JSON as an example: $ curl -X GET https://pastebin.com/raw/S5bxekgg {"foo": "bar", "a": 2} The body is so relevant you even believe the information you need is in it - but it is not! It is in the headers. In this case, we need curl to give us the headers as well. It is easy, we only need to give it the -i option: $ curl -i -X GET https://pastebin.com/raw/S5bxekgg HTTP/1.1 200 OK Date: Mon, 07 May 2018 23:12:36 GMT Content-Type: text/plain; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Set-Cookie: __cfduid=d570bd74e5f34b1ef0d5fe4658ba5e0461525734756; expires=Tue, 07-May-19 23:12:36 GMT; path=/; domain=.pastebin.com; HttpOnly Cache-Control: public, max-age=1801 Access-Control-Allow-Origin: * Vary: Accept-Encoding X-XSS-Protection: 1; mode=block CF-Cache-Status: HIT Expires: Mon, 07 May 2018 23:42:37 GMT Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" Server: cloudflare CF-RAY: 41775f564ca44bbd-GRU {"foo": "bar", "a": 2} Now we have much more information! Alas, my example does not contain the X-Subject-Token header you want, so I'll use another header: X-XSS-Protection. It is not in the JSON, though; how do we get it? Well, it is even easier: use shell! Personally, I'd grep for the header I want: $ curl --silent -i -X GET https://pastebin.com/raw/S5bxekgg | grep X-XSS-Protection X-XSS-Protection: 1; mode=block Once I have it, I'd use cut to take out the value: $ curl --silent -i -X GET https://pastebin.com/raw/S5bxekgg | grep X-XSS…
answers question: http://stackoverflow.com/q/50222720
score: 2
upvote count: 2

http://stackoverflow.com/a/50220797
answers question: http://stackoverflow.com/q/50220770
has body: I think need GroupBy.transform for return Series with same size as original DataFrame: df['from_max'] = df.groupby(['Group'])['Value'].transform(lambda x: x.max() - x) Or: df['from_max'] = df.groupby(['Group'])['Value'].transform(max) - df['Value'] Alternative is Series.map by aggregate max: df['from_max'] = df['Group'].map(df.groupby(['Group'])['Value'].max()) - df['Value'] print (df) Group Value from_max 0 A 4 6 1 A 6 4 2 A 10 0 3 B 5 6 4 B 8 3 5 B 11 0
downvote count: 0
type: Answer
score: 7
upvote count: 7

http://stackoverflow.com/comment/87349413
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50165568
has text: I don't understand what you're asking. I don't see a function named `course_select` that you're calling and passing things into anywhere.
type: QuestionComment

http://stackoverflow.com/comment/87255164
has text: We might better be able to assist you if you post a sample text file that you're trying to parse and the intended result.
comment on: http://stackoverflow.com/q/50118909
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87244193
comment on: http://stackoverflow.com/q/50113511
type: QuestionComment
score: 0
has text: You can use sudo su tomcat8 to switch the user and execute the script under the tomcat8 user context
type: Comment

http://stackoverflow.com/comment/87227980
type: Comment
score: 3
type: QuestionComment
has text: an approach is: send a request to a specific view via ajax.
comment on: http://stackoverflow.com/q/50105188

http://stackoverflow.com/q/50148819
tagged with: authentication
type: Question
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/50148898
tagged with: python
has answer: http://stackoverflow.com/a/50148898
tagged with: label
tagged with: logic
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87323473
score: 0
has body: I am a beginner to python and trying to make a simple log in system for a school program together with it's GUI. I did a good job since I am a beginner in python (and coding in general) and I am trying to learn to work with tkinter. I have figured everything out except when I tried to make the program change the label text when the user "access = True". Here is the code snippet: from tkinter import * from time import sleep usernamelist = ["bob123","tim321","me","duda"] passwordlist = ["banana","apple","password123","duda2000"] def checklogin(): global access global mode username = entuser.get() password = entpass.get() userfound = False if username == "admin": if password == "allowmein": access = True mode = "admin" else: lberror.config(text="Incorrect password, try again") entpass.delete(0, END) else: for i in range(len(usernamelist)): if username == usernamelist[i]: userfound = True if password == passwordlist[i]: access = True else: lberror.config(text="Incorrect password, try again") entpass.delete(0, END) if userfound == False and username != "admin": lberror.config(text="Username not found, try again") entuser.delete(0, END) entpass.delete(0, END) if access == True: lberror.config(text= "Access Granted") sleep(1) mainlog.destroy() return access return mode access = False mode = "student" mainlog = Tk() mainlog.title("Maths Quiz Login") lbuser = Label(mainlog, text= "Username: ") lbpass = Label(mainlog, text= "Password: ") entuser = Entry(mainlog,) entpass = Entry(mainlog, show="*") logbtn = Button(mainlog, text= "Login", command= checklogin) lberror = Label(mainlog, text= "") lbuser.grid(row=0, column=0) lbpass.grid(row=1, column=0) entuser.grid(row=0, column=1) entpass.grid(row=1, column=1) logbtn.grid(row=2, column=1) lberror.grid(row=3,column = 0, columnspan = 2) mainlog.geometry("250x150+100+100") mainlog.mainloop() When I am trying to run the code the lberror label appears to obey all commands when ordered to show incorrect password or username not found …
answer count: 1
has title: Don't know why label is not updating using tkinter

http://stackoverflow.com/a/50122514
has comment: http://stackoverflow.com/comment/87263005
has comment: http://stackoverflow.com/comment/87267054
has body: You can use matplotlib.barh directly: barh(range(4), ax.sum(axis=1), color=['blue' if one else 'green' for one in ax.one == ax.max(axis=1)]); barh(range(4), ax.max(axis=1), color=['green' if one else 'blue' for one in ax.one == ax.max(axis=1)]); Of course you can make the ticks and labels nicer with yticks and so. Edit For the general case, here's an outline on how to expand things scalably. First, start with d = s.unstack(level=1).as_matrix() Now iterate until np.nansum(d) == 0. For each iteration, the lengths of the bars should be np.nansum(d, axis=1) To get the colors to plot, you can use np.nanargmin(d, axis=1) (you need to map these numbers to colors). At the end of each iteration, use d[:, np.nanargmin(d, axis=1)] = np.nan This will plot shorter bars on top of longer bars, giving the illusion of stacked bars.
score: 1
has comment: http://stackoverflow.com/comment/87263103
has comment: http://stackoverflow.com/comment/87266016
answers question: http://stackoverflow.com/q/50122145
has comment: http://stackoverflow.com/comment/87266059
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/50219459
favorite count: 0
has answer: http://stackoverflow.com/a/50219576
type: Question
has body: I am designing an online bidding system. I want to remove the product details from the table name PRODUCT with fields pid,proname,price,pdesc. I am using sqlite3 with python. I am not clear how to use timestamp in this case.
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87858680
upvote count: 0
tagged with: sqlite
answer count: 1
has title: How to delete a particular data from database after certain time in python
downvote count: 1

http://stackoverflow.com/a/50223489
downvote count: 1
has comment: http://stackoverflow.com/comment/87496322
has comment: http://stackoverflow.com/comment/87501879
has body: The data you provide is broken, so it is hard to reproduce. Try to provide a reproducible case when asking! ;-) Anyway I guess you just need to: df = pandas.DataFrame(data['DATA']) Where data is the dictionary you created with json.load(). A pandas.DataFrame() can be initialized with a list of dictionaries with no problem, but you need to pass the list of dictionaries. If you are concerned about performance then yeah, append to your list of dictionaries first and convert the whole list to a DataFrame with pandas.DataFrame(list_of_dictionaries).
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/87466854
answers question: http://stackoverflow.com/q/50221204
score: 1

http://stackoverflow.com/comment/87304503
comment on: http://stackoverflow.com/q/50143132
type: Comment
type: QuestionComment
has text: when in doubt, try `latin1` or `iso-8859-1`
score: 0

http://stackoverflow.com/comment/87433685
comment on: http://stackoverflow.com/q/50203965
has text: I know I am not modifying it, but can I? Can I modify the item that is already in the heap. Can I change the date of Job4 for example?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87296769
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50139150
type: AnswerComment
has text: Perfect! Thanks!

http://stackoverflow.com/q/50174247
upvote count: 1
score: 1
tagged with: metaprogramming
has title: Python: create a subclass dynamically in class body
has body: In the following snippet I'm trying to define a factory function which would return objects of different classes derived from Hero based on arguments. class Hero: Stats = namedtuple('Stats', ['health', 'defence', 'attack', 'mana', 'experience']) RaceMaxStats = OrderedDict([ ('Knight', Stats(100, 170, 150, 0, inf)), ('Barbarian', Stats(120, 150, 180, 0, inf)), ('Sorceress', Stats(50, 42, 90, 200, inf)), ('Warlock', Stats(70, 50, 100, 180, inf)) ]) @staticmethod def def_race(race: str): return type(race, (Hero,), {'max': Hero.RaceMaxStats[race]}) Races = OrderedDict([ (race, Hero.def_race(race)) for race in RaceMaxStats.keys() ]) def __init__(self, lord, health, defence, attack, mana, experience): self.race = self.__class__.__name__ self.lord = lord self.stats = Hero.Stats(min(health, self.max.health), min(defence, self.max.defence), min(attack, self.max.attack), min(mana, self.max.mana), min(experience, self.max.experience)) @staticmethod def summon(race, *args, **kwargs): return Hero.Races[race](*args, **kwargs) With the intention of later using it like so: knight = Hero.summon('Knight', 'Ronald', 90, 150, 150, 0, 20) warlock = Hero.summon('Warlock', 'Archibald', 50, 50, 100, 150, 50) The problem is that I cannot initialize the subclasses because Hero is not yet defined: (race, Hero.def_race(race)) for race in RaceMaxStats.keys() NameError: name 'Hero' is not defined Obviously, if I replaced the static method call with the direct type() call I would still need Hero to be defined. My question is how do I best implement this kind of factory. The priority is for the summon() method to retain the same signature, and to return instances of classes derived from Hero. P.S. none of the code above has ever been run successfully, so it may contain other mistakes.
has answer: http://stackoverflow.com/a/50174349
possible better answer: http://stackoverflow.com/a/50174296
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50174349
has answer: http://stackoverflow.com/a/50174386
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50174296
tagged with: oop
tagged with: introspection
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/87265811
type: QuestionComment
comment on: http://stackoverflow.com/q/50122268
has text: any idea???????????
score: 0
type: Comment

http://stackoverflow.com/q/50186237
tagged with: for-loop
answer count: 0
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87389417
score: 1
has body: I am experimenting a little with python and flask, how can I make a webpage that keeps updating itself? Here I make a for-loop to keep x counting, I set it to index.html using jinja2 but it doesn't work, also when I try to access the website the browser keeps charging and then nothing happens just a white page and no request at all in the shell. Flask from flask import Flask, render_template import time app = Flask(__name__) @app.route("/") def index(): for x in range(0, 1000): time.sleep(1) return render_template("index.html", x=x) HTML &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;h1&gt; Title &lt;/h1&gt; &lt;tbody&gt; {{ x }} &lt;/body&gt; &lt;/html&gt;
has title: How to display a variable that keeps changing with flask and python?
tagged with: jinja2
has comment: http://stackoverflow.com/comment/87389473
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87397527
type: UnansweredQuestion
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/87393013
tagged with: auto-update
has comment: http://stackoverflow.com/comment/87397417

http://stackoverflow.com/comment/87199269
score: 0
has text: See for instance https://www.groupe-casino.fr/fr/wp-content/uploads/sites/5/2018/04/2018-04-17-CP-Chiffre-d-affaires-T1-2018.pdf It's something that I have noticed on many files
type: Comment
comment on: http://stackoverflow.com/q/50091012
type: QuestionComment

http://stackoverflow.com/comment/87338130
type: Comment
type: AnswerComment
has text: That is definitely it. In the text editor I see the original csv file has " " around each value. After I save it in excel and reopen it in a text editor, the " " are no longer there. Any suggestions on an easy work around?
comment on: http://stackoverflow.com/a/50104566
score: 0

http://stackoverflow.com/q/50221861
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87461210
has comment: http://stackoverflow.com/comment/87461211
duplicate of: http://stackoverflow.com/q/15112125
tagged with: python
has body: So i am currently using python to create an AI bot, and what i want is for the user to input something like "Hi my name is Bryan" and then i want to set that last word of the input ("Bryan") as a variable for later use. But at the same time i want the code to recognise that they are saying their name, and i have got a bit of that so far. Any help would be greatly appreciated. This is my code for this section if "My name is" or "my name is" in inp: name = print("Hello", name) ("inp" is input btw)
score: 0
has comment: http://stackoverflow.com/comment/87461363
has comment: http://stackoverflow.com/comment/87461228
has comment: http://stackoverflow.com/comment/87461183
has answer: http://stackoverflow.com/a/50222323
has answer: http://stackoverflow.com/a/50222198
has title: Need Some Help: Python String and Variable
linked to: http://stackoverflow.com/q/15112125
type: Question
answer count: 2

http://stackoverflow.com/a/50127321
downvote count: 0
score: 3
has body: in your build logs below:- Step 6/6 : CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] you are running the server on port 8000 so to run the things perfectly you need to do things like below for running the container using our image:- docker run -d -p &lt;port&gt;:8000 test_4 here &lt;port&gt; will be dynamic, you can choose it yourself, as per your needs and after that, it should be available at http://localhost:&lt;port&gt;
answers question: http://stackoverflow.com/q/50127140
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50127140
type: AcceptedAnswer

http://stackoverflow.com/comment/87192150
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50086574
has text: @Martijn ive shortened it down a bit, theres nor much more i cna do to give you an example really - There are meant to be multiple spiders per level but only one spawns in. I think it is an instancing problem with the sprite groups but im not completely sure
type: Comment

http://stackoverflow.com/comment/87270388
has text: `os.fork()` does make a copy of the process. In the parent process, the call returns the process id of the child. In the child process (which is a copy of the parent), the call returns 0. I suspect that calling `os.fork()` in a Kivy App is likely to cause problems. In your case, I don't think you even need to fork, A simple call to `webbrowser.open()` will start the web browser in its own window and your Kivy App will continue.
comment on: http://stackoverflow.com/q/50120769
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87297391
type: AnswerComment
has text: No, those lines assign value to the variables `weight` and `height` respectively. You don't try to assign a value to `b` until you get to the line `b=bmi(weight,height)`. That line says "set `b` to be the return value of the function `bmi` when called with the parameters `weight` and `height`". It so happens that the return value of `bmi` is `None` since you don't have a return statement in that function.
type: Comment
comment on: http://stackoverflow.com/a/50139204
score: 0

http://stackoverflow.com/a/50130619
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You can not do that, you should serve it using urls and views or directly using TemplateView. from django.views.generic import TemplateView urlpatterns = [ (r'^somefile/$', TemplateView.as_view(template_name='somefile.html')), ]
has comment: http://stackoverflow.com/comment/87279137
type: Answer
accepted answer of: http://stackoverflow.com/q/50130493
answers question: http://stackoverflow.com/q/50130493

http://stackoverflow.com/comment/87442775
type: Comment
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/50212975
has text: 1) I see no loop, 2) loops don't create a scope in Python anyway

http://stackoverflow.com/comment/87479514
comment on: http://stackoverflow.com/a/50210882
score: 0
type: Comment
type: AnswerComment
has text: need to say i can enter this ftp dir in explorer just by clicking it twice.

http://stackoverflow.com/q/50100752
has answer: http://stackoverflow.com/a/50235847
type: Question
answer count: 2
tagged with: mocking
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: pymongo
has body: I have a script called commons.py which contains some most commonly used functions. In my main script, I am creating a mongo connection object: db_ob = commons.db_connection() db_connection returns a MongoReplicaSetClient connection object. how to write test cases for my below function?? def check_entries(): try: db_ob = commons.db_connection() except: print('Unable to connect to db!!') return False db_name = 'my_db_name' collection_name = 'my_collection_name' db_data = db_ob[db_name][collection_name].find() if db_data.count() == 0: print('No entries found in the collection!') return False return True I can mock my db_connection function but I am having problem mocking the .count() and .find() functions.
favorite count: 0
has answer: http://stackoverflow.com/a/50101960
tagged with: testing
tagged with: pytest
score: 1
has title: pytest mocking .count() and .find() functions of MongoReplicaSetClient object
tagged with: python

http://stackoverflow.com/comment/87269806
comment on: http://stackoverflow.com/a/50123596
score: 1
has text: Thanks, I'm getting closer, now running it in terminal is giving me this error: **Could not find QtWebEngineProcess**. Tried including QtWebEngineWidgets.so, QtWebEngineCore.so, QtWebEngine.so, but no luck yet. Gonna keep trying things...
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50079674
score: 0
has body: This is actually just an error by you because you are overwriting loops, which means it can't be pickled (pickle just stores a reference to the function). If you say this error didn't occur in python3.6.1, than probably there are test missing in python3.6.1
answers question: http://stackoverflow.com/q/50079165
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/87177412
accepted answer of: http://stackoverflow.com/q/50079165

http://stackoverflow.com/comment/87260880
comment on: http://stackoverflow.com/a/50117671
type: Comment
has text: Thank you for answering ! First, actually my program doesn't make any sense on its own, I was just pointing out the problem I had and thus reduced the code to its minimum. Secondly, Your solution solves the problem I had but it doesn't explain me why I had it which was my main goal. Finally, if you try the code you suggest me (using an image smaller than 50px * 50px) you'll see that I still have an issue : when I delete an image and then try to recreate one I get an error saying that the image doesn't exist...
type: AnswerComment
score: 0

http://stackoverflow.com/a/50124432
has body: In your second block of code, your variable names talk about dictionaries, but your they are actually lists: journal_dict = [] datep_dict = [] place_dict = [] So, let's fix that (this will also be useful later when writing to CSV): record_list = [] for record in records: record_dict = {'ID': record['ID'], 'Journal Title': record['JT'], 'Publication Date': record['DP'] 'Place of Publication': record['PL']} record_list.append(record_dict) Now let's write this list of dictionaries into a CSV file import csv with open('medline.csv', 'w', newline='') as csvfile: fieldnames = ['ID', 'Journal Title', 'Publication Date', 'Place of Publication'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for record_dict in record_list: writer.writerow(record_dict)
type: Answer
accepted answer of: http://stackoverflow.com/q/50122828
answers question: http://stackoverflow.com/q/50122828
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/87275810
score: 0
has text: Have you tried `pd.read_csv(path, error_bad_lines=False, lineterminator='\n')`?
comment on: http://stackoverflow.com/q/50124650
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50146993
has comment: http://stackoverflow.com/comment/87312204
accepted answer: http://stackoverflow.com/a/50147094
has answer: http://stackoverflow.com/a/50147094
possible better answer: http://stackoverflow.com/a/50147073
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I'm currently learning about permutation generation via recursion. The following code I found works great for printing the permutations, but I can't seem to store the values: all values in the stack are lost upon going a level up. def permute_util(str, count, result, level): if level == len(result): print(result) return for i in range(len(str)): if count[i] == 0: continue; result[level] = str[i] count[i] -= 1 permute_util(str, count, result, level + 1) count[i] += 1 permute_util(list("ABC"), [2,1,1], [None]*len("AABC"), 0) Results: ['A', 'A', 'B', 'C'] ['A', 'A', 'C', 'B'] ['A', 'B', 'A', 'C'] ['A', 'B', 'C', 'A'] ['A', 'C', 'A', 'B'] ['A', 'C', 'B', 'A'] ['B', 'A', 'A', 'C'] ['B', 'A', 'C', 'A'] ['B', 'C', 'A', 'A'] ['C', 'A', 'A', 'B'] ['C', 'A', 'B', 'A'] ['C', 'B', 'A', 'A'] I've tried adding result to a global list in the base case, but only the latest level will get store while all other previous values will get overwritten, like so def permute_util(str, count, result, level): global glob if level == len(result): **glob += [result]** return for i in range(len(str)): if count[i] == 0: continue; result[level] = str[i] count[i] -= 1 permute_util(str, count, result, level + 1) count[i] += 1 permute_util(list("ABC"), [2,1,1], [None]*len("AABC"), 0) ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] ['C', 'B', 'A', 'A'] Also tried this to the same effect: def permute_util(str, count, result, level, lists): global glob if level == len(result): return [result] for i in range(len(str)): if count[i] == 0: continue; result[level] = str[i] count[i] -= 1 foo = permute_util(str, count, result, level + 1, lists) lists = lists + foo count[i] += 1 lists = [] permute_util(list("ABC"), [2,1,1], [None]*len("AABC"), 0, lists) What would be the best approach to store all "result" in t…
has comment: http://stackoverflow.com/comment/87312230
answer count: 2
has title: How to store recursive results while backtracking?
has answer: http://stackoverflow.com/a/50147073
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87312224
tagged with: backtracking
has comment: http://stackoverflow.com/comment/87312365
favorite count: 0
tagged with: recursion
has comment: http://stackoverflow.com/comment/87312171
type: Question

http://stackoverflow.com/comment/87522558
has text: Why pyqtSignal will become to pyqtBoundSignal, if it is defined in the subclass of QObject? Does QObject have special inner implementation?
type: Comment
comment on: http://stackoverflow.com/a/50197956
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87595535
type: QuestionComment
has text: i have tried to make the data in a format that is easy to reproduce. Hopefully this helps to find a better solution
score: 0
comment on: http://stackoverflow.com/q/50177258
type: Comment

http://stackoverflow.com/a/50211287
answers question: http://stackoverflow.com/q/50201953
has comment: http://stackoverflow.com/comment/87446817
has body: I think the major problem is that you didn't specify enqueue_many to True so that the it will just repeat the whole batch. You can read more at official document. Here is a working sample: a = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] b = [1,2,3,4] a, b = tf.train.batch([a,b], batch_size=1, num_threads=1, capacity=4, enqueue_many=True) with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess, coord) for i in range(4): print(sess.run([a,b])) coord.request_stop() coord.join(threads)
type: Answer
has comment: http://stackoverflow.com/comment/87439777
has comment: http://stackoverflow.com/comment/87480627
score: 0
accepted answer of: http://stackoverflow.com/q/50201953
type: AcceptedAnswer

http://stackoverflow.com/comment/87194912
type: Comment
comment on: http://stackoverflow.com/a/50086586
type: AnswerComment
has text: @jimbasquiat It's a "Pull Request" which is the mechanism that changes get merged into a project. There's quite a few tutorials online about how to make your first PR, but maybe the simplest thing for now is just to file an issue about it so it does not get lost: https://github.com/bokeh/bokeh/issues Thanks!
score: 1

http://stackoverflow.com/comment/87236836
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50109667
has text: Hmm, this should actually work, because you're passing a non-primitive python type as a reference in your function. Maybe there isn't any values in 'group' keys?
type: Comment

http://stackoverflow.com/comment/87357842
comment on: http://stackoverflow.com/q/50170079
type: Comment
type: QuestionComment
score: 0
has text: Would using a trie tree helped?

http://stackoverflow.com/a/50170734
type: Answer
has comment: http://stackoverflow.com/comment/87358951
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50170505
has body: A function is a first-class object in Python. One of the corollaries of this is that a function may return another function. Your particular example can be written as follows: def general_poly(A): k = len(A) def power(n): return sum(j*n**(k-i) for i, j in enumerate(A, 1)) return power res = general_poly([1, 2, 3, 4])(10) # 1234 The outer function general_poly returns the inner function power. The former takes a list, or an array, while the latter takes a scalar. An alternative way of structuring your logic is to use functools.partial. This creates a new function which one or more parameters fixed and obviates the need for an inner function. from functools import partial def general_poly(A, n): k = len(A) return sum(j*10**(k-i) for i, j in enumerate(A, 1)) genral_poly_10 = partial(general_poly, n=10) res = genral_poly_10([1, 2, 3, 4]) # 1234 Of course, this is only useful if you wish to create a function for a specific power; trivially, n can be used directly as an additional parameter without functools.partial. Note: Beware of mutable default arguments. So if your function has a mutable default argument, e.g. setting A=[] in the above examples, the same list may be reused in an unforeseen way.
upvote count: 2
has comment: http://stackoverflow.com/comment/87358986

http://stackoverflow.com/comment/87189581
score: 6
comment on: http://stackoverflow.com/q/50079735
type: Comment
type: QuestionComment
has text: This is just a guess. Have checked the init methods? I'm not sure what init is used in keras, but with default init method, the values for weights in pytorch can grow quite large - this could result in faster learning. Can you check the difference in the training acc?

http://stackoverflow.com/a/50098158
type: Answer
upvote count: 3
downvote count: 0
has body: Thanks all! I didn't perform a linear reression for a while, and of course it's because X is not invertible (in R, it gives me 'nan'). So it wasn't a smart question... Thanks again!
answers question: http://stackoverflow.com/q/50096831
has comment: http://stackoverflow.com/comment/87212781
score: 3

http://stackoverflow.com/q/50158866
upvote count: 4
has body: I am trying to set some buttons in tkinter, and I do not understand what is the difference between column and columnspan. Can anybody explain in a few words?
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/50159213
answer count: 3
downvote count: 3
has title: What is the difference between "column" and "columnspan" in tkinter python?
has answer: http://stackoverflow.com/a/70280614
has answer: http://stackoverflow.com/a/73024454
favorite count: 0
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50159213
tagged with: python
possible better answer: http://stackoverflow.com/a/70280614

http://stackoverflow.com/q/50225050
tagged with: datetime
tagged with: python
has body: I was trying to convert time object to datetime64 format. I used following: time =['87:38:00','51:48:00','26:05:00','10:04','69:21:00','66:56:00','47:12:00'] time1 =pd.to_datetime(time, format ='%d/%m/%Y/%H/%m/%s', errors ='coerce') it (time1) returned me object. How can i convert it to datetime64[ns] Thanks zephyr
has comment: http://stackoverflow.com/comment/87467764
has title: converting object to datetime64[ns]
has comment: http://stackoverflow.com/comment/87467794
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50226487
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50226487
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50089779
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/50089809
tagged with: function
upvote count: 0
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/87481567
has title: Calling an object attribute within another object's method in python
tagged with: oop
tagged with: instance
has body: i am making a MLP and connecting my final hidden layer to the output. class connection: def __init__(self): self.value = 0 self.weight = 0 self.network_output_index = 0 def connect(self,**network_instance**): **network_instance**.output_array[self.network_output_index] = self.value * self.weight class network: def __init__(self): self.output_array = [0,0,0,0] blah blah python blah; How do I call network_instance's attribute output_array?
downvote count: 2
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/87389563
type: AnswerComment
comment on: http://stackoverflow.com/a/50186392
has text: ...or use sets on both side to spare the expensive sorting.
type: Comment
score: 2

http://stackoverflow.com/q/50082977
has title: couldn't open .png file in python 3.6.5
tagged with: python
tagged with: pygame
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87183701
has body: I was trying to understand a pygame code but I couldn't run it on my computer.I am very new in python.The portion of the code that is giving error is here.. from pygame.locals import * from random import randint import pygame import time class App: windowWidth = 800 windowHeight = 600 player = 0 apple = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.player = Player(5) self.apple = Apple(8,5) self.computer = Computer(5) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame pythonspot.com example') self._running = True self._image_surf = pygame.image.load("pygame.png").convert() self._apple_surf = pygame.image.load("apple.png").convert() if __name__ == "__main__" : theApp = App() theApp.on_execute() the error message is exactly like this... RESTART: C:/Users/Dipto/AppData/Local/Programs/Python/Python36/gametest1.py Traceback (most recent call last): File "C:/Users/Dipto/AppData/Local/Programs/Python/Python36/gametest1.py", line 263, in &lt;module&gt; theApp.on_execute() File "C:/Users/Dipto/AppData/Local/Programs/Python/Python36/gametest1.py", line 233, in on_execute if self.on_init() == False: File "C:/Users/Dipto/AppData/Local/Programs/Python/Python36/gametest1.py", line 185, in on_init self._image_surf = pygame.image.load("pygame.png").convert() pygame.error: Couldn't open pygame.png
has comment: http://stackoverflow.com/comment/87183823
has comment: http://stackoverflow.com/comment/87183747
has comment: http://stackoverflow.com/comment/87182132
score: 0
linked to: http://stackoverflow.com/q/42335678
answer count: 0
has comment: http://stackoverflow.com/comment/87183732
duplicate of: http://stackoverflow.com/q/42335678
type: Question

http://stackoverflow.com/comment/87808364
comment on: http://stackoverflow.com/a/50360218
type: Comment
score: 0
type: AnswerComment
has text: Would you consider subclassing the operators? For bash operators, there is probably a way to achieve a similar result through templating.

http://stackoverflow.com/comment/87449900
comment on: http://stackoverflow.com/q/50216345
has text: @Stack , the Power Of Multi-Threading can be better found on Multi-Proccesing , Because the multiprocess Module Create Threads and Will Use Multi Processors for Increase the Speed
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87373233
score: 0
comment on: http://stackoverflow.com/a/50177323
type: AnswerComment
type: Comment
has text: Hmm. Upon debugging, the contents of the array end up looking like: ["id", "type", "ip", "blah"....] instead of the entire JSON string, based on your suggestion of result.extend(load(json_data)) with well-formatted JSON

http://stackoverflow.com/comment/87189570
comment on: http://stackoverflow.com/q/50086725
type: Comment
score: 1
has text: BTW, you should _seriously_ consider learning Python 3, Python 2 will reach its official End Of Life in 2020. But in the mean time, please do **not** use Python 2's `input` function, it is a big security hole. Use `raw_input` instead. In Python 3, `raw_input` has been renamed to `input`, and the old `input` function has been killed.
type: QuestionComment

http://stackoverflow.com/q/50130798
has answer: http://stackoverflow.com/a/50138587
has comment: http://stackoverflow.com/comment/87280309
score: 0
has body: I'm building module odoo. In my module need two form and tree with different field from one class. I had been tried, but doesn't work. This is my code Trial new.trial form tree,form [] { 'form_view_ref' : 'client_form_view_2', 'tree_view_ref':'client_form_view_2_tree'} Click to add a new project. and errors like this . How can i solve this?
tagged with: odoo-9
answer count: 1
tagged with: http://stackoverflow.com/tag/xml
type: Question
has comment: http://stackoverflow.com/comment/87279538
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87280765
tagged with: python
has title: Create different form and tree in odoo 9

http://stackoverflow.com/q/50139189
has comment: http://stackoverflow.com/comment/87296947
type: Question
tagged with: operator-overloading
has comment: http://stackoverflow.com/comment/87297303
has answer: http://stackoverflow.com/a/50139331
answer count: 2
has answer: http://stackoverflow.com/a/50139366
accepted answer: http://stackoverflow.com/a/50139366
upvote count: 1
has body: In my classes, I often use overloading like in this site to define their behavior when using operators like +,-, etc. by overwriting the __add__,__sub__, etc. methods. An example would be this: class MyClass: def __add__(self, other): result = my_custom_adder(self, other) return self.__class__(result) Is there any way to define the behavior when chaining of such overwritten operators? For example, an addition of three elements a + b + c of a complex class could be implemented much more efficiently by taking all three elements into account at once and not just calculating (a + b) + c sequentially. Of cause I can just introduce a classmethod: class MyClass: def __add__(self, other): return self.my_custom_adder(self, other) @classmethod def my_custom_adder(cls, *args): result = do_efficient_addition(*args) return cls(result) Then, I can call my_custom_adder(a, b, c) instead. But this requires the user to know that there is a method like this and calling it explicitly, instead of just using a + b + c.
downvote count: 0
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/46885618
has title: Overload chaining of arithmetic operators in Python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50139331
duplicate of: http://stackoverflow.com/q/46885618
score: 1

http://stackoverflow.com/a/50158022
downvote count: 0
upvote count: 1
has body: You are selecting two layers, but one doesn't appear in the auto-generated dialog because it is assumed to be the active layer(*): the PF_DRAWABLE argument after the PF_IMAGE is implicitly the current active layer (or active channel) when the script/plugin is called. In other words your script doesn't work with two random layers, but with the active layer and another random layer (which is usually a good idea from a UI perspective, especially if you script modifies only one of the two). (*) In some cases (Filters>Reshow ...) the auto-generated dialog can show a selector for that layer and so show you the two layer selectors you expect.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50140316

http://stackoverflow.com/comment/87348356
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50150081
has text: That link is an old tutorial. The current tutorial is at https://github.com/oracle/python-cx_Oracle/tree/master/samples/tutorial (and the "official documentation" for cx_Oracle is at http://cx-oracle.readthedocs.io/en/latest/installation.html)

http://stackoverflow.com/q/50218274
has title: Renaming the '_' variable in Python
has comment: http://stackoverflow.com/comment/87453607
score: 1
has answer: http://stackoverflow.com/a/50218405
answer count: 1
downvote count: 0
upvote count: 1
tagged with: alias
has comment: http://stackoverflow.com/comment/87453777
has body: I recently learned about the builtin variable _ in the python shell, the purpose of which is to store the last console answer. For example: &gt;&gt;&gt; 4 + 7 11 &gt;&gt;&gt; _ 11 &gt;&gt;&gt; Test = 4 &gt;&gt;&gt; Test + 3 7 &gt;&gt;&gt; _ 7 Being a longtime TI-Basic programmer, I'm far more comfortable with thinking of this variable as Ans instead of _. (Yes, I know it's merely personal preference, but it's an interesting question in any case.) Question: How do I set up my Ans variable so that its value is always the same as the _ variable? It's not as simple as just doing Ans = _, as this shell log shows: &gt;&gt;&gt; "test string" 'test string' &gt;&gt;&gt; _ 'test string' &gt;&gt;&gt; Ans = _ &gt;&gt;&gt; Ans 'test string' &gt;&gt;&gt; list('Other String') ['O', 't', 'h', 'e', 'r', ' ', 'S', 't', 'r', 'i', 'n', 'g'] &gt;&gt;&gt; _ ['O', 't', 'h', 'e', 'r', ' ', 'S', 't', 'r', 'i', 'n', 'g'] &gt;&gt;&gt; Ans 'test string'
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87453595
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87453651
tagged with: python
has comment: http://stackoverflow.com/comment/87453983
has comment: http://stackoverflow.com/comment/87453633

http://stackoverflow.com/a/50106745
has body: The closure variable mechanisms that would provide inner with access to var_outer are only triggered if inner actually contains accesses to the var_outer variable. Otherwise, var_outer is not saved, and no introspection will give you access to it.
downvote count: 0
answers question: http://stackoverflow.com/q/50106661
upvote count: 6
type: Answer
score: 6

http://stackoverflow.com/q/50130230
tagged with: arrays
has comment: http://stackoverflow.com/comment/87297316
tagged with: python
has body: I've got a three-dimensional numpy array of shape (2,2,2). I would like to think of it as a two-dimensional matrix with 1-dimensional arrays as entries. What I would like to do is applying a function to each entry (i.e. each 1-d array) in my matrix. I know that I could vectorize my function to apply it to each number in my array. I also know that I can apply a function along one axis. However, I haven't managed to apply the functions along two axes. Here's my latest trial: import numpy as np def sqrtSum(a, b): return np.sqrt(a+b) def sqrtSumWrapper(row): return np.array([sqrtSum(x[0], x[1]) for x in row]) z = np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) np.apply_along_axis(sqrtSumWrapper, 1, z) In the example above, my desired outcome would be an array of shape (2,2) with the entries ((sqrt(3), sqrt(7)),(sqrt(11), sqrt(15)). When I run the code above I get a invalid index to scalar variable. error. I think I'm missing an important aspect of how apply_along_axis works and would be thankful for your input how to correct the code. EDIT: The answers so far are focussing on changing the input function sqrtSum. This function is just an example. I'm interested in a general answer for an arbitrary input function that takes n input parameters and returns a scalar. Solution: The solution is amazingly simple (shame on me that I haven't seen it) import numpy as np def sqrtSum(a, b): return np.sqrt(a+b) def sqrtSumWrapper(x): return sqrtSum(x[0], x[1]) z = np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) np.apply_along_axis(sqrtSumWrapper, 2, z) Thanks to all repliers.
type: AnsweredQuestion
score: 3
tagged with: functional-programming
accepted answer: http://stackoverflow.com/a/50130478
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50130478
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50130340
answer count: 2
has title: How to iterate over "some" dimensions of a numpy array?
has answer: http://stackoverflow.com/a/50130340

http://stackoverflow.com/q/50138141
accepted answer: http://stackoverflow.com/a/50138332
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: python
tagged with: astropy
favorite count: 0
has title: Create a date range in julian date python
has body: I have to create a range between two dates, interval between dates of some minutes, in Julian date, i create a code, but is taking a lot of time about(15 minutes, for the ex.) my code is: from astropy.time import Time import pandas as pd timedelta = "600s" start = "2018-01-01" end = "2018-06-30" dateslist = pd.date_range(start,end, freq =timedelta ).tolist() dates = pd.DataFrame({'col':dateslist}) dates["col2"] ="" for i in range(len(dateslist)): #print(i," / ", len(dateslist)) dates["col2"][i] = (Time(str(dateslist[i]).replace(" ", "T"), format="fits").jd) I tried using Time without for, but is getting error time = str(list(dates['col'])).replace("[Timestamp('","").replace(" Timestamp('","").replace("')","").replace(" ","T").split(",") time Time(time, format="fits") ValueError: Input values did not match the format class fits Is there some way of doing this quickly? Thanks for now,
type: Question
has answer: http://stackoverflow.com/a/50140363
possible better answer: http://stackoverflow.com/a/50140363
answer count: 2
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50138332

http://stackoverflow.com/q/50195948
tagged with: nlp
type: Question
score: 0
has body: Word2Vec Currently I am trying to perform text classification on a text corpus. In order to do so, I have decided to perform word2vec with the help of gensim. In order to do so, I have the code below: sentences = MySentences("./corpus_samples") # a memory-friendly iterator model = gensim.models.Word2Vec(sentences, size=100, window=5, min_count=5, workers=4) My sentences is basically a class that handles the File I/O class MySentences(object): def __init__(self, dirname): self.dirname = dirname def __iter__(self): for fname in os.listdir(self.dirname): for line in open(os.path.join(self.dirname, fname)): yield line.split() Now we can get the vocabulary of the model that has been created through these lines: print(model.wv.vocab) The output of which is below(sample): t at 0x106f19438&gt;, 'raining.': &lt;gensim.models.keyedvectors.Vocab object at 0x106f19470&gt;, 'fly': &lt;gensim.models.keyedvectors.Vocab object at 0x106f194a8&gt;, 'rain.': &lt;gensim.models.keyedvectors.Vocab object at 0x106f194e0&gt;, 'So…': &lt;gensim.models.keyedvectors.Vocab object at 0x106f19518&gt;, 'Ohhh,': &lt;gensim.models.keyedvectors.Vocab object at 0x106f19550&gt;, 'weird.': &lt;gensim.models.keyedvectors.Vocab object at 0x106f19588&gt;} As of now, the dictionary that is the vocabulary, contains the word string and a &lt;gensim.models.keyedvectors.Vocab object at 0x106f19588&gt; object or such. I want to be able to query an index of a particular word. In order to make my training data like: w91874 w2300 w6 w25363 w6332 w11 w767 w297441 w12480 w256 w23270 w13482 w22236 w259 w11 w26959 w25 w1613 w25363 w111 __label__4531492575592394249 w17314 w5521 w7729 w767 w10147 w111 __label__1315009618498473661 w305 w6651 w3974 w1005 w54 w109 w110 w3974 w29 w25 w1513 w3645 w6 w111 __label__-400525901828896492 w30877 w72 w11 w2828 w141417 w77033 w10147 w111 __label__4970306416006110305 w3332 w1107 w4809 w1009 w327 w84792 w6 w922 w11 w2182 w79887 w1099 w111 __label__-3645735357732416904 w471 w14752 w163…
type: UnansweredQuestion
answer count: 1
tagged with: word2vec
has answer: http://stackoverflow.com/a/50208329
has title: I am trying to get the key of a particular word from a Word2Vec Vocabulary
tagged with: python
tagged with: gensim
tagged with: dictionary

http://stackoverflow.com/q/50082528
answer count: 2
has comment: http://stackoverflow.com/comment/87183495
downvote count: 0
has answer: http://stackoverflow.com/a/61725380
type: UnansweredQuestion
score: 6
upvote count: 6
has answer: http://stackoverflow.com/a/77261108
favorite count: 0
has comment: http://stackoverflow.com/comment/87181155
has title: Unmatched ''"' when when decoding 'string' error in reading json file into pandas dataframe
has body: I am trying to load a amazon review data into pandas dataframe, which is a JSON file , using the pd.read_json(), I am getting the following error Unmatched ''"' when when decoding 'string'. I am using jupyter notebook Data format: {"reviewerID": "AGL65XWV7MH3C", "asin": "B003FMUVKO", "reviewerName": "William B. Bebout \"Acknud\"", "helpful": [0, 1], "reviewText": "Too short. I would have rated it higher if it was long enough to hold my attention! It did have significant violence but not much else.", "overall": 3.0, "summary": "Short", "unixReviewTime": 1304985600, "reviewTime": "05 10, 2011"} Python code: data =pd.read_json('sample_data.json', lines=True)
tagged with: pandas
has comment: http://stackoverflow.com/comment/94012281
has comment: http://stackoverflow.com/comment/87198225
has comment: http://stackoverflow.com/comment/126210757
tagged with: python
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/87181013

http://stackoverflow.com/comment/87262102
score: 0
type: Comment
type: QuestionComment
has text: @fferri Great, thanks for the tip!
comment on: http://stackoverflow.com/q/50106345

http://stackoverflow.com/comment/87238370
type: Comment
score: 0
type: AnswerComment
has text: @Dan: Perhaps I don't understand your comment, but one can't call `self.win.cv.bind("<KeyPress>", eventfun)` directly because `eventfun` is in a function nested inside the `TurtleScreenBase._onkeypress()` method.
comment on: http://stackoverflow.com/a/50110341

http://stackoverflow.com/comment/87255742
has text: what is the different between yours and mine ?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50119137
type: AnswerComment

http://stackoverflow.com/q/50079311
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50079362
upvote count: 8
has comment: http://stackoverflow.com/comment/87203436
possible better answer: http://stackoverflow.com/a/50079356
has answer: http://stackoverflow.com/a/50079362
has title: How to write code that works in both Python 2 and Python 3?
has body: A Django website I maintain currently uses Python 2.7 but I know that I'll have to upgrade it to Python 3 in a couple of months. If I'm writing code right now that has to work in Python 2, is there a Pythonic way to write it such that it would also work in Python 3 without any changes if I know what the syntax is going to be in Python 3? Ideally I'd like the code to continue to work even after the upgrade without changing it but it would be easy for me to spot where I've done this in the codebase so that I can change the code when I have time. Here's an example of what I'm talking about: # Python 2 uses 'iteritems' def log_dict(**kwargs): for key, value in kwargs.iteritems(): log.info("{0}: {1}".format(key, value)) # Python 3 uses 'items' def log_dict(**kwargs): for key, value in kwargs.items(): log.info("{0}: {1}".format(key, value))
tagged with: django
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/50079389
has answer: http://stackoverflow.com/a/50084417
score: 6
has comment: http://stackoverflow.com/comment/87199905
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/106882440
has answer: http://stackoverflow.com/a/50079590
downvote count: 2
has answer: http://stackoverflow.com/a/50079356
has comment: http://stackoverflow.com/comment/106895760
has answer: http://stackoverflow.com/a/50079400
favorite count: 0

http://stackoverflow.com/comment/87210589
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50095950
score: 0
has text: Or using notnull method : `df = df[pd.notnull(df['lat'])]`

http://stackoverflow.com/comment/87421244
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50200917
type: QuestionComment
has text: @EugeneYarmash, your title may not ask for debugging help but I think the body of the question does. (If we're just looking at the title, isn't it dangerously close to code translation?)

http://stackoverflow.com/comment/90219340
score: 0
comment on: http://stackoverflow.com/q/50205683
type: QuestionComment
type: Comment
has text: Your virtual environment is missing `django-envrion`, which you need to install with `pip install django-environ`

http://stackoverflow.com/q/50081500
has answer: http://stackoverflow.com/a/50081720
has title: Create a new column with the value found in another DataFrame
tagged with: python
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/50081720
type: AnsweredQuestion
downvote count: 0
answer count: 1
has body: I have two DataFrames: df_components: list of unique components (ID, DESCRIPTION) dataset: several rows and columns from a CSV (one of these columns contains the description of a component). I need to create a new column in the dataset with the ID of the component according to the df_components. I tried to do this way: Creating the df_components and the ID column based on the index components = dataset["COMPDESC"].unique() df_components = pd.DataFrame(components, columns=['DESCRIPTION']) df_components.sort_values(by='DESCRIPTION', ascending=True, inplace=True) df_components.reset_index(drop=True, inplace=True) df_components.index += 1 df_components['ID'] = df_components.index Sample output: DESCRIPTION ID 1 AIR BAGS 1 2 AIR BAGS:FRONTAL 2 3 AIR BAGS:FRONTAL:SENSOR/CONTROL MODULE 3 4 AIR BAGS:SIDE/WINDOW 4 Create the COMP_ID in the dataset: def create_component_id_column(row): found = df_components[df_components['DESCRIPTION'] == row['COMPDESC']] return found.ID if len(found.index) &gt; 0 else None dataset['COMP_ID'] = dataset.apply(lambda row: create_component_id_column(row), axis=1) However this gives me the error ValueError: Wrong number of items passed 248, placement implies 1. Being 248 the number of items on df_components. How can I create this new column with the ID from the item found on df_components?
favorite count: 0
type: Question

http://stackoverflow.com/comment/87430266
comment on: http://stackoverflow.com/a/50206438
type: AnswerComment
score: 1
has text: That's a problem with the Python code. Your code is probably importing the python module `smtplib`. It may be that your computer is running a newer or older version of python than that module requires, and something in the module has been moved. I've run across similar issues with the http libraries. But, I am not sure how to solve that. That has nothing to do with the C++ program running the Python program. Does the python program invoke successfully when run directly from command line?
type: Comment

http://stackoverflow.com/q/50110798
has comment: http://stackoverflow.com/comment/87238998
type: Question
has answer: http://stackoverflow.com/a/50111019
tagged with: python
has body: I am trying to use image.paste to paste many images onto one background. My images contain their x,y offset values in their filenames (eg. Image_1000_2000.png is offset 1000,2000). The code below works, but it's painfully slow. Here's what I've got: import re import glob from PIL import Image # Disable Decompression Bomb Protection Image.MAX_IMAGE_PIXELS = None # Set the dimensions of the blank canvas newheight = 13000 newwidth = 13000 # Glob all the PNG images in the folder and create the blank canvas photos = glob.glob("*.png") blankbackground = Image.new('RGB', (newheight, newwidth), (0, 0, 0)) blankbackground.save(r'..\bg999.png', "PNG") for photo in photos: blankbackground = Image.open(r'..\bg999.png') photog = Image.open(photo) # Get the x , y offsets from the filenames using re y_value = re.findall(r"0_(\d*).", photo)[0] y = int(y_value) x_value = re.findall(r'_(\d*).', photo)[0] x = int(x_value) # The actual paste operation, and save the image to be re-opened later blankbackground.paste(photog,(x,y)) blankbackground.save(r"..\bg999.png") print(photo) Any suggestions on a speedier alternative? EDIT: As per the comments below, it is not necessary to save / reload the image with every photo. This makes it considerably faster.
has comment: http://stackoverflow.com/comment/87239073
accepted answer: http://stackoverflow.com/a/50111019
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87239129
tagged with: python-imaging-library
has title: Is there a faster alternative to PIL's Image.paste for multiple images?
has comment: http://stackoverflow.com/comment/87239247
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87238999

http://stackoverflow.com/q/50188462
has comment: http://stackoverflow.com/comment/87394973
has body: I have two models called Event and Registration. Each Registration has as ForeignKey an Event object. Now, in my web application I provide a RegistrationForm so that people can register for an event. Example: A user can register at /event/&lt;pk&gt;/register/. From the URL I get the event the user would like to register for and pass the public key of the event to the RegistrationForm. class RegistrationForm(forms.ModelForm): class Meta: model = Registration exclude = ['event'] def __init__(self, *args, **kwargs): self.event = kwargs.pop('pk') super().__init__(*args, **kwargs) In the form I, of course, do not display the event field (so that's why it's excluded). Because when the user is at e.g. /event/5/register/ is clear that he would like to register for event 5. In the view I create the Form using form = RegistrationForm(pk=pk). In case you know a better solution how to solve this, please come up with it. :) Now the problem: In my RegistrationForm I have also some validation logic and when I create/edit a new Registration object in the Admin, I'd also like to have those validations. class RegistrationInline(admin.StackedInline): model = Registration extra = 0 form = RegistrationForm @admin.register(Event) class EventAdmin(admin.ModelAdmin): form = EventForm inlines = [RegistrationInline] Thing is, however, that my RegistrationForm does need the public key of the event and I do not know how to solve that problem. I looked at the Django documentation, but I am overwhelmed about the many methods and functionality as a beginner. What is a good solution? Here my validations in the RegistrationForm: def clean_number_of_tickets(self): number_of_tickets = self.cleaned_data.get('number_of_tickets') # Event object event = Event.objects.get(pk=self.event) if self.instance.number_of_tickets: available = self.instance.number_of_tickets + event.get_number_of_available_tickets() else: available = event.get_number_of_available_tickets() if number_of_tickets &gt; available: raise…
has comment: http://stackoverflow.com/comment/87394754
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django
tagged with: python
has title: Django: Pass parameter to Form in Admin
score: 1
has comment: http://stackoverflow.com/comment/87394617
has comment: http://stackoverflow.com/comment/87394904
favorite count: 0
type: Question

http://stackoverflow.com/q/50118352
type: Question
tagged with: smtplib
upvote count: 2
accepted answer: http://stackoverflow.com/a/50120253
linked to: http://stackoverflow.com/q/50116967
tagged with: python
has answer: http://stackoverflow.com/a/50120253
has body: After failing to send email with Mailgun API, I have been sending email with SMTP successfully using smtplib, with the following code. def send_simple_message(mailtext, mailhtml): print("Mailhtml is:" + mailhtml) logging.basicConfig(level=logging.DEBUG) import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg = MIMEMultipart('alternative') msg['Subject'] = "Summary of Credit Card payments due" msg['From'] = "creditcards@domain.in" msg['To'] = "me@domain.in" s = smtplib.SMTP('smtp.mailgun.org', 587) part1 = MIMEText(mailtext, 'plain') part2 = MIMEText(mailhtml, 'html') msg.attach(part1) msg.attach(part2) s.login('postmaster@domain.in', 'password') s.sendmail(msg['From'], msg['To'], msg.as_string()) s.quit() However this displays the sender field as creditcards@domain.in. How can I add a sender header field so the sender is shown as Someone important (creditcards@domain.in) instead?
has title: Send email with sender and recipient header in python
score: 2
type: AnsweredQuestion
tagged with: email
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/87295688
type: AnswerComment
has text: You're an absolute saint. Thanks so much!
type: Comment
comment on: http://stackoverflow.com/a/50138423
score: 0

http://stackoverflow.com/q/50075613
has answer: http://stackoverflow.com/a/50075647
type: AnsweredQuestion
score: 0
answer count: 2
has title: How is a global variable declared?
has body: I want my method to have access to the variable defined outside the method, but even if i use global keyword it says it can't: global var = 0 def test(): var = var +1 Compiler still says var is not defined in test method Where is my mistake?
tagged with: global
tagged with: variables
has answer: http://stackoverflow.com/a/50075662
accepted answer: http://stackoverflow.com/a/50075662
linked to: http://stackoverflow.com/q/423379
type: Question
duplicate of: http://stackoverflow.com/q/423379
has comment: http://stackoverflow.com/comment/87167520
possible better answer: http://stackoverflow.com/a/50075647
tagged with: python

http://stackoverflow.com/q/50104422
has body: I am working with PySpark using mixin factory of two classes But each time map function is called the kernel just break, tried to debug and find relevant solution but didn't find any support . At the moment I have multiple classes, those classes are called as according to the needs Interestingly, this format worked on previous version of Spark (1.6) but don't work with latest Spark 2.0 later I believe its due to conflicting similar meta-class name among workers... so, correction or some reference would be deeply appreciated def mixin_factory(name, base, mixin): class _tmp(base, mixin): pass _tmp.__name__ = name return _tmp def Mix_map_function(dataframe) : MixClass = mixin_factory("MixClass", Class_A, Class_B) MixClass( .... , dataframe ) # class initialization parameters using constructor PiplinedRDD.map(lambda x: Mix_map_function(x[0]) , preservesPartitioning=True ) # x[0] some partitioned data from rdd
type: Question
tagged with: apache-spark-sql
answer count: 0
linked to: http://stackoverflow.com/q/31093179
type: UnansweredQuestion
score: 0
tagged with: apache-spark
tagged with: pyspark
has title: Mixin Factory Classes with pyspark
has comment: http://stackoverflow.com/comment/87226148
tagged with: python
tagged with: rdd
has comment: http://stackoverflow.com/comment/87226301
has comment: http://stackoverflow.com/comment/87226362

http://stackoverflow.com/q/50226170
type: Question
has comment: http://stackoverflow.com/comment/87469632
has body: I need to run .py files by python3.5 on the Raspberry-Pi. Firstly I need to install packages, such as OpenCV or else. pi@raspberrypi:~ $ sudo pip3 install opencv-python Collecting opencv-python Could not find a version that satisfies the requirement opencv-python (from versions: ) No matching distribution found for opencv-python It worked for python2 by pip install opencv-python. But it doesn't work for python3. pip3 -V command shows pip 10.0.1 from /home/pi/.local/lib/python3.5/site-packages/pip (python 3.5). Is there something I forgot?
tagged with: raspberry-pi
answer count: 0
has comment: http://stackoverflow.com/comment/87469624
type: UnansweredQuestion
tagged with: package
tagged with: pip
tagged with: python
has title: Installing packages for python3 in Raspberry
score: 0

http://stackoverflow.com/q/50171872
tagged with: reinforcement-learning
tagged with: deep-learning
answer count: 0
has comment: http://stackoverflow.com/comment/87393608
upvote count: 3
downvote count: 0
tagged with: tensorflow
has body: In my thesis I am describing a Deep Reinforcement Learning (DRL) example which is written in python. I did not write the code, I just got it running an training on a linux server an it all works fine. Now I am on the point where I want to visualize the accuracy/prediction, loss, learning stability and so on with tensorboard. I am working in a conda virutal environment where I have installed gym, atari-py, Pillow and PyOpenGL. On the server TensorFlow-GPU is installed. This is the link to the repository where I got the code from. I have watched tutorials about tensorboard and I get it, but I can not include those variables, like tf.summary.histogram() into my code. I do not know where exactly to put them and what variables might be important to visualize. I already made it that tensorboard visualizes the whole network with the file writer as a graph which looks like this. But now I am stuck. Every time I want to try including histograms of variables the code throws errors. It seems like I put them into the wrong positions, or I am trying to visualize the wrong variables. (I am not so familiar with python code, maybe I get the syntax wrong.) It would be super nice if someone could help me. This is the link to the tensorboard tutorial I oriented towards. Below you see the code. The example consists only of this file. from __future__ import division, print_function, unicode_literals # Handle arguments (before slow imports so --help can be fast) import argparse parser = argparse.ArgumentParser( description="Train a DQN net to play MsMacman.") parser.add_argument("-n", "--number-steps", type=int, default=4000000, help="total number of training steps") parser.add_argument("-l", "--learn-iterations", type=int, default=4, help="number of game iterations between each training step") parser.add_argument("-s", "--save-steps", type=int, default=1000, help="number of training steps between saving checkpoints") parser.add_argument("-c", "--copy-steps", type=int, default=10000, hel…
favorite count: 0
type: Question
has title: Tensorboard Visualization in Deep Reinforcement Learning Atari (MsPacman) Example
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87394821
tagged with: tensorboard
tagged with: python
score: 3

http://stackoverflow.com/comment/87292535
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50136817
has text: You can reverse your format terms and get the exact OP output request `.columns.map('{0[1]}_{0[0]}'.format)`
score: 0

http://stackoverflow.com/comment/87443318
score: 0
type: AnswerComment
has text: Ok, I edited in an example of nested dicts. You can't make a set of dicts because they're unhashable. You also have the option of making a list of dicts if you want.
type: Comment
comment on: http://stackoverflow.com/a/50211843

http://stackoverflow.com/comment/87249544
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50114747
type: Comment
has text: can you share the original image?

http://stackoverflow.com/comment/136212980
score: 0
type: Comment
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment
comment on: http://stackoverflow.com/a/77261108

http://stackoverflow.com/comment/87418290
comment on: http://stackoverflow.com/a/50197393
score: 0
type: AnswerComment
has text: when saying it's not working I meant I see the warnings multiple times, same as earlier, and not just once.
type: Comment

http://stackoverflow.com/comment/87473450
has text: For the examples you got, can you add the expected date?
comment on: http://stackoverflow.com/q/50227956
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50192322
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87401688
has comment: http://stackoverflow.com/comment/87401626
tagged with: python
has answer: http://stackoverflow.com/a/50192375
has comment: http://stackoverflow.com/comment/87401763
has comment: http://stackoverflow.com/comment/87401585
score: 0
tagged with: printing
has comment: http://stackoverflow.com/comment/87401567
has comment: http://stackoverflow.com/comment/87401796
has body: this is my code the I am currently writing for a robot in my university project. This code works, however the loop will constantly print statements every second and I would like it to only print when I change the input condition (break the if condition), so it wouldn't keep on printing. Is there anyway to fix this? Thanks for the help in advance. PS: this is in python 2.7 (I think) try: while True: #some stuff if 0.01 &lt; joystick.get_axis(1) &lt;= 0.25: print ('moving backward with 25% speed') # performing some actions elif 0.25 &lt; joystick.get_axis(1) &lt;= 0.5: print ('moving forward with 50% speed') # performing some actions elif 0.5 &lt; joystick.get_axis(1) &lt;= 0.75: print ('moving backward with 75% speed') # performing some actions the while loop continues in the same fashion...
has title: How to print once until the if condition is broken?
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50192520
tagged with: if-statement

http://stackoverflow.com/comment/87476362
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50229523
has text: I need it to be saved there forever, maby something like into the file?

http://stackoverflow.com/q/50164816
downvote count: 0
has comment: http://stackoverflow.com/comment/87347882
answer count: 1
favorite count: 0
has body: I'm trying to open a specific location within an HTML file with python, but it doesn't work. The code is import webbrowser url = '~\docs\index.html#api.method_name' webbrowser.open(f'file:///{url}') This code opens the file in the browser, but the url '~\docs\index.html'. It doesn't take me to the part location of api.method_name. But if I copy and paste the ulr in a web browser, it works. I have already tried changing the hash sign to %23, but it didn't work either.
type: Question
has answer: http://stackoverflow.com/a/50164891
type: UnansweredQuestion
has title: webbrowser open location python
tagged with: python
tagged with: python-webbrowser
has comment: http://stackoverflow.com/comment/87347687
upvote count: 2
score: 2

http://stackoverflow.com/comment/87370419
score: 4
has text: In the context of Clojure, this is called threading (as in argument threading). It doesn't have anything to do with Threads. And it's more complicated than what deceze's suggestion would allow. The threading macro above inserts the threaded argument as the first argument of the other forms, in front of other arguments that were supplied. It doesn't simply take function references and do application.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50176529

http://stackoverflow.com/a/50194302
accepted answer of: http://stackoverflow.com/q/50194231
has comment: http://stackoverflow.com/comment/87405866
type: AcceptedAnswer
has body: I feel that there must be a better solution. Define "better". Do you mean faster? There isn't, not for structures like this, no. List comprehensions are optimised to be even faster than their for-loop equivalents in almost every instance. Do you mean something that looks nicer? I think a list comprehension looks quite nice, to be honest. Is there a magic one-liner to automagically process data in this format? Yes! Sadly, you've already found it (json_normalize), and as you've discovered, is much slower than the list comp: In [431]: data = data * 10000 In [432]: %timeit json_normalize(data) 1.3 s ± 19.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [433]: %timeit pd.DataFrame([d['entry'] for d in data]) 63.2 ms ± 1.26 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) So, no, there's isn't a better solution.
score: 3
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50194231
has comment: http://stackoverflow.com/comment/87405836

http://stackoverflow.com/comment/87210060
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50095511
has text: @WillemVanOnsem, yes, It must raise an AttributeError.
score: 0

http://stackoverflow.com/q/50206431
has answer: http://stackoverflow.com/a/50206494
tagged with: dataframe
tagged with: python
tagged with: split
has body: I have a dataframe column with pairs of data, LHS is the column name, RHS is the column value: display(df_Normal.head(1)) Data 0 {'MktUMidInit': 'a', 'ProdTemplateName': '', 'ForwardPriceDrop': '99.10', 'CoverPrice': '99.20 'CustParentCdr': '', ...} Desired output: Data MktUMidInit ProdTemplateName ForwardPriceDrop CoverPrice CustParentCdr... a 99.10 99.20 There are over fifty pairs of data in each row df.head(1).to_dict() {'Data': {0: {'Action': 'CustAcceptedQuote', 'AllQ': '104.643', 'AutoNegDealerMidValue': '0', 'AutoNegDealerSpread': '0', 'AutoNegDealerValue': '-1', 'ClearingChannel': '', 'ClearingCode': '', 'ClearingHouse': '', 'ClearingMember': '', 'ClearingModel': '', 'CneResultMessage': '', 'Code': 'AU3TB0000036', 'Commission': '', }}} I was thinking of first splitting on the comma then trasposing. The split command appears not to work on the data: dfSplit = df_Normal['Data'].str.split(',', 1, expand=True) display(dfSplit.head(1)) NaN For the traspose I looks at df.set_index but this errored. and Any suggestions ?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87430073
accepted answer: http://stackoverflow.com/a/50206494
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has title: Dataframe Split and transpose such that the leftmost value becomes the header
has comment: http://stackoverflow.com/comment/87430025
type: Question
tagged with: pandas

http://stackoverflow.com/a/50108722
accepted answer of: http://stackoverflow.com/q/50108583
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50108583
has body: Since you are generating a pd.MultiIndex, you must use a tuple in sort_values. Try: df2.sort_values(('Z','amin'))
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/50121426
has comment: http://stackoverflow.com/comment/87260698
has comment: http://stackoverflow.com/comment/87260862
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87260692
answers question: http://stackoverflow.com/q/50121369
has comment: http://stackoverflow.com/comment/87260809
has body: What you're trying to write here doesn't quite make sense: def new_q(question_text = '', offset=timedelta(**kwargs)): This creates a default value for offset, and that value is created by calling timedelta(**kwargs) on whatever happens to be in kwargs at the time the function is defined. (Which is probably nothing at all, so you get a NameError.) What you want is something like this: def new_q(question_text = '', offset=None, **kwargs): if offset is None: offset = timedelta(**kwargs) Now you're calling timedelta when the function is called, rather than when it's defined, and using the value of kwargs passed into the function, rather than whatever value that variable has at function definition time. You could of course add some error handling, so the TypeError you get for an unknown keyword argument mentions new_q instead of timedelta, and so that it's an error to specify both offset and minutes, and so on. Also, if someone passes neither offset nor any other keyword arguments, this will create a timedelta()—which is an empty timedelta (0 seconds). Is that what you want?
type: Answer

http://stackoverflow.com/a/50094913
has comment: http://stackoverflow.com/comment/87206098
answers question: http://stackoverflow.com/q/50094765
downvote count: 2
score: 28
has body: As t.m.adam said in the comments, use bytearray.decode b = bytearray("test", encoding="utf-8") b.decode() #&gt; 'test'
upvote count: 30
type: Answer

http://stackoverflow.com/q/50115102
has title: How to make the output of OS.popen command a list of choice menu?
has comment: http://stackoverflow.com/comment/87249533
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87247335
tagged with: python-os
type: AnsweredQuestion
tagged with: python-2.6
has comment: http://stackoverflow.com/comment/87247526
has comment: http://stackoverflow.com/comment/87247576
has comment: http://stackoverflow.com/comment/87249787
accepted answer: http://stackoverflow.com/a/50116740
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50116740
has body: How to make the output of os.popen a list of choice menu options which will be used as input for another program? Note - Every time the output varies we cannot define one constant choice menu. It can be more than 10 or sometimes less than 10 elements. SG = "dzdo symaccess -sid {0} show {1} view -detail" IG = os.popen SG).read() print SG Above is the program if the output of SG has some ten elements like below: tiger lion elephant deer pigeon fox hyena leopard cheatah hippo The above elements I want to make as choice of elements like: print("1. tiger") print("2. lion") print("3. elephant") print("4. deer") . . . print("11. exit") print ("\n") choice = input('enter your choice [1-11] :') choice = int(choice) if choice ==1: ... So how do we add each element in each print statement and make it have a choice option, and how can we know the number of elements and make the same number of choices menu?
has comment: http://stackoverflow.com/comment/87248735
type: Question

http://stackoverflow.com/q/50166782
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50166802
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: selenium
has title: Add a column to a CSV that is scraped by python selenium
has body: Below is python code that extracts a CSV file from a website using selenium. When you originally go to this website (Fangraphs.com), you can export data from an "export data" link that packages the desired data in a CSV. The code essentially opens up Firefox and executes the "Export Data" button to download the CSV to a folder on my computer. Does anyone know if it is possible to insert an additional column of data to the scraped CSV? The additional column would only contain one value. For example, a column that lists the year (2018). I was thinking the Pandas package might be useful in this case, but I wasn't sure how it would interact with the selenium scraper. Thanks in advance for the advice! import sys import os import time from datetime import datetime from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile today = datetime.today() download_dir = os.getcwd() default_filepath = os.path.join(download_dir, 'Fangraphs Leaderboard.csv') desired_filepath = os.path.join(download_dir, '{}_{}_{}_steamer.csv'.format(today.year, today.month, today.day)) profile = FirefoxProfile() profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'text/csv') profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference("browser.download.dir", download_dir) profile.set_preference("browser.download.folderList", 2) driver = webdriver.Firefox(firefox_profile=profile) driver.get("https://www.fangraphs.com/projections.aspx? pos=all&amp;stats=bat&amp;type=steamer") driver.find_element_by_link_text('Export Data').click() time.sleep(10) driver.quit() if os.path.isfile(default_filepath): os.rename(default_filepath, desired_filepath) print('Renamed file {} to {}'.format(default_filepath, desired_filepath)) else: sys.exit('Error, unable to locate file at {}'.format(default_filepath))
type: Question
has answer: http://stackoverflow.com/a/50166802

http://stackoverflow.com/comment/87236855
has text: `Scope` does not mean what you think it means; the term you seem to be looking for is *range*.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50109804
type: Comment

http://stackoverflow.com/q/50081424
tagged with: jupyter-notebook
score: 0
has body: !pip install ipython-sql %load_ext sql !pip install psycopg2 import dj_database_url import psycopg2 DATABASE_URL = {'default':dj_database_url.config(default='postgresql://postgres:Roha11*@localhost:5432/postgres')} "DATABASE_URL not set" this is what I'm getting after each output
upvote count: 1
has answer: http://stackoverflow.com/a/50086089
tagged with: output
has title: Database_url not set in python code
answer count: 1
downvote count: 1
favorite count: 0
tagged with: postgresql
type: Question
tagged with: database
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50089202
answer count: 0
has comment: http://stackoverflow.com/comment/87231439
type: UnansweredQuestion
has title: Start Python executable on Windows start-up
has comment: http://stackoverflow.com/comment/87194367
has comment: http://stackoverflow.com/comment/87233712
tagged with: python
has body: I have been researching for long, trying to find how to make a .exe made with python execute itself each time that Windows starts, without having to create a setup wizard, or having to manually store the program in the Start Menu folder but I have not found anything. What I want is that, by simply executing the exe once, it auto executes on each windows start-up. It has occured to me to get the program to create a shortcut to itself, and auto store it in the start menu folder. Is that possible? Thank you very much in advance
has comment: http://stackoverflow.com/comment/87233952
linked to: http://stackoverflow.com/q/42605055
has comment: http://stackoverflow.com/comment/87247630
type: Question
has comment: http://stackoverflow.com/comment/87194447
score: 0

http://stackoverflow.com/a/50145600
has comment: http://stackoverflow.com/comment/87309837
has body: all_news = News.objects.all().order_by('-pk') to all_news = News.objects.filter(select_news__isnull=True).order_by('-pk') free advice: change bestnews1 = Best.objects.filter(select_reason="左一")[0].select_news to bestnews1 = Best.objects.filter(select_reason="左一").first() bestnews1_new = None if bestnew1 is None else bestnews1.select_news return render(request, 'index.html', { 'all_news': news, 'bestnews1_new':bestnews1_new, 'bestnews2_new':bestnews2_new, })
has comment: http://stackoverflow.com/comment/87309390
has comment: http://stackoverflow.com/comment/87309552
has comment: http://stackoverflow.com/comment/87309565
has comment: http://stackoverflow.com/comment/90750048
type: Answer
accepted answer of: http://stackoverflow.com/q/50145502
has comment: http://stackoverflow.com/comment/87309324
answers question: http://stackoverflow.com/q/50145502
has comment: http://stackoverflow.com/comment/87309344
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87309507

http://stackoverflow.com/comment/87424326
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50093900
type: Comment
has text: after adding the code, I am always getting `RuntimeError: The size of tensor a (181) must match the size of tensor b (180) at non-singleton dimension 1` error in `torch.autograd.backward` at the end of the epoch iteration, is anything in the code adding some extra parameters to the model that I have to track?

http://stackoverflow.com/a/50123343
accepted answer of: http://stackoverflow.com/q/50090252
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50090252
type: Answer
has body: Problem The character was not displayed because no location was given to add the character. Solution Replaced return m with self.add_widget(m) Snippet class GameScreen(Screen): def playy(self): print('playy fired') wimg = Basic(source='sprite.png') m = Character() m.add_widget(wimg) self.add_widget(m) Output
score: 0

http://stackoverflow.com/comment/87397134
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50189848
has text: So this circumvents the problem by suggesting `transform()` and never "loosing" the dimension in the index. What if I was given the `.mean()` dataset and had to somehow merge it?

http://stackoverflow.com/comment/87350877
score: 0
type: Comment
has text: @CWeeks glad I could help you.
type: AnswerComment
comment on: http://stackoverflow.com/a/50166267

http://stackoverflow.com/comment/87340360
has text: It's not so much "computer science" as tradeoffs among speed vs space vs complexity vs ... CPython made choices that made most sense for _it_, given that it was intended to work well with C code. Jython is an implementation running on the Java virtual machine, and behavior is different there: Java implements compacting ("get rid of holes") garbage collection, and Jython inherits that. It's not simple. Example: `id(x)` in CPython is free, because it returns x's memory address, which never changes. But it's hard for Jython, because Java may move objects in memory at any time.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50125550
type: AnswerComment

http://stackoverflow.com/q/50118097
has answer: http://stackoverflow.com/a/50120143
has comment: http://stackoverflow.com/comment/87255892
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/1355150
upvote count: 2
score: 2
answer count: 2
type: UnansweredQuestion
downvote count: 0
has title: I am trying to get all updated value in a model and send an email to users about the changes in django
has answer: http://stackoverflow.com/a/50120800
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/87255263
has body: i have a model A which has a many to one relationship with another model B,i want to be able to get send an email notification to emails which will be queried from model B any time values change in model A how can i do that in django? class ModelA(models.Model): """ model to store informations about the ModelA """ name = models.CharField(max_length=15, blank=True, unique=True) creator = models.ForeignKey(AppUser, blank=True, null=True, on_delete=models.CASCADE) periodicity = models.CharField(max_length=10, blank=False, choices=PERIODICITY_CHOICES) begin_date = models.DateField(blank=False) end_date = models.DateField(blank=True, null=True) subscription_fee = models.DecimalField(max_digits=5, decimal_places=2, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) public = models.BooleanField(default=False) maximum_sub = models.PositiveIntegerField(blank=True, null=True, validators=[MinValueValidator(2)]) def save(self): emails = [] body = """ Hello &lt;user first name or nothing&gt;, This is to notify you that ModelA you're subscribed to has been updated. Here is what has changed: &lt;field_name_1&gt;: &lt;current_value&gt; &lt;field_name_2&gt;: &lt;current_value&gt; etc... Thank you """ if self.pk is not None: modelA_id = ModelA.objects.get(pk=self.pk) modelA_members = ModelB.objects.filter(pk=modelA_ID) emails = [i for i in modelA_members.email] send_mail('ModelA change Notification', body, "noreply@example.com", [emails]) super(ModelB, self).save() # def __unicode__(self): return u'{0}'.format(self.name) class ModelB(models.Model): """ defineModelB """ modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE, blank=False) user = models.ForeignKey(AppUser, on_delete=models.CASCADE, blank=False, ) cash_out_date = models.DateField(blank=True, null=True)
favorite count: 0
type: Question

http://stackoverflow.com/comment/87832942
has text: I think that's becoming overkill. I'm really after a generic solution for all operator classes. My DAGs have operators for bash, python, emr, docker, s3 etc. I would like one uncomplicated way to test any of these operators while providing them with a dag_run.conf object.
type: Comment
comment on: http://stackoverflow.com/a/50360218
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87288265
has text: Could I ask you for a bit of explanation, maybe some links to the `ast` module docs, and maybe even a "caveats" section? (Doesn't work if the function's source code can't be accessed, doesn't detect attribute access with `getattr` or `vars` or `__dict__`, gets tripped up by assignments like `foo = c; c.bar`, if the same attribute is accessed twice it's included in the output twice, etc.) Your code is good, but the answer is not.
type: AnswerComment
score: 3
comment on: http://stackoverflow.com/a/50134712
type: Comment

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/50121222
tags question: http://stackoverflow.com/q/50174855
tags question: http://stackoverflow.com/q/50218528
tags question: http://stackoverflow.com/q/50078222
tags question: http://stackoverflow.com/q/50181896
tag name: xml
tags question: http://stackoverflow.com/q/50085833
tags question: http://stackoverflow.com/q/50159205
tags question: http://stackoverflow.com/q/50110868
type: Tag
tags question: http://stackoverflow.com/q/50203640
tags question: http://stackoverflow.com/q/50077995
tags question: http://stackoverflow.com/q/50212122
tags question: http://stackoverflow.com/q/50135592
tags question: http://stackoverflow.com/q/50176457
tags question: http://stackoverflow.com/q/50130798
tags question: http://stackoverflow.com/q/50116026
tags question: http://stackoverflow.com/q/50160821
tags question: http://stackoverflow.com/q/50132516
tags question: http://stackoverflow.com/q/50091049
tags question: http://stackoverflow.com/q/50216844
tags question: http://stackoverflow.com/q/50097547
tags question: http://stackoverflow.com/q/50158745
tags question: http://stackoverflow.com/q/50096918
tags question: http://stackoverflow.com/q/50193149
tags question: http://stackoverflow.com/q/50088032
tags question: http://stackoverflow.com/q/50077734
tags question: http://stackoverflow.com/q/50114239
tags question: http://stackoverflow.com/q/50164915
tags question: http://stackoverflow.com/q/50201769
tags question: http://stackoverflow.com/q/50129339
tags question: http://stackoverflow.com/q/50111462
tags question: http://stackoverflow.com/q/50164823

http://stackoverflow.com/q/50089541
has body: I want to run a python script in Microsoft Azure. For that purpose I followed the tutorial here. Downloaded the sample code, ran pip install -r requirements.txt, got a message that flask was installed successfully but when I ran python main.py , I get the error: Traceback (most recent call last): File "main.py", line 1, in &lt;module&gt; from flask import Flask ImportError: No module named 'flask' If I open python and run help('modules') , flask is not listed there although I supposedly just installed it. I have the same problem with other modules.
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87196010
has comment: http://stackoverflow.com/comment/87195634
tagged with: python
has answer: http://stackoverflow.com/a/50089801
has comment: http://stackoverflow.com/comment/87195471
score: 2
has comment: http://stackoverflow.com/comment/87195989
has answer: http://stackoverflow.com/a/50089728
answer count: 2
tagged with: azure
upvote count: 2
has comment: http://stackoverflow.com/comment/87196097
downvote count: 0
has title: Pip install doesn't add module to python in Microsoft Azure
tagged with: pip
favorite count: 0

http://stackoverflow.com/q/50165419
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50166963
downvote count: 0
answer count: 1
has body: I have to create a data structure to store distances from each point to every other point in a very large array of 2d-coordinates. It's easy to implement for small arrays, but beyond about 50,000 points I start running into memory issues -- not surprising, given that I'm creating an n x n matrix. Here's a simple example which works fine: import numpy as np from scipy.spatial import distance n = 2000 arr = np.random.rand(n,2) d = distance.cdist(arr,arr) cdist is fast, but is inefficient in storage since the matrix is mirrored diagonally (e.g. d[i][j] == d[j][i]). I can use np.triu(d) to convert to upper triangular, but the resulting square matrix still takes the same memory. I also don't need distances beyond a certain cutoff, so that can be helpful. The next step is to convert to a sparse matrix to save memory: from scipy import sparse max_dist = 5 dist = np.array([[0,1,3,6], [1,0,8,7], [3,8,0,4], [6,7,4,0]]) print dist array([[0, 1, 3, 6], [1, 0, 8, 7], [3, 8, 0, 4], [6, 7, 4, 0]]) dist[dist&gt;=max_dist] = 0 dist = np.triu(dist) print dist array([[0, 1, 3, 0], [0, 0, 0, 0], [0, 0, 0, 4], [0, 0, 0, 0]]) sdist = sparse.lil_matrix(dist) print sdist (0, 1) 1 (2, 3) 4 (0, 2) 3 The problem is getting to that sparse matrix quickly for a very large dataset. To reiterate, making a square matrix with cdist is the fastest way I know of to calculate distances between points, but the intermediate square matrix runs out of memory. I could break it down into more manageable chunks of rows, but then that slows things down a lot. I feel like I'm missing some obvious easy way to go directly to a sparse matrix from cdist.
favorite count: 0
accepted answer: http://stackoverflow.com/a/50166963
score: 9
type: Question
upvote count: 9
has title: Memory-efficient storage of large distance matrices
tagged with: python
has comment: http://stackoverflow.com/comment/87348786
has comment: http://stackoverflow.com/comment/87348779
tagged with: numpy

http://stackoverflow.com/comment/87329092
has text: e.g. `test $ pytest` should be `my_package $ pytest`?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50155464

http://stackoverflow.com/comment/87528056
score: 0
comment on: http://stackoverflow.com/q/50198820
type: QuestionComment
type: Comment
has text: @jpp Got it. Thank you.

http://stackoverflow.com/comment/87500613
type: Comment
comment on: http://stackoverflow.com/a/50225975
type: AnswerComment
has text: @halbe Ah, in that case, you should probably go with Paul's suggestion. :P
score: 0

http://stackoverflow.com/a/50199572
type: Answer
has body: This page is around 1MB, so spitting more than 974047 bytes (soup.prettify() adds more spaces and newlines) into the terminal at once is probably what makes it stuck. Try printing this text line by line: for line in soup.prettify().splitlines(False): print(line)
answers question: http://stackoverflow.com/q/50199452
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/87477846
comment on: http://stackoverflow.com/q/50229030
type: Comment
type: QuestionComment
has text: Thanks Salman. Your video and monitor have different aspect ratios? If yes, video is stretched or there are black bars on top and bottom?
score: 0

http://stackoverflow.com/q/50141308
accepted answer: http://stackoverflow.com/a/50141337
has answer: http://stackoverflow.com/a/50141379
possible better answer: http://stackoverflow.com/a/50141379
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87301091
has comment: http://stackoverflow.com/comment/87300874
has comment: http://stackoverflow.com/comment/87301206
has body: Is there an easy way to format a float so that there is at least one trailing digit, but allows for as many as are present? Desired output would be below: x = function(1) x = '1.0' y = function(1.1) y = '1.1' z = function(1.2345) z = '1.2345' Using '%.1f' will add the trailing zero, but it will also clip any longer values. I can probably kludge together a small function that checks if the value is an integer and adds a '.0', but that seems un-pythonic. def function(value): if int(value) == value: form_string = '%i.0' % value else: form_string = ('%f' % value).rstrip('0') return form_string Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/87300870
has comment: http://stackoverflow.com/comment/87301052
has comment: http://stackoverflow.com/comment/87300894
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87300878
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87300927
has title: How to format a minimum number of digits for a float in python
has comment: http://stackoverflow.com/comment/87300954
has answer: http://stackoverflow.com/a/50141337
upvote count: 1

http://stackoverflow.com/q/50128142
score: 0
has answer: http://stackoverflow.com/a/50240953
has title: kivy passing widget to different class
tagged with: python
tagged with: kivy
has body: I am new to kivy. I really want to make the "yes" button inside the popup of the "popup_add" class to read the listview widget inside the "invoice" class. I have searched many posts about passing widgets to different class, but all of them require having the class inside the parent class, i do not want to show the popup window unless the user clicked the button. I have extract the important codes here: python file: class invoice(BoxLayout): shop_list_input = ObjectProperty() shop_name_input = ObjectProperty() def add_shop(self): add_popup = popup_add() add_popup.open() class popup_add(Popup): def pop_yes(self, text_input,listView): store_name = text_input listView.adapter.data.extend([store_name]) listView._trigger_reset_populate() kivy file: #: import main testKivy #: import ListAdapter kivy.adapters.listadapter.ListAdapter #: import ListItemButton kivy.uix.listview.ListItemButton invoice: &lt;invoice&gt;: orientation: "vertical" padding: 10 spacing: 10 shop_name_input: shop_name shop_list_input: shop_list BoxLayout: orientation: "vertical" size_hint_y: None height: "60dp" TextInput: # i found on google to use app to allow other class to access text, is there # a way to make listview global similar to app? on_text: app.input_sentence=self.text id: shop_name size_hint: 1,1 BoxLayout: size_hint_y: None height: "40dp" Button: text: "Add Store" size_hint_x: 15 on_press: root.add_shop() # anyway to make listview widget accessible to other classes? ListView: id: shop_list adapter: ListAdapter(data=["Shop A","Shop B","Shop C"], cls=main.ShopListButton) &lt;popup_add&gt;: title: 'notification' auto_dismiss: False size_hint: .6,.3 FloatLayout: Button: text: "Yes" # here is where i want to insert listview, inside root.pop_yes. on_press: root.pop_yes(app.input_sentence) pos_hint: {"x": .2, 'y':.25} size_hint: .2, .2 Button: text: "No" on_press: root.dismiss() pos_hint: {"x": .6, 'y':.25} size_hint: .2, .2 Label: text: "Are you sure to add " + app.input_sentence pos_hint: {"x"…
type: Question
answer count: 2
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50253023
favorite count: 0

http://stackoverflow.com/a/50076052
score: 0
answers question: http://stackoverflow.com/q/50075940
has comment: http://stackoverflow.com/comment/87174551
has body: If I have checkbox defined like below: &lt;input type="checkbox" id="checkbox1"&gt; I can use javascript &lt;script&gt; var isChecked isChecked = document.getElementById("checkbox1").checked; checkbox_status= isChecked.toString() return alert_status; &lt;/script&gt;
has comment: http://stackoverflow.com/comment/87168540
type: Answer
has comment: http://stackoverflow.com/comment/87174477

http://stackoverflow.com/q/50158890
score: 2
upvote count: 2
has body: I am getting this error: AttributeError: module 'midi' has no attribute 'read_midifile' I have tried all the solutions that are available on GitHub. I have also tried to reinstall the module and the most suggested solution for python3 was: pip install git+https://github.com/vishnubob/python-mid i@feature/python3 but still, it's giving me this error. Thanks in advance.
has comment: http://stackoverflow.com/comment/87341475
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87342133
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/65050264
has title: AttributeError: module 'midi' has no attribute 'read_midifile'
tagged with: python
tagged with: midi
has comment: http://stackoverflow.com/comment/87341694
type: Question
has comment: http://stackoverflow.com/comment/87336232

http://stackoverflow.com/comment/87226048
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50104434
score: 0
has text: Where to the types come from? If they have a custom implementation of `__eq__` and such, they can pretend (even for good reason) to not be equal to anything.

http://stackoverflow.com/a/58250822
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50202238
downvote count: 0
has body: I fixed this problem with pip install --upgrade requests==2.20.1 If you see version incompatible message like following, you should try other versions. All versions are: here ERROR: docker-compose 1.24.1 has requirement requests!=2.11.0,!=2.12.2,!=2.18.0,&lt;2.21,&gt;=2.6.1, but you'll have requests 2.21.0 which is incompatible.
upvote count: 1

http://stackoverflow.com/a/50179970
accepted answer of: http://stackoverflow.com/q/50179762
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: In the line for x,line in clf.score(d2_testX, testY): you're trying to iterate over a float value returned by score(). score(X, y, sample_weight=None) ... Returns: score : float See the documentation for score for more details.
has comment: http://stackoverflow.com/comment/87377487
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50179762

http://stackoverflow.com/comment/87705998
score: 1
has text: Two quick notes: * You can rewrite `simple_segment` as a terminal, and then you can remove it from the transformer * Your grammar is lalr compatible, so you can add `parser="lalr"` for better performance.
type: Comment
comment on: http://stackoverflow.com/a/50219987
type: AnswerComment

http://stackoverflow.com/a/50094027
answers question: http://stackoverflow.com/q/50093582
has body: Have you already activated the environment for this use case? There is a long running thread about this on the GitHub conda discussion regarding conda failures various Windows 7 and higher, here: https://github.com/conda/conda/issues/626 One suggestion is: The down and dirty: Check to see if activate works in cmd.exe. If doesn't work or not acceptable--as @TurboTim shows: Powershell needs the path to each env (anaconda3\envs\someenv\py33.exe. Laborious! :p If you don't mind polluting your powershell a little, you can create a profile script which is run every time you open powershell. The below will add the functions Invoke-CmdScript, Conda-Activate, Conda-Deactivate to your powershell. See Tim's link above for why. PS C:> New-Item -Path $profile -ItemType File -Force This creates a script at: PS C:\&gt; echo $profile ...something like C:\Users\yourUser\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 Edit that script. PS C:\&gt; explorer $profile Add this code, save, and reopen powershell (or . $profile ) : function Invoke-CmdScript { param( [String] $scriptName ) $cmdLine = """$scriptName"" $args &amp; set" &amp; $Env:SystemRoot\system32\cmd.exe /c $cmdLine | Select-String '^([^=]*)=(.*)$' | ForEach-Object { $varName = $_.Matches[0].Groups[1].Value $varValue = $_.Matches[0].Groups[2].Value Set-Item Env:$varName $varValue } } $condaRoot = "$Env:USERPROFILE\Anaconda3" function Conda-Activate([string]$condaEnv) {Invoke-CmdScript $condaRoot\Scripts\activate.bat $condaEnv} function Conda-Deactivate {Invoke-CmdScript $condaRoot\Scripts\deactivate.bat} Usage: C:\&gt; Conda-Activate TFTheano C:\&gt; Conda-Activate root C:\&gt; conda info --envs Disclaimers: Deactivate, as written, didn't do the job for me, thus I just use Conda-Activate to move around. Also, I don't suspect there are security cautions with adding Invoke-Cmd to profile, so please chime in if 2 cents
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/87267219
score: 0
has text: It sounds like you need a data structure other than a queue, though. A queue is designed to hold more than one thing. A data structure that holds exactly one thing is quite trivial.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50121287

http://stackoverflow.com/comment/87396380
has text: All, I have updated my response with code and current output.
score: 0
comment on: http://stackoverflow.com/q/50189659
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50147246
has body: If a point is described as P(v,t). A = (3,1) and B = (10,5). Thus any C(v,t) = A(v) + (B(v)-A(v)) * ((C(t)-A(t)) : (B(t)-A(t)). A(v,1) = 3 C(v,2) = 3 + (10-3) * ((2-1):(5-1)) = 4,75 C(v,3) = 3 + (10-3) * ((3-1):(5-1)) = 6,5 C(v,4) = 3 + (10-3) * ((4-1):(5-1)) = 8,25 B(v,5) = 10
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50146978

http://stackoverflow.com/comment/87348476
type: Comment
type: AnswerComment
has text: This solved it, i didnt knew i can use two findAll like that. Thanks!
comment on: http://stackoverflow.com/a/50165058
score: 0

opencsv
tag name: opencsv
type: Tag
tags question: http://stackoverflow.com/q/50173419

http://stackoverflow.com/comment/87379961
type: QuestionComment
has text: try printing `range`. What does it look like?
comment on: http://stackoverflow.com/q/50179510
score: 1
type: Comment

http://stackoverflow.com/q/50134859
has comment: http://stackoverflow.com/comment/87370552
tagged with: logging
type: Question
has body: I have a python pipeline code which calls around 10 to 12 python classes. I wanted to know and log time consumed by each method in each class. Could anyone suggest some methods to do this in python I'm using python inbuilt logging module for logging
has comment: http://stackoverflow.com/comment/87353653
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87318319
has comment: http://stackoverflow.com/comment/87329329
tagged with: python
has comment: http://stackoverflow.com/comment/87289787
has title: How can we log time spend by each module in a large pipeline in python.
has comment: http://stackoverflow.com/comment/87296651
has comment: http://stackoverflow.com/comment/87361246
score: 0
has answer: http://stackoverflow.com/a/50135260
has comment: http://stackoverflow.com/comment/87287665
tagged with: profiling
tagged with: performance-testing
answer count: 1

http://stackoverflow.com/q/50150398
upvote count: 2
type: UnansweredQuestion
has body: When I am using PHP I can connect to the phpMyAdmin at the localhost simply by writing the following lines in my php script: &lt;?php $dbServername = 'localhost'; $dbUsername = 'root'; $dbPassword = ''; $dbName = 'Work'; $conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName); ?&gt; (The directory of this script is /Users/User/.bitnami/stackman/machines/xampp/volumes/root/htdocs/index.php) Before running the above lines, I have firstly activated XAMPP and I have enabled port localhost:8080. phpMyAdmin is located at http://localhost:8080/phpmyadmin/. This connects perfectly fine to the database. Now, in Python I have downloaded PyMySQL and I have written the following lines to do the same simple task: import pymysql conn = pymysql.connect(host='localhost', user='root', password='', db='Work') (The directory of this script is /Users/User/PycharmProjects/First/Main.py) However, when I try to run this (after I have firstly activated XAMPP and I have enabled port localhost:8080) I am getting the following error: Traceback (most recent call last): File "/Users/User/Library/Python/3.6/lib/python/site-packages/pymysql/connections.py", line 920, in connect **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 724, in create_connection raise err File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 713, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/User/PycharmProjects/GCP-OCR/Main.py", line 14, in &lt;module&gt; conn = pymysql.connect(host='localhost', user='root', password='', db='Work') File "/Users/User/Library/Python/3.6/lib/python/site-packages/pymysql/__init__.py", line 90, in Connect return Connection(*args, **kwargs) File "/Users/User/Library/Python/3.6/lib/python/site-packages/pymysql/connections.py", line 699, in _…
has comment: http://stackoverflow.com/comment/87360328
downvote count: 0
has comment: http://stackoverflow.com/comment/87319309
tagged with: mysql
has answer: http://stackoverflow.com/a/50179250
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55984880
has comment: http://stackoverflow.com/comment/98618450
has comment: http://stackoverflow.com/comment/87318569
has comment: http://stackoverflow.com/comment/87333436
has comment: http://stackoverflow.com/comment/87319167
tagged with: python
has comment: http://stackoverflow.com/comment/87319263
has comment: http://stackoverflow.com/comment/87319039
has comment: http://stackoverflow.com/comment/87319373
has title: Python script (PyMySQL) does not connect to database on localhost
score: 2
has comment: http://stackoverflow.com/comment/87360606
answer count: 2

http://stackoverflow.com/comment/87372313
type: Comment
comment on: http://stackoverflow.com/a/50167856
score: 0
type: AnswerComment
has text: @KunalJathal Do you have a specific use case in mind or are you asking for the sake of asking? If you really don't have a concrete use case then I'm sorry, but I'm not about to go writing a blog post to enumerate all the use cases for you because there are thousands.

http://stackoverflow.com/a/50185856
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50185696
type: Answer
has body: Perhaps I misunderstand your question but the items in filtered_list are already references to the same objects held in Heroes. No copy of the objects have been made. Modifications to the objects in filtered_list will also be visible if accessing the objects in heroes because they refer to the same objects. &gt;&gt;&gt; h = Hero() &gt;&gt;&gt; l1 = [h] &gt;&gt;&gt; l2 = [x for x in l1 if x._alive] &gt;&gt;&gt; l1[0] is l2[0] # are they same object? True &gt;&gt;&gt; l2[0]._active = False &gt;&gt;&gt; l1[0]._active False &gt;&gt;&gt; l1[0] is l2[0] # are they still same object? True They are the same object, hence the list is storing references to the objects, not the objects themselves, and no copy of the object is made by the list comprehension.
answers question: http://stackoverflow.com/q/50185696
upvote count: 1

http://stackoverflow.com/comment/87397783
type: Comment
type: AnswerComment
has text: I havent installed logging through pypi- i was assuming that i needed to.
score: 0
comment on: http://stackoverflow.com/a/50190004

http://stackoverflow.com/comment/87443843
comment on: http://stackoverflow.com/q/50076900
has text: Sorry, it was a little confusing! My question is: is there a way to only predict the verbs? Because when I run the model, the predicted classes are composed mostly of closed classes words, such as 'in', 'all', 'the' and so on! My training set is composed by sentences, my test set is composed by sentences without verbs and my labels are the verbs. I changed the output layer to be the size of the label classes.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87401569
comment on: http://stackoverflow.com/q/50191997
type: Comment
has text: Hey Daniel, am I not using 2 bytes? I'm not sure how to fix this thing, it's really simpler using GameMaker and I'm searching for 2 days without any luck of an answer...
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87310643
type: QuestionComment
score: 0
has text: np.equal returns .... Output array of bools, or a single bool if x1 and x2 are scalars. Adding is different
comment on: http://stackoverflow.com/q/50146213
type: Comment

http://stackoverflow.com/q/50201412
has comment: http://stackoverflow.com/comment/87419459
type: UnansweredQuestion
has body: I apologize in advance if a topic like this has already been made, if so, please link me to it, thank you. So, I have been trying to create a multiple choice quiz in python (yes, very iconic) but when I try to run it, I get a syntax error which is common I suppose, however, it seems to have an issue with the print variable: print ('QUESTION 1: WHAT IS A NON-MOVING OBJECT CALLED?\n') print ('A. Solid') print ('B. Still object') print ('C. Stationery') print ('D. not moving') print ('E. Stationary') print ('') Q1answer = "E" Q1response= input('Your answer : ') if (Q1response != Q1answer): print ('Sorry! It appears that your answer is incorrect! A non-moving object is called Stationary.') print ('Better luck next time!' , answer) else: print ('Well done! ' + Q1response + ' is correct!') score = score + 1 print ("Even I got that one right!" **print("Your current score is ' str(score) + ' out of 10")** print ('\n-----------------------------------------------------------\n') the print variable for showing the score you get out of 10 doesn't seem to work. Am I doing something wrong? It'd be a great help if someone could tell me, I'm not very good at coding.
tagged with: python
has comment: http://stackoverflow.com/comment/87419701
has comment: http://stackoverflow.com/comment/87419439
has answer: http://stackoverflow.com/a/50201511
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87419387
has title: How to fix a print error in python for a multiple choice quiz?
type: Question
has answer: http://stackoverflow.com/a/76493100
has comment: http://stackoverflow.com/comment/87419615

http://stackoverflow.com/q/50223488
answer count: 1
tagged with: django
has title: Elasticsearch-dsl nested queries
has answer: http://stackoverflow.com/a/50233969
has body: I am using the elasticsearch-dsl library in my Django project to index data and then query it back. I have the following models: class Comments(models.Model): comment_id = models.CharField(max_length=1000,blank=True,null=True) user_post_id = models.ForeignKey('UserPosts',null=True) score = models.CharField(max_length=1000,blank=True,null=True) text = models.TextField(blank=True,null=True) creation_date = models.CharField(max_length=1000,blank=True,null=True) def __unicode__(self): return self.comment_id def indexing(self): obj = CommentsIndex( meta={'id': self.id}, comment_id=self.comment_id, user_post_id=self.user_post_id, score=self.score, text=self.text, creation_date=self.creation_date, ) obj.save(index='comments-index') return obj.to_dict(include_meta=True) class UserPosts(models.Model): user_post_id = models.CharField(max_length = 1000 , blank = True , null = True) user_post_type_id = models.CharField(max_length = 1000 , blank = True , null = True) accepted_answer_id = models.CharField(max_length = 1000 , blank = True , null = True) creation_date = models.CharField(max_length=1000,blank = True , null = True) score = models.CharField(max_length = 1000 , blank = True , null = True) view_count = models.CharField(max_length = 1000 , blank = True , null = True) body = models.TextField( blank = True , null = True) last_editor_user_id = models.CharField(max_length = 1000 , blank = True , null = True) last_editor_display_name = models.CharField(max_length = 1000 , blank = True , null = True) last_edit_date = models.CharField(max_length = 1000 , blank = True , null = True) last_activity_date =models.CharField(max_length = 1000 , blank = True , null = True) title = models.CharField(max_length = 1000 , blank = True , null = True) tags = models.CharField(max_length = 1000 , blank = True , null = True) answer_count = models.CharField(max_length = 1000 , blank = True , null = True) comment_count = models.CharField(max_length = 1000 , blank = True , null = True) favorite_cou…
tagged with: elasticsearch
tagged with: python
tagged with: elasticsearch-dsl
linked to: http://stackoverflow.com/q/50252992
favorite count: 0
type: Question
score: 5
upvote count: 5
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50146426
tagged with: socket.io
type: Question
has title: python SocketIO-client and nodejs socket.io server namespace mismatch
type: UnansweredQuestion
tagged with: python
tagged with: namespaces
tagged with: node.js
score: 0
has answer: http://stackoverflow.com/a/52699844
answer count: 1
has body: My backend (nodejs) server defines a new namespace by var clients = io.of('/clients'). It looks something like this: clients.on('connection', function(socket) { socket.on('descriptor', function(data) { // do something cool here } }); My python client looks something like this: from socketIO_client import SocketIO, class ClientNameSpace(BaseNamespace): def on_connect(self): logger.info("connected") socketIO.emit("descriptor", "some cool data") socketIO = SocketIO('127.0.0.1', 80) clientSocket = socketIO.define(ClientNameSpace, '/clients') socketIO.wait() Running this code, the descriptor method in the server never gets called (I assume to it not being in the /clients namespace). But I can't use clientSocket inside ClientNameSpace as it says it is not defined. I assume the class gets activated as soon as the SocketIO() constructor gets activated and clientSocket does not get created until after.

http://stackoverflow.com/q/50126154
downvote count: 1
has body: I have two dataframes: NAME base RED 3 % free 2.00 4 % freemem 0.10 5 sys1 freemem 0.20 and NAME 0 sys1 1 sys2 There are other columns, which must also exist in the output dataframe, but they don't contain key values, and only one non-key is kept for clarity of description. I want to merge them together to form permutations of 'base' and 'red' for each value in name. The sticky point is that if a value from df2.NAME appears as a value in df1.NAME, precedence should be given to that row when forming the merge. Otherwise, the values for 'red' should be taken from the row whose name is '%'. Eg, for the values above, I'd like the output to look like: NAME base RED 0 sys1 free 2.00 1 sys1 freemem 0.20 2 sys2 free 2.00 3 sys2 freemem 0.10 I can think how to do this using apply, but it seems like something that should be possible to do with a merge op for better performance. Thanks for your help.
favorite count: 0
type: Question
upvote count: 2
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
tagged with: merge
answer count: 1
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50126478
has title: pandas merge two dataframes with default value if key missing

http://stackoverflow.com/comment/87443632
score: 0
type: Comment
has text: could you add more code? I don't have monochromatic camera next to me, but I could try to spot the issue? I assume that you don't try to split your frame!
comment on: http://stackoverflow.com/a/50213290
type: AnswerComment

http://stackoverflow.com/comment/87412342
comment on: http://stackoverflow.com/a/50197771
type: AnswerComment
score: 2
has text: He is asking if it is possible to get unique numbers only, set will return both 2 and 3
type: Comment

http://stackoverflow.com/a/50177323
has comment: http://stackoverflow.com/comment/87376341
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50176471
has body: You have illegally formatted JSON. You cannot have any stray commas, so I removed them with an expression below. Example from json import dumps, loads from os import listdir from os.path import isfile, join from re import sub '''This function transforms a directory of JSON array files and returns a single-dimensional array of all of the items. ''' def build_json_array(dir): result = [] for f in listdir(dir): if isfile(join(dir, f)): with open(join(dir, f)) as json_data: json_text = sub(',\s+\]', ']', json_data.read()) # We need to repair the data result.extend(loads(json_text)) return result if __name__ == '__main__': print(dumps(build_json_array(CONFIG.DATA_DIR), indent=4)) Tip: You can run your JSON data through a Linter before loading and manipulating it. If your JSON is formed correctly, you can simply load the data directly from the file. from json import load result.extend(load(json_data)) Code golf Implemented a one-liner that utilizes list comprehension and reduces the arrays by flatting them. from functools import reduce from json import dumps, load from os import listdir from os.path import isfile, join def build_json_array(dir): return reduce(lambda x,y: x+y,(load(open(join(dir,f))) for f in listdir(dir) if isfile(join(dir,f))))
has comment: http://stackoverflow.com/comment/87373233

http://stackoverflow.com/comment/87413656
type: QuestionComment
has text: It only works in Python2 (see above).
score: 0
comment on: http://stackoverflow.com/q/50194521
type: Comment

http://stackoverflow.com/q/50216005
has comment: http://stackoverflow.com/comment/87451676
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87452291
has comment: http://stackoverflow.com/comment/87452836
has comment: http://stackoverflow.com/comment/87451601
has body: I have the following dataframe (df): ID Age Code 1111 66 C18.2 1111 66 C98.4 1111 66 I50 1111 66 D20 1112 45 C54 1112 45 C54 1113 78 N18.3 1113 78 N18.6 1113 78 N18.2 1113 78 N18.1 1113 78 N18.1 1114 52 C40 1114 52 C19 1114 52 C100 1114 52 C100 I would like to first group the data based on ID using df.groupby('ID') and then on this grouped data, I would like to apply some arithmetic and comparison operators. If those conditions are met, add a new column (df[risk]) and enter H, otherwise enter L in the new risk column. I would like to apply the following conditions on the grouped data: (Age &gt; 65) &amp; ((Code &gt;= C00.00 &amp; Code &lt;= C99.00) | (Code &gt;= N18.1 &amp; Code &lt; N18.6)) I tried to do for Age using df1=df.groupby('ID').apply(lambda x: x['Age']&gt;65) and it shows True and False for rows depending if condition is met. But I could not add H if it is True or L when it is False in a new column. The second part of the comparison is a bit more difficult as Code column contains characters and floating numbers. What I did is that I separated the characters and numbers into two additional columns using: df'Let', 'Num' = df['Code'].str.extract(r'([A-Za-z]+)([\d\.]+)', expand=True) df['Num'] = df['Num'].astype(float) and then i can select the data based on conditions using: df1 = df[(df['Age'] &gt; 65) &amp; (((df['Let']=='C') &amp; ((df['Num'] &gt;= 00.00) &amp; (df['Num'] &lt;= 99.00))) | ((df['Let']=='N') &amp; ((df['Num'] &gt;= 18.00) &amp; (df['Num'] &lt; 18.60))))] The above code writes a new dataframe based on the conditions but if you see my example df, it will only separate rows where the conditions are met (without any groupby feature) but I want all the rows of the same ID regardless of they meet the conditions or not. How could I apply similar thing on groupby object and also add H (if conditions met) or L (if conditions do not met). I would like to get the following output: ID Age Code risk 1111 66 C18.2 H 1111 66 C98.4 H 1111 66 I50 L 111…
tagged with: python
has comment: http://stackoverflow.com/comment/87450325
tagged with: comparison
tagged with: arithmetic-expressions
has comment: http://stackoverflow.com/comment/87452288
has comment: http://stackoverflow.com/comment/87452462
has title: apply arithmetic and comparison operators on groupby object
score: 0
tagged with: pandas
type: Question

http://stackoverflow.com/q/50136568
type: Question
has comment: http://stackoverflow.com/comment/87291468
tagged with: copy-paste
has comment: http://stackoverflow.com/comment/87291898
has comment: http://stackoverflow.com/comment/87297655
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87291334
has comment: http://stackoverflow.com/comment/87291520
tagged with: text-files
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87291902
has comment: http://stackoverflow.com/comment/87291318
has body: I've searched for a while for the solution, so I won't bother you, but I can't find it for my problem. I want to copy text from .txt file and paste it to another one. The problem is, I've got a bunch of these files. I've tried to do this in python, as I have the previous script to add a new line to .txt file based on the folder name, but I just can't figure it myself. So what I did so far based on research is: import os rootdir = 'FOLDERS' for subdir, dirs, files in os.walk(rootdir): for file in files: if file == 'opis.txt': source = '%s.txt' % subdir if os.path.exists(source): target = os.path.join(subdir, file) with open(source) as source_file: with open(target, 'a') as target_file: target_file.write(source_file.read()) In folder 'FOLDERS' I have .txt files that have a name as a folder containing "opis.txt" file (where I want to paste text from the text file with folder name), e.g. \FOLDERS\P.1417.1969.11.txt \FOLDERS\P.1417.1969.11\opis.txt I want to copy the line starting with "R:" (or just whole file content, as this line is the only text there) from the P.1417.1969.11.txt file and paste it to P.1417.1969.11\opis.txt I have hundreds of files and folders with corresponding names, that's why I need a script. EDIT: I've changed the code to the one that works.
has title: Copy text file content and paste it to another

http://stackoverflow.com/q/50150289
upvote count: 3
type: UnansweredQuestion
has body: I have a main Python-program called mainProgram.py. It looks like this (simplified example): import numpy as np import pandas as pd from packOne import functionOne from packTwo import functionTwo ResultOne = functionOne() ResultTwo = functionTwo() File __init__.py was also created. After running the main program mainProgram.py I received NameError: NameError: name 'np' is not defined In package PackOne.py I use some functions from NumPy, but I didn't import NumPy in the package PackOne.py. Should I also import NumPy in packOne and all other packages which I'm going to import? Are there any elegant solutions, how to import packages like NumPy or Pandas once in main python program?
downvote count: 0
has title: Import python packages like NumPy or Pandas in imported modules
has comment: http://stackoverflow.com/comment/87318367
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/100447525
has comment: http://stackoverflow.com/comment/87318644
has comment: http://stackoverflow.com/comment/87318558
tagged with: package
score: 3
tagged with: python
tagged with: module
tagged with: python-import
answer count: 0
has comment: http://stackoverflow.com/comment/87318762

http://stackoverflow.com/q/50184219
downvote count: 0
has answer: http://stackoverflow.com/a/50228069
has body: I am trying to query MS-SQL database view and convert the result to Pandas DataFrame. Below are the two different ways I tried and in both cases it is taking ~439.98 seconds (~7 minutes) in order to query and convert to DataFrame that has 415076 records (This time is for converting it to the DataFrame, not for data retrieval). This is a typical case in the data input/retrieval part of my application business logic for user request. Note: For queries that have fewer records (say in x1000's) the query result to DataFrame conversion performance is fast in both cases. query = """ SELECT * FROM db_view_name WHERE CONDITION_1 = %d AND CONDITION_2 IN (%s) """ %(int(val), ','.join(map(str, my_values_list))) con = pyodbc.connect(con_string) Case 1: cursor = con.cursor() result = cursor.execute(query) items = [dict(zip([key[0] for key in cursor.description], row)) for row in result] df = pd.DataFrame(items) Case 2: df = pd.read_sql_query(query, con) My Environment: I am using Python 3.6 with Pyramid web framework and SQLAlchemy ORM. How can I reduce the time it takes to process these many records? Any help on this problem will be greatly appreciated :)
tagged with: python
has comment: http://stackoverflow.com/comment/87386445
has comment: http://stackoverflow.com/comment/87455893
tagged with: data-science
score: 2
type: AnsweredQuestion
tagged with: data-analysis
tagged with: pandas
tagged with: sql
has comment: http://stackoverflow.com/comment/87451754
answer count: 1
accepted answer: http://stackoverflow.com/a/50228069
has comment: http://stackoverflow.com/comment/87386270
favorite count: 0
type: Question
upvote count: 2
has title: Trying to find the most efficient way to convert SQL Query to Pandas DataFrame that has large number of records

http://stackoverflow.com/comment/87409413
score: 0
comment on: http://stackoverflow.com/q/50196216
type: Comment
type: QuestionComment
has text: You just need to specify the full path so that python knows what function you're talking about help(pandas.Series.nunique)

http://stackoverflow.com/comment/87383779
type: QuestionComment
has text: @user9613318 thanks, currently unsure how to address the issue, updated with information about the producer
score: 0
comment on: http://stackoverflow.com/q/50182869
type: Comment

http://stackoverflow.com/comment/87469017
comment on: http://stackoverflow.com/a/50222161
score: 0
type: AnswerComment
type: Comment
has text: I need the neuron with the highest weight, not thw highest activation. My question is should I consider the weights only or the bias as well?

http://stackoverflow.com/q/50221008
tagged with: pandas
score: 3
has answer: http://stackoverflow.com/a/50221225
has answer: http://stackoverflow.com/a/50221272
has body: I am new to Python. I am stuck on this simple task for quite a while, but can't seem to find an answer. I have a pandas dataframe, all I am trying to do is take take a min of two columns but where one column is lagged enter code x = {'A': pd.Series([1,3,6,5,3,2]), 'B': pd.Series([4,2,8,4,4,2])} x1 = pd.DataFrame(x) x1.rolling(2).apply(lambda x: np.min(x['A'].iloc[1],x['B'].iloc[0],axis=1)) This gives me error: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices If the code works, the answer should be c = [NaN,3,2,5,3,2]
tagged with: python
type: Question
answer count: 2
upvote count: 3
type: UnansweredQuestion
has title: Min using right indexing python
downvote count: 0
favorite count: 0

printing
tags question: http://stackoverflow.com/q/50131396
tags question: http://stackoverflow.com/q/50158420
tags question: http://stackoverflow.com/q/50225015
tags question: http://stackoverflow.com/q/50162004
type: Tag
tags question: http://stackoverflow.com/q/50221412
tag name: printing
tags question: http://stackoverflow.com/q/50123161
tags question: http://stackoverflow.com/q/50150727
tags question: http://stackoverflow.com/q/50214629
tags question: http://stackoverflow.com/q/50192322

http://stackoverflow.com/q/50182001
has answer: http://stackoverflow.com/a/50182119
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87381239
tagged with: python
accepted answer: http://stackoverflow.com/a/50182119
has comment: http://stackoverflow.com/comment/87381293
has comment: http://stackoverflow.com/comment/87381478
has comment: http://stackoverflow.com/comment/87381243
has title: Error Running Django tutorial : Page not found
answer count: 1
tagged with: django
has body: I am facing trouble while running the tutorial for Django. I have attached the error details and the complete code. I am using python 3.x, django 2.0.x with anaconda distribution on python. Error details

http://stackoverflow.com/comment/87204352
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50094124
type: QuestionComment
has text: Is that really where the syntax error is? `else pass` doesn't make sense. Pass isnt a value.

http://stackoverflow.com/comment/87211650
score: 0
type: AnswerComment
has text: Look the documentation of `pypac`, there are some options on how to authenticate with a pac proxy. You are welcome!
comment on: http://stackoverflow.com/a/50096568
type: Comment

http://stackoverflow.com/comment/87266690
has text: The terminal doesn't cause the buffering. mintty uses named pipes for standard I/O (stdin, stdout, stderr) as part of its emulation of a POSIX terminal and signals such as SIGTSTP for Ctrl+Z. This works well for other MSYS2 linked programs such as cat.exe. OTOH, python.exe is a Windows console application, which by default fully buffers its output if stdin is a pipe.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50121192

http://stackoverflow.com/comment/87266571
type: QuestionComment
score: 6
has text: If you want any sort of aggregation, it turns out a dict comprehension is almost always a terrible fit. Dict comprehensions require you to specify a key's value in one expression, but doing that is clumsy and inefficient for aggregation.
comment on: http://stackoverflow.com/q/50124201
type: Comment

http://stackoverflow.com/comment/87309007
type: Comment
type: AnswerComment
has text: Hi ... Is there any way to remove first and last square bracket? [[['A'], ['V'], ['V'], ['A'], ['A']], [['C'], ['A'], ['A'], ['V'], ['B']]] in this?
comment on: http://stackoverflow.com/a/50145071
score: 0

http://stackoverflow.com/comment/87300993
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50124993
has text: I think I'm not smart enough, sorry. It is not trivial for me. I don't know what transformation and where should I apply. After researching the problem I came up with the following solution and updated my post accordingly: `centers = pca.transform(kmeans.cluster_centers_)`. But not sure if it is correct.

pyside2
tags question: http://stackoverflow.com/q/50167096
tags question: http://stackoverflow.com/q/50202328
type: Tag
tags question: http://stackoverflow.com/q/50128293
tag name: pyside2
tags question: http://stackoverflow.com/q/50160098

http://stackoverflow.com/comment/87258256
type: Comment
comment on: http://stackoverflow.com/q/50120247
score: 0
type: QuestionComment
has text: For one thing, a MCVE would not include file input at all: just hard-code your data frames. Most important, your posting must be self-contained, not depending on links. Why does your code include transcendental functions and plotting routines? How does the problem depend on those?

http://stackoverflow.com/a/50166377
has body: It's saying there's a missing comma in line 17 in one of your JSON files. Which one? There should have been more context in the error, but if not you should try to isolate it by processing smaller batches of files. Also, why would you have 700+ characters in the JSON data?
downvote count: 0
has comment: http://stackoverflow.com/comment/87350606
has comment: http://stackoverflow.com/comment/87350646
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50166308
upvote count: 1

http://stackoverflow.com/comment/96726207
type: QuestionComment
comment on: http://stackoverflow.com/q/50136482
score: 0
has text: I am facing the same problem with tensorflow 1.12 on windows 10.
type: Comment

http://stackoverflow.com/comment/87376050
has text: Are the columns tab delimited?
comment on: http://stackoverflow.com/q/50179334
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87471750
score: 0
comment on: http://stackoverflow.com/q/50226433
has text: i got negative vote
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87438632
score: 0
type: Comment
has text: @Gunther For me, Its not working. These logs are coming from Chatterbot i.e a library to debelop chatbot.
type: AnswerComment
comment on: http://stackoverflow.com/a/50184342

http://stackoverflow.com/comment/87355866
type: AnswerComment
score: 0
type: Comment
has text: Oh I see your using the `tf.Estimator`. This is a high level API which gives little low level control to the programmer. I've never used it - so you'll have to probably try something like provided here: https://stackoverflow.com/questions/48286968/how-to-get-the-default-session-for-an-estimator-in-tensorflow. In any case once you store the model - you can follow the rest of the provided steps.
comment on: http://stackoverflow.com/a/50167544

http://stackoverflow.com/q/50191406
has comment: http://stackoverflow.com/comment/87400016
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50191788
has comment: http://stackoverflow.com/comment/87399884
type: UnansweredQuestion
tagged with: python-multithreading
has body: I'm trying to develop a multithread function in python 3.6 and sometime my code freeze. from my tests I think that the problem come from os.write() or os.read(), but I don't know why. here is my code (I don't think that partialTransform() cause the freeze but I put it to understand the code): def naiveTransform(netData,**kwargs): #parralelisable part def partialTransform(debut, fin) : for i in range(debut, fin) : j = 0 #calcul of all the distances : while j &lt; nbrPoint : distance[j] = euclidianDistance(netData[i], netData[j]) j += 1 #construction of the graph : j = 0 del distance[i] while j &lt; k : nearest = min(distance, key=distance.get) del distance[nearest] #if k &gt; 1 we don't want to get always the same point. graph.append([i, nearest]) j += 1 return graph k = kwargs.get('k', 1) # valeur par défault à definir. nbrCore = kwargs.get('Core', 1) nbrPoint = len(netData) nbrPointCore = nbrPoint//nbrCore distance = dict() graph = [] #pipes r = [-1]*nbrCore w = [-1]*nbrCore pid = [-1]*nbrCore for i in range(nbrCore): r[i], w[i] = os.pipe() try: pid[i] = os.fork() except OSError: exit("Could not create a child process\n") if pid[i] == 0: if i &lt; nbrCore-1 : g = partialTransform(i*nbrPointCore, (i+1)*nbrPointCore) else : g = partialTransform(i*nbrPointCore, nbrPoint) #to be sure that there is not a forgoten point. print("write in " + str(i)) import sys print(sys.getsizeof(g)) os.write(w[i], pickle.dumps(g)) print("exit") exit() for i in range(nbrCore): print("waiting " + str(i)) finished = os.waitpid(pid[i], 0) print("received") graph += pickle.loads(os.read(r[i], 250000000)) return graph When the argument k is superior or equal to 5 the code freeze after the print(sys.getsizeof(g)) For my example case when k = 4 the size is of 33928 and for k = 5 the size is of 43040 so I don't think that it's the problem ? The number of core used don't seem to have any influence on the freeze. I'm still a beginner in python so it may be something obvious but I didn't find any si…
has comment: http://stackoverflow.com/comment/87400001
has comment: http://stackoverflow.com/comment/87399980
tagged with: python
tagged with: python-3.6
has title: multithread communication in python3.6 freeze
score: 0
has comment: http://stackoverflow.com/comment/87399960
has comment: http://stackoverflow.com/comment/87400000

http://stackoverflow.com/comment/87424458
has text: It's too big and after pd.get_dummies column count are not matching.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50203732

http://stackoverflow.com/a/50138436
has comment: http://stackoverflow.com/comment/87295728
answers question: http://stackoverflow.com/q/50138060
downvote count: 0
has comment: http://stackoverflow.com/comment/87295765
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87295647
has comment: http://stackoverflow.com/comment/139535623
has body: I found a somewhat simple way of doing it, that is possible not perfect, but it will work: def find_names_of_module(module): code = compile(open(module.__file__).read(), module.__name__, "exec") return code.co_names Sadly this does also return modules imported with from module import * or import module and also functions. You could filter it to not have modules and functions if you don't want them. If you need only the top-level variable names, here is a tweak of Tom Dalton answer that only includes top level variables: def find_names_of_module(module): with open(module.__file__) as f: code = f.read() tree = ast.parse(code) assignments = (node for node in tree.body if isinstance(node, ast.Assign)) return {target.id for a in assignments for target in a.targets}

http://stackoverflow.com/q/50162424
tagged with: format
score: 0
upvote count: 1
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87342752
has body: I am writing some code that uses matrices, and in some processes I want to display the matrix to console. I am storing the matrices as multidimensional lists. An assignment may look like: mat = [[1242,2.01],[10,42.1]] My aim is to have a function that returns a string of the array that would look like: 1242 2.01 10 42.1 The issue is that I do not know how large the matrix will be, i.e., it will not always be 2x2, it may be a 34x84. The below code shows how I have approached this, but I feel like there must be a better way to do it. size = len(mat) for i in range(size): print(('{:4d} '*(size)).format(*mat[i])) Where mat is the matrix stored as show above. Is there a better way to do this, or is this the most pythonic way to do it?
favorite count: 0
linked to: http://stackoverflow.com/q/13214809
type: Question
has comment: http://stackoverflow.com/comment/87342769
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: Formatting an unknown sized list, python
tagged with: arrays
has comment: http://stackoverflow.com/comment/87342997
has comment: http://stackoverflow.com/comment/87343101

http://stackoverflow.com/q/50188035
downvote count: 1
linked to: http://stackoverflow.com/q/49748063
score: 3
duplicate of: http://stackoverflow.com/q/49748063
tagged with: pypi
has title: pip install fails for all the packages
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/87396546
has body: I'm unable to install any python package using pip. Everything used to work perfectly until a few days back. But now I get the following errors while installing. I think the issue is because of the URLs that pip uses to fetch the wheel packages. Now I install all these packages by manually downloading the package wheels, but it's very cumbersome task. Python version: 3.5.2, OS: Ubuntu 16.04 Command: pip -v install pandas Log: Created temporary directory: /tmp/pip-ephem-wheel-cache-qfdazbyv Created temporary directory: /tmp/pip-install-sew6kypd Collecting pandas 1 location(s) to search for versions of pandas: * https://pypi.python.org/simple/pandas/ Getting page https://pypi.python.org/simple/pandas/ Looking up "https://pypi.python.org/simple/pandas/" in the cache Returning cached "301 Moved Permanently" response (ignoring date and etag information) Looking up "https://pypi.org/simple/pandas/" in the cache No cache entry available Starting new HTTPS connection (1): pypi.org Incremented Retry for (url='/simple/pandas/'): Retry(total=4, connect=None, read=None, redirect=None, status=None) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))': /simple/pandas/ Starting new HTTPS connection (2): pypi.org Incremented Retry for (url='/simple/pandas/'): Retry(total=3, connect=None, read=None, redirect=None, status=None) Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))': /simple/pandas/ Starting new HTTPS connection (3): pypi.org Incremented Retry for (url='/simple/pandas/'): Retry(total=2, connect=None, read=None, redirect=None, status=None) Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', C…
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87397966
has comment: http://stackoverflow.com/comment/87393546
tagged with: pip
tagged with: python

http://stackoverflow.com/comment/87392359
type: AnswerComment
has text: So I'm not sure if the instance of the object is available for you to look at it's account type. In your implementation, `account_type` points to the field that you've defined, not the value of an instance of a user. Ideally, I'd change `account _type` to a property, or use a post save signal to set it appropriately
type: Comment
comment on: http://stackoverflow.com/a/50187392
score: 0

http://stackoverflow.com/q/50209102
tagged with: python
upvote count: 2
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/70040982
downvote count: 0
has answer: http://stackoverflow.com/a/50209248
favorite count: 0
type: Question
has title: How to find last 24 hours data from pandas data frame
type: UnansweredQuestion
tagged with: datetime
has body: I have a data in which we have two columns, one is description and another is publishedAt. I applied sort function on publishedAt column and get the output of descending order of date. Here is the sample of my data frame: description publishedAt 13 Bitcoin price has failed to secure momentum in... 2018-05-06T15:22:22Z 16 Brian Kelly, a long-time contributor to CNBC’s... 2018-05-05T15:56:48Z 2 The bitcoin price is less than $100 away from ... 2018-05-05T13:14:45Z 12 Mati Greenspan, a senior analyst at eToro and ... 2018-05-04T16:05:37Z 52 A Singaporean startup developing ‘smart bankno... 2018-05-04T14:02:30Z 75 Cryptocurrencies are set to make a comeback on... 2018-05-03T08:10:19Z 76 The bitcoin price is hovering near its best le... 2018-04-30T16:26:57Z 74 In today’s climate of ICOs with 100 billion to... 2018-04-30T12:03:31Z 27 Investment guru Warren Buffet remains unsold o... 2018-04-29T17:22:19Z 22 The bitcoin price has increased by around $400... 2018-04-28T12:28:35Z 68 Bitcoin futures volume reached an all-time hig... 2018-04-27T16:32:44Z 14 Biotech-company-turned-cryptocurrency-investme... 2018-04-27T14:25:15Z 67 The bitcoin price has rebounded to $9,200 afte... 2018-04-27T06:24:42Z Now i want to description of last 3 hours, 6 hours, 12 hours and 24 hours. How can i find it? Thanks

http://stackoverflow.com/comment/87338076
type: Comment
type: QuestionComment
has text: You mean using the predict method as m_ann.predict(X_new)?
comment on: http://stackoverflow.com/q/50160086
score: 0

http://stackoverflow.com/a/50115627
accepted answer of: http://stackoverflow.com/q/50115038
has comment: http://stackoverflow.com/comment/87249086
answers question: http://stackoverflow.com/q/50115038
type: Answer
score: 0
type: AcceptedAnswer
has body: Okay, so the issue runs a bit deeper than the if condition being incorrect. In get_action() you effictively do not modify the actual movies_list object, but rather the local variable current, as proven by this simple test: def action_genre(): for current in movies_list: print(current) if not current["action"]: del current print(current) The second print(current) will result in an UnboundLocalError saying that current does not exist anymore, while in movies_list the entry it just deleted continues to exist. But in general, using del in loops indeed causes problems because that's how iterables and del itself behave. I encourage you to read up more on this on other sources or SO if you wish, like here. Using the answer from the provided link above, we can use list comprehension to filter the movies: def action_genre(): filtered_movies_list = [movie for movie in movies_list if movie['action']] print(filtered_movies_list) This creates a new list (so it does not modify movies_list), which includes all dictionary entries where item['action'] == True. I hope this helps.

http://stackoverflow.com/comment/117900119
has text: So, a custom cell renderer would allow to achieve this for sure but it seems massively overkill.
comment on: http://stackoverflow.com/q/50201727
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87437253
comment on: http://stackoverflow.com/a/50208821
type: Comment
score: 0
type: AnswerComment
has text: Do you mean if you have multiple *id* and *name* and you update its corresponding status and remarks, the Insert will only insert the first record? Yes?

http://stackoverflow.com/comment/87418462
type: QuestionComment
comment on: http://stackoverflow.com/q/50200696
has text: I hope you understand my intentions.
score: 0
type: Comment

performance
tags question: http://stackoverflow.com/q/50186541
tags question: http://stackoverflow.com/q/50161515
tags question: http://stackoverflow.com/q/50087315
tags question: http://stackoverflow.com/q/50105305
tags question: http://stackoverflow.com/q/50088464
tags question: http://stackoverflow.com/q/50161084
tags question: http://stackoverflow.com/q/50175671
tags question: http://stackoverflow.com/q/50225178
tags question: http://stackoverflow.com/q/50209291
tags question: http://stackoverflow.com/q/50156001
tags question: http://stackoverflow.com/q/50118786
tags question: http://stackoverflow.com/q/50095730
tags question: http://stackoverflow.com/q/50178595
tags question: http://stackoverflow.com/q/50082441
tags question: http://stackoverflow.com/q/50084497
tags question: http://stackoverflow.com/q/50119976
tags question: http://stackoverflow.com/q/50206440
tags question: http://stackoverflow.com/q/50221512
tag name: performance
tags question: http://stackoverflow.com/q/50154930
tags question: http://stackoverflow.com/q/50134545
tags question: http://stackoverflow.com/q/50227310
type: Tag
tags question: http://stackoverflow.com/q/50164743
tags question: http://stackoverflow.com/q/50211629
tags question: http://stackoverflow.com/q/50104837
tags question: http://stackoverflow.com/q/50228673

http://stackoverflow.com/a/50172996
upvote count: 1
downvote count: 0
score: 1
type: Answer
has body: re.match looks for a complete string match, which is not what you want. Your regex is also more complicated than it needs to be. The below should work. import re product_image_list = [ 'FINAL 10008_01_angle.jpeg', 'FINAL 10008_detail_B.jpeg' ] for image in product_image_list: if re.search(r"[0-9]{5}_[0-9]{2}", image): print('Match: '+ image) else: print("NO match: " + image)
answers question: http://stackoverflow.com/q/50172878

http://stackoverflow.com/comment/87271533
type: QuestionComment
has text: You're misinterpreting what non-greediness means. It means that starting at some left anchor, it will read as little as it has to to form a match. If there is any match from some left anchor, it keeps it. It does *not* mean that it will pull the left anchor to the right in order to shorten a match.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50126788

http://stackoverflow.com/q/50163219
has answer: http://stackoverflow.com/a/50265267
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50170012
has body: I am trying to run the NTT pessto pipeline that uses PyRAF. I have everything installed but when I try to test if it works I have two issues, first, the image enviroment opens but the image is never displayed. Then when I try to Edit apertures for the file I am analyzing I get the error: PANIC in /home/anaconda2/envs/iraf27/iraf/noao/bin.linux/x_apextract.e':Write to IPC with no reader I am currently using Python 2.7.15 :: Anaconda, Inc. and I also have IRAF installed. I am using a astroconda environment that I installed following the legacy software directions from: https://astroconda.readthedocs.io/en/latest/installation.html#legacy-software-stack-with-iraf I use setuptools so I don't think is an issue of PYTHONPATH If anyone could help me I would really apreciate it. Cheers.
tagged with: iraf
score: 0
has title: Image not display and error: PANIC in `/home/anaconda2/envs/iraf27/iraf/noao/bin.linux/x_apextract.e': Write to IPC with no reader
tagged with: python
type: Question
answer count: 2

http://stackoverflow.com/comment/88360644
score: 1
comment on: http://stackoverflow.com/a/50288075
type: Comment
type: AnswerComment
has text: Technically it’s the other way around—Pipenv uses Pew under the hood, so its virtualenvs are compatible with Pew :)

http://stackoverflow.com/a/76063683
score: 0
has body: I see this as a 2-step problem Step 1: Convert json to string my_string = json.dumps(my_json) Step 2: Convert string to binary string my_binary_string = my_string.encode('utf-8') Or obviously in one line my_binary_string = json.dumps(my_json).encode('utf-8')
answers question: http://stackoverflow.com/q/50083912
type: Answer

http://stackoverflow.com/a/50147126
has comment: http://stackoverflow.com/comment/87312830
upvote count: 4
has comment: http://stackoverflow.com/comment/87312979
has comment: http://stackoverflow.com/comment/87312670
has comment: http://stackoverflow.com/comment/87313199
has comment: http://stackoverflow.com/comment/87312972
type: Answer
has body: HI you can use bulk create method. This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are): Refer the document bulk-create
has comment: http://stackoverflow.com/comment/87312647
score: 4
has comment: http://stackoverflow.com/comment/87312940
has comment: http://stackoverflow.com/comment/87312815
answers question: http://stackoverflow.com/q/50147095
has comment: http://stackoverflow.com/comment/87312908
downvote count: 0
has comment: http://stackoverflow.com/comment/87312784

http://stackoverflow.com/a/50203236
score: 0
answers question: http://stackoverflow.com/q/50197609
type: Answer
has body: I researched Exclusive Join and figured out the problem. It should have been None == Comment.filename, not Picture.filename != Comment.filename. I fixed the code like below code and it is working now. session.query(Picture.filename).outerjoin(Comment).filter( None == Comment.filename, Picture.picture_type == 'photograph' ).all() The problem was the resulting table of left outer join would not have any row that meet left_field != right_field condition. The resulting rows would meet conditions left_field == right_field or None == right_field since the missing value in the right table would be marked as null in the resulting table. Below link gave me good learnings about this subject. http://www.datasavantconsulting.com/roland/sql_excl.html Thanks all for trying to help. However, I will still be open to better suggestions!!!

http://stackoverflow.com/a/50187492
score: 0
answers question: http://stackoverflow.com/q/50187177
has body: It is ok to use global constants. At the end all the first-level function and classes defined in the same module are also "global" in this sense. Using gobal variables becomes messy when different components of the system start re-assigning their values or mutate their content. In this case it's an obvious antipattern and can lead to a debugging hell.
type: Answer

http://stackoverflow.com/comment/87234246
type: Comment
comment on: http://stackoverflow.com/q/50108048
type: QuestionComment
score: 0
has text: I would use it for element-wise lookup. rels['a']['c'].

http://stackoverflow.com/comment/122610015
has text: DEPRECATED: please use new aiohttp-socks package: https://github.com/romis2012/aiohttp-socks
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/53657536

python-requests
tags question: http://stackoverflow.com/q/50202238
tags question: http://stackoverflow.com/q/50165281
tags question: http://stackoverflow.com/q/50090122
tags question: http://stackoverflow.com/q/50151435
tags question: http://stackoverflow.com/q/50195368
tags question: http://stackoverflow.com/q/50078736
tags question: http://stackoverflow.com/q/50221284
tags question: http://stackoverflow.com/q/50142357
tags question: http://stackoverflow.com/q/50225264
type: Tag
tags question: http://stackoverflow.com/q/50175793
tags question: http://stackoverflow.com/q/50188251
tags question: http://stackoverflow.com/q/50190480
tags question: http://stackoverflow.com/q/50178943
tags question: http://stackoverflow.com/q/50207157
tags question: http://stackoverflow.com/q/50105305
tags question: http://stackoverflow.com/q/50216362
tags question: http://stackoverflow.com/q/50181332
tags question: http://stackoverflow.com/q/50081793
tags question: http://stackoverflow.com/q/50187280
tags question: http://stackoverflow.com/q/50113077
tags question: http://stackoverflow.com/q/50111322
tags question: http://stackoverflow.com/q/50149940
tags question: http://stackoverflow.com/q/50154804
tags question: http://stackoverflow.com/q/50218297
tags question: http://stackoverflow.com/q/50173582
tags question: http://stackoverflow.com/q/50091130
tags question: http://stackoverflow.com/q/50111041
tags question: http://stackoverflow.com/q/50214506
tags question: http://stackoverflow.com/q/50196650
tags question: http://stackoverflow.com/q/50218268
tag name: python-requests
tags question: http://stackoverflow.com/q/50079826
tags question: http://stackoverflow.com/q/50199166
tags question: http://stackoverflow.com/q/50205818
tags question: http://stackoverflow.com/q/50213271
tags question: http://stackoverflow.com/q/50189438
tags question: http://stackoverflow.com/q/50189486
tags question: http://stackoverflow.com/q/50209990
tags question: http://stackoverflow.com/q/50178410
tags question: http://stackoverflow.com/q/50116967
tags question: http://stackoverflow.com/q/50171758

http://stackoverflow.com/a/50173106
downvote count: 0
upvote count: 1
has body: I think you can simply check the item node value and remove the one not present on your list. Here is the implementation: from lxml import etree as ET doc = ET.parse("data1.xml") arrDat = ['20072129', '67332054'] for order in doc.xpath("//SalesOrderDetail"): item = order.xpath('ItemCode') item_code = item[0].text if item_code not in arrDat: order.getparent().remove(order) doc.write('output.xml', xml_declaration=True, encoding='utf-8', method="xml")
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50172576
answers question: http://stackoverflow.com/q/50172576
type: AcceptedAnswer

http://stackoverflow.com/comment/87384373
has text: @AndrewHenle gethostbyname
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50182546
score: 0

http://stackoverflow.com/comment/87169118
comment on: http://stackoverflow.com/a/50076341
has text: Thank you for the reply, unfortunately, for this task, I cannot consider the multiplication as one opertaion, and I do need to consider the number of arithmetic operations for my calculations. I've tried to formulate with the formula of number of arithemtic operations I have, but I cannot find how to formulate the line of `result=result*a` as a function of `i` (current iteration). Also, I didnt quite understand how you got the n^log2(3) computation for the first a*a, i got n^2+2n for the first one
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/50328207
answers question: http://stackoverflow.com/q/50218268
has body: Need to open port 443 for outgoing traffic (to specific IP(s)) on Google Compute Engine instance since pip3 runs over HTTPS. Refer to GCP docs for detailed instructions on how to do it (using command line or the GUI). Get the IP of files.pythonhosted.org to set the destination IP. (This helpful comment points out the same issue with using pip3 on an AWS EC2 instance)
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/50218268
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50128691
type: Answer
has comment: http://stackoverflow.com/comment/87275365
accepted answer of: http://stackoverflow.com/q/50128665
has comment: http://stackoverflow.com/comment/87279717
score: 0
has body: Use .dt to access the datetime methods. Ex: dates = pd.to_datetime(data['Order Date']).dt.strftime('%m-%d-%Y')
has comment: http://stackoverflow.com/comment/87279730
answers question: http://stackoverflow.com/q/50128665
has comment: http://stackoverflow.com/comment/87275658
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87351619
has comment: http://stackoverflow.com/comment/87275232

http://stackoverflow.com/comment/137195373
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50155464
score: 2
has text: @Dogweather are you just venting because the import system bit you, or do you seriously mean that "if `python my_code.py` works, then `python-test-runner` should just work too"? Linking library code correctly is a Tricky Problem, and any framework that tries to handle it for you will come with heavy assumptions and restrictions on how your code can be structured which may bite you much harder.

http://stackoverflow.com/comment/87360093
has text: Thanks for the reference to your earlier post, will look into it!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50170252
type: Comment

http://stackoverflow.com/a/50205291
downvote count: 0
answers question: http://stackoverflow.com/q/50205064
has body: Since your range starts at 2, and ends at 11, this code won't work since you are stepping down by -2. You will have to START at 10 and then step down negatively instead of stepping down from 2. Below I have an example that gets you the output that you are seeking: print('Hello') for i in range(10, 1, -2): print(i) And here is your output: Hello 10 8 6 4 2
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/q/50122983
type: Question
has comment: http://stackoverflow.com/comment/87264087
has body: I have tried to implement the first is_prime-function from this answer: https://stackoverflow.com/a/17298131/6208280 # for large numbers, xrange will throw an error. # OverflowError: Python int too large to convert to C long # to get over this: def mrange(start, stop, step): while start &lt; stop: yield start start += step # benchmarked on an old single-core system with 2GB RAM. from math import sqrt def is_prime(num): if num == 2: return True if (num &lt; 2) or (num % 2 == 0): return False return all(num % i for i in mrange(3, int(sqrt(num)) + 1, 2)) Yet I have a little probleme while testing high numbers. For really high numbers, I get an overflow error: long int too large to convert to float I checked the max for float: sys.float_info.max 1.7976931348623157e+308 for is_prime(10**308) everything works fine... but for example with is_prime(10**309) there will be this overflow error (because of the float max?). Does that mean 1.7976931348623157e+308 is the limit for this kind of is_prime()-function or is there any solution to check higher numbers with the is_prime()-function? In my mind such solutions as "use decimal" will not really solve the problem, because of the lack of precision a prime number checking function will need?
has comment: http://stackoverflow.com/comment/87264503
has answer: http://stackoverflow.com/a/50123088
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
tagged with: primes
linked to: http://stackoverflow.com/q/17298130
tagged with: int
has title: Python: "long int too large to convert to float" when checking (really big) prime numbers
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/15390807
tagged with: precision

http://stackoverflow.com/comment/87271521
type: AnswerComment
has text: @IljaEverilä Yes I've just confirmed it. My bad I'll delete my comment
score: 0
comment on: http://stackoverflow.com/a/50085384
type: Comment

http://stackoverflow.com/comment/96242828
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/53492115
has text: Thanks. I've just flagged it. Should I delete this answer? Also, thanks for the tips!!

http://stackoverflow.com/a/50106927
has body: Changed in Django 1.9: In previous versions, you would pass admin.site.urls to include(). The properly way to add django admin app is from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]
score: 14
upvote count: 14
has comment: http://stackoverflow.com/comment/87231690
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50106798
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87231210
answers question: http://stackoverflow.com/q/50106798
type: Answer

http://stackoverflow.com/q/50103582
favorite count: 0
has comment: http://stackoverflow.com/comment/87224447
type: Question
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87225121
has comment: http://stackoverflow.com/comment/87224545
has body: What is the difference between `sep` and `delimiter` attributes in pandas.read_csv() method? sought an answer for the differences between sep and delimiter arguments of read_csv function of pandas. The answers and the documentation clearly stated that sep and delimiter are the same. This separation does not exist in read_fwf and to_csv to name but a few; yet exists in read_table. Nevertheless, none of the above explained why this separation is present and why it is needed. Could you please tell us what is the use of separating sep and delimiter for read_csv and read_table?
tagged with: python
has comment: http://stackoverflow.com/comment/87224744
has comment: http://stackoverflow.com/comment/87224640
linked to: http://stackoverflow.com/q/49532873
has comment: http://stackoverflow.com/comment/87224528
answer count: 0
has title: Why do 'sep' and 'delimiter' arguments exist together in read_csv and read_table of pandas?
has comment: http://stackoverflow.com/comment/87224874
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/49532873
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87290456
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50136143
has text: Can you `join()` your threads? This will block until the thread has finished.

http://stackoverflow.com/q/50119203
has title: Pipenv not resolving dependencies correctly with two sources listed
tagged with: python
type: Question
upvote count: 2
score: 2
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87255959
has answer: http://stackoverflow.com/a/50497441
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87255776
tagged with: pipenv
has body: I've got a Pipfile with two sources declared: one source is the global, public PyPI, while the other is a small local repository which hosts some private packages, but doesn't mirror PyPI itself. I've got this set up as follows: source url = "http://my.private.repo.example.com/pypi/simple" verify_ssl = false name = "private" source url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" This being in place, I use both mirrors to source packages: [packages] requests = "*" some_private_package = {version="*", index="private"} My issue is that this results in a failure to resolve some dependencies. Let's say that some_private_package depends on Flask -- which is available from public PyPI, but isn't hosted on the private repo; building some_private_package fail because Flask can't be found on the private repo, and no attemps are made to scan PyPI for it. Is there any way to get Pipenv to search for dependencies on both available sources?

http://stackoverflow.com/comment/87398893
type: AnswerComment
has text: Answer originally provided in a comment by @Divakar
type: Comment
comment on: http://stackoverflow.com/a/50191010
score: 0

http://stackoverflow.com/a/51680042
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50124466
answers question: http://stackoverflow.com/q/50124466
downvote count: 0
score: 1
has body: Here's a better result. I made the random initial samples not so close to the maximum likelihood value and run the chain for a lot more steps with fewer walkers/chains. Notice that I'm plotting the m parameter and not its exponential, as you did. The mean acceptance fraction is ~0.48, and it took about 1 min to run in my laptop. You can of course add more steps and get an even better result. import numpy as n import emcee import corner import scipy.optimize as op import matplotlib.pyplot as pl from matplotlib.ticker import MaxNLocator def sersic(x, B, r_s, m): return B * n.exp( -1.0 * (1.9992 * m - 0.3271) * ((x / r_s)**(1.0 / m) - 1.)) def lnprior(theta): B, r_s, m, lnf = theta if 0.0 &lt; B &lt; 500.0 and 0.5 &lt; m &lt; 10. and r_s &gt; 0. and -10.0 &lt; lnf &lt; 1.0: return 0.0 return -n.inf def lnlike(theta, x, y, yerr): # "least squares" B, r_s, m, lnf = theta model = sersic(x, B, r_s, m) inv_sigma2 = 1.0 / (yerr**2 + model**2 * n.exp(2 * lnf)) return -0.5 * (n.sum((y - model)**2 * inv_sigma2 - n.log(inv_sigma2))) def lnprob(theta, x, y, yerr): # kills based on priors lp = lnprior(theta) if not n.isfinite(lp): return -n.inf return lp + lnlike(theta, x, y, yerr) profile = open("testprofile.dat", 'r') # read in the data file profilelines = profile.readlines() x = n.empty(len(profilelines)) y = n.empty(len(profilelines)) yerr = n.empty(len(profilelines)) for i, line in enumerate(profilelines): col = line.split() x[i] = col[0] y[i] = col[1] yerr[i] = col[2] # Find the maximum likelihood value. chi2 = lambda *args: -2 * lnlike(*args) result = op.minimize(chi2, [50, 2.0, 0.5, 0.5], args=(x, y, yerr)) B_ml, rs_ml, m_ml, lnf_ml = result["x"] print("""Maximum likelihood result: B = {0} r_s = {1} m = {2} lnf = {3} """.format(B_ml, rs_ml, m_ml, lnf_ml)) # Set up the sampler. ndim, nwalkers = 4, 10 pos = [result["x"] + 1e-1 * n.random.randn(ndim) for i in range(nwalkers)] sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(x, y, yerr)) # Clear and run the produc…
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50135741
answer count: 2
has answer: http://stackoverflow.com/a/50141554
has comment: http://stackoverflow.com/comment/87299370
score: 7
downvote count: 0
upvote count: 7
has title: Function speed improvement: Convert ints to list of 32bit ints
favorite count: 0
has answer: http://stackoverflow.com/a/50181782
type: Question
has body: I'm looking for speedy alternatives to my function. the goal is to make a list of 32 bit integers based of any length integers. The length is explicitly given in a tuple of (value, bitlength). This is part of a bit-banging procedure for a asynchronous interface which takes 4 32 bit integers per bus transaction. All ints are unsigned, positive or zero, the length can vary between 0 and 2000 My inputs is a list of these tuples, the output should be integers with implicit 32 bit length, with the bits in sequential order. The remaining bits not fitting into 32 should also be returned. input: [(0,128),(1,12),(0,32)] output:[0, 0, 0, 0, 0x100000], 0, 12 I've spent a day or two on profiling with cProfile, and trying different methods, but I seem to be kind of stuck with functions that takes ~100k tuples in one second, which is kinda slow. Ideally i would like a 10x speedup, but I haven't got enough experience to know where to start. The ultimate goal for the speed of this is to be faster than 4M tuples per second. Thanks for any help or suggestions. the fastest i can do is: def foo(tuples): '''make a list of tuples of (int, length) into a list of 32 bit integers [1,2,3]''' length = 0 remlen = 0 remint = 0 i32list = [] for a, b in tuples: n = (remint &lt;&lt; (32-remlen)) | a #n = (a &lt;&lt; (remlen)) | remint length += b if length &gt; 32: len32 = int(length/32) for i in range(len32): i32list.append((n &gt;&gt; i*32) &amp; 0xFFFFFFFF) remint = n &gt;&gt; (len32*32) remlen = length - len32*32 length = remlen elif length == 32: appint = n &amp; 0xFFFFFFFF remint = 0 remlen = 0 length -= 32 i32list.append(appint) else: remint = n remlen = length return i32list, remint, remlen this has very similar performance: def tpli_2_32ili(tuples): '''make a list of tuples of (int, length) into a list of 32 bit integers [1,2,3]''' # binarylist = "".join([np.binary_repr(a, b) for a, b in inp]) # bin(a)[2:].rjust(b, '0') binarylist = "".join([bin(a)[2:].rjust(b, '0') for a, b in tuples]) t…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87292947

http://stackoverflow.com/comment/113598092
has text: https://github.com/machinalis/quepy
comment on: http://stackoverflow.com/q/50226219
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50202239
has answer: http://stackoverflow.com/a/50210708
has comment: http://stackoverflow.com/comment/87421228
has comment: http://stackoverflow.com/comment/87421696
has comment: http://stackoverflow.com/comment/87421624
has comment: http://stackoverflow.com/comment/87438993
type: Question
score: 2
has body: The script below filters frequencies by cutting of all frequencies larger than 6. However instead of using the seemingly correct function rfftfreq, fftfreq is being used. To my understandnig rfftfreq should be used together with rfft. Why does this code work although it uses fftfreq with rfft? import numpy as np from scipy.fftpack import rfft, irfft, fftfreq time = np.linspace(0,10,2000) signal = np.cos(5*np.pi*time) + np.cos(7*np.pi*time) W = fftfreq(signal.size, d=time[1]-time[0]) f_signal = rfft(signal) # If our original signal time was in seconds, this is now in Hz cut_f_signal = f_signal.copy() cut_f_signal[(W&lt;6)] = 0 cut_signal = irfft(cut_f_signal) Background: rfft gives an array sorting the fourier modes with real and imaginery in separate entries. Such as [R(0), R(1), I(1), ... R(N/2),I(N/2)] for R(n) and I(n) being the real and imaginery part of the fourier mode respectively. (assuming an even entry array) Therefore, rfftfreq yields an array of frequencies corresponding to this array such as (assuming an even entry array and sampling spacing of 1): [0, 1/n, 1/n, 2/n, 2/n ... n/(2n), n/(2n)] However this code works with fftfreq where the output of the function is [0, 1/n, ... n/(2n), -n/(2n), ..., -1/n] Clearly, fftfreq should lead to wrong results when used together with rfft because the frequencies and FFT bins do not match.
upvote count: 2
has comment: http://stackoverflow.com/comment/87438445
answer count: 1
downvote count: 0
has title: Python Frequency filtering with seemingly wrong frequencies
tagged with: scipy
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/87438947
type: AnsweredQuestion
tagged with: frequency
accepted answer: http://stackoverflow.com/a/50210708
has comment: http://stackoverflow.com/comment/87421308
tagged with: python

http://stackoverflow.com/q/50213563
has comment: http://stackoverflow.com/comment/87450039
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87449628
has title: redircet stdout to file using variable python 3
upvote count: 1
has answer: http://stackoverflow.com/a/50216732
has comment: http://stackoverflow.com/comment/87449052
linked to: http://stackoverflow.com/q/89228
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87449641
has comment: http://stackoverflow.com/comment/87449711
has answer: http://stackoverflow.com/a/50216423
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
downvote count: 2
has body: I want to redirect o/p of shell commands to file using variable "path" but it is not working import os, socket, shutil, subprocess host = os.popen("hostname -s").read().strip() path = "/root/" + host if os.path.exists(path): print(path, "Already exists") else: os.mkdir("Directory", path , "Created") os.system("uname -a" &gt; path/'uname') # I want to redirect o/p of shell commands to file using varibale "path" but it is not working os.system("df -hP"&gt; path/'df')

http://stackoverflow.com/comment/87170462
comment on: http://stackoverflow.com/a/50077027
type: Comment
type: AnswerComment
score: 1
has text: You divide the input file every 11 lines (10 for GDPs and country's name) in `content = [content[i:i+11] for i in range(0,len(content),11)]` and in `result` you make the calculations. You convert all numbers from strings to floats, you find the sum with `sum` and you divide by 10 to get the average. Then you use `join` to concatenate the results in a single string.

http://stackoverflow.com/comment/87183015
type: AnswerComment
comment on: http://stackoverflow.com/a/50083610
has text: what is ast here?
score: 0
type: Comment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/50162165
tags question: http://stackoverflow.com/q/50158218
tags question: http://stackoverflow.com/q/50214897
tags question: http://stackoverflow.com/q/50215931
tags question: http://stackoverflow.com/q/50202369
tags question: http://stackoverflow.com/q/50113443
tags question: http://stackoverflow.com/q/50192786
tags question: http://stackoverflow.com/q/50191395
tags question: http://stackoverflow.com/q/50078086
tags question: http://stackoverflow.com/q/50141734
tags question: http://stackoverflow.com/q/50158589
tags question: http://stackoverflow.com/q/50199145
tags question: http://stackoverflow.com/q/50211040
tags question: http://stackoverflow.com/q/50216508
tags question: http://stackoverflow.com/q/50213921
type: Tag

http://stackoverflow.com/a/50109120
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: when not form.is_valid(), you do not return any HttpResponse... def novo_material(request): current_page='material' if request.method =='POST': form = SystemInventoryUpdate(request.POST) if form.is_valid(): name=form.cleaned_data['name'] '''''' t= NewMaterial(name=name,qty=qty,unit=unit) t.save() return HttpResponseRedirect(reverse('material')) # No need to add `else` statement, the `return HttpResponseRedirect` above stops the `if` # when form is invalid, it will jump to return render, with form validations generated by Django else: form=NewMaterial() return render(request,'novo_material.html',{'form':form})
score: 2
accepted answer of: http://stackoverflow.com/q/50109084
answers question: http://stackoverflow.com/q/50109084
upvote count: 2

http://stackoverflow.com/comment/87271278
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50120507
has text: I don't see any unnamed column in the data. I have uploaded the final out.csv as a zip file on the grdive folder in case you want to take a look at it https://drive.google.com/open?id=1_1jgRS2IrnHJ_ogHYyVuRzgEnmpuQave

http://stackoverflow.com/a/50214782
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50209229
has body: Okay, so it turns out that I could not cast the result set into a Dict, however I could assign the values of the ResultSet to a new Dict by the reference to the value of each of the items I intend to include in the new Dict. For example, say the goal is to separate the items by gender the loop for the solution would be: Separate males from females in loop: for item in response: female_smile = {} male_smile = {} print("start") # Get Dicts of Females who are smiling over time if item['Gender'] == 'Female': female_smile['timestamp'] = item['timestamp'] female_smile['Store'] = item['Store'] female_smile['smile'] = item['smile'] female_smile_list.append(female_smile) # Get Dicts of Males who are smiling over time else: male_smile['timestamp'] = item['timestamp'] male_smile['Store'] = item['Store'] male_smile['smile'] = item['smile'] male_smile_list.append(male_smile) The question is not entirely answered, being "how do I cast a ResultSet to a Dict". That said the desired outcome was to form a new Dict from the ResultSet which was achieved by assigning the values of the ResultSet to a Dict.
score: 0
answers question: http://stackoverflow.com/q/50209229

http://stackoverflow.com/a/50081774
has comment: http://stackoverflow.com/comment/87181037
accepted answer of: http://stackoverflow.com/q/50081520
type: Answer
has comment: http://stackoverflow.com/comment/87180912
answers question: http://stackoverflow.com/q/50081520
has comment: http://stackoverflow.com/comment/87180899
score: 0
has comment: http://stackoverflow.com/comment/87181074
has comment: http://stackoverflow.com/comment/87181023
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87181185
has body: If input doesnt show in frame, you must scroll browser to related area for show elements.. Selenium works with remote control, so it is not parse content before load. When page load, you see everthing fine, but element cannot located, because some elements may place bottom of page and this unvisible elements cannot parse for browsers, in truth they are in the RAM (memory). Also, sleep not recommended for detect page loading, you should search in google and SO with these keywords; selenium wait for page load.
has comment: http://stackoverflow.com/comment/87181151
has comment: http://stackoverflow.com/comment/87180888

http://stackoverflow.com/a/50081755
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50081702
score: 1
type: Answer
has body: You are receiving this error because you are passing the sqrt() function a negative number. To avoid this validate when b^2 - 4ac is negative, because the square root of said result can only be obtained when it is is greater or equal to 0.

http://stackoverflow.com/a/50119244
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50119106
has body: You can use collections.defaultdict for this. Code: from collections import defaultdict G = [['a', 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h', 'i', 'j'], [({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8), ({'b', 'e'}, 1) , ({'b', 'f'}, 9), ({'c', 'f'}, 2), ({'d', 'g'}, 7), ({'d', 'h'}, 1) , ({'e', 'i'}, 2), ({'e', 'j'}, 7), ({'g', 'h'}, 2), ({'i', 'j'}, 4)]] result = defaultdict(dict) for edge in G[1]: v1, v2 = edge[0] result[v1][v2] = edge[1] result[v2][v1] = edge[1] print(result) Output: defaultdict(&lt;class 'dict'&gt;, {'a': {'b': 4, 'c': 6, 'd': 8}, 'b': {'a': 4, 'e': 1, 'f': 9}, 'c': {'a': 6, 'f': 2}, 'd': {'a': 8, 'g': 7, 'h': 1}, 'e': {'b': 1, 'i': 2, 'j': 7}, 'f': {'b': 9, 'c': 2}, 'g': {'d': 7, 'h': 2}, 'h': {'d': 1, 'g': 2}, 'i': {'e': 2, 'j': 4}, 'j': {'e': 7, 'i': 4}})
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50119106

http://stackoverflow.com/comment/87337494
comment on: http://stackoverflow.com/q/50159682
has text: why did you tag this java
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87453994
has text: That's the point, the model form *does* create the object and *does* do database validation. I don't understand what you mean about only living on the front end.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50216749

point
type: Tag
tag name: point
tags question: http://stackoverflow.com/q/50210703

aes
tag name: aes
type: Tag
tags question: http://stackoverflow.com/q/50081261

http://stackoverflow.com/comment/87246925
score: 0
has text: When I run savefig without the fname paramater, I get an error. I will edit my question to show this.
comment on: http://stackoverflow.com/q/50114882
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87429552
has text: Hey, thank you for you kind help. However, after I add your code, it has sth wrong.
score: 0
comment on: http://stackoverflow.com/a/50204991
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50119663
score: 0
has answer: http://stackoverflow.com/a/50119907
has answer: http://stackoverflow.com/a/50119783
accepted answer: http://stackoverflow.com/a/50119981
has comment: http://stackoverflow.com/comment/87257019
has comment: http://stackoverflow.com/comment/87257015
type: Question
has answer: http://stackoverflow.com/a/50120226
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I am trying to create a JSON file through a CSV. Below code creates the data however not quite where I want it to be. I have some experience in python. From my understanding the JSON file should be written like this [{},{},...,{}]. How do I?: I am able to insert the ',', however how do I remove the last ','? How do I insert '[' at the very beginning and ']' at the very end? I tried inserting it into outputfile.write('['...etc), it shows up too many places. Not include header on the first line of json file. Names.csv: id,team_name,team_members 123,Biology,"Ali Smith, Jon Doe" 234,Math,Jane Smith 345,Statistics ,"Matt P, Albert Shaw" 456,Chemistry,"Andrew M, Matt Shaw, Ali Smith" 678,Physics,"Joe Doe, Jane Smith, Ali Smith " Code: import csv import json import os with open('names.csv', 'r') as infile, open('names1.json','w') as outfile: for line in infile: row = dict() # print(row) id, team_name, *team_members = line.split(',') row["id"] = id; row["team_name"] = team_name; row["team_members"] = team_members json.dump(row,outfile) outfile.write("," + "\n" ) Output so far: {"id": "id", "team_name": "team_name", "team_members": ["team_members\n"]}, {"id": "123", "team_name": "Biology", "team_members": ["\"Ali Smith", " Jon Doe\"\n"]}, {"id": "234", "team_name": "Math", "team_members": ["Jane Smith \n"]}, {"id": "345", "team_name": "Statistics ", "team_members": ["\"Matt P", " Albert Shaw\"\n"]}, {"id": "456", "team_name": "Chemistry", "team_members": ["\"Andrew M", " Matt Shaw", " Ali Smith\"\n"]}, {"id": "678", "team_name": "Physics", "team_members": ["\"Joe Doe", " Jane Smith", " Ali Smith \""]},
has answer: http://stackoverflow.com/a/50119981
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87258423
has title: Add character and remove the last comma in a JSON file
has comment: http://stackoverflow.com/comment/87256722
has comment: http://stackoverflow.com/comment/87257400
possible better answer: http://stackoverflow.com/a/50119783

http://stackoverflow.com/a/50131547
downvote count: 1
has comment: http://stackoverflow.com/comment/87280949
answers question: http://stackoverflow.com/q/50131449
has body: You could build a new string using slices: s = "My Wurds" t = s[:4] + "o" + s[5:]
has comment: http://stackoverflow.com/comment/87281444
type: Answer
has comment: http://stackoverflow.com/comment/87281127
upvote count: 2
score: 1

http://stackoverflow.com/a/50095542
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87238515
has body: You missed return statement in sum1 function. def sum1(f: int, a, b) -&gt; int: if a &gt; b: return 0 else: return f(a) + sum1(f, a+1, b)
accepted answer of: http://stackoverflow.com/q/50093955
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50093955

http://stackoverflow.com/a/55401060
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50125472
type: Answer
has body: Came across the CondaHTTP Connection error after installing Anaconda environment on a new Windows 10 computer. I tried virtually all the recommendations above unsuccessfully! Looking up the Anaconda archives ( https://repo.continuum.io/archive/ ), I downloaded the immediate previous release .... and on installation and rebooting my PC, all is now wellscreenshot of release

http://stackoverflow.com/comment/87301284
type: Comment
has text: Something like `df.groupby(['name', 'visit', 'foo']).ngroup() + 1`?
type: QuestionComment
comment on: http://stackoverflow.com/q/50141501
score: 3

http://stackoverflow.com/q/50087442
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87190693
downvote count: 0
upvote count: 1
tagged with: import
favorite count: 0
type: Question
has title: python import from parent directories '__init__.py' file
accepted answer: http://stackoverflow.com/a/50087704
has answer: http://stackoverflow.com/a/50087704
tagged with: python
has comment: http://stackoverflow.com/comment/87190880
tagged with: flask
has body: I am working on a flask app with the following structure: . ├── app │ ├── __init__.py │ ├── forms │ │ └── login.py │ ├── models │ │ ├── __init__.py │ │ └── user.py │ ├── templates │ │ ├── base.html │ │ ├── home.html │ │ └── login.html │ └── views │ ├── __init__.py │ └── login.py in app/__init__.py I am creating an instance of the LoginManager extension: from flask import Flask from config import app_config from flask_login import LoginManager def create_app(config_mode='development'): """Wrapping app creation in factory according to specified config.""" app = Flask(__name__, template_folder='templates') ... # register login manager extension login = LoginManager(app) return app I now need to import login in app/models/user.py in order to provide the user_loader implementation: from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin from . import db from .. import login class User(UserMixin, db.Model): """User model.""" ... @login.user_loader def load_user(id): return User.query.get(int(id)) However, any attempt to do this fails with: from .. import login ImportError: cannot import name 'login' My question is: is there any way to import from a parent directories __init__.py file, or am I making some other mistake here? I tried a number of different combinations of absolute and relative imports but all yield the same result, and searched extensively on SO and google, but did not find a direct answer to my question. I would like to keep the user.py module the current directory as the directory structure is nice and concisely organized. Thanks in advance edit: clarified import location
type: AnsweredQuestion

http://stackoverflow.com/comment/87421464
has text: It is a variable in a broader sense of the word. In a module or a class object, for instance, variables are held in dictionaries. When you reference the variable, python looks it up in the namespace `__dict__`. You can reassign `"jake"` in the dict, so its variable-like in that case too. The thing you can't do is use it as a variable on the dictionary, e.g., `students.Jake`. You could even make that work if you inherit from `dict` can create your own magic methods to use it.
comment on: http://stackoverflow.com/q/50202224
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/87437365
type: AnswerComment
has text: @smci oh I also tried uninstalling ans reinstalling Qt and pyqt. it did not solve the problem.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50190086

http://stackoverflow.com/comment/87384069
score: 0
comment on: http://stackoverflow.com/q/50182459
type: Comment
has text: Thanks! @ScottMermelstein I changed it to 1 and changed the `continue` state into a `break`, and the problem of the clusters was solved. The problem that it is still very slow still exists though.
type: QuestionComment

http://stackoverflow.com/comment/87428677
score: 1
type: Comment
type: QuestionComment
has text: You are not modifying it above. You may want to change your `while True:` to simply `while h:` then you can remove your `if` condition. BTW: you shouldn't name you variables after python types (`tuple`) because you hide the type functions.
comment on: http://stackoverflow.com/q/50203965

http://stackoverflow.com/comment/87433346
comment on: http://stackoverflow.com/a/50181564
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170513/discussion-between-python-newbie-and-pm-2ring).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87399665
comment on: http://stackoverflow.com/q/50183277
has text: What you happen when there's no signal at an exact XX ms time? You need to describe the input, processing, and desired output in much more detail.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87418510
type: Comment
comment on: http://stackoverflow.com/a/50200792
type: AnswerComment
score: 0
has text: I am also trying to horizontally and vertically stack in addition to diagonal stack.

http://stackoverflow.com/a/50140025
has body: In order to convert timestamps to numeric matplotlib dates you may e.g. use data.date = date2num([dt.datetime.fromtimestamp(d) for d in data.date]) Next you would need to bring your data in the correct format for ohlc to understand it, ohlc = list(zip(date, opens, highs, lows, closes, volume)) Next you need to use a valid datetime formatter, e.g. ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m %H')) Finally you need to adjust the width of your candles to something useful, e.g. width=1./24 to make them one hour wide.
score: 0
answers question: http://stackoverflow.com/q/50118203
type: Answer

http://stackoverflow.com/a/50154029
type: AcceptedAnswer
has body: Short version: Remove , state_is_tuple=False Longer version: According to tensorflow document of LSTMCell, state_is_tuple: If True, accepted and returned states are 2-tuples of the c_state and m_state. If False, they are concatenated along the column axis. This latter behavior will soon be deprecated. And LSTMStateTuple Stores two elements: (c, h), in that order. Where c is the hidden state and h is the output. Only used when state_is_tuple=True. So I suggest change cell_fw = tf.contrib.rnn.LSTMCell(self._hps.hidden_dim.value, initializer=self.rand_unif_init, state_is_tuple=False) to cell_fw = tf.contrib.rnn.LSTMCell(self._hps.hidden_dim.value, initializer=self.rand_unif_init)
type: Answer
accepted answer of: http://stackoverflow.com/q/50153105
score: 0
answers question: http://stackoverflow.com/q/50153105

http://stackoverflow.com/comment/87268424
has text: `$_` is whatever you piped in - since you're already passing bare strings, `$_` will be a string, yes :)
type: Comment
comment on: http://stackoverflow.com/a/50124958
score: 0
type: AnswerComment

http://stackoverflow.com/q/50079165
has answer: http://stackoverflow.com/a/50079674
has body: The following code works in Python 3.6.1 ... but returns this error in Python 3.6.5: Traceback (most recent call last): File "G:/GOOD/Coding/Deepthroat/Deepthroat2/Bin/Testing/gh.py", line 36, in &lt;module&gt; loops.start() File "C:\Program Files\Python36\lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Program Files\Python36\lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Program Files\Python36\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "C:\Program Files\Python36\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__ reduction.dump(process_obj, to_child) File "C:\Program Files\Python36\lib\multiprocessing\reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) _pickle.PicklingError: Can't pickle &lt;function loops at 0x0000019D3E30B598&gt;: it's not the same object as __main__.loops Here is the code: from multiprocessing import Process import time def timeout(mm): for i in range(6): time.sleep(0.1) print('stop all bla loops now') mm.terminate() return def loops(): for i in range(5): time.sleep(0.1) print('loop1') billy = 'loop1 done' for i in range(5): time.sleep(0.1) print('loop2') billy = 'loop2 done' for i in range(5): time.sleep(0.1) print('loop3') billy = 'loop3 done' billy = 'cool' loops = Process(target=loops) loops.start() timeout = Process(target=timeout(loops)) timeout.start()
tagged with: process
has comment: http://stackoverflow.com/comment/87175329
has answer: http://stackoverflow.com/a/73800768
tagged with: multiprocessing
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50079674
possible better answer: http://stackoverflow.com/a/73800768
tagged with: python
has title: multiprocessing PicklingError in Python 3.6.5 that doesn't occur in 3.6.1
has comment: http://stackoverflow.com/comment/87174436
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87177484
answer count: 2

http://stackoverflow.com/comment/87321268
type: Comment
has text: Yup i copied your code and this is the result: https://imgur.com/wgDn9oa version: 2.2.2
comment on: http://stackoverflow.com/a/50151352
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87210010
comment on: http://stackoverflow.com/a/50096723
has text: hi, I don't know but I tried it again and it work thanks
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50116967
has title: Error sending html email with mailgun python API
has answer: http://stackoverflow.com/a/50117801
type: Question
has body: I can send text email with the Mailgun python API fine: def send_simple_message(mailtext, filename=""): requests.post("https://api.mailgun.net/v3/mydomain.in/messages", auth=("api", "key-1234"), files=[("attachment", open(filename))], data={"from": "Credit Card Manager <creditcards@mydomain.in>", "to": ["bob@mydomain.in"], "subject": "Summary of Credit Card payments due", "text": mailtext}) The above code works fine, and message is delivered. However when I try the following, using an html string, def send_simple_message(mailtext, mailhtml, filename=""): requests.post("https://api.mailgun.net/v3/mydomain.in/messages", auth=("api", "key-61a652b57"), files=[("attachment", open(filename))], data={"from": "Credit Card Manager <creditcards@mydomain.in>", "to": ["bob@mydomain.in"], "subject": "Summary of Credit Card payments due", "text": mailtext, "html": mailhtml}) where, mailhtml is the following string: CREDIT CARD STATEMENT FOR MAY Card Dues Date Standard Chartered 3,755.29 16/05/2018 HDFC 41,616.90 04/05/2018 ICICI 5,833.74 11/05/2018 SBI 20,667.00 01/05/2018 I get the following error: Traceback (most recent call last): File "getcreditcards.py", line 611, in <module> send_simple_message(txtbody, htmlbody, os.getcwd() + '/' + excelfilename) File "getcreditcards.py", line 484, in send_simple_message "html": mailhtml File "/usr/lib/python3/dist-packages/requests/api.py", line 112, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/lib/python3/dist-packages/requests/api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "/usr/lib/python3/dist-packages/requests/sessions.py", line 488, in request prep = self.prepare_request(req) File "/usr/lib/python3/dist-packages/requests/sessions.py", line 431, in prepare_request hooks=merge_hooks(request.hooks, self.hooks), File "/usr/lib/python3/dist-packages/requests/models.py", line 308, in prepare self.prepare_body(data, files, json) File "/usr/lib/python3/dist-packag…
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: python-requests
tagged with: mailgun
tagged with: python

http://stackoverflow.com/q/50112001
type: Question
type: UnansweredQuestion
tagged with: python
has title: In pandas Series data, how do you get the keys based on data the function returns?
has answer: http://stackoverflow.com/a/50112396
tagged with: pandas
score: 1
has body: I have a working script that creates an array of each line of text in a file. This data is passed to a pandas Series(). The function startswith("\n") is used to return boolean True or False for each string, to determine if it begins with \n (a blank line). I am currently using a counter i and a conditional statement to iterate through and match position the startswith() function is returning. import pandas as pd import numpy as np f = open('list-of-strings.txt','r') lines = [] for line in f.xreadlines(): lines.append(line) s = pd.Series(lines) i = 0 for b in s.str.startswith("\n"): if b == 0: print s[i],; i += 1 else: i += 1 I've realized I am looking at this from two different approahces. One being to to directly handle each item as it is evaluated by the startswith() function. Since the startswith() function returns boolean values, it is possible to allow direct handling of data based on the values returned. Something like for each item in startswith(), if value returned is True, index = current_index, print s[index]. In addition to being able to print only the strings that are evaluated as False by startswith(), how would I get the current key value from startswith()? References: https://www.tutorialspoint.com/python_pandas/python_pandas_series.htm https://www.tutorialspoint.com/python_pandas/python_pandas_working_with_text_data.htm
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87227087
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50104938
type: QuestionComment
has text: if you have to ask questions like this, you're likely doing it wrong. Consider re-engineering your code.

http://stackoverflow.com/a/50088722
answers question: http://stackoverflow.com/q/50088108
type: Answer
score: 0
has body: The biggest challenge here is that "#" is used as a token separator and as the space character, you have to know the context to tell which you've got at any given time, and that makes it difficult to simply split the string. So write a simple parser. This one will accept anything as the first character in a token and then grab everything until it sees the next "#". ABSTRACT ={"A":"1","B":"2","C":"3","D":"4","E":"5","F":"6","G":"7","H":"8","I":"9", "J":"10","K":"11","L":"12","M":"13","N":"14","O":"15","P":"16","Q":"17","R":"18","S":"19","T":"20","U":"21","V":"22","W":"23", "X":"24","Y":"25","Z":"26", " ":"###","":"#" } ABSTRACT_SHIFTED = {value:key for key,value in ABSTRACT.items()} user_input = "8#15#23###23#1#19###9#20" def from_abstract(s): result = [] while s: print 'try', s # tokens are terminated with # idx = s.find("#") # ...except at end of line if idx == -1: idx = len(s) - 1 token = s[:idx] s = s[idx+1:] result.append(ABSTRACT_SHIFTED.get(token, ' ')) return ''.join(result) print from_abstract(user_input)

http://stackoverflow.com/comment/87256868
score: 0
comment on: http://stackoverflow.com/q/50119123
type: Comment
has text: Without looking in detail into the code here, I seems this is similar to [How to add Roulette Wheel background image to matplotlib Radar Chart](https://stackoverflow.com/questions/49554591/how-to-add-roulette-wheel-background-image-to-matplotlib-radar-chart).
type: QuestionComment

http://stackoverflow.com/a/50167669
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50161427
has body: Since you want to process multiple templates, you need to make your load_args capable of handling multiple --template= arguments/options. I adapted your load_args to return a dict with values that are lists, but the check on number of arguments allowed (multiple templates, single YAML file) is crude. For processing your commandline you should look at the standard arparse module, where you can indicate per argument/option that it can occur multiple times. Since you are going to reuse the data from YAML, load it only once, outside of the call make(). There is no excuse for not using safe_load() instead of the documented unsafe load(). With: #Import necessary functions from Jinja2 module from jinja2 import Environment, FileSystemLoader #Import YAML module import yaml import sys ALLOWED_ARGS = set(['template', 'data']) def print_usage(): print('Wrong arguments: Usage: configplate.py --template=&lt;template.jinja&gt; --data=&lt;data.yaml&gt;') def load_args(args): out = {} for arg in args: if arg == __file__: #ignore the filename argument continue args_split = arg.split('=', 1) out.setdefault(args_split[0].lstrip('-'), []).append(args_split[1]) if (set(out.keys()) != set(ALLOWED_ARGS)) or len(out['data']) != 1: print_usage() raise ValueError('Required argument not present.') return out def make(template, data): #Load Jinja2 templates env = Environment(loader = FileSystemLoader('.'), trim_blocks=True, lstrip_blocks=True) template = env.get_template(template) #Render the template with data and print the output return template.render(data) sys.argv=[ __file__, '--template=config1.jinja', '--template=config2.jinja', '--data=data.yaml' ] if __name__ == '__main__': if len(sys.argv) &lt; 4: print_usage() else: args = load_args(sys.argv) # Load data from YAML into Python dictionary **once** and **safely** config_data = yaml.safe_load(open(args['data'][0])) for template_file in args['template']: res = make(template_file, config_data) print(res) And the appropriate files you get: …
answers question: http://stackoverflow.com/q/50161427

http://stackoverflow.com/q/50194519
type: Question
has answer: http://stackoverflow.com/a/50194560
linked to: http://stackoverflow.com/q/26910708
has answer: http://stackoverflow.com/a/50194552
has title: Consolidate python dictionary
type: UnansweredQuestion
tagged with: python
has body: I need help converting these dictionaries to a single dictionary. See below data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}] I want to convert it to below: {'x':[3,5,1], 'y':[3,3,4] thank you!
has comment: http://stackoverflow.com/comment/87406204
score: 0
linked to: http://stackoverflow.com/q/5946236
answer count: 2
has comment: http://stackoverflow.com/comment/87406212
duplicate of: http://stackoverflow.com/q/5946236

http://stackoverflow.com/a/50190380
score: 2
has comment: http://stackoverflow.com/comment/87400266
upvote count: 2
answers question: http://stackoverflow.com/q/50190283
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can write your own product method which finds out the cartesian product of multiple lists. def cartesian_product(*lists): result = [[]] for list in lists: result = [x + [y] for x in result for y in list] return result l = [1, 2, 3] lst = [l for i in l] x = cartesian_product(*lst) for tuple in x: print(tuple) Output (1, 1) (1, 2) (2, 1) (2, 2)
has comment: http://stackoverflow.com/comment/87397554
accepted answer of: http://stackoverflow.com/q/50190283
has comment: http://stackoverflow.com/comment/87400531

http://stackoverflow.com/q/50079921
has answer: http://stackoverflow.com/a/50080016
has title: create a dubs duplication item in a list comprehension in python
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87175808
has body: I want to create a duplication item in a list comprehension in python In Python you can have multiple iterators in a list comprehension, like [(x,y) for x in a for y in b] for some suitable sequences a and b. I'm aware of the loop semantics of Python's list comprehensions. My question is: Can an iterator in the comprehension refer to the other? In other words: Could I have something like this: arr = [1,2,3,4] dubs = [] dubs = [[x] + [arr[arr.index(x)]] for x in ] dubs = [x for l in dubs for x in l] As an example, if I have a simple list: arr = [1,2,3,4] what would the list comprehension expression be to achieve this result: dubs = [1, 1, 2, 2, 3, 3, 4, 4] Please only list comprehension answers.
tagged with: python
has answer: http://stackoverflow.com/a/50080051
accepted answer: http://stackoverflow.com/a/50080051
has comment: http://stackoverflow.com/comment/87175929
tagged with: list-comprehension
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/87175996
answer count: 3
has comment: http://stackoverflow.com/comment/87175930
has answer: http://stackoverflow.com/a/50080158
possible better answer: http://stackoverflow.com/a/50080158

http://stackoverflow.com/comment/87445283
type: Comment
has text: Yes, but the `source` command is a bashism (and the question is tagged bash). Bash is not what `subprocess.call(..., shell=True)` uses on Windows. Thus, absent any explicit specification, it is a likely presumption that the OP is not on Windows.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50213925

http://stackoverflow.com/comment/87177142
type: QuestionComment
comment on: http://stackoverflow.com/q/50080565
type: Comment
score: 0
has text: If you're trying to parse Java source code, you probably want to build a parser at a higher level rather than a bunch of local special cases around a pile of regexes. Or use an existing Java parser.

http://stackoverflow.com/a/50222079
upvote count: 1
has body: It's not a clean solution but the cells which data I need to keep are not computationally expensive. Therefore I found it most convenient to simply do: %reset -f exec In[n:m]
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50156009
downvote count: 0

http://stackoverflow.com/comment/87399066
comment on: http://stackoverflow.com/a/50186285
score: 0
type: AnswerComment
type: Comment
has text: The machine is a macPro ,how to check if SELinux is enabled on the machine ,if not how to enable it?

http://stackoverflow.com/comment/87458661
has text: @DanielRoseman you're right. Filter method returns empty queryset when it can't find any match to filters (and True or False would be meaningful if filter returns False when nothing is found). But that is not an answer to my question. My problem is that I can't apply filter method in template and don't know alternative solution.
comment on: http://stackoverflow.com/q/50220503
type: Comment
score: 0
type: QuestionComment

django-views
tags question: http://stackoverflow.com/q/50125720
tags question: http://stackoverflow.com/q/50172456
tags question: http://stackoverflow.com/q/50228397
tags question: http://stackoverflow.com/q/50127835
tags question: http://stackoverflow.com/q/50091350
tags question: http://stackoverflow.com/q/50093408
tags question: http://stackoverflow.com/q/50174149
tags question: http://stackoverflow.com/q/50187703
tags question: http://stackoverflow.com/q/50189134
tags question: http://stackoverflow.com/q/50162139
tags question: http://stackoverflow.com/q/50091266
tags question: http://stackoverflow.com/q/50095916
tag name: django-views
tags question: http://stackoverflow.com/q/50109321
tags question: http://stackoverflow.com/q/50109084
tags question: http://stackoverflow.com/q/50214621
tags question: http://stackoverflow.com/q/50092605
tags question: http://stackoverflow.com/q/50086621
tags question: http://stackoverflow.com/q/50097688
type: Tag
tags question: http://stackoverflow.com/q/50137536
tags question: http://stackoverflow.com/q/50220221
tags question: http://stackoverflow.com/q/50158139
tags question: http://stackoverflow.com/q/50145502

http://stackoverflow.com/comment/87271814
comment on: http://stackoverflow.com/q/50126234
type: Comment
type: QuestionComment
has text: I found my path, and this is it: /Users/myname/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin so it looks like my computer is defaulting to a path that isn't really there anymore? If I try "which python" it returns "/usr/bin/python"
score: 0

http://stackoverflow.com/comment/87263793
has text: So, if it's grey, then R=G=B, correct? So, just discard Green and Blue (as they are just useless duplicates), and call the Red channel the depth and your job is done.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50119785
type: Comment

http://stackoverflow.com/a/50310459
answers question: http://stackoverflow.com/q/50175311
downvote count: 0
has body: you can use this code in Telethon V 0.19 from telethon import TelegramClient import socks from telethon.tl.functions.channels import GetParticipantsRequest api_id = XXXX api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' phone_number = '+98XXXXXXXX' ################################################ # invite link for private channel inveite_link='telegram.me/joinchat/AAAAAE84o7DErer_YqAohQ' ################################################ proxy_ip = 'YY.YY.YY.YY' proxy_username = 'proxy_username' proxy_password = 'proxy_password' proxy_port = 123456 ################################################ client = TelegramClient('session_name', api_id, api_hash, proxy=(socks.HTTP, proxy_ip, int(proxy_port), None, proxy_username, proxy_password)) assert client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) channel = client.get_entity(inveite_link) offset = 0 limit = 100 while True: participants = client(GetParticipantsRequest( channel, channel, offset, limit,hash=0)) if not participants.users: break for _user in participants.users: print('user : ', _user.id, _user.username) # save User info to Database offset += len(participants.users) I used socks. If you do not want to use socks, then remove it Because private channels do not have a username, I used invite link You can also use the ‍‍channel ID instead of invite link. In this case, you should use channel = client.get_entity(PeerChannel(channel_id)) instead of ‍‍channel = client.get_entity(inveite_link)
score: 3
has comment: http://stackoverflow.com/comment/119916671
type: Answer
upvote count: 3

k-means
tags question: http://stackoverflow.com/q/50110837
type: Tag
tags question: http://stackoverflow.com/q/50098689
tags question: http://stackoverflow.com/q/50153049
tags question: http://stackoverflow.com/q/50106516
tags question: http://stackoverflow.com/q/50138405
tags question: http://stackoverflow.com/q/50123704
tags question: http://stackoverflow.com/q/50137134
tag name: k-means
tags question: http://stackoverflow.com/q/50177981
tags question: http://stackoverflow.com/q/50146570

http://stackoverflow.com/comment/109106088
has text: Have you solved your question? How would you calculate it for the training-data? Btw. I dont think setting a threshold is very wise since keras does not use a threshold
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50075541

http://stackoverflow.com/q/50132215
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50360218
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50360218
tagged with: airflow
has body: Does anyone know if there is a way to set dag_run.conf parameters when running airflow test in the bash prompt? For example, I've downloaded the example_trigger_target_dag from the official airflow repository and I'd like to test the run_this task. Usually I would do the following: ~/$ airflow test example_trigger_target_dag run_this '2018-01-01' However running this produces the error: -------------------------------------------------------------------------------- Starting attempt 1 of 1 -------------------------------------------------------------------------------- [2018-05-02 10:50:01,154] {models.py:1342} INFO - Executing &lt;Task(PythonOperator): run_this&gt; on 2018-01-01 00:00:00 [2018-05-02 10:50:01,262] {models.py:1417} ERROR - 'NoneType' object has no attribute 'conf' Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1374, in run result = task_copy.execute(context=context) File "/usr/local/lib/python2.7/dist-packages/airflow/operators/python_operator.py", line 80, in execute return_value = self.python_callable(*self.op_args, **self.op_kwargs) File "/home/annalect/uk_ds_airflow/dags/playpen/example_trigger_target_dag.py", line 56, in run_this_func print("Remotely received value of {} for key=message".format(kwargs['dag_run'].conf['message'])) AttributeError: 'NoneType' object has no attribute 'conf' I've had a go at using the task_params argument however I either have the wrong syntax or it doesn't achieve what I'm after as it produces the same error as above: ~/$ airflow test --task_params '{"kwargs": {"dag_run": {"conf": {"message": "Hey world"}}}}' example_trigger_target_dag run_this '2018-01-01' [2018-05-02 11:10:58,065] {models.py:1441} INFO - Marking task as FAILED. [2018-05-02 11:10:58,070] {models.py:1462} ERROR - 'NoneType' object has no attribute 'conf' So does anyone know how to test a task that depends on dag_run.conf values? Thanks!
score: 13
tagged with: python
has title: Set dag_run.conf parameters in call to airflow test

http://stackoverflow.com/comment/87375491
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50179009
has text: d dictionary has no key '1'... d['1'].keys()

http://stackoverflow.com/q/50146239
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50147319
score: 0
tagged with: deep-learning
answer count: 1
has body: I'm a new here, studying tensorflow and encountering a problem. import model_method fittt(model_method.build(self,...),...parameters...) The above is in the main.py importing model_method.py. Function fittt in main.py: def fittt(model,...): model.fit(...) build() in model_method.py: def build(self,...): self.op_C,self.op_A = self.function_A(...) self.op_B = self.function_B(self.op_C,...) fit() in model_method.py: def fit(self,...): sess = tf.Session(graph=self.graph,config=config) BB,AA = sess.run([self.op_B,self.op_A],feed_dict) To check running process, I added pdb.set_trace() at the beginning of function_A() and function_B() in model_method.py as follows: def function_A(self,...): pdb.set_trace() ...... def function_B(self,...): pdb.set_trace() ...... The two pdb.set_trace() only stopped when the build() called and didn't work when sess.run([self.op_B,self.op_A],feed_dict) called. So it means the sess.run() didn't run function_A() and function_B() actually. I wonder why and wanna know how to make the two functions work?
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/50147319
has title: sess.run() does not run?

http://stackoverflow.com/comment/87369297
has text: its kinda funny that i can do such thing on windows just with one argument but in python/linux its a more complicated process
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50158512

http://stackoverflow.com/a/50135703
answers question: http://stackoverflow.com/q/50124932
type: AcceptedAnswer
type: Answer
has body: I found a few things: I'm getting an error when I call the function submit(): TypeError: submit() missing 1 required positional argument: 's' because I'm not passing any arguments when I press the button. Since you don't use the argument for anything you can write it as: def submit(*s): The star tells the function to accept zero ar more argument and to store them in s. The same thing with the stop() function. I also think maybe it is better to destroy the window than to use sys.exit(). def stop(*e): window.destroy() As you are giving these buttoans a callback function you don't need to also bind them to the mouse button s.bind('&lt;Button-1&gt;', submit) # Not necessary set up a button As for the button you can create it and then forget it until you want to display it again: t = Button(window, text='Try again', ... , command=try_again) t.grid(row=12, column=0, sticky=N) # Did not quite understand your layout t.grid_remove() # Hide the button Then in the submit() function you can show it again. if guesses == 0: ... t.grid() # It will remember its place The easiest way to store the amount of wins, losses, and guesses is what you already have, in variables. Then write the try_again() function and let it assign new values to your variables.
accepted answer of: http://stackoverflow.com/q/50124932
score: 0

http://stackoverflow.com/q/50123260
has title: Python: ValueError: setting an array element with a sequence
has answer: http://stackoverflow.com/a/50124828
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has body: I'm trying to use scikit-learn to do some ML. I am using the preprocessing module to prep my data. The data are of type float. From reading other questions regarding this issue: ValueError: setting an array element with a sequence, it's either due to wrong structure of my data or because my data is of type string. Neither seem to be the case here. Please let me know if you have any idea how to solve this issue or what it even means. Thank you. The code: print(X) pred_X = np.array(pred_X) pred_Y = np.array(pred_Y) X = np.array(X) Y = np.array(Y) X = preprocessing.scale(X) pred_X = preprocessing.scale(pred_X) print(x): [[547180.0, 120.0, 113.0, 456701.0, 1.0, 6.43, -1.0, 0.313, 0.42, 0.267 3.0, 11800.0, 607208.0, 120.0, 113.0, 456701.0, 1.0, 0.273, 0.331, 0.154, 6.0, 10300.0, 458015.0, 113.0, 120.0, 45328 6.0, 1.0, 2.54, -1.0, 0.32, 0.443, 0.257, 3.0, 92000.0, 543685.0, 120.0, 113.0, 456701.0, 1.0, 6.43, 1.0, 0.296, 0.4, 0.234, 2.0, 8800.0, 594809.0, 475582.0, 120.0, 113.0, 456701.0, 1.0, 1.0, 0.295, 0.384, 0.264, 4.0, 7700.0], [547180.0, 120.0, 113.0, 456701.0, 1.0, 6.43, -1.0, 0.313, 0.42, 0.267, 3.0, 11800.0, 607208.0, 120.0, 113.0, 456701.0, 1.0, 0.273, 0.331, 0.154, 6.0, 10300.0, 458015.0, 113.0, 120.0, 453286.0, 1.0, 2.54, -1.0, 0.32, 0.443, 0.257, 3.0, 92000.0, 543685.0, 120.0, 113.0, 456701.0, 1.0, 6.43, 1.0, 0.296, 0.4, 0.234, 2.0, 8800.0, 594809.0, 435062.0, 120.0, 113.0, 456701.0, 1.0, 1.0, 0.312, 0.364, 0.154, 5.0, 6900.0], [547180.0, 120.0, 113.0, 456701.0, 1.0, 6.43, -1.0, 0.313, 0.42, 0.267, 3.0, 11800.0, 607208.0, 120.0, 113.0, 456701.0, 1.0, 0.273, 0.331, 0.154, 6.0, 10300.0, 458015.0, 113.0, 120.0, 453286.0, 1.0, 2.54, -1.0, 0.32, 0.443, 0.257, 3.0, 92000.0, 543685.0, 120.0, 113.0, 456701.0, 1.0, 6.43, 1.0, 0.296, 0.4, 0.234, 2.0, 8800.0, 594809.0, 446308.0, 120.0, 113.0, 456701.0, 1.0, 0.0, 0.221, 0.28e, 0.115, 8.0, 6400.0]] The Error: Traceback (most recent call last): File "sampleSVM.py", line 46, in &lt;module&gt; X = preprocessing.scale(X) File …
has comment: http://stackoverflow.com/comment/87275088
linked to: http://stackoverflow.com/q/4674473
tagged with: valueerror
has comment: http://stackoverflow.com/comment/87481511
downvote count: 2
answer count: 1
tagged with: scikit-learn
upvote count: 7
favorite count: 0
type: Question
tagged with: numpy
score: 5

http://stackoverflow.com/a/50183760
has body: Two possibilities: assign the function's return value (which is a tuple) to a variable, and access its elements: var = my_func(2) var1 = var[0] var2 = var[1] var3 = var[2] or use unpacking: var1, var2, var3 = my_func(2) Re: Which method runs faster in most cases? Let's compare the disassemble (I hilighted with &gt; the differences): dis.dis('t=my_func(2);d=t[0]+t[1]+t[2]') 1 0 LOAD_NAME 0 (my_func) 2 LOAD_CONST 0 (2) 4 CALL_FUNCTION 1 &gt; 6 STORE_NAME 1 (t) 8 LOAD_NAME 1 (t) &gt; 10 LOAD_CONST 1 (0) &gt; 12 BINARY_SUBSCR 14 LOAD_NAME 1 (t) &gt; 16 LOAD_CONST 2 (1) &gt; 18 BINARY_SUBSCR 20 BINARY_ADD 22 LOAD_NAME 1 (t) &gt; 24 LOAD_CONST 0 (2) &gt; 26 BINARY_SUBSCR 28 BINARY_ADD 30 STORE_NAME 2 (d) 32 LOAD_CONST 3 (None) 34 RETURN_VALUE dis.dis('a,b,c=my_func(2);d=a+b+c') 1 0 LOAD_NAME 0 (my_func) 2 LOAD_CONST 0 (2) 4 CALL_FUNCTION 1 &gt; 6 UNPACK_SEQUENCE 3 &gt; 8 STORE_NAME 1 (a) &gt; 10 STORE_NAME 2 (b) &gt; 12 STORE_NAME 3 (c) 14 LOAD_NAME 1 (a) 16 LOAD_NAME 2 (b) 18 BINARY_ADD 20 LOAD_NAME 3 (c) 22 BINARY_ADD 24 STORE_NAME 4 (d) 26 LOAD_CONST 1 (None) 28 RETURN_VALUE So, the first approach takes two more instructions each time a variable is used (LOAD_CONST, BINARY_SUBSCR), while the second approach takes one more instruction when the variable is created. The difference is practically meaningless.
type: Answer
has comment: http://stackoverflow.com/comment/87385016
accepted answer of: http://stackoverflow.com/q/50183728
has comment: http://stackoverflow.com/comment/87384955
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50183728
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87384934

http://stackoverflow.com/a/50311323
answers question: http://stackoverflow.com/q/50202762
score: 0
upvote count: 1
downvote count: 1
type: Answer
has body: I'm fairly certain your issue is that you run Python 2.7, where doing a plain import a is ambiguous wether a means the one relative to the current module or from the base path. Add the line from __future__ import absolute_import to the top of your files (it has to be the first non-comment line). I'd recommend you do it on all files, but it should be enough to do it on the test/*.py files. Once done, you should be able to run python -m unittest discover -s test -p '*.py'

http://stackoverflow.com/a/50079959
upvote count: 4
has comment: http://stackoverflow.com/comment/87175869
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50079915
downvote count: 0
has body: This problem is setup for itertools, e.g.: In []: import itertools as it n = 4 choices = ['James']*n + ['Pauline', 'Sarah', 'Benedict', 'Phillippa', 'John'] list(it.combinations(choices, r=n)) Out[]: [('James', 'James', 'James', 'James'), ('James', 'James', 'James', 'Pauline'), ('James', 'James', 'James', 'Sarah'), ('James', 'James', 'James', 'Benedict'), ... ('Pauline', 'Sarah', 'Benedict', 'John'), ('Pauline', 'Sarah', 'Phillippa', 'John'), ('Pauline', 'Benedict', 'Phillippa', 'John'), ('Sarah', 'Benedict', 'Phillippa', 'John')] But it is hard to tell from your example, you may be looking for permutations: In []: list(it.permutations(choices, r=n)) Out[]: [('James', 'James', 'James', 'James'), ('James', 'James', 'James', 'Pauline'), ('James', 'James', 'James', 'Sarah'), ('James', 'James', 'James', 'Benedict'), ... ('James', 'John', 'Benedict', 'James'), ('James', 'John', 'Benedict', 'James'), ('James', 'John', 'Benedict', 'James'), ('James', 'John', 'Benedict', 'Pauline'), ...]
answers question: http://stackoverflow.com/q/50079915
type: Answer
has comment: http://stackoverflow.com/comment/87175882
score: 4

http://stackoverflow.com/comment/87200971
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50092332
has text: @user3650827 you can use an OrderedDict type to index key, value pairs.

http://stackoverflow.com/q/50182568
tagged with: pandas
has answer: http://stackoverflow.com/a/50183103
tagged with: datetime
tagged with: dataframe
has body: I have columnar data of dates of the form mm-dd as shown. I need to add the correct year (dates October to December are 2017 and dates after 1-1 are 2018) and make a datetime object. The code below works, but it's ugly. Is there a more Pythonic way to accomplish this? import pandas as pd from datetime import datetime import io data = '''Date 1-3 1-2 1-1 12-21 12-20 12-19 12-18''' df = pd.read_csv(io.StringIO(data)) for i,s in enumerate(df.Date): s = s.split('-') if int(s[0]) &gt;= 10: s = s[0]+'-'+s[1]+'-17' else: s = s[0]+'-'+s[1]+'-18' df.Date[i] = pd.to_datetime(s) print(df.Date[i]) Prints: 2018-01-03 00:00:00 2018-01-02 00:00:00 2018-01-01 00:00:00 2017-12-21 00:00:00 2017-12-20 00:00:00 2017-12-19 00:00:00 2017-12-18 00:00:00
tagged with: string-to-datetime
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87382759
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: Create datetime column from month and day with year based on month
has answer: http://stackoverflow.com/a/50182846
score: 2
has comment: http://stackoverflow.com/comment/87448564

http://stackoverflow.com/q/50088215
tagged with: python
has comment: http://stackoverflow.com/comment/87192298
has comment: http://stackoverflow.com/comment/87193638
has comment: http://stackoverflow.com/comment/87193732
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87192797
has comment: http://stackoverflow.com/comment/87192499
tagged with: pandas
linked to: http://stackoverflow.com/q/240178
has title: Working with a List of pandas dataFrames
type: Question
has comment: http://stackoverflow.com/comment/87192219
type: UnansweredQuestion
has body: I have notice something weird in the behaviour of my code while using pandas dataFrames and lists. I don't know if they are correlated or if the problem is coming from something beyond my understanding. I would appreciate if someone could explain the reason. My code is similar to the following example: list_of_df=[] for i in range(0,5): df=a_function(data) list_of_df.append(df) a_function is taking a initial dataFrame named "data", modify it and return it. This is a silly example but basically shows the operations I am making: def a_function(data): data[new_column]=1 data.loc[:,existing_column]=0 return data What I am expecting is to end up with list_of_df being a list of different dataFrames however I end up with all the dataFrames being the same and equal to the one that was appended last. When I used the following workaround, the code is working as expected: list_of_df=[] for i in range(0,5): df=data.copy() df=a_function(df) list_of_df.append(df) But I am not sure why. Thank you for your help! edit: more information of what a_function is doing on the dataFrame

http://stackoverflow.com/q/50119211
score: 1
upvote count: 1
has body: I'm trying to retrieve tweets from a single user_id as per the JSON data tweepy fetches. The issue is im also retrieving all mentions of the user_id i.e. other people mentioning the user_id in any way (RT, Mentions etc) I have quoted my script below. Please let me know if this is possible in tweepy at all. the snippet streamer.filter(follow = ['25073877'], encoding = 'utf8') shows which user i am wanting to follow Thank you in advance. from __future__ import print_function import tweepy import json import MySQLdb from dateutil import parser import Twitter_API import DBConfig Access_Token = "" Access_Token_Secret = "" Consumer_Key = "" Consumer_Secret = "" class StreamListener(tweepy.StreamListener): def on_connect(self): print("You are now connected to the streaming API.") def on_error(self, status_code): print('An Error has occured: ' + repr(status_code)) return False def on_data(self, data): try: # Decode the JSON from Twitter datajson = json.loads(data) #grab the wanted data from the Tweet text = datajson['extended_tweet']['full_text'] screen_name = datajson['user']['screen_name'] tweet_id = datajson['id'] created_at = parser.parse(datajson['created_at']) replying_to = datajson['in_reply_to_screen_name'] #print out a message to the screen that we have collected a tweet #print("Tweet collected at " + str(created_at)) print(text, screen_name, tweet_id, created_at, replying_to) #insert the data into the MySQL database #store_data(created_at, text, screen_name, tweet_id) except Exception as e: print(e) auth = tweepy.OAuthHandler(Consumer_Key, Consumer_Secret) auth.set_access_token(Access_Token, Access_Token_Secret) #Set up the listener. The 'wait_on_rate_limit=True' is needed to help with Twitter API rate limiting. listener = StreamListener(api=tweepy.API(wait_on_rate_limit=True)) streamer = tweepy.Stream(auth=auth, listener=listener) #print("Tracking: " + str(WORDS)) streamer.filter(follow = ['25073877'], encoding = 'utf8') Sorry for the bad indentation if any.
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Using Tweepy to get live tweets from single user
tagged with: python
tagged with: twitter
tagged with: tweepy
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/87464139
score: 0
comment on: http://stackoverflow.com/q/50223325
type: Comment
has text: There is nothing I can do with the corresponding html code?
type: QuestionComment

http://stackoverflow.com/comment/87333962
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50156833
has text: I have already have countdown code, just want to make it work for showing on tittle. There is no answer there
score: 0

http://stackoverflow.com/comment/87395216
comment on: http://stackoverflow.com/q/50189140
score: 1
type: Comment
has text: Did you run the code? What happend? Also, please note there is a separate domain for code review:https://codereview.stackexchange.com/
type: QuestionComment

http://stackoverflow.com/a/50220771
downvote count: 0
answers question: http://stackoverflow.com/q/50220379
upvote count: 1
type: Answer
has body: So I am not really sure how to explain this but the class value is an attribute of tag "a". There are two main ways to solve this, 1) companies = browser.find_all(a) for company in companies: if company.has_attr("class") and company.attrs['class'] == "action-view-record": print(company.text) 2) The other way which is a little cleaner works by actually specifying the attrs in the find_all function. This can be done as follows: companies = browser.find_all("a", {"class": "action-view-record"}) for company in companies: print(company.text) And of course, because python is the bees knees you could actually accomplish all of this inside a list comprehension as such: companies = [company.text for company in browser.find_all("a", {"class": "action-view-record"})] Hope this helps. UPDATE: I have never used robobrowser before but from the github page it seems you can find : using - browser.find('div.teaser-icon') so... this might work for you, browser.find('a.action-view-record') also make sure that you are in the right point in the html tree if the element is in side of another like - TEXT you may need to do the find("a") from body like this. head = browser.find('head') body = head.find("body") atags = body.find_all("a")
has comment: http://stackoverflow.com/comment/87490976
score: 1

http://stackoverflow.com/comment/87423771
comment on: http://stackoverflow.com/a/50190598
type: Comment
has text: getattr(x_all,'class').value_counts().plot(kind='bar') ---------- this worked. thanks much Fatahzade
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87246286
comment on: http://stackoverflow.com/q/50114484
score: 0
has text: I just changed that as you were commenting, it's now included.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50142846
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50146514
accepted answer: http://stackoverflow.com/a/50237462
possible better answer: http://stackoverflow.com/a/50146514
type: Question
tagged with: pyomo
answer count: 2
upvote count: 1
has title: How to change Pyomo solver interface
downvote count: 0
has answer: http://stackoverflow.com/a/50237462
tagged with: python
has body: Using Pyomo, instead of creating a file that is to be sent to the solver, I want to start using the Python interface of solvers that are compatible (i.e. CPLEX or GUROBI). What is the default solver interface when not specified, and how can someone specify the wanted solver interface within this code?: opt = SolverFactory('gurobi') results = opt.solve(model, options= solverOptions)
favorite count: 0

http://stackoverflow.com/comment/87240234
has text: riiight, it's because requests doesn't run the javascript! Of course! The annoying thing is that the header is necessary for some of the other redirects to work. Found another question on this, so marking this as dublicate. https://stackoverflow.com/questions/41352373/how-to-python-requests-to-follow-url-like-my-browser
comment on: http://stackoverflow.com/a/50111203
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50175706
linked to: http://stackoverflow.com/q/8768540
has comment: http://stackoverflow.com/comment/87368477
has comment: http://stackoverflow.com/comment/87368971
score: 1
tagged with: time-complexity
has answer: http://stackoverflow.com/a/50175924
has comment: http://stackoverflow.com/comment/87369827
upvote count: 1
has answer: http://stackoverflow.com/a/50175751
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
has title: Binary Arrays: Determine if all 1s in one array come before first 1 in the other
type: UnansweredQuestion
tagged with: algorithm
tagged with: bit-manipulation
downvote count: 0
has body: I've been working on an interesting problem and figured I should post about it on here. The problem is the following: You are given two arrays, A and B, such that the elements of each array are 0 or 1. The goal is to figure out if all the 1s in A come before the first 1 in B. You can assume that all 1s are sequential - you cannot have a 0 between 2 ones. (i.e. you would never have [1,0,1]). Some examples: True: A = [0,1,1,0], B = [0,0,0,1] True: A = [1,0,0,0], B = [0,1,1,0] False: A = [0,0,0,1], B = [1,0,0,0] False: A = [0,1,1,0], B = [0,0,1,0] You can assume that len(A) = len(B) = N, but N can be very large. Therefore, you cannot simply convert the entire array into a binary number because it will be too large to represent. I'd like to find the solution in the most efficient way possible, ideally O(1). I've been coding this in Python using Numpy arrays, so you can perform logical operations on the arrays (e.g. A &amp; B, which would tell you if any 1s overlap between A and B). Curious to see any solutions that you can come up with!
tagged with: python

http://stackoverflow.com/comment/87417492
comment on: http://stackoverflow.com/a/50200394
score: 0
type: Comment
type: AnswerComment
has text: I try this: def __init__(self): self.user_name_textbox = Driver.WebDriverWait120Seconds.until( expected_conditions.visibility_of(By.ID("login_email"))) anf still same error

http://stackoverflow.com/comment/87303525
type: Comment
score: 0
has text: what if i wanted to filter out certain columns based on name? could i make a variable with teh column names and swap that for columns?
type: AnswerComment
comment on: http://stackoverflow.com/a/50142557

http://stackoverflow.com/q/50156118
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87333905
linked to: http://stackoverflow.com/q/2134706
downvote count: 0
answer count: 1
tagged with: pickle
tagged with: python
has title: RecursionError: maximum recursion depth exceeded while calling a Python object when using pickle.load()
score: 4
favorite count: 0
type: AnsweredQuestion
has body: Firstly I'm aware that there have been multiple questions already asked regarding this particular error but I can't find any that address the precise context in which it's occurring for me. I've also tried the solutions provided for other similar errors and it hasn't made any difference. I'm using the python module pickle to save an object to file and the reload it using the following code: with open('test_file.pkl', 'wb') as a: pickle.dump(object1, a, pickle.HIGHEST_PROTOCOL) This doesn't throw any error but then when I try and open the file using the following code: with open('test_file.pkl', 'rb') as a: object2 = pickle.load(a) I get this error: --------------------------------------------------------------------------- RecursionError Traceback (most recent call last) &lt;ipython-input-3-8c5a70d147f7&gt; in &lt;module&gt;() 1 with open('2test_bolfi_results.pkl', 'rb') as a: ----&gt; 2 results = pickle.load(a) 3 ~/.local/lib/python3.5/site-packages/elfi/methods/results.py in __getattr__(self, item) 95 def __getattr__(self, item): 96 """Allow more convenient access to items under self.meta.""" ---&gt; 97 if item in self.meta.keys(): 98 return self.meta[item] 99 else: ... last 1 frames repeated, from the frame below ... ~/.local/lib/python3.5/site-packages/elfi/methods/results.py in __getattr__(self, item) 95 def __getattr__(self, item): 96 """Allow more convenient access to items under self.meta.""" ---&gt; 97 if item in self.meta.keys(): 98 return self.meta[item] 99 else: RecursionError: maximum recursion depth exceeded while calling a Python object I'm aware other people have seen this same error (Hitting Maximum Recursion Depth Using Pickle / cPickle) when doing pickle.dump and I've tried increasing the maximum recursion depth by doing sys.setrecursionlimit() but this doesn't work, I either get the same error as above or I increase it further and python crashes with the message: Segmentation fault (core dumped). I suspect that the root of the problem is actually…
accepted answer: http://stackoverflow.com/a/50158865
has comment: http://stackoverflow.com/comment/87330817
has answer: http://stackoverflow.com/a/50158865
has comment: http://stackoverflow.com/comment/87332116
type: Question
upvote count: 4

pygame
tags question: http://stackoverflow.com/q/50109054
tags question: http://stackoverflow.com/q/50185092
tag name: pygame
tags question: http://stackoverflow.com/q/50091372
tags question: http://stackoverflow.com/q/50165177
tags question: http://stackoverflow.com/q/50075703
tags question: http://stackoverflow.com/q/50188782
tags question: http://stackoverflow.com/q/50159527
tags question: http://stackoverflow.com/q/50165753
tags question: http://stackoverflow.com/q/50119383
tags question: http://stackoverflow.com/q/50113576
tags question: http://stackoverflow.com/q/50081067
tags question: http://stackoverflow.com/q/50150906
tags question: http://stackoverflow.com/q/50193825
tags question: http://stackoverflow.com/q/50139853
tags question: http://stackoverflow.com/q/50180227
tags question: http://stackoverflow.com/q/50084357
tags question: http://stackoverflow.com/q/50155571
tags question: http://stackoverflow.com/q/50117105
tags question: http://stackoverflow.com/q/50146564
tags question: http://stackoverflow.com/q/50115630
tags question: http://stackoverflow.com/q/50189744
tags question: http://stackoverflow.com/q/50223922
tags question: http://stackoverflow.com/q/50175817
tags question: http://stackoverflow.com/q/50082977
tags question: http://stackoverflow.com/q/50086574
tags question: http://stackoverflow.com/q/50100358
tags question: http://stackoverflow.com/q/50192897
type: Tag
tags question: http://stackoverflow.com/q/50147156

http://stackoverflow.com/q/50156408
tagged with: flask
has comment: http://stackoverflow.com/comment/87365387
has title: flask does not handle uriencoded parameters the same way on appengine and dev_appserver
type: AnsweredQuestion
tagged with: urlencode
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87439329
favorite count: 0
type: Question
has body: I've been struggling with this for a while, and can't seem to figure it out. I have a google appengine project, with flask, and I need a route that handles base64 URIencoded data. Here is the handler I have for this route: @app.route('/test/&lt;data1&gt;/&lt;data2&gt;', methods=['GET']) def test(data1, data2): return "data1:%s&lt;br&gt;data2:%s"%(data1, data2) Now, this works nicely when running with dev_appserver: http://localhost/test/hi/there # returns: data1:hello data2:there and http://localhost/test/hi%2fho/there # returns: data1:hi%2Fho data2:there which is what I would expect. Using the same urls on a deployed version to appengine: The first one returns the same result The second one fails, because the %2f gets decoded before the routing to a /, therefore the route does not match the pattern anymore. My question(s): Why does appengine (or flask?) decode the url before routing ? Why is the behavior not consistent between local and deployed appengine ? Thanks for your help
tagged with: google-app-engine
accepted answer: http://stackoverflow.com/a/57341177
tagged with: python
has answer: http://stackoverflow.com/a/57341177

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/50154948
tags question: http://stackoverflow.com/q/50092205
tags question: http://stackoverflow.com/q/50194414
tags question: http://stackoverflow.com/q/50162847

http://stackoverflow.com/a/50166539
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87351082
answers question: http://stackoverflow.com/q/50166194
score: 4
has body: You could use a fused type. Please note that the below doesn't compile on my system because ddot and sdot apparently require 5 parameters: # cython: infer_types=True cimport cython from scipy.linalg.cython_blas cimport ddot, sdot ctypedef fused anyfloat: double float cpdef anyfloat func(int n, anyfloat[:] x): cdef int inc = 1 if anyfloat is double: return ddot(&amp;n, &amp;x[0], &amp;inc) else: return sdot(&amp;n, &amp;x[0], &amp;inc)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87350946
has comment: http://stackoverflow.com/comment/87353969
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50166194

http://stackoverflow.com/a/50161384
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50161070
has body: json_normalize is what you're loooking for! import pandas as pd from pandas.io.json import json_normalize x = [{'a': 1, 'b': {'c': 1, 'd': 2, 'e': 3}, 'f': 4}, {'a': 2, 'b': {'c': 2, 'd': 3, 'e': 4}, 'f': 3}, {'a': 3, 'b': {'c': 3, 'd': 4, 'e': 5}, 'f': 2}, {'a': 4, 'b': {'c': 4, 'd': 5, 'e': 6}, 'f': 1 }] sep = '::::' # string that doesn't appear in column names frame = json_normalize(x, sep=sep) frame.columns = frame.columns.str.split(sep).str[-1] print(frame) Output a c d e f 0 1 1 2 3 4 1 2 2 3 4 3 2 3 3 4 5 2 3 4 4 5 6 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50161070
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87341070

http://stackoverflow.com/a/50178688
has comment: http://stackoverflow.com/comment/87389620
has body: You can use np.trim_zeros(x, 'f'). The 'f' means to trim the zeros from the front. Option 'b' would trim the zeros from the back. Default option 'fb' trims them from both sides. x = np.array([0,0,1,1,1,1,0,1,0,0]) # [0 0 1 1 1 1 0 1 0 0] np.trim_zeros(x, 'f') # [1 1 1 1 0 1 0 0]
accepted answer of: http://stackoverflow.com/q/50178595
answers question: http://stackoverflow.com/q/50178595
score: 7
type: Answer
upvote count: 9
downvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87405049
type: Comment
type: AnswerComment
has text: but why setting limit in TCP connector doesn't work?
score: 0
comment on: http://stackoverflow.com/a/50193520

http://stackoverflow.com/comment/87277685
type: AnswerComment
comment on: http://stackoverflow.com/a/50129351
score: 0
has text: @JoeLu: I'm not sure I understand what you mean. The function I answered with will take your list `["alice", "bob", ...]` and truncate it so it's only two characters. I thought that's what you were looking to do.
type: Comment

http://stackoverflow.com/q/50086924
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/87190015
has body: I need to install python3 and django via user data on EC2 instances. I know I can do it with Cloudformation or directly on EC2 but I need to install and deploy it via user data. I am creating the VPC and autoscaler but I need to automate the install and deployment of python3 and django automatically. Here is what I have but it doesn't seem to work. UserData="""#!/bin/bash yum install httpd php php-mysql -y echo y | sudo yum install python36 python36-virtualenv python36-pip sudo pip install --upgrade pip python3 -m venv venv source ./venv/bin/activate pip install django pip install --upgrade pip yum update -y service httpd start chkconfig httpd on adduser Eteram I have tried enclosing them in the double quotes but still doesn't work. I am basically trying to install python3 and django and deploy a test application to be able to go to the django admin url. If I run the above commands on the EC2, it runs just fine. But when I include it in the user data, after I login to EC2 and check the cloud init log, I see the following: /var/lib/cloud/instance/scripts/part-001: line 3: echo y | sudo yum install python36 python36-virtualenv python36-p ip: command not found /var/lib/cloud/instance/scripts/part-001: line 4: sudo pip install --upgrade pip: command not found /var/lib/cloud/instance/scripts/part-001: line 5: python3 -m venv venv: command not found /var/lib/cloud/instance/scripts/part-001: line 6: source ./venv/bin/activate: No such file or directory /var/lib/cloud/instance/scripts/part-001: line 7: pip install django: command not found /var/lib/cloud/instance/scripts/part-001: line 8: pip install --upgrade pip: command not found
score: 3
upvote count: 3
answer count: 1
downvote count: 0
tagged with: amazon-ec2
has answer: http://stackoverflow.com/a/50088372
favorite count: 0
type: Question
has title: How to install python3 and Django using userdata in AWS EC2 with aws cli boto3
has comment: http://stackoverflow.com/comment/87190509

http://stackoverflow.com/q/50110748
type: Question
tagged with: jwt
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50126835
tagged with: python
tagged with: hmac
answer count: 2
has title: How to calculate the HMAC(hsa256) of a text using a public certificate (.pem) as key
has body: I'm working on Json Web Tokens and wanted to reproduce it using python, but I'm struggling on how to calculate the HMAC_SHA256 of the texts using a public certificate (pem file) as a key. Does anyone know how I can accomplish that!? Tks
downvote count: 0
has comment: http://stackoverflow.com/comment/87250902
upvote count: 1
has answer: http://stackoverflow.com/a/51356271
favorite count: 0

http://stackoverflow.com/a/50202278
answers question: http://stackoverflow.com/q/50201024
has comment: http://stackoverflow.com/comment/87421902
downvote count: 0
upvote count: 1
has body: Yes this is okay, model.save saves the weights, model architecture, and optimizer state, so you can resume training with no problems.
score: 1
type: Answer

http://stackoverflow.com/comment/87319032
type: Comment
comment on: http://stackoverflow.com/a/50138740
type: AnswerComment
score: 0
has text: Hi Manar! I added pictures of train_y and train_x to the question. They are basically in a pandas dataframe. :) I am running it in Jupyter notebook.

http://stackoverflow.com/comment/87300785
comment on: http://stackoverflow.com/a/50141226
type: Comment
has text: i tried your method just now. The URL got updated but now i'm getting only headings of the table. Do you why I'm getting this?
type: AnswerComment
score: 0

http://stackoverflow.com/q/50083062
tagged with: python
accepted answer: http://stackoverflow.com/a/50111312
tagged with: bokeh
has answer: http://stackoverflow.com/a/50111312
has title: How to add legend inside Python's Bokeh circle plot
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50215251
upvote count: 7
score: 7
has answer: http://stackoverflow.com/a/50215251
favorite count: 0
tagged with: plot
has body: I have the following code: from bokeh.plotting import figure, show, output_file from bokeh.sampledata.iris import flowers colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] p = figure(title = "Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.2, size=10) output_file("iris.html", title="iris.py example") show(p) Which produces this plot How can I add legend based on the color of the circle to the plot? Where: setosa : red versicolor : green virginica : blue
type: Question

http://stackoverflow.com/comment/87461210
has text: You could just use `if 'my name is' in inp.lower()`:
comment on: http://stackoverflow.com/q/50221861
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55758849
has body: Better late than never for who is still stumbling on the problem. Make sure that the $ is included in the topic. This was what was going wrong for me. The response comes back on the /accepted or /rejected (/# for the combination of them). Also you might want to subscribe to the topic $aws/events/# to check if your device subscribed to the topic when testing. This example might help you.
answers question: http://stackoverflow.com/q/50155195
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87353251
type: Comment
type: QuestionComment
has text: Great it works good. Just removed the duplicates in beer name and merged as mentioned by you people
score: 0
comment on: http://stackoverflow.com/q/50167692

unit-testing
tags question: http://stackoverflow.com/q/50203382
tags question: http://stackoverflow.com/q/50209580
type: Tag
tags question: http://stackoverflow.com/q/50157543
tags question: http://stackoverflow.com/q/50170064
tags question: http://stackoverflow.com/q/50162089
tag name: unit-testing
tags question: http://stackoverflow.com/q/50132703
tags question: http://stackoverflow.com/q/50165477
tags question: http://stackoverflow.com/q/50090857
tags question: http://stackoverflow.com/q/50180122
tags question: http://stackoverflow.com/q/50091784
tags question: http://stackoverflow.com/q/50131489
tags question: http://stackoverflow.com/q/50210524
tags question: http://stackoverflow.com/q/50172358
tags question: http://stackoverflow.com/q/50138219
tags question: http://stackoverflow.com/q/50116836
tags question: http://stackoverflow.com/q/50163587
tags question: http://stackoverflow.com/q/50202762

http://stackoverflow.com/a/50228831
has comment: http://stackoverflow.com/comment/87493985
type: Answer
has body: You can do this with a recursive function: folders = [ ((b'\\HasChildren',), b'.', 'welcome'), ((b'\\HasChildren',), b'.', 'welcome.welcomeqqqqq'), ((b'\\HasNoChildren',), b'.', 'welcome.welcomeqqqqq.downunder'), ((b'\\HasNoChildren',), b'.', 'test2'), ((b'\\HasNoChildren',), b'.', 'Arunnnnnnnnn') ] def make_my_list_of_dict(my_list_of_folders, check_parent = None): my_list = [] for e in my_list_of_folders: split_char = e[1].decode() parent = e[2].split(split_char)[-2] if split_char in e[2] else None folder = e[2].split(split_char)[-1] if parent == check_parent: if e[0][0] == b'\\HasChildren': children = make_my_list_of_dict(my_list_of_folders, folder) my_list.append({'folder':folder, 'parent':parent, 'children':children}) else: my_list.append({'folder':folder, 'parent':parent, 'children':[]}) return my_list result = make_my_list_of_dict(folders) print(result) output: [ {'folder': 'welcome', 'parent': None, 'children': [ {'folder': 'welcomeqqqqq', 'parent': 'welcome', 'children': [ {'folder': 'downunder', 'parent': 'welcomeqqqqq', 'children': [] } ] } ] }, {'folder': 'test2', 'parent': None, 'children': [] }, {'folder': 'Arunnnnnnnnn', 'parent': None, 'children': [] } ]
score: 4
accepted answer of: http://stackoverflow.com/q/50227723
upvote count: 4
answers question: http://stackoverflow.com/q/50227723
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87491956

http://stackoverflow.com/q/50188085
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50188280
answer count: 1
downvote count: 0
tagged with: image-processing
favorite count: 0
type: Question
tagged with: numpy
tagged with: opencv
has body: Let's say I have an OpenCV image in form of a numpy array. I want to collect all (x, y) point coordinates of points that have greater than zero blue color component. The naive way would be something like this: n_rows, n_cols, _ = image.shape points = [] for row in range(n_rows): for col in range(n_cols): if image[row, col, 0] &gt; 0: points.append((row, col)) Is there a smarter and more efficient way to do the same, using numpy or OpenCV capabilities?
accepted answer: http://stackoverflow.com/a/50188280
score: 3
has title: Select coordinates from image, based on certain criteria

http://stackoverflow.com/q/50187519
tagged with: oracle-database
upvote count: 1
score: 1
favorite count: 0
type: Question
has body: I have an oracle of version 11g and python 3 on my system. However when i try to run the certain insert query it won't work. It always throw a not connected exception. I have checked my connection and the select queries are working fine. My end goal is to register an user in the database and then return its row id. What i did? def db_register_applicant(applicant_name,password,years_of_experience,prefered_technology,skill_set): try: con=DBConnectivity.create_connection() cur=DBConnectivity.create_cursor(con) skills=skill_set.split(",") db_skills=[] applicant_id_db=None cur.execute("select skill_name from skills") for skill_name in cur: db_skills.append(skill_name) final_skills=[] for x in skills: if x not in db_skills: final_skills.append(x) cur.execute("select nvl(max(applicant_id),0) from applicant") last_row_id=int(cur.fetchone()[0]) // works till here, if i print this, it prints 7 query="insert into applicant (applicant_id,applicant_name,password,years_of_experience,prefered_technology) values ('%d','%s','%s','%d','%s')"%\ (last_row_id+1,applicant_name,password,years_of_experience,prefered_technology,skill_set) cur.execute(query) applicant_id_db=last_row_id+1 for x in final_skills: cur.execute("select nvl(max(skill_id),0) from skills") skill_max=int(cur.fetchone()[0]) print(skill_max) query="insert into skills values (skill_id,skill_name) values ('%d','%s')"%\ (skill_max+1,x) cur.execute(query) con.commit() finally: con.close() cur.close() return applicant_id_db This function is called from this function: def register(): try: print("Enter the applicant name:") name=input() print("Enter the password:") password=input() print("Enter your skill set:") skill_set=input() print("Enter the number of years of experience:") experience=int(input()) print("Enter prefered technology:") prefered_tech=input() if check_experience(experience) and check_password(password): applicant_id=db_register_applicant(name, password, experience, prefered_tech, skill_set) print("Your applica…
has comment: http://stackoverflow.com/comment/87391763
has comment: http://stackoverflow.com/comment/87392016
has comment: http://stackoverflow.com/comment/87392109
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87391735
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87391709
has title: insert query not working python oracle
answer count: 0

http://stackoverflow.com/comment/87180651
has text: If you have more information to add, please do so. You don't need to say that it's not letting you in the post itself. If it's giving you the majority code error, then you need to include more info.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50082324
score: 0

http://stackoverflow.com/q/50157795
score: 0
has answer: http://stackoverflow.com/a/50157924
answer count: 2
tagged with: pandas
upvote count: 2
downvote count: 2
tagged with: histogram
accepted answer: http://stackoverflow.com/a/50179007
linked to: http://stackoverflow.com/q/1934751
has answer: http://stackoverflow.com/a/50179007
favorite count: 0
type: Question
has title: Pandas: Stacked dots histogram
has body: Basically, title. I want to do a histogram where bars are replaced by column of stacked dots. There is an answer to this specific question in R but I'd like to stay within python. Any help is much appreciated :) Edit: Added link to image example of what the final result should look like
tagged with: python
possible better answer: http://stackoverflow.com/a/50157924
type: AnsweredQuestion

http://stackoverflow.com/comment/87426117
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50204202
has text: columns[3] should be the SA data in a python list form. If you want it to be structured like "item1,item2,item3,item4", you can use ",".join(columns[3])
type: Comment

http://stackoverflow.com/q/50156009
has body: I need to import and manipulate memory heavy data in jupyter. Because I tend to have rather long notebooks were several data sets will be importer I need to clear them continuously by hand. This is tideous. If possible, i would like to have a tool which clears all variables introduced in a cell and only those without the need of addressing them by hand after they fullfilled there purpose. I could of course overwrite variables, however as they all serve rather different purposes this will drastically reduce the readabiliy of the code. To summarize: Cell 1: variable overhead #this will be used in the entire notebook Cell 2: import or generate data &amp; manipulate data clear all variables introduced in cell without the need of addressing every single one of them by hand &lt;-- this is what i am looking for. Thank you very much!
answer count: 2
accepted answer: http://stackoverflow.com/a/50158046
downvote count: 0
possible better answer: http://stackoverflow.com/a/50222079
has answer: http://stackoverflow.com/a/50222079
type: AnsweredQuestion
score: 7
has title: Clear all variables which where defined in Jupiter cell after execution finished
has answer: http://stackoverflow.com/a/50158046
tagged with: python
tagged with: jupyter
upvote count: 7
favorite count: 0
type: Question

http://stackoverflow.com/comment/87408199
type: QuestionComment
comment on: http://stackoverflow.com/q/50195565
type: Comment
score: 0
has text: Please describe what the problem is in detail, the behavior you expect, or post the Error stack trace.

http://stackoverflow.com/a/50122329
accepted answer of: http://stackoverflow.com/q/50121980
score: 4
has comment: http://stackoverflow.com/comment/87264727
has body: You can do this in pure numpy using a clever application of np.diff and np.add.reduceat. np.diff will give you the indices where the rightmost column changes: d = np.diff(arr[:, -1]) np.where will convert your boolean index d into the integer indices that np.add.reduceat expects: d = np.where(d)[0] reduceat will also expect to see a zero index, and everything needs to be shifted by one: indices = np.r_[0, e + 1] Using np.r_ here is a bit more convenient than np.concatenate because it allows scalars. The sum then becomes: result = np.add.reduceat(arr, indices, axis=0) This can be combined into a one-liner of course: &gt;&gt;&gt; result = np.add.reduceat(arr, np.r_[0, np.where(np.diff(arr[:, -1]))[0] + 1], axis=0) &gt;&gt;&gt; result array([[ 6, 8, 10, 12, 4000], [ 12, 4, 6, 8, 4002], [ 8, 10, 12, 4, 4004], [ 14, 6, 8, 10, 4006]])
upvote count: 4
has comment: http://stackoverflow.com/comment/87262750
answers question: http://stackoverflow.com/q/50121980
has comment: http://stackoverflow.com/comment/87382932
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/50187994
has comment: http://stackoverflow.com/comment/87392792
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50187956
has comment: http://stackoverflow.com/comment/87392716
type: Answer
accepted answer of: http://stackoverflow.com/q/50187956
has body: Use a generator with next(). next(m['result'] for m in L if m['name'] == 'sara')
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87392675

http://stackoverflow.com/comment/87354859
type: Comment
comment on: http://stackoverflow.com/a/50150008
has text: Thanks R.yan! It is almost complete now, only issue I am having is that it duplicates the output when it shouldn't! I updated the post, could you please help?? Thanks in advance!
type: AnswerComment
score: 0

http://stackoverflow.com/q/50214026
has comment: http://stackoverflow.com/comment/87445102
has comment: http://stackoverflow.com/comment/87444999
has comment: http://stackoverflow.com/comment/87444798
has title: Python replace text in string
accepted answer: http://stackoverflow.com/a/50214187
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50214187
favorite count: 0
has comment: http://stackoverflow.com/comment/87452610
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87444961
tagged with: python
has body: I'm using a software that can handle python scripts. There are list/tables in it, like layers. I can get the list, but cannot replace part of the text. list: 06H_906_283_B__DMU_TMU_000_000_EL-UMSCHALTVENTIL_______________________S_P@SKIN 05E_906_051____GEO_TM__001_____DRUCKSENSOR________09_08_2016_EE_______.1\NAUO7\ 03H_260_089_K__DMU_TMU_000_000_HALTER__________________________________S_POS001 ENT_406_001_FB_GEO_TM__009_____HALTER_SENSOR_MOT__________20170502_VIF.1\PartBo want to replace stuff like: TM_009 to TM009 _GEO_ to 'delete' ______ to _ Tried many things, but nothing worked. I think easiest way would be a dictionary. But I'm stuck and can't get it to work. some part that I have yet: ... names = base.GetEntityCardValues(deck, prop, ('Name',)) #getting the list with names for prop in props: dict = { 'EN_0+':'EN0', '-TM_0':'-TM0', '_+':'_', 'DMU_':'', 'GEO_':'', } . . .stuck with the replacing . . base.SetEntityCardValues(deck, prop, {'Name':new_names}) #the end where I want to write back the new names
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87419387
has text: `print("Your current score is "+ str(score) + " out of 10")`
comment on: http://stackoverflow.com/q/50201412
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50100812
has comment: http://stackoverflow.com/comment/87257606
upvote count: 0
answers question: http://stackoverflow.com/q/50100756
has comment: http://stackoverflow.com/comment/87219377
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87257761
downvote count: 1
has comment: http://stackoverflow.com/comment/87219562
has comment: http://stackoverflow.com/comment/87220586
has comment: http://stackoverflow.com/comment/87219689
type: Answer
score: -1
has body: try: from bs4 import BeautifulSoup soup = BeautifulSoup(s, 'html.parser') articles =[] for links in soup.find_all('div', {'class':'cnnSectBulletItems'}): for link in links.find_all('a'): #--&gt;Fetch Values from links instead of soup print link.get('href') articles.append(link.get('href')) print(articles) Output: /TRANSCRIPTS/1804/29/cnr.21.html /TRANSCRIPTS/1804/29/cnr.22.html /TRANSCRIPTS/1804/29/cnr.03.html /TRANSCRIPTS/1804/29/rs.01.html /TRANSCRIPTS/1804/29/ndaysun.02.html /TRANSCRIPTS/1804/29/sotu.01.html [u'/TRANSCRIPTS/1804/29/cnr.21.html', u'/TRANSCRIPTS/1804/29/cnr.22.html', u'/TRANSCRIPTS/1804/29/cnr.03.html', u'/TRANSCRIPTS/1804/29/rs.01.html', u'/TRANSCRIPTS/1804/29/ndaysun.02.html', u'/TRANSCRIPTS/1804/29/sotu.01.html']
accepted answer of: http://stackoverflow.com/q/50100756

http://stackoverflow.com/comment/87462870
has text: Can i have example? xy_list = [[-50, -50], [-50, 50], [50, 50], [75, 0], [50, -50]]
type: Comment
comment on: http://stackoverflow.com/a/50222299
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87242039
type: QuestionComment
has text: Possible duplicate of [Using Sliders for shapes in Maya with Python](https://stackoverflow.com/questions/50110785/using-sliders-for-shapes-in-maya-with-python)
comment on: http://stackoverflow.com/q/50111472
score: 0
type: Comment

http://stackoverflow.com/a/53526442
upvote count: 2
has body: For a loop update in pandas dataframe: for i, row in df_merged.iterrows(): df_merged.set_value(i,'new_value',i) Should be able to update values in pandas dataframe. FutureWarning: set_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead. for i, row in df_merged.iterrows(): df_merged.at[i,'new_value'] = i Should be preferred.
score: 2
answers question: http://stackoverflow.com/q/50187932
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87182012
type: QuestionComment
comment on: http://stackoverflow.com/q/50082987
has text: Because there is a "log" file in each entry , sorry I didn't show that in my description. What I need to do is "diff" those log contents . when diff them I need to know what is the newly generated error/logs . List_D1 is generally the 'original' while List_D2 is the newer generated one.
score: 0
type: Comment

http://stackoverflow.com/comment/87227783
score: 1
type: Comment
type: AnswerComment
has text: I see. It will even clear the complete figure. Pretty unefficient if you ask me. Btw, the [drawnow page](https://github.com/stsievert/python-drawnow) clearly states that it's not working in IPython (hence also not in Juypter). I updated the answer.
comment on: http://stackoverflow.com/a/50104646

http://stackoverflow.com/a/50192161
answers question: http://stackoverflow.com/q/50192123
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You could try this: ''.join([x + y for x, y in zip(a, b)]) which gives: 'hweolrllod'
score: 3
accepted answer of: http://stackoverflow.com/q/50192123
type: Answer

http://stackoverflow.com/comment/87194214
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50081891
has text: I got rid of the QDesigner code and thought it would alleviate the problem, but that didn't help. The revised code is below.

http://stackoverflow.com/q/50095311
tagged with: pandas
has comment: http://stackoverflow.com/comment/87207281
answer count: 1
has answer: http://stackoverflow.com/a/50095768
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87206826
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50095768
has title: Extract pandas index with binary numpy array
tagged with: python
has body: import pandas as pd import numpy as np binArray = np.array([[1, 0, 1]]) print(binArray) list = ('Text0', 'Text1', 'Text2') indx = pd.Index(list) print(indx) Hi ! How do I extract 'Text0' and 'Text2' with the help of binArray variable? Please note that both binArray &amp; indx will always be of length N in my code. Thank you!
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87207376

http://stackoverflow.com/q/50132456
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/21999923
type: AnsweredQuestion
has title: Fetch all records but some condition on filed in SQLAlchemy?
has comment: http://stackoverflow.com/comment/87283499
accepted answer: http://stackoverflow.com/a/50132533
upvote count: 0
duplicate of: http://stackoverflow.com/q/21999923
answer count: 1
has comment: http://stackoverflow.com/comment/87283400
has answer: http://stackoverflow.com/a/50132533
tagged with: sqlalchemy
downvote count: 1
favorite count: 0
type: Question
has body: I need select * from new_entry where batch=2018. I tried query.filter(NewEntry.batch==batch).first() i got first record in database but i need all columns which is matched to batch.What can I do?
tagged with: pyramid

http://stackoverflow.com/q/50150627
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50150928
answer count: 2
has comment: http://stackoverflow.com/comment/87319364
downvote count: 0
has comment: http://stackoverflow.com/comment/87318965
upvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/87319029
has title: How to delete tabs in pycharm
accepted answer: http://stackoverflow.com/a/50150928
type: Question
has answer: http://stackoverflow.com/a/76866666
tagged with: python
has body: Im refactoring the code and want to delete tabs in almost hundred of line. It's python. To illustrate what I want to do here is initial code: def func(): a = x b = z f(x) # lines of code ... Here I want to get this: a = x b = z f(x) #lines of code without tabs Is it possible to do it in pycharm cause manually it takes a lot of time?
score: 7
possible better answer: http://stackoverflow.com/a/76866666
tagged with: pycharm

http://stackoverflow.com/a/54390600
score: 1
upvote count: 1
has body: I recommend you create a new conda enviroment and try to reinstall PyTorch in this way: To install PyTorch via Anaconda, and do not have a CUDA-capable[LINK] system or do not require CUDA, use the following conda command. conda install pytorch-cpu torchvision-cpu -c pytorch To install PyTorch via Anaconda, and you are using CUDA 9.0, use the following conda command: conda install pytorch torchvision -c pytorch CUDA 8.x conda install pytorch torchvision cuda80 -c pytorch CUDA 10.0 conda install pytorch torchvision cuda100 -c pytorch #Inno
type: Answer
answers question: http://stackoverflow.com/q/50195080
downvote count: 0

http://stackoverflow.com/q/50089580
has body: I have a pandas dataframe as shown here. There are many more columns in that frame that are not important concerning the task. id pos value sente 1 a I 21 2 b have 21 3 b a 21 4 a cat 21 5 d ! 21 1 a My 22 2 a cat 22 3 b is 22 4 a cute 22 5 d . 22 I would like to make a list out of certain colums so the first sentence (sente=21) and every other looks something like that. Meaing that every sentence has an unique entry for itself. `[('I', 'a', '1'), ..., ('!','d','5')]` I already have a function to do this for one sentence but I can not figure out how to do it for all sentences (sentences that have the same sente value) in the frame. `class SentenceGetter(object): def __init__(self, data): self.n_sent = 1 self.data = data self.empty = False def get_next(self): for t in self.data: try: s = self.data[(self.data["sente"] == 21)] self.n_sent += 1 return s["id"].values.tolist(), s["pos"].values.tolist(), s["value"].values.tolist() except: self.empty = True return None,None,None foo = SentenceGetter(df) sent, pos, token = foo.get_next() in = zip(token, pos, sent) ` As my frame is very large there is no way to use constructions like this: df.loc[((df["sente"] == df["sente"].shift(-1)) &amp; (df["sente"] == df["sente"].shift(+1))), ["pos","value","id"]] Any ideas?
tagged with: python
has title: Making a list ouf of values in a DataFrame depending on values in another column
has answer: http://stackoverflow.com/a/50090186
has answer: http://stackoverflow.com/a/50089740
has answer: http://stackoverflow.com/a/50089698
tagged with: multiple-columns
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 3
downvote count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50089740
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50089698
favorite count: 0
type: Question

http://stackoverflow.com/comment/87240147
has text: I have found the error in my code and posted the solution below. It implements your suggestions.
comment on: http://stackoverflow.com/q/50097431
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50162722
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87344107
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/268272
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50166249
answer count: 1
has title: How to manipulate dictionary with tuple keys to output pandas dataframe
has comment: http://stackoverflow.com/comment/87344631
upvote count: 1
has answer: http://stackoverflow.com/a/50166249
favorite count: 0
type: Question
has body: Say I have a dictionary that looks like: {('a','1'):2, ('a','2'):1, ('b','1'):3, ('b','2'):2} I want to get a dataframe result that takes the highest value item for the first key ('a','b' in this case) and create a dataframe from the tuple key. key value 'a' '1' 'b' '1' How can I do this in python?
downvote count: 2
tagged with: dataframe
tagged with: python
score: -1

http://stackoverflow.com/comment/87332209
comment on: http://stackoverflow.com/a/50156014
score: 0
type: AnswerComment
has text: @EhsanMehralian - not so easy, one question - `labels` are from `row` like `labels= row['labels']` ?
type: Comment

http://stackoverflow.com/a/50082035
type: Answer
answers question: http://stackoverflow.com/q/50081702
has body: As some of the other comments also indicate, the error is caused by you taking the square root of a negative number. If you add an if condition before everything else that checks for this, it should resolve your issue: #First check if there are any real solutions? if b_squared_minus_four_a_c &lt; 0: print('No real solutions') elif a == 1: print("solving equation x^2+" + str(b) + "x+" + str(c)) answer_one_step_one = minus_b + root_b_squared_minus_four_a_c answer_one = answer_one_step_one / two_a answer_two_step_one = minus_b - root_b_squared_minus_four_a_c answer_two = answer_two_step_one / two_a print("The two solutions for x are:" + str(answer_one) + ",and " + str(answer_two)) else: print("Solving equation" + str(a)+ "x^2+" + str(b) + "x+" + str(c)) answer_one_step_one = minus_b + sqrt(b_squared_minus_four_a_c) answer_one = answer_one_step_one / two_a answer_two_step_one = minus_b - sqrt(b_squared_minus_four_a_c) answer_two = answer_two_step_one / two_a print("The two solutions for x are:" + str(answer_one) + ",and " + str(answer_two))
score: 0

http://stackoverflow.com/comment/87270763
comment on: http://stackoverflow.com/q/50126274
type: Comment
type: QuestionComment
has text: @bro-grammer I guess I should mention that I use Python 3. I do not get a syntax error.
score: 0

http://stackoverflow.com/comment/87351443
comment on: http://stackoverflow.com/a/50166677
has text: No problem bro!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87426272
has text: Thanks sacul. I found it pretty handy and used it in my solution.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50195187
type: Comment

http://stackoverflow.com/comment/87447909
score: 0
has text: I have added the code as you suggested as well as the code when using matrix operations. Thanks for feedback!
comment on: http://stackoverflow.com/q/50215003
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87453598
type: QuestionComment
comment on: http://stackoverflow.com/q/50217771
has text: The _why_ doesn't really mater for the question. You did a good job explaining the situation, its the code that's the problem. I wanted to copy your code to test my answer but you didn't make that easy. It has bugs and stuff I don't have installed on my machine. Make it easy!
type: Comment
score: 1

http://stackoverflow.com/comment/87463489
type: AnswerComment
comment on: http://stackoverflow.com/a/50206139
score: 0
type: Comment
has text: Update to using the `WSGIDaemonProcess` http://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIDaemonProcess.html

http://stackoverflow.com/q/50108642
has body: Using cairosvg in python (on Windows) to convert some SVGs to PNGs and struggling with it a little, the line I'm stuck on is: cairosvg.svg2png(url=r'C:\images\image.svg', write_to=r'C:\images\image.png') The error seems to be suggesting that the URL is incorrect, but I'm not quite sure what to do with the information that it's giving me: urllib.error.URLError: &lt;urlopen error unknown url type: c&gt; I'm guessing that this could be something to do with using a C drive location rather than a web URL, as it works fine with something like: cairosvg.svg2png(url=r'http://www.images.com/image.svg', write_to=r'C:\images\image.png') I'm not sure how to do anything differently when I have locally stored images?
type: AnsweredQuestion
has title: Getting CairoSVG to recognise a local image in the URL
has comment: http://stackoverflow.com/comment/87265305
accepted answer: http://stackoverflow.com/a/50123608
tagged with: python
has answer: http://stackoverflow.com/a/50123608
score: 0
answer count: 1
type: Question

http://stackoverflow.com/a/58521018
score: 0
has body: From my experience this can be a really frustrating error to debug. You probably solved the error but l'll add my solution here for anyone who struggles with a similar error connecting to Oracle through cx_Oracle. Important points to note here: Although this is a database error, it would not be solved by killing and restarting the database listened service, it is to do with our connection through cx_ Make sure the Oracle client and Python have the same architectures, either both are 32 bit or both are 64 bit. Here's how you can check your Python architecture: import platform platform.architecture() Make sure the environment path variable has the complete path of the Oracle client till the bin folder. Make sure to set the TNS_ADMIN variable to where the TNS file exists. Connection: import cx_Oracle conn = cx_Oracle.connect('&lt;username&gt;','&lt;password&gt;','&lt;service name variable in your TNS file&gt;') This method uses the connection details provided in the TNS file and cx_Oracle accesses the host and port details from the file itself.
type: Answer
answers question: http://stackoverflow.com/q/50149844

http://stackoverflow.com/a/50167520
answers question: http://stackoverflow.com/q/50167423
score: 1
downvote count: 0
upvote count: 1
type: Answer
has body: You could try: a = {'Andy':[2,4,6,8],'Bryce':[1,2,3], 'Charile': [3,6], 'David':[10], 'Elaine' :[5,10]} new_a = dict(list((key, list(map(lambda i:i*2, value))) for key, value in a.items())) Output: {'Andy': [4, 8, 12, 16], 'Bryce': [2, 4, 6], 'Charile': [6, 12], 'David': [20], 'Elaine': [10, 20]}

http://stackoverflow.com/comment/87414125
comment on: http://stackoverflow.com/a/50186227
has text: This might be tricky. It could be related to VS Code, your python code or the machine on which VS Code is running. I am sure you must have tried to reinstall the VS Code and Python plugin. While debugging, does the whole program goes unresponsive when you face delay? What do you see in the call stack/watch when the debugging is unresponsive,anything out of ordinary? In your code, are you using some globally declared which might have to fetch some token/authentication over internet or something( too far fetched but I faced something similar).
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50177594
has answer: http://stackoverflow.com/a/50177656
tagged with: mean
tagged with: arrays
has comment: http://stackoverflow.com/comment/87374014
has comment: http://stackoverflow.com/comment/87373624
has comment: http://stackoverflow.com/comment/87372441
has answer: http://stackoverflow.com/a/50177793
has answer: http://stackoverflow.com/a/50177667
has body: I am attempting to create an array with a predetermined mean and standard deviation value using Numpy. The array needs random numbers within it. So far I can produce an array and calculate the mean and std. but can not get the array to be controlled by the values: import numpy as np x = np.random.randn(1000) print("Average:") mean = x.mean() print(mean) print("Standard deviation:") std = x.std() print(std) How to control the array values through the mean and std?
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87372445
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87372473
upvote count: 10
has comment: http://stackoverflow.com/comment/87372765
tagged with: python
has comment: http://stackoverflow.com/comment/87372470
score: 9
tagged with: numpy
has title: Create an array with a pre determined mean and standard deviation
answer count: 3

http://stackoverflow.com/comment/87359828
type: QuestionComment
comment on: http://stackoverflow.com/q/50171217
has text: Are you asking how you write command-line programs in Python? Because you can't import a Python module into a shell script.
score: 0
type: Comment

http://stackoverflow.com/q/50178139
has answer: http://stackoverflow.com/a/50178198
has body: How do I perform the comparison between two strings to determine which is alphabetically smaller? Example, if I have strings 'aberr' and 'aftward' how do I determine which is alphabetically smaller? Another example would be 'beast' and 'best'. Do I have to make the strings into it's ascii representation such as: ascii a + ascii b + ascii e...
score: 0
has comment: http://stackoverflow.com/comment/87373579
has comment: http://stackoverflow.com/comment/87373636
upvote count: 2
has comment: http://stackoverflow.com/comment/87373626
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/4806911
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87373798
has comment: http://stackoverflow.com/comment/87402754
type: UnansweredQuestion
tagged with: python
has title: Checking strings and determine which is alphabetically smaller

http://stackoverflow.com/a/54220095
has body: I have not found out a way to do it exactly but if you are referring to opening a prompt in the context of anaconda as the conda prompt does, you need to create a conda environment then activate and deactivate it as shown below: conda create -n conda_env1 conda activate conda_env1 or source activate conda_env1 conda deactivate
has comment: http://stackoverflow.com/comment/122426610
type: Answer
answers question: http://stackoverflow.com/q/50202418
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/comment/87472248
comment on: http://stackoverflow.com/a/50225975
score: 0
type: AnswerComment
has text: @halbe I suppose you need to be wary that `np.bincount()` outputs an extra `0` at the beginning. I've sliced it off above with `[1:]`. Also make sure that `num_samples` is indeed your maximum frequency. Or consider using `np.histogram` since that seems to handle these edge cases a bit better.
type: Comment

http://stackoverflow.com/q/50188646
has answer: http://stackoverflow.com/a/50272351
tagged with: amazon-ec2
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/87413180
has comment: http://stackoverflow.com/comment/87395091
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87401181
has title: How to mimic AWS CLI EC2 filter in boto3
tagged with: python
possible better answer: http://stackoverflow.com/a/50205443
tagged with: boto3
has answer: http://stackoverflow.com/a/50205443
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50272351
has comment: http://stackoverflow.com/comment/87416187
answer count: 2
has body: I'm looking for a way to mimic the AWS CLI EC2 Filter using Boto3 let say i want to translate the filters portion of describe-instances command: aws ec2 describe-instances --filters "Name=instance- type,Values=m1.small,t2.small" into Boto3 describe_instances method: response = client.describe_instances( Filters=[ { 'Name': 'instance- type', 'Values': [ 'm1.small','t2.small', ] } ] ) So basically what i'm asking, what is good why in python to take the string: "Name=instance-type,Values=m1.small,t2.small" and convert it to: [ { 'Name': 'instance- type', 'Values': [ 'm1.small','t2.small', ] } ] so that i can use it as a filter parameter in boto3's decribe_instances method.

http://stackoverflow.com/q/50179822
possible better answer: http://stackoverflow.com/a/50180037
has answer: http://stackoverflow.com/a/50180037
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50180135
tagged with: opencv
linked to: http://stackoverflow.com/q/33029697
type: AnsweredQuestion
tagged with: opencv3.0
score: 1
downvote count: 0
has title: How to do image processing on a certain area of an image in python OpenCV 3?
has body: Considering I have the coordinates already of the area of the image I want to do image processing on. It was already explained here using Rect but how do you do this on python OpenCV 3?
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50180135

http://stackoverflow.com/comment/87372286
comment on: http://stackoverflow.com/a/50177342
has text: For this specific case this works: `df2[~df2[df1.columns].astype(str).sum(1).isin(df1.astype(np.float).astype(str).sum(1))]`
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50190685
answer count: 1
has comment: http://stackoverflow.com/comment/87398200
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87398831
type: Question
tagged with: c#
has body: In Python I create a list of upto 10 million elements with this declaration, res = [0, 1] * (N // 2) + [1] Is there a way to do the equivalent in C# without iterating over the list? I'm trying something like this, List&lt;int&gt; res = Enumerable.Repeat(0, N).ToList(); But can't quite figure out the correct syntax.
accepted answer: http://stackoverflow.com/a/50191186
upvote count: 1
tagged with: python
has title: How can I create this equivalent list in C#?
tagged with: list-comprehension
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87398382
has answer: http://stackoverflow.com/a/50191186
has comment: http://stackoverflow.com/comment/87398336

http://stackoverflow.com/q/50227723
score: 1
tagged with: python
tagged with: dictionary
has title: Python : Convert list of tuple to dict
type: Question
accepted answer: http://stackoverflow.com/a/50228831
has answer: http://stackoverflow.com/a/50228831
upvote count: 2
tagged with: treeview
answer count: 1
has body: I am receiving a response from imap server like below. Which contains all the folders for particular user account. imap.list_folders() outputs : [((b'\\HasChildren',), b'.', 'welcome'), ((b'\\HasChildren',), b'.', 'welcome.welcomeqqqqq'), ((b'\\HasNoChildren',), b'.', 'welcome.welcomeqqqqq.downunder'), ((b'\\HasNoChildren',), b'.', 'test2'), ((b'\\HasNoChildren',), b'.', 'Arunnnnnnnnn')] Here welcome is the folder name. And HasChildren means the folder has a child. welcome.welcomeqqqqq is the children of welcome. Parent and Child are separated by dot. I want to form a treeview format from the folder list recursively. Expected output : [ { "folder": "Top", "parent": "None", "children": [ { "folder": "Folder 1", "parent": "Top", "children": [ { "folder": "Sub Folder 1", "parent": "Folder 1", "children": [] }, { "folder": "Sub Folder 2", "parent": "Folder 1", "children": [ { "folder": "Sub Folder Sub Folder 1", "parent": "Sub Folder 2", "children": [] }, { "folder": "Sub Folder Sub Folder 2", "parent": "Sub Folder 2", "children": [] } ] } ] }, { "folder": "Folder 2", "parent": "Top", "children": [] } ] } ] Any help would be appreciated.
tagged with: imap
downvote count: 1
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/87270690
type: Comment
comment on: http://stackoverflow.com/a/50126006
score: 0
type: AnswerComment
has text: So I found numpy in the anaconda navigator. When I right click a menu pops up with an option for Mark for Specific Installation. However, the newest option available for numpy is only 14.0 instead of 14.3

http://stackoverflow.com/q/50075393
downvote count: 0
has body: I have been working a lot with Django's template language lately, and it works well in most cases, but recently I've come across a small problem it hasn't been able to solve. I'm iterating over a bunch of database objects, and building a button in the template from each of them. Something like this: {% for item in items %} &lt;button id="{{ item.action.id }}"&gt; {{ item.action.text }} &lt;/button&gt; {% endfor %} This works fine, but my Action class is inheritable, and may have a different button structure. Say I wanted to sometimes have a javascript function attached as well. My first though was well, let's just create a render method in my class, and then call that in my template. class ScriptAction(Action): def render(self): return ''' &lt;button id="{}" onclick={}&gt; {} &lt;/button&gt;'''.format(self.id, self.func, self.text) Because no the template is much more elegant, and doesn't rely on a fixed button structure: {% for item in items %} {% endfor %} And now for my actual problem: what if this rendered string needs further processing by django? Maybe render method returns a string like &lt;button id="action-button-id" onclick="console.log('clicked')"&gt; {{ item.name }} &lt;/button&gt; Currently, {{ item.name }} will not be rendered in the template loop. Is there a way of getting around this? Perhaps I making this more complicated than it should be, but I've looked through the Django built-in tags and filters, even looked at writing you own parser. But at this point something inside me told me that I was being obsessive. This is actually just a small problem, and would require a fair amount of time, so - is this more effort than it is worth? is writing complex parsers like this secure? is the Django template language even able to do something like this? If you could hone in on some of these points, I would really appreciate it. This problem is really bugging me. Thanks in advance!
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50075489
type: AnsweredQuestion
score: 1
answer count: 1
tagged with: django-template-filters
upvote count: 1
has title: Render returned string in django template
favorite count: 0
type: Question
tagged with: django-templates
has answer: http://stackoverflow.com/a/50075489

http://stackoverflow.com/q/50127294
tagged with: kafka-python
has body: We are using the kafka-python to connect to our Kafka-instances. To access this we need to be authenticated and it is not plain username/password authentication, we need to get an access_token from an Identity-Service and use it to access the Kafka-instances. Can someone please help me with the configuration for this in kafka-python? It is same as doing something below in java:- KafkaClient { com.mykafka.KafkaIdentityClientLoginModule required; }; Where KafkaIdentityClientLoginModule is the name of the custom login module. Thanks Note:- If there is another library which supports this authentication we are open for that. References https://github.com/dpkp/kafka-python http://kafka-python.readthedocs.io/en/master/
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: apache-kafka
tagged with: sasl
score: 1
tagged with: python
has title: Kafka-Python Use custom Login Module instead of PlainLoginModule

http://stackoverflow.com/a/50139964
has comment: http://stackoverflow.com/comment/87298431
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87298114
downvote count: 1
has comment: http://stackoverflow.com/comment/87298252
answers question: http://stackoverflow.com/q/50139812
has body: So you need a QHBoxLayout for your buttons, nested in a QVBoxLayout: class Main(QMainWindow): def __init__(self, parent=None): super(Main, self).__init__(parent) self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self.vLayout = QVBoxLayout(self.centralWidget) self.buttonsWidget = QWidget() self.buttonsWidgetLayout = QHBoxLayout(self.buttonsWidget) self.buttons = [QPushButton(c) for c in 'ABC'] for button in self.buttons: self.buttonsWidgetLayout.addWidget(button) self.placeHolder = QWidget() self.placeHolder.setMinimumWidth(480) self.placeHolder.setMinimumHeight(320) self.placeHolder.setStyleSheet('* {background: red;}') self.vLayout.addWidget(self.placeHolder) self.vLayout.addWidget(self.buttonsWidget)
accepted answer of: http://stackoverflow.com/q/50139812
type: Answer
upvote count: 4
score: 3

aix
type: Tag
tag name: aix
tags question: http://stackoverflow.com/q/50127970

http://stackoverflow.com/q/50083806
has answer: http://stackoverflow.com/a/50083898
has body: Simply I wanted to read the CSV file that I converted from a data frame after reading another CSV file and at the same time I tried to remove the header from it. Then I got the error below: PermissionError: [Errno 13] Permission denied: 'X_Data.csv' My Python code: import pandas as pd import numpy as np df = pd.read_csv('input_doc.csv').replace(' ?', np.nan).dropna() data_X = df.iloc[:, 1:15].values data_Y = df.iloc[:, :1].values clean_X = pd.DataFrame(data_X); clean_Y = pd.DataFrame(data_Y); clean_X.to_csv("X_Data.csv", index=False) clean_Y.to_csv("Y_Data.csv", index=False) X = pd.read_csv("X_Data.csv", encoding="utf-8", header=1) Y = pd.read_csv("Y_Data.csv", encoding="utf-8", header=1) Also I got the same error without removing header when reading. I found several issues that are similar to my problem, but those didn't fix my problem. I coded on Anaconda Spyder Editor in Windows 10. How can I read this file without getting this error? What am I missing?
answer count: 7
has answer: http://stackoverflow.com/a/75290785
score: 11
has answer: http://stackoverflow.com/a/60239289
has comment: http://stackoverflow.com/comment/87183415
has comment: http://stackoverflow.com/comment/87183929
favorite count: 0
has comment: http://stackoverflow.com/comment/87183492
has comment: http://stackoverflow.com/comment/87183935
tagged with: pandas
has answer: http://stackoverflow.com/a/74927581
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/77137070
has comment: http://stackoverflow.com/comment/89552305
has answer: http://stackoverflow.com/a/50085974
tagged with: python
upvote count: 13
linked to: http://stackoverflow.com/q/13207450
has answer: http://stackoverflow.com/a/60441519
type: Question
has comment: http://stackoverflow.com/comment/87183847
has title: PermissionError: Permission denied to reading CSV File in Python
has comment: http://stackoverflow.com/comment/87183858
has comment: http://stackoverflow.com/comment/87183690
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/87183786

http://stackoverflow.com/q/50146968
has title: python module attribute error - subpackage
tagged with: python
tagged with: module
type: Question
has comment: http://stackoverflow.com/comment/87313704
answer count: 0
has comment: http://stackoverflow.com/comment/87312120
type: UnansweredQuestion
tagged with: package
has body: I tried looking through stackoverflow but did not find a specifc explanation on how this works or what causes this error. Here is my setup python 3.6 here is my package structure main.py package1 - init.py (empty) - subpackage1 - init.py (empty) - module1.py in main.py import package1.subpackage1.module1 as moduel1 gives me this error AttributeError: module 'package1.subpackage1' has no attribute 'module1' Help me understand what I am doing wrong. Thanks in advance!!
score: 0
has comment: http://stackoverflow.com/comment/87312141

http://stackoverflow.com/q/50151655
tagged with: python
upvote count: 2
score: 2
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50182669
favorite count: 0
type: Question
has body: I have a device which is sending packet with its own specific construction (header, data, crc) through its ethernet port. What I would like to do is to communicate with this device using a Raspberry and Python 3.x. I am already able to send Raw ethernet packet using the "socket" Library, I've checked with wireshark on my computer and everything seems to be transmitted as expected. But now I would like to read incoming raw packet sent by the device and store it somewhere on my RPI to use it later. I don't know how to use the "socket" Library to read raw packet (I mean layer 2 packet), I only find tutorials to read higher level packet like TCP/IP. What I would like to do is Something similar to what wireshark does on my computer, that is to say read all raw packet going through the ethernet port. Thanks, Alban
has title: Read raw ethernet packet using python on Raspberry
tagged with: ethernet
tagged with: raspberry-pi
tagged with: linux
has comment: http://stackoverflow.com/comment/87321588
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/a/50216423
answers question: http://stackoverflow.com/q/50213563
has comment: http://stackoverflow.com/comment/87450797
has body: Here's a very minimal example using subprocess.run. Also, search StackOverflow for "python shell redirect", and you'll get this result right away: Calling an external command in Python import subprocess def run(filename, command): with open(filename, 'wb') as stdout_file: process = subprocess.run(command, stdout=subprocess.PIPE, shell=True) stdout_file.write(process.stdout) return process.returncode run('test_out.txt', 'ls')
has comment: http://stackoverflow.com/comment/87450763
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87450698

http://stackoverflow.com/comment/87259066
comment on: http://stackoverflow.com/q/50109515
type: Comment
score: 0
type: QuestionComment
has text: @Yabusa: what do you mean "why?" There is no deeper reason than that it is how the language works. In one case the argument to Button is a function, in the other case it is the result of a function call.

http://stackoverflow.com/a/57842166
has body: I realize this question has been answered, but I have recently had a similar issue with numpy and pandas dependancies with a dockerized project. That being said, I hope that this will be of benefit to someone in the future. My solution: As pointed out by Aviv Sela, Alpine does not contain build tools by default and will need to be added though the Dockerfile. Thus see below my Dockerfile with the build packages required for numpy and pandas for be successfully installed on Alpine for the container. FROM python:3.6-alpine3.7 RUN apk add --no-cache --update \ python3 python3-dev gcc \ gfortran musl-dev g++ \ libffi-dev openssl-dev \ libxml2 libxml2-dev \ libxslt libxslt-dev \ libjpeg-turbo-dev zlib-dev RUN pip install --upgrade pip ADD requirements.txt . RUN pip install -r requirements.txt The requirements.txt numpy==1.17.1 pandas==0.25.1 EDIT: Add the following (code snippet below) to the Dockerfile, before the upgrade pip RUN command. It is critical to the successful installation of pandas as pointed out by Bishwas Mishra in a comment. RUN pip install --upgrade cython
has comment: http://stackoverflow.com/comment/105574093
downvote count: 0
answers question: http://stackoverflow.com/q/50190676
upvote count: 13
score: 13
has comment: http://stackoverflow.com/comment/131325369
has comment: http://stackoverflow.com/comment/110998423
type: Answer
has comment: http://stackoverflow.com/comment/105540449
has comment: http://stackoverflow.com/comment/111014937

http://stackoverflow.com/q/50101117
score: 2
type: AnsweredQuestion
tagged with: pca
upvote count: 3
answer count: 1
tagged with: scikit-learn
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49160206
has title: TypeError grid search
tagged with: grid-search
tagged with: python
accepted answer: http://stackoverflow.com/a/50101641
tagged with: svm
has body: I used to create loop for finding the best parameters for my model which increased my errors in coding so I decided to use GridSearchCV. I am trying to find out the best parameters for PCA for my model (the only parameter I want to grid search on). In this model, after normalization I want to combine the original features with the PCA reduced features and then apply the linear SVM. Then I save the whole model to predict my input on. I have an error in the line where I try to fit the data so I can use best_estimator_ and best_params_ functions. The error says: TypeError: The score function should be a callable, all (&lt;type 'str'&gt;) was passed. I did not use any parameters for which I might need to give string in GridSearchCVso not sure why I have this error I also want to know if the line print("shape after model",X.shape) before saving my model, should should print (150, 7) and (150, 5) both based on all possible parameter? from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC from sklearn.datasets import load_iris from sklearn.decomposition import PCA from sklearn.feature_selection import SelectKBest from sklearn.preprocessing import StandardScaler from sklearn.externals import joblib from numpy import array iris = load_iris() X, y = iris.data, iris.target print(X.shape) #prints (150, 4) print (y) #cretae models and piplline them combined_features = FeatureUnion([("pca", PCA()), ("univ_select", SelectKBest(k='all'))]) svm = SVC(kernel="linear") pipeline = Pipeline([("scale", StandardScaler()),("features", combined_features), ("svm", svm)]) # Do grid search over n_components: param_grid = dict(features__pca__n_components=[1,3]) grid_search = GridSearchCV(pipeline, param_grid=param_grid, cv=5, verbose=10) grid_search.fit(X, y) print("best parameters", grid_search.best_params_) print("shape after model",X.shape) #should this print (150, 7) or (150, 5) based on best parameter? #save the mode…
has answer: http://stackoverflow.com/a/50101641

http://stackoverflow.com/comment/87402073
comment on: http://stackoverflow.com/a/50175924
has text: @ChatterOne I don't think that is enough. The sum of 2 means they intersect, not that a's 1's are first.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87422628
comment on: http://stackoverflow.com/a/50202890
score: 1
type: Comment
type: AnswerComment
has text: @Anonymous and yet it isn't, like you asked.

http://stackoverflow.com/q/50136894
has comment: http://stackoverflow.com/comment/106265887
tagged with: python
has comment: http://stackoverflow.com/comment/106266186
has comment: http://stackoverflow.com/comment/87292044
tagged with: putty
has body: I am new to Linux, and I want to run my python scripts using Jupyter Notebook from remote machine using Putty. I have set environment variables for Anaconda. After successful login I enter the command $ export PATH="/share/apps/packages/anaconda2/bin:$PATH" and $ jupyter notebook It displays the following window and a message "Jupyter Notebook requires Javascript. Please enable it to proceed". My question is how to enable javascript and run scripts on notebook.
tagged with: linux
tagged with: anaconda
downvote count: 0
has answer: http://stackoverflow.com/a/60084077
answer count: 1
favorite count: 0
tagged with: jupyter-notebook
type: Question
has title: Jupyter Notebook requires javascript. Accesing from remote server machine using Putty.
upvote count: 5
score: 5
type: UnansweredQuestion

http://stackoverflow.com/comment/87326442
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50153065
type: Comment
has text: You need something with 2 dimensions but the product must be equal to `206580`. You can try something like this: `test_image = test_image.reshape(img_width, img_height * 3)` but I don't know if it's correct.

http://stackoverflow.com/q/50205251
has title: Hello, someone knows how to make 3D games with Python?
has comment: http://stackoverflow.com/comment/87427702
accepted answer: http://stackoverflow.com/a/50205601
has body: As the programming language that is Python I wanted to know if in addition to making games in 2d with pygame I can create 3D games with Python which would be much more attractive for people (I guess) thanks in advance.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50205601
downvote count: 4
upvote count: 2
has comment: http://stackoverflow.com/comment/87427654
score: -2
answer count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/87329342
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50146616
has text: @DanielF You are right, that should be even faster. Could you give me a pointer to your post so I can properly credit you?

http://stackoverflow.com/q/50189659
has body: I need to figure out how to structure my data in python such that when I call dumps and write to file I get the following structure of data as an example: { "Prop_a": [ { "car": "brown", "color": "yellow", "engine": [ { "mod_a": "x1", "name": [ { "diesel": "yes", } ... As you can see, I have nested elements that need expanded. The end-goal is to import the data into a database, I need JSON or CSV formatted data to do it. EDIT: To all: I can easily print a single level of the dict of lists to JSON. What I need assistance with is how to format the nested structure. EDIT #2: Since code is being requested... my_dict = {} for x in group: my_dict[x] = [] for y in sub_group: mydict[x].append(data_symbol_reference) Produces an output like: { "Prop_a" : [ "car", "color", ], ... I need assistance on the nesting the dict of lists within the list structure.
has comment: http://stackoverflow.com/comment/87396144
has comment: http://stackoverflow.com/comment/87396125
has comment: http://stackoverflow.com/comment/87396883
downvote count: 3
has comment: http://stackoverflow.com/comment/87396380
tagged with: python
has comment: http://stackoverflow.com/comment/87405845
has comment: http://stackoverflow.com/comment/87396303
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87396214
has comment: http://stackoverflow.com/comment/87397144
has comment: http://stackoverflow.com/comment/87396947
has comment: http://stackoverflow.com/comment/87397193
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87396189
score: -2
has comment: http://stackoverflow.com/comment/87396105
linked to: http://stackoverflow.com/q/17043860
answer count: 1
has comment: http://stackoverflow.com/comment/87396124
upvote count: 1
has title: Writing nested lists to json
has answer: http://stackoverflow.com/a/50189694
has comment: http://stackoverflow.com/comment/87396492

http://stackoverflow.com/comment/87282881
comment on: http://stackoverflow.com/a/50131943
type: Comment
score: 0
type: AnswerComment
has text: what can be the problem? because i did not find any error

http://stackoverflow.com/comment/87174299
type: Comment
has text: @Mr.Robot I think your code is modifying objects that you have not mentioned. What variables are you modifying ?, in my example I do not modify variables created in the GUI thread, use QThread in this case it would have the same effect but you would have to write more code, please provide a code closer to the one you have.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50078592

http://stackoverflow.com/comment/87237421
comment on: http://stackoverflow.com/a/50109189
type: Comment
score: 0
type: AnswerComment
has text: @bariumdose yes, thanks for that. Wrote this without an ounce of testing, so glad it worked! As for the regex, that's easily explained. It's just specifying a named capture group (you can look this concept up on the docs), and pandas translates that to the column name. If you liked the answer, do consider up voting it as well. Good luck!

http://stackoverflow.com/comment/87468242
has text: You will need a different library to manipulate excel files to this granularity (e.g. [`openpyxl`](http://openpyxl.readthedocs.io/en/stable/)). Splitting `col1` is pretty simple, e.g.: `df'svc_no', 'port', 'Result' = df.col1.str.split('|', expand=True)`. Then you can drop `col1`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50225400
score: 0
type: Comment

http://stackoverflow.com/a/50096338
has body: your chrome driver seems to be old , the latest version is 2.38, try to upgrade and check
answers question: http://stackoverflow.com/q/50093985
score: 0
has comment: http://stackoverflow.com/comment/87220907
has comment: http://stackoverflow.com/comment/87226579
has comment: http://stackoverflow.com/comment/87221330
type: Answer

http://stackoverflow.com/a/50102819
answers question: http://stackoverflow.com/q/50102678
has body: You're printing out something, because you are adding 8 to the start variable. Find returns negative one if the string is not found. So what you end up doing is printing out the elements from [7:-1]. I would add an if statement before the print statement: start = file.find('Bad value') end = file.find('SPAN', start) if start != -1 and end != -1: print(file[start + 9: end])
type: Answer
score: 0

http://stackoverflow.com/a/50180068
has comment: http://stackoverflow.com/comment/87377594
upvote count: 3
has comment: http://stackoverflow.com/comment/87379679
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87377886
downvote count: 0
has body: If your CSV file isn't enormous, I suggest reading the whole thing, extracting the data you want into a dictionary, with the ticket number as the key. Searching a dict is very fast. I've modified your file opening code to use the with statement, which fails gracefully if there's a problem reading the file. BTW, there's no need to specify the comma as the CSV delimiter, since that the default delimiter. import csv with open('Path To CSV file', "rb") as f: data = {line[1]: (line[36], line[37]) for line in csv.reader(f)} newtickets = raw_input('Enter Ticket Numbers:').split() for ticket in newtickets: line = data.get(ticket) if line: print(ticket, line) else: print(ticket, "not found") The dict.get method returns None if the key isn't in the dict, although you can specify another default return value if you want. So we could re-write that part like this: for ticket in newtickets: line = data.get(ticket, "not found") print(ticket, line) Alternatively, we could use the in operator: for ticket in newtickets: if ticket in data: print(ticket, data[ticket]) else: print(ticket, "not found") All 3 versions have roughly the same efficiency, choose whichever you feel is the most readable.
score: 3
accepted answer of: http://stackoverflow.com/q/50179852
has comment: http://stackoverflow.com/comment/87377580
has comment: http://stackoverflow.com/comment/87377396
type: Answer
answers question: http://stackoverflow.com/q/50179852
has comment: http://stackoverflow.com/comment/87377703
has comment: http://stackoverflow.com/comment/87377954

http://stackoverflow.com/comment/87425052
type: AnswerComment
comment on: http://stackoverflow.com/a/50203906
has text: Well, according to [the docs](https://github.com/nschloe/pygmsh/blob/master/README.md), it should be `pg.built_in.Geometry()`.
score: 0
type: Comment

http://stackoverflow.com/comment/87420629
comment on: http://stackoverflow.com/q/50201842
type: Comment
score: 1
has text: @all - see **UPDATE** above...this is insane!
type: QuestionComment

http://stackoverflow.com/comment/87282373
comment on: http://stackoverflow.com/q/50131823
type: QuestionComment
score: 1
has text: Pretty much every operation in every data pipe line entails generating a CSV file and passing it to the next step.
type: Comment

http://stackoverflow.com/comment/87337702
has text: Also, you need to tell us what was wrong with your output. Just saying "another way" isn't much help. To get help from us, you must help us help you. Do all the work you can think of doing to make it easy for others to help you!
comment on: http://stackoverflow.com/q/50159682
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87188157
comment on: http://stackoverflow.com/q/50086216
score: 0
type: Comment
has text: Can you try removing the app_name parameter. Also are you using standalone spark or did you `pip install pyspark`?
type: QuestionComment

http://stackoverflow.com/a/50151810
type: Answer
score: 0
has body: is this dataset a .csv file or a dataframe. This NA is a 'NaN' or a string ? import pandas as pd import numpy as np df=pd.read_csv('your dataset',sep=' ') df.replace('NA',np.nan) df.fillna(method='ffill',inplace=True) you mention something about mean of 3 values..the above simply forward fills the last observation before the NaNs begin. This is often a good way for forecasting (better than taking means in certain cases, if persistence is important) ind = df['NET_SALES'].index[df['NET_SALES'].apply(np.isnan)] Meanof3 = df.iloc[ind[0]-3:ind[0]].mean(axis=1,skipna=True) df.replace('NA',Meanof3) Maybe the answer can be generalised and improved if more info about the dataset is known - like if you always want to take the mean of last 3 measurements before any NA. The above will allow you to check the indices that are NaNs and then take mean of 3 before, while ignoring any NaNs
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50151197
answers question: http://stackoverflow.com/q/50151197

http://stackoverflow.com/a/50204751
has body: You can do a groupby with axis=1: In [11]: df Out[11]: first_RG7509 first_YY6124 last_YY6124 first_WE4818 first_AA7542 last_RG7509 0 1 0 1 1 0 0 In [12]: df.groupby(lambda x: x.split("_")[1], axis=1).sum() Out[12]: AA7542 RG7509 WE4818 YY6124 0 0 1 1 1
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50204623
downvote count: 0

http://stackoverflow.com/comment/87337770
type: QuestionComment
has text: We don't need to see your Google Calendar code, but we _do_ need to see the strings you're feeding to the code you posted so we can try to reproduce this bug.
type: Comment
comment on: http://stackoverflow.com/q/50159655
score: 0

http://stackoverflow.com/comment/87276473
type: Comment
has text: If you want to return a string when calling `type` on object, you should look into metaclasses. But I really think what you are trying to achieve can be done in a simpler way.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50128608

http://stackoverflow.com/a/50176245
downvote count: 1
has body: Use basename instead of splitting: &gt;&gt;&gt; s = r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls" &gt;&gt;&gt; import os &gt;&gt;&gt; os.path.basename(s) 'futurefilesomf.egus.xls'
type: Answer
answers question: http://stackoverflow.com/q/50176087
upvote count: 2
score: 1

http://stackoverflow.com/comment/87268282
type: Comment
has text: Looks like that's the issue, I never did save it. I came from PyCharm and you don't have to save it to run the script
comment on: http://stackoverflow.com/a/50124994
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87304606
has text: @cᴏʟᴅsᴘᴇᴇᴅ ok, but outer is restricted to division or multiplication between a and d. With broadcasting you could do the same for addition, for example.
comment on: http://stackoverflow.com/a/50143168
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87286869
has text: @PratikKumar, Ooops... I missed the square brackets... But now, I have another problem... The newly created csv file has an extra column (the '0' th column) of numbers from 0, 1, 2... for each row. It does not have any header though. Any ideas on how to delete that column??? Thanks!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50129767

http://stackoverflow.com/q/50105309
upvote count: 2
score: 2
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50105428
downvote count: 0
has answer: http://stackoverflow.com/a/50105428
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am able to convert the csv to json file.Right now, I can create JSON file through the field names, see current output section. There are multiple name in "team_members" field that has been separated by ','. How do I convert the team_members names into a Element through python? Data: (demo.csv) id,team_name,team_members 123,Biology,"Ali Smith, Jon Doe" 234,Math,Jane Smith 345,Statistics ,"Matt P, Albert Shaw" 456,Chemistry,"Andrew M, Matt Shaw, Ali Smith" 678,Physics,"Joe Doe, Jane Smith, Ali Smith " Python Code: import csv import json csvfile = open('files/csv/input/demo.csv', 'r') jsonfile = open('files/csv/input/demo.csv', 'w') fieldnames = ("id", "team_name", "team_members") reader = csv.DictReader( csvfile) # without headers # reader = csv.DictReader( csvfile, fieldnames) # with headers for row in reader: json.dump(row, jsonfile) jsonfile.write('\n') Current Output: Gives the json file with fields {"id": "123", "team_name": "Biology", "team_members": "Ali Smith, Jon Doe"} {"id": "234", "team_name": "Math", "team_members": "Jane Smith "} {"id": "345", "team_name": "Statistics ", "team_members": "Matt P, Albert Shaw"} {"id": "456", "team_name": "Chemistry", "team_members": "Andrew M, Matt Shaw, Ali Smith"} {"id": "678", "team_name": "Physics", "team_members": "Joe Doe, Jane Smith, Ali Smith "} Final Output Needed: {"id": "123", "team_name": "Biology", "team_members": ["Ali Smith", "Jon Doe"]} {"id": "234", "team_name": "Math", "team_members": ["Jane Smith"]}, {"id": "345", "team_name": "Statistics ", "team_members": ["Matt P", "Albert Shaw"]} {"id": "456", "team_name": "Chemistry", "team_members": ["Andrew M", "Matt Shaw", "Ali Smith"]} {"id": "678", "team_name": "Physics", "team_members": ["Joe Doe", "Jane Smith", "Ali Smith "]}
possible better answer: http://stackoverflow.com/a/50105365
tagged with: python
has answer: http://stackoverflow.com/a/50105365
has title: python: csv to json create elements separated by comma
has answer: http://stackoverflow.com/a/50105507
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/a/50194409
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50191768
type: Answer
has body: You can try OpenFaas to dockerize your python scripts with a webserver on top. You can use the full OpenFaas stack to create single API functions mapped to single containers or you can use only the OpenFaas web component. A simple Dockerfile could be something like: FROM python:3.4-alpine ADD . /workdir WORKDIR /workdir ADD https://github.com/openfaas/faas/releases/download/0.7.9/fwatchdog /usr/bin RUN chmod +x /usr/bin/fwatchdog ENV fprocess="python yourPythonScript.py" CMD ["fwatchdog"] Build it and run it: $ docker build . -t dockerized-python-script [....] $ docker run -p 8080:8080 dockerized-python-script And you are ready to "talk" to your script via http with plaintext parameters: $ curl yourserver:8080 -d "param1 param2 param3" Some output from your script If you want to talk JSON, you'll need to modify yourPythonScript.py accordingly to manage input and output.
downvote count: 0

http://stackoverflow.com/comment/87498604
type: Comment
comment on: http://stackoverflow.com/a/50107933
has text: I just realized that I don't need to use `.apply`. I can simply do `.diff() < pd.Timedelta(days=5)`. It saves a lot of execution time.
type: AnswerComment
score: 1

http://stackoverflow.com/a/50135782
accepted answer of: http://stackoverflow.com/q/50134448
type: Answer
answers question: http://stackoverflow.com/q/50134448
score: 0
type: AcceptedAnswer
has body: I got the answer from the following link: PYQT Qcombobox set value selected to a variable It is quite helpful. Just had to add the following lines to the code. The code looks neat by creating a separate method (temp_var). self.comboBox.activated[str].connect(self.temp_var) def temp_var(self, text): cur_txt = text if cur_txt == 'A': self.groupBox.show() else: self.groupBox.hide()

http://stackoverflow.com/a/50124926
has body: i think that you should have something like a ForeignKey to Question model to your Vote model? If it so, you maybe should do something like this: {% for choice in question.vote_set.all %} {% empty %} {% endfor %} If think that we need more information about your models in order to help you. Please add your models code, at least the Question models.
type: Answer
has comment: http://stackoverflow.com/comment/87268589
answers question: http://stackoverflow.com/q/50124863
score: 0

http://stackoverflow.com/comment/87329961
type: Comment
score: 0
type: AnswerComment
has text: Oh Christ, I feel so dumb now. Thanks a lot for your help! On a side note, how would you do it if you had not one `QLineEdit`, but like 20 of them? Would you pass them individually to the function `export`, with a list or dictionary? Or would you change the structure entirely?
comment on: http://stackoverflow.com/a/50155660

http://stackoverflow.com/q/50076420
answer count: 1
has body: For one my Robotics projects, I am trying to grab an image from Nao Robot's camera and use Tensorflow for object recognition. The problem is that the Robot's NaoQi API is built on Python2.7 32bit. (http://doc.aldebaran.com/1-14/dev/python/install_guide.html) The Tensorflow Object recognition API works only with 64bit. (https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md and https://www.tensorflow.org/install/install_windows) I am using Windows 10 and I have both Python 2.7 32 bit and 3.6 64bit installed and I am able to run the modules independently but I am unable to pass the image between the two. Are there any workarounds to address this issue? Thank you.
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: robotics
tagged with: nao-robot
downvote count: 0
has title: How to combine Python 32bit and 64bit modules
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50076925
score: 3
has answer: http://stackoverflow.com/a/50076925
upvote count: 3

http://stackoverflow.com/comment/131859514
has text: @JeffLearman I came back to this post today because someone upvoted it. I now see what you meant at the time. Thanks for trying to steer me in the right direction (although I think it flew straight over my head at the time lol)
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50124425

http://stackoverflow.com/q/50141802
tagged with: dataframe
tagged with: python
has title: Claasification of testdata containg string columns
type: Question
answer count: 0
tagged with: random-forest
tagged with: classification
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87328298
has comment: http://stackoverflow.com/comment/87313163
score: 0
has comment: http://stackoverflow.com/comment/87301911
has body: So I am using Machine Learning to predict class of some data as given below sample. My data is related to some scheduler running on server and by submission time and server_type I am labeling the class Dataframe: df= sch_name server_type subit_time submit_by Class RCALCAPP X3333 165703 AAAA 1 RCALCAPP X3333 105703 BBBB 0 PCALCAPP X3333 165703 AAAA 1 . . TCALCAPP X3344 095703 CCCC 0 TO run classifier I am doing lableencoding for string column values. Not sure if it is correct approch to ecode or not but it is working for me le = preprocessing.LabelEncoder() df = df.apply(le.fit_transform) Also I dont need submit_by column to train classifier so I am removing it featureNames = [col for col in df.columns if col not in ['submit_by','status']] TO prepare a model I have splitted above dataframe into training, cv, test and using below trainFeatures = training[featureNames].values trainClasses = training['status'].values testFeatures= test[featureNames].values testClasses = test['status'].values clf = RandomForestClassifier() clf.fit(trainFeatures, trainClasses) score = clf.score(testFeatures, testClasses) print(score) #.99823742 Till here every thing is okay.classifier is running on data. But nowI want to test new new record for classification. I tried to do following: test_sch = ['TCALCAPP', 'X3344', '075703'] class_code = clf.predict(test_sch) # [1] It gave error ValueError: could not convert string to float: 'TCALCAPP' And I know the reason as It has not been encoded to number. Here is my problem how to do that exactly. I need to pass encoded value for 'TCALCAPP', 'X3344'. But How I would know encoded value for a new test data. My approach could be wrong but requirement is same as above. Kindly help.

http://stackoverflow.com/comment/87299028
has text: SQLite column names are not case sensitive, and there is no HELP command.
comment on: http://stackoverflow.com/a/50139527
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87260413
type: Comment
comment on: http://stackoverflow.com/a/50116516
type: AnswerComment
has text: Thanks, it's great. would you please post the full code below?
score: 1

http://stackoverflow.com/comment/129224745
has text: It's not only limited, but also more complex and harder to use...
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50215974
type: AnswerComment

http://stackoverflow.com/q/50160889
has body: I recently started programming with Tensorflow on python. I wanted to improve the calculation-power using my GTX 1050 in my laptop but i didn't success... After installing all the required libraries and softwares (CUDA 9.0, CuDNN for CUDA 9.0, imported : tensorflow and tensorflow-gpu...), I tryed basic example from the Tensorflow website : import tensorflow as tf 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) sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) print(sess.run(c))` but this return the following answer (I translate it right after) : 2018-05-03 19:15:59.540038: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 Device mapping: no known devices. 2018-05-03 19:15:59.543664: I T:\src\github\tensorflow\tensorflow\core\common_runtime\direct_session.cc:284] Device mapping: MatMul: (MatMul): /job:localhost/replica:0/task:0/device:CPU:0 2018-05-03 19:15:59.546930: I T:\src\github\tensorflow\tensorflow\core\common_runtime\placer.cc:886] MatMul: (MatMul)/job:localhost/replica:0/task:0/device:CPU:0 b: (Const): /job:localhost/replica:0/task:0/device:CPU:0 2018-05-03 19:15:59.547254: I T:\src\github\tensorflow\tensorflow\core\common_runtime\placer.cc:886] b: (Const)/job:localhost/replica:0/task:0/device:CPU:0 a: (Const): /job:localhost/replica:0/task:0/device:CPU:0 2018-05-03 19:15:59.547597: I T:\src\github\tensorflow\tensorflow\core\common_runtime\placer.cc:886] a: (Const)/job:localhost/replica:0/task:0/device:CPU:0 [[22. 28.] [49. 64.]] This heavy message mean that the only device available on my laptop is my CPU but I have a GTX 1050. I tried to add this line at the begining : with tf.device("/device:gpu:0"): I spare you all the insult of the command line but it return me this : Operation was explicitly assigned to /d…
answer count: 1
upvote count: 1
has title: How to use Tensorflow with a GTX 1050 mobile edition?
downvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87344804
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50164342
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87345572
score: 0
has comment: http://stackoverflow.com/comment/87343993

http://stackoverflow.com/q/50165123
type: Question
has title: Python - Concatenate Two Strings Separated by Double Newline
has answer: http://stackoverflow.com/a/50165151
tagged with: python
has answer: http://stackoverflow.com/a/50165207
favorite count: 0
score: -1
tagged with: list
answer count: 4
has body: I currently have a list, one index of which contains a double newline (\n\n). I want to remove the \n\n and concatenate the two strings it separated. I.e. "hello\n\nworld" becomes "hello world", and not "hello", "world".
has answer: http://stackoverflow.com/a/50165149
downvote count: 2
upvote count: 1
type: UnansweredQuestion
tagged with: string
has comment: http://stackoverflow.com/comment/87348241
linked to: http://stackoverflow.com/q/14560863
has answer: http://stackoverflow.com/a/50165191

http://stackoverflow.com/a/50183074
score: 2
has comment: http://stackoverflow.com/comment/87383894
has comment: http://stackoverflow.com/comment/87383644
has comment: http://stackoverflow.com/comment/87383627
downvote count: 0
has body: d = {'a': {'1':4,'2':6},'b': {'1':5,'2':10}} newd = {} for key, value in d.items(): max_value = max([i for i in value.values()]) for k in value: if value[k] == max_value: newd[key] = k print(newd) # prints '{'a': '2', 'b': '2'}'
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/87383958
answers question: http://stackoverflow.com/q/50183032

http://stackoverflow.com/comment/87425170
comment on: http://stackoverflow.com/q/50203934
type: Comment
type: QuestionComment
has text: `kwargs['size']=5` would be preferred if the user of your class might specify size and you want to override.
score: 0

http://stackoverflow.com/q/50134545
favorite count: 0
tagged with: plot
type: Question
tagged with: python-3.x
tagged with: performance
has title: What is more efficient?: Many small CDSs or one huge CDS with many "NaN" values?
tagged with: python
answer count: 0
downvote count: 0
upvote count: 1
has body: I am developing an Bokeh Server Application. I would like to plot 10-15 plots with 10 glyphs each one, at least. So I need some ColumnDataSource (CDS) with different sizes. I have checked that if I use many CDS, the bokeh server becomes unstable. So I had to reduce the number of CDSs. I need to use at least 4 CDSs in the application: CDS for points - 2500 values - main data, three point glyphs per plot CDS for multilines (profiles) - few values, three lists of points per profile, six profiles per plot CDS for profile circles - the same points as the multiline profiles, but I could use a CDSView here with filters CDS for datatable - 10-20 values, two columns, to show the selected sample Questions Which is the limit number of CDS I should use? Instead of many CDSs I could add many columns to the main CDS (2400 rows), but if I do this I had to fill each column with many NaN values (2400 - N values, where N is about 10-20). Is this the most efficient way to do this?
type: UnansweredQuestion
score: 1
tagged with: bokeh

http://stackoverflow.com/q/50187342
tagged with: tensorflow
favorite count: 0
type: Question
has title: TensorFlow gradient with tf.where returns NaN when it shouldn't
tagged with: python
accepted answer: http://stackoverflow.com/a/50189279
score: 2
type: AnsweredQuestion
has body: Below is reproducible code. If you run it, you will see that in the first sess run, the result is nan, whereas the second case gives the correct gradient value of 0.5. But per tf.where and condition specified, they should return the same value. I also simply don't understand why the tf.where function gradient is nan at 1 or -1, which seem to be totally fine input values to me. tf.reset_default_graph() x = tf.get_variable('x', shape=[1]) condition = tf.less(x, 0.0) output = tf.where(condition, -tf.log(-x + 1), tf.log(x + 1)) deriv = tf.gradients(output, x) with tf.Session() as sess: print(sess.run(deriv, {x:np.array([-1])})) logg = -tf.log(-x+1) derivv = tf.gradients(logg, x) with tf.Session() as sess: print(sess.run(derivv, {x:np.array([-1])})) Thanks for comments!
has comment: http://stackoverflow.com/comment/87391939
upvote count: 2
tagged with: gradient
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50189279

http://stackoverflow.com/q/50203382
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/87464356
tagged with: custom-errors
score: 1
has comment: http://stackoverflow.com/comment/87506359
favorite count: 0
type: Question
has body: I have three different files: A class file lang.py that has the following function from errors import StatusCodeError class LangModel: def __init__(self, localpath2fst, host="127.0.0.1", port="5000", logfile="log"): ... def state_update(self): """ Initialize the language model (on the server side) """ try: r = requests.post( 'http://' + self.host + ':' + self.port + '/init') except requests.ConnectionError: raise ConnectionErr(self.host, self.port) if not r.status_code == requests.codes.ok: raise StatusCodeError(r.status_code) An error file errors.py: class StatusCodeError(Exception): def __init__(self, status_code): self.dErrArgs = status_code Exception.__init__( self, "Connection was not established and has status code {0}".format(self.dErrArgs)) and a third file test.py import unittest from lang import LangModel from errors import StatusCodeError class TestPreLM(unittest.TestCase): def test_incorrect_input(self): """ confirm the process provides an error given an incorrect input """ abs_path_fst = os.path.abspath("a valid path") # local fst localfst = abs_path_fst # init LMWrapper lmodel = LangModel( localfst, host='127.0.0.1', port='5000', logfile="lmwrap.log") # try to get priors with self.assertRaises(StatusCodeError): lmodel.state_update(['3']) Oddly enough when I have the test code found within the class file, the test succeeds but when it is found in isolation (in test.py) the test fails and I'm unsure why. If you can lighten my way I'll be happy ;)
has title: unittest for custom errors
answer count: 0

http://stackoverflow.com/comment/87200364
type: Comment
type: QuestionComment
has text: @slackmart, it returns the same list containing the same single element before and after.
score: 0
comment on: http://stackoverflow.com/q/50082612

http://stackoverflow.com/q/50075259
accepted answer: http://stackoverflow.com/a/50075269
type: AnsweredQuestion
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: decorator
favorite count: 0
type: Question
has body: The code is given as following: import time import sys def LogClassFuncInfos(func): def wrapper(*s, **gs): methodName = format(func.__name__) print(methodName) func(*s, **gs) return wrapper class NameModel(): def __init__(self): self.name = 'test' @LogClassFuncInfos def getName(self): return self.name a = NameModel() print(a.getName()) The code is expected to print 'test', but the code prints None. If the @LogClassFuncInfos before def getName(self) is removed, the 'test' can be normally printed.
tagged with: python
has answer: http://stackoverflow.com/a/50075269
has title: A bug about decorator in Python

http://stackoverflow.com/a/50156650
answers question: http://stackoverflow.com/q/50156579
type: Answer
has body: You have set related_name='user' on the foreign key on you UserProfile model, which means you have to access it with user.user. related_name defines how you access the reverse relationship, not the forward one, so setting it to user is a bit confusing, and probably isn't how you intended for it to work. You might consider changing the related_name to "profile" so that you can instead access it as user.profile.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50156579
score: 5
upvote count: 5

http://stackoverflow.com/q/50148148
score: 1
possible better answer: http://stackoverflow.com/a/50148506
accepted answer: http://stackoverflow.com/a/50148427
downvote count: 0
has answer: http://stackoverflow.com/a/50148506
has answer: http://stackoverflow.com/a/50148427
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50148481
has comment: http://stackoverflow.com/comment/87316926
has body: A bank has the following exchange rates: 83.5 ($ to tzsh), 86.8 (tzsh to $). A customer wants to repeatedly exchange 1,000 dollars back and forth from dollars to shillings and vice versa. Develop a simple program (in any language) to show after how many exchanges the customer ends up with zero. I am new at Python and I am sure there is something wrong with my code: x=0 y=1000 while x&lt;1000: x=(83.5*y)/86.8 print x y=x
tagged with: python
has comment: http://stackoverflow.com/comment/87314526
has comment: http://stackoverflow.com/comment/87314624
type: AnsweredQuestion
has title: How to calculate exchange rate with python script
answer count: 3

http://stackoverflow.com/comment/87266016
type: Comment
has text: I agree partially with your other comment - I may have simplified the example a bit too much. I've updated my question! Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/50122514
score: 0

http://stackoverflow.com/comment/87280022
type: Comment
type: QuestionComment
has text: yeah, your logic seems to be much more pytonic than my. There are random chance for each value to become 0 .
comment on: http://stackoverflow.com/q/50130781
score: 0

http://stackoverflow.com/comment/87401175
type: Comment
type: QuestionComment
has text: Try `import foo.bar` followed by `print(foo.bar)` and `print(dir(foo.bar))`, to see what you actually imported.
comment on: http://stackoverflow.com/q/50191395
score: 0

http://stackoverflow.com/a/50194479
type: Answer
answers question: http://stackoverflow.com/q/50194414
has comment: http://stackoverflow.com/comment/87574086
has comment: http://stackoverflow.com/comment/87406972
downvote count: 0
upvote count: 1
has body: You can create a simple function outside the class to wrap each method: def create_session(**kwargs): def outer(f): def wrapper(cls, *args): Session = sessionmaker(bind=getattr(cls, 'engine')) session = Session() getattr(session, kwargs.get('action', 'add'))(f(cls, *args)) session.commit() session.close() return wrapper return outer class UserDatabaseManager(object): DEFAULT_DB_PATH = 'test.db' def __init__(self, dbpath=DEFAULT_DB_PATH): dbpath = 'sqlite:///' + dbpath self.engine = create_engine(dbpath, echo=True) @create_session(action = 'add') def add_user(self, username, password): return User(username, password) @create_session(action = 'delete') def delete_user(self, user): return User(username, password) Generally, setup and tear-down operations like the above are best put in a contextmanager: class UserDatabaseManager(object): DEFAULT_DB_PATH = 'test.db' def __init__(self, dbpath=DEFAULT_DB_PATH): dbpath = 'sqlite:///' + dbpath self.engine = create_engine(dbpath, echo=True) class UserAction(UserDatabaseManager): def __init__(self, path): UserDatabaseManager.__init__(self, path) def __enter__(self): self.session = sessionmaker(bind=self.engine)() return self.session def __exit__(self, *args): self.session.commit() self.session.close() with UserAction('/the/path') as action: action.add(User(username, password)) with UserAction('/the/path') as action: action.remove(User(username, password))
has comment: http://stackoverflow.com/comment/87407052
score: 1

http://stackoverflow.com/comment/100079450
has text: This worked for fixing the example code for [pyzmq](https://pyzmq.readthedocs.io/en/latest/serialization.html) as well.
comment on: http://stackoverflow.com/a/50163814
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50182991
score: 0
has title: Using both SPIs of Rasberry with two different RTDs
tagged with: sensors
tagged with: python
tagged with: spi
tagged with: raspberry-pi
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100367502
answer count: 1
has body: I am using the following code to get the temperature of a PT100 (3-wire) and a PT1000 (2-wire) simultaneously on my raspberry. According to https://cdn-learn.adafruit.com/downloads/pdf/adafruit-max31865-rtd-pt100-amplifier.pdf my wiring is correct. from Max31865 import Max31865 maxGarraum = Max31865() maxGarraum.initPt100_3WireSensor(26, True) maxFleisch = Max31865() maxFleisch.initPt1000_2WireSensor(24, True) while True: maxGarraum.getCurrentTemp() time.sleep(1) My Max31865.py looks like the following: import time, math import RPi.GPIO as GPIO # import numpy class Max31865(): def initPt1000_2WireSensor(self, iCsPin): self.csPin = iCsPin # Fleischsensor Pt1000 (2-wire) self.registerCode = 0xA2 self.setupGPIO() def initPt100_3WireSensor(self, iCsPin): self.csPin = iCsPin # Garraumsensor Pt100 (3-wire) self.registerCode = 0xB2 self.setupGPIO() def setupGPIO(self): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.csPin, GPIO.OUT) GPIO.setup(self.misoPin, GPIO.IN) GPIO.setup(self.mosiPin, GPIO.OUT) GPIO.setup(self.clkPin, GPIO.OUT) GPIO.output(self.csPin, GPIO.HIGH) GPIO.output(self.clkPin, GPIO.LOW) GPIO.output(self.mosiPin, GPIO.LOW) def getCurrentTemp(self):is # b10000000 = 0x80 # 0x8x to specify 'write register value' # 0xx0 to specify 'configuration register' # # 0b10110010 = 0xB2 # Config Register - https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf # --------------- # bit 7: Vbias -&gt; 1 (ON) # bit 6: Conversion Mode -&gt; 0 (MANUAL) # bit 5: 1-shot -&gt;1 (ON) # bit 4: 3-wire select -&gt; 1 (3 wire config) (0 for 2-/4-wire) # bit 3-2: fault detection cycle -&gt; 0 (none) # bit 1: fault status clear -&gt; 1 (clear any fault) # bit 0: 50/60 Hz filter select -&gt; 0 (60Hz) # # 0b11010010 or 0xD2 for continuous auto conversion # at 60Hz (faster conversion) # one shot self.writeRegister(0, self.registerCode) # conversion time is less than 100ms time.sleep(.1) # give it 100ms for conversion # read all registers out = self.readRegisters(0, 8) co…
type: Question
has answer: http://stackoverflow.com/a/50184445

http://stackoverflow.com/q/50198172
score: 3
type: UnansweredQuestion
has body: I am pretty new to Django and I am trying to figure out how to add content dynamically coming from a python script without reloading a page. Currently, I have two functions in my views.py file. One handles uploading a file (home), and the other handles calling a python script and handling the file (handle). The reason I separated it like this is because I want to sequentially populate a HTML table as the python script works with the uploaded file. However, my ajax function is not receiving any data from the handle function's http response and I am not sure why. Neither the success nor the error functions are being called. This is really strange because the print statement in the handle function in views.py prints successfully with data. Views.py i=0 uploaded_file = None def home(request): if (request.method == 'POST'): file_form = UploadFileForm(request.POST, request.FILES) if file_form.is_valid(): global uploaded_file uploaded_file = request.FILES['file'] print(uploaded_file) else: file_form = UploadFileForm() return render(request, 'personal/home.html', {'form': file_form}) def handle(request): # TODO make ajax wait for a response from 'home' # so I don't have to wait for 1 second time.sleep(1) data = {} data['Name'] = fileName(uploaded_file) if(request.is_ajax()): print(data) # prints succesfully return HttpResponse(json.dumps(data), content_type="application/json") home.html &lt;script type = "text/javascript" language = "javascript"&gt; function post_tables(data) { alert(data) } $(document).ready(function(post_tables) { $("#upload").click(function(event){ $.ajax( { contentType: "application/json; charset=utf-8", dataType: "json", type: "get", url:'/handler', success: function(data) { console.log("over here") post_tables(data) }, error: function(data) { console.log("down here") post_tables("error being thrown") } }); }); }); &lt;/script&gt; urls.py urlpatterns = [ path(r'', views.home, name='home'), path(r'handler', views.handle, name='handle'), ]
tagged with: javascript
tagged with: python
has title: Django: Ajax not receiving data from server response
has comment: http://stackoverflow.com/comment/87414732
has answer: http://stackoverflow.com/a/50198718
upvote count: 3
answer count: 1
downvote count: 0
tagged with: django
tagged with: jquery
favorite count: 0
type: Question
tagged with: ajax

http://stackoverflow.com/comment/87462872
type: Comment
type: AnswerComment
has text: Great Suggestion Most of our code is written in HTML. Verify Email How will I translate the phrases like "Verify Email"? Do I need to write the translation of it in every required language in excel and figure out how to import in html file?
comment on: http://stackoverflow.com/a/50222109
score: 0

http://stackoverflow.com/a/50272109
score: 2
answers question: http://stackoverflow.com/q/50229314
type: Answer
has comment: http://stackoverflow.com/comment/104096026
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50229314
has body: I found the answer. change_upstream_proxy_server is the function that can only CHANGE the upstream server. It can't enable it if the upstream server was not enabled earlier. This mean that if you want to change upstream server you need to start mitmproxy with -U parameter, for example: mitmdump -U http://127.0.0.1:9999 -s server.py After this you the change_upstream_proxy_server will work.
has comment: http://stackoverflow.com/comment/131096209

http://stackoverflow.com/comment/87472805
type: Comment
has text: yes, there is a whitespace in the string of '农电工 ', thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50227676

http://stackoverflow.com/comment/108327665
score: 1
has text: It seems to me that this answer answers the OP's question best
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/57382223

http://stackoverflow.com/a/50171650
has comment: http://stackoverflow.com/comment/87360660
has body: since I cant post just comments, you can try this command: pip uninstall -y -r &lt;(pip freeze). It clears your user packages folder outside of the context of a virtualenv. Try this command with care.
score: 1
answers question: http://stackoverflow.com/q/50171413
has comment: http://stackoverflow.com/comment/87360782
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/87305067
comment on: http://stackoverflow.com/q/50143132
type: QuestionComment
score: 0
has text: I got the file from someone else in the form of a spreadsheet.
type: Comment

http://stackoverflow.com/comment/87491996
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50224471
has text: The important point is that I want to remove everything until the first time we hit 00:00 and then I I want the function to stop. I don't want to remove any more entries. All I am doing is ensuring the array starts at 00:00. The boolean filter looks through the whole dataset.
type: Comment

http://stackoverflow.com/comment/87428316
comment on: http://stackoverflow.com/q/50205618
has text: Possible duplicate of [Why does Python not implement the elif statement on try statement?](https://stackoverflow.com/questions/32115375/why-does-python-not-implement-the-elif-statement-on-try-statement)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50180284
has body: I'm trying to create a simple python code to convert UT to Julian dates, but my code keeps spitting out the wrong numbers and I'm not sure why, I can't see where I went wrong. This is the formula I am trying to follow: UT to JD formula with example dates = ['4/01/2018 01:06', '4/01/2018 01:10', '4/01/2018 01:14', '4/09/2018 00:37', '4/09/2018 00:41', '4/09/2018 00:45', '4/22/2018 00:28', '4/22/2018 00:33', '4/22/2018 00:37', '4/24/2018 00:40', '4/24/2018 00:44', '4/24/2018 00:51', '4/24/2018 00:58'] JD = [] for item in dates: M = int(item[0]) D = int(item[2:4]) H = int(item[10:12]) if M &gt; 2: m = M - 3 y = int(item[5:9]) else: y = int(item[5:9]) - 1 m = M + 9 JD += [ (1721103.5) + int((362.25) * y) + int(((30.06*m) + 0.5)) + D + (H/24) ] print(JD)
has comment: http://stackoverflow.com/comment/87378748
has comment: http://stackoverflow.com/comment/87378819
tagged with: astronomy
has title: Converting UT (universal time) to JD (julian date) (astronomy)
tagged with: python
has comment: http://stackoverflow.com/comment/87378944
has answer: http://stackoverflow.com/a/59735681
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87378841
tagged with: python-3.x

http://stackoverflow.com/a/50222223
type: Answer
answers question: http://stackoverflow.com/q/50222042
score: 1
downvote count: 0
upvote count: 1
has body: You can also use YearEnd. You'll get a timedelta64 column with this method. import pandas as pd from pandas.tseries.offsets import YearEnd df['Date'] = pd.to_datetime(df.Date) (df.Date + YearEnd(1)) - (df.Date - YearEnd(1)) 1 365 days 2 365 days 3 366 days 4 366 days Name: Date, dtype: timedelta64[ns]

http://stackoverflow.com/a/50102966
answers question: http://stackoverflow.com/q/50098611
has comment: http://stackoverflow.com/comment/87223588
accepted answer of: http://stackoverflow.com/q/50098611
type: Answer
has body: If p_type holds the name of the field you want to query, then you can do: elif p_type: kwargs = { '{}__contains'.format(p_type): s_type } queryset_find = queryset_list.filter(Q(**kwargs)) ...
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87403332
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50108601
has text: AFAIK only data (RDD) serializer is configurable. In general there are a few sources of serialization issues with closures - objects using native extensions (typically with direct memory access or memory mapping, but not limited to these), objects which are intentionally not serializable (thread locks and connections for example) and object referencing local classes (as `cloudpickle`, same as pickle, doesn't serialize class definitions). If you have something sharable (tracebacks maybe) these might give us some hints.

bipartite
type: Tag
tags question: http://stackoverflow.com/q/50159206
tag name: bipartite

http://stackoverflow.com/q/50179024
score: 1
has title: Can not import python modules from package
upvote count: 1
has comment: http://stackoverflow.com/comment/87375434
has body: My project path is like: main.py modules/ __init__.py databaseManager.py sync.py excel.py in main.py: from modules.databaseManger import addExcelToDb, searchInDbAll from modules.excel import search, showExcelDirContents from modules.sync import syncExcelAndDB and for example in database.py : from modules.excel import showExcelDirContents from modules.sync import insertExcelNameToSyncDb but when I run main.py I get this error: Traceback (most recent call last): File "main.py", line 6, in &lt;module&gt; from modules.databaseManger import searchIn ImportError: cannot import name 'searchInDbAll' and also having error when trying to import a function from each file in modules directory to others. I need some examples of importing.
has comment: http://stackoverflow.com/comment/87377277
downvote count: 0
has answer: http://stackoverflow.com/a/50180584
tagged with: import
accepted answer: http://stackoverflow.com/a/50180584
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87378037
has comment: http://stackoverflow.com/comment/87375474
tagged with: package
has comment: http://stackoverflow.com/comment/87454468
tagged with: python
has comment: http://stackoverflow.com/comment/87376350
has answer: http://stackoverflow.com/a/50179204
possible better answer: http://stackoverflow.com/a/50179204
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/87307292
comment on: http://stackoverflow.com/q/50144269
type: Comment
type: QuestionComment
score: 0
has text: @tdelaney I have updated question to include a sample subprocess call

http://stackoverflow.com/q/50091999
has comment: http://stackoverflow.com/comment/87200278
has comment: http://stackoverflow.com/comment/87200208
duplicate of: http://stackoverflow.com/q/22741319
favorite count: 0
type: Question
tagged with: sample
answer count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/50097779
tagged with: python
has title: How to generate random samples from a population in Python?
has comment: http://stackoverflow.com/comment/87201333
upvote count: 6
has answer: http://stackoverflow.com/a/50097779
score: 4
possible better answer: http://stackoverflow.com/a/50092079
linked to: http://stackoverflow.com/q/22741319
tagged with: random
has comment: http://stackoverflow.com/comment/87200253
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50092079
has body: I'm trying to address this question: Generate 1,000 random samples of size 50 from population. Calculate the mean of each of these samples (so you should have 1,000 means) and put them in a list norm_samples_50. My guess is I have to use the randn function, but I can't quite guess on how to form the syntax based on the question above. I've done the research and can't find an answer that fits.
has comment: http://stackoverflow.com/comment/87227199

http://stackoverflow.com/q/50182683
has comment: http://stackoverflow.com/comment/87386895
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87405020
has answer: http://stackoverflow.com/a/50194030
accepted answer: http://stackoverflow.com/a/50194030
has answer: http://stackoverflow.com/a/50183293
possible better answer: http://stackoverflow.com/a/50183293
linked to: http://stackoverflow.com/q/45576958
tagged with: python
has comment: http://stackoverflow.com/comment/87404899
has comment: http://stackoverflow.com/comment/87405035
has title: Element identified through find_element_by_xpath returns selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
has comment: http://stackoverflow.com/comment/87404884
linked to: http://stackoverflow.com/q/72799696
tagged with: selenium-webdriver
has body: I have problem with click button. This button can click if enemy is on play and can't click if enemy go out start I tried with this: try: element= driver.find_element_by_xpath("//button[@class='butwb']") if element.is_displayed(): print ("Element found") else: print ("Element not found") except NoSuchElementException: print("No element found") Result: Element not found If I add element.click() : selenium.common.exceptions.ElementNotVisibleException: Message: element not visible What I do wrong?
score: 0
answer count: 2

http://stackoverflow.com/a/50150151
type: Answer
accepted answer of: http://stackoverflow.com/q/50150090
score: 2
answers question: http://stackoverflow.com/q/50150090
has comment: http://stackoverflow.com/comment/87320313
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You are are using a {set} of columns, which is NOT an ordered collection (neither are dictionaries). Try with a (tuple), o simply a [list] df = pd.Dataframe(data, columns=['col1', 'col2', 'col3'])

http://stackoverflow.com/q/50184021
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87385496
type: UnansweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/37601644
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87387015
tagged with: magic-string
has comment: http://stackoverflow.com/comment/87385638
has comment: http://stackoverflow.com/comment/87385376
has comment: http://stackoverflow.com/comment/87385425
has comment: http://stackoverflow.com/comment/87385806
has comment: http://stackoverflow.com/comment/87385419
tagged with: enums
has body: EDIT: I've heavily edited this question from the original, to focus on the advantages of Enum in this case (the question had been put on hold for being primarily opinion-based) I understand the sense of using an Enum when it's converting a human-readable string into an underlying (e.g. numeric) value, with the FederalHoliday class in this answer being a good example of that. But the use-case I'm considering is just where a function parameter is restricted to a set of possible values, which are currently passed as "magic strings". So implementing an Enum here wouldn't really improve code readability (if anything, it would make the code more cluttered). And turning a string into an Enum, only to compare on what is effectively the same string (i.e. the name of the Enum) feels like overkill. This answer has a fantastic list of general advantages of enums, but I'm not sure how many of them apply in this case. To clarify the case I'm meaning, there is an example of it here, with a function that prints a string with certain capitalization as specified by mode: def print_my_string(my_string, mode): if mode == 'l': print(my_string.lower()) elif mode == 'u': print(my_string.upper()) elif mode == 'c': print(my_string.capitalize()) else: raise ValueError("Unrecognised mode") To see this in action, running this: for mode in ['l', 'u', 'c']: print_my_string("RaNdoM CAse StRING", mode) gives: random case string RANDOM CASE STRING Random case string So my question is: What advantage does an Enum bring when the strings don't represent another value underneath? Is there any way that it makes the code more robust? Other things I've read: Mainly about Enums in general, especially when the strings represent another value underneath: How can I represent an 'Enum' in Python? Python enum, when and where to use? This seems to have an example similar to mine (under Enums are interoperable), but I struggled to understand the technical discussion around it, and it only shows setting the Enum, …
has title: What advantage does using an Enum bring if it's not encoding underlying values?
has comment: http://stackoverflow.com/comment/87385444
score: 1
has comment: http://stackoverflow.com/comment/87386724
linked to: http://stackoverflow.com/q/22586895
linked to: http://stackoverflow.com/q/36932
has comment: http://stackoverflow.com/comment/87385676
has comment: http://stackoverflow.com/comment/87385423
tagged with: python
has answer: http://stackoverflow.com/a/50184640
has comment: http://stackoverflow.com/comment/87386053
has comment: http://stackoverflow.com/comment/87385442
has comment: http://stackoverflow.com/comment/87385614
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87385535

http://stackoverflow.com/q/50081088
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/50081314
has body: I have one Worker Thread on my program that returns a number every second, forever, until the stop signal is emmited on the Main Window. I want it to emit a signal everytime it changes a value, so I can update the Main Window with the returned value. I tried simply emmiting a signal in the function itself, but doesn't work. Worker: from test import save_data class Worker(QObject): finished = pyqtSignal() # give worker class a finished signal def __init__(self, parent=None): QObject.__init__(self, parent=parent) def do_work(self): save_data.main() self.finished.emit() # emit the finished signal when the loop is done def stop(self): save_data.run = False # set the run condition to false on stop test.py: import time from Pyqt5.QtCore import pyqtSignal run = True value = pyqtSignal(int) def main(): x = 1 while run: print(x) x += 1 time.sleep(1) #value.emit(x)
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50081314
has title: How to send signal from inside of imported function on pyqt5?
type: Question
tagged with: python-3.x
answer count: 1
has comment: http://stackoverflow.com/comment/87178152
tagged with: python
has comment: http://stackoverflow.com/comment/87178527
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50096918
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has title: Beautiful soup find gets results, however findall gets empy list
type: Question
has comment: http://stackoverflow.com/comment/87249657
tagged with: python
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/xml
has body: I am trying to use Beautiful Soup to parse an XBRL document (a standard tagged XML). I was trying to find all the elements with the tag "iic-com:inversionesfinancierasrvcotizada". When I use the function find it returns a result, the first of the desired entries. soup.find('iic-com:inversionesfinancierasrvcotizada') returns the XML &lt;iic-com:inversionesfinancierasrvcotizada&gt; &lt;iic-com:codigoisin contextref="FIM_T12018_V86902186_ia"&gt;ES0105130001&lt;/iic-com:codigoisin&gt; &lt;iic-com:inversionesfinancierasdescripcion contextref="FIM_T12018_V86902186_ia"&gt;GLOBAL DOMINION ACCESS SA&lt;/iic-com:inversionesfinancierasdescripcion&gt; &lt;dgi-lc-int:xcode_iso4217.eur contextref="FIM_T12018_V86902186_da"&gt;EUR&lt;/dgi-lc-int:xcode_iso4217.eur&gt; &lt;iic-com:inversionesfinancierasimporte&gt; &lt;iic-com:inversionesfinancierasvalor contextref="FIM_T12018_V86902186_ia" decimals="2" unitref="euro"&gt;190490&lt;/iic-com:inversionesfinancierasvalor&gt; &lt;iic-com:inversionesfinancierasporcentaje contextref="FIM_T12018_V86902186_ia" decimals="2" unitref="pure"&gt;0.10&lt;/iic-com:inversionesfinancierasporcentaje&gt; &lt;/iic-com:inversionesfinancierasimporte&gt; &lt;iic-com:inversionesfinancierasimporte&gt; &lt;iic-com:inversionesfinancierasvalor contextref="FIM_T12018_V86902186_ipy" decimals="2" unitref="euro"&gt;185545&lt;/iic-com:inversionesfinancierasvalor&gt; &lt;iic-com:inversionesfinancierasporcentaje contextref="FIM_T12018_V86902186_ipy" decimals="2" unitref="pure"&gt;0.11&lt;/iic-com:inversionesfinancierasporcentaje&gt; &lt;/iic-com:inversionesfinancierasimporte&gt; &lt;/iic-com:inversionesfinancierasrvcotizada&gt; However, when I try the find_all or findAll methods I would expect to see this entry plus other additional entries, yet the result is. soup.find_all('iic-com:inversionesfinancierasrvcotizada') Yielding [] I don't know what I am doing wrong in here. EDIT: If you want to try the full example, first you would need to get the document from here downl…
has comment: http://stackoverflow.com/comment/87240474
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50097554
downvote count: 0

http://stackoverflow.com/q/50118909
has title: Python Regex match multiple and write to file
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87255279
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87255164
has body: I have a file with events from multiple Windows servers stored in it, that are non separated (all exports are in one long line, sometimes tabbed, sometimes not). I've built regex to pull out the information I want to store in a CSV (a total of 20 match groups) but I'm now trying to cycle through many rows in the files and output the relevant information in CSV format. My code is below: #!/usr/bin/env python import csv import re match1 = re.compile('(\D{3} \d+ \d{2}[:]\d{2}[:]\d{2})') &lt;snipped for brevity&gt; match20 = re.compile('(?:Logon Type: (.+?) )') regexes = [match1, match2, match3, match4, match5, match6, match7, match8, match9, match10, match11, match12, match13, match14, match15, match16, match17, match18, match19, match20] pattern_combined = '|'.join(x.pattern for x in regexes) print(pattern_combined) print("End of combined regexes\n\n\n") with open('Argus.csv', 'r') as fobj: with open('Argus1.csv', 'w') as resultFile: reader = csv.reader(fobj, delimiter=',') for row in reader: output = re.findall(r'pattern_combined',row) print(output) print("End of OUTPUT\n\n\n") out_str = ','.join(output) print(out_str) print("Final output\n\n\n") resultFile.write(out_str) There's a bit of debugging in there as well for my own sanity, trying to see the steps it takes, but I'm failing on making it match (at print(output) I just get a null output) I've tested with a single regex on a single line and can get that to work, but need to expand it to multiple, with each match being exported as a field in a CSV and can't seem to progress. edit: Sample data added to show the type of extractions required: &lt;13&gt;Mar 8 05:56:00 PHCHBS-TP320161.XX.domain.net MSWinEventLog 4 Security 364388 Thu Mar 08 05:56:00 2018 4634 Microsoft-Windows-Security-Auditing DOMAINNET\SYS_APM_XXXXXX1 N/A Success Audit PHCHBS-TP320161.XX.DOMAIN.net Logoff An account was logged off. Subject: Security ID: S-1-5-21-2025429265-1383384898-682003330-43805 Account Name: SYS_APM_XXXXXX1 Account Domain: DOM…
has comment: http://stackoverflow.com/comment/87322027
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87259883

http://stackoverflow.com/q/50195385
has body: I have the following dataframe: dataframe = pd.DataFrame({'Date': ['2017-04-01 00:24:17','2017-04-01 00:54:16','2017-04-01 01:24:17'] * 1000, 'Luminosity':[2,3,4] * 1000}) The output of dataframe is this: Date Luminosity 0 2017-04-01 00:24:17 2 1 2017-04-01 00:54:16 3 2 2017-04-01 01:24:17 4 . . . . . . I want remove or select just the Luminosity column, then, with python slices I have the following: X = dataframe.iloc[:, 1].values # Give a new form of the data X = X.reshape(-1, 1) And the output of X is the following numpy array: array([[2], [3], [4], ..., [2], [3], [4]]) I have the same situation, but a new dataframe with 76 columns, like this This is the output when I read it. In total, the dataframe have 76 columns, I just want select 25 columns which are the columns named PORVL2N1 , PORVL2N2, PORVL4N1 and so successively until arrive to the end column named PORVL24N2 which is the 76th column For the moment, the solution that I have is create a new data frame only with the columns of my interest, this is: a = df[['PORVL2N1', 'PORVL2N2', 'PORVL4N1', 'PORVL5N1', 'PORVL6N1', 'PORVL7N1', 'PORVL9N1', 'PORVL9N1', 'PORVL10N1', 'PORVL13N1', 'PORVL14N1', 'PORVL15N1', 'PORVL16N1', 'PORVL16N2', 'PORVL18N1', 'PORVL18N2', 'PORVL18N3','PORVL18N4', 'PORVL21N1', 'PORVL21N2', 'PORVL21N3', 'PORVL21N4', 'PORVL21N5', 'PORVL24N1', 'PORVL24N2'] And the output is: I want make the same, select just the columns of my interest, but using python slices with iloc to indexing and selecting by position, such as I make in the beginning of my question. I know that this is possible with slides, but I cannot understand good the slices sintax to get it. How to can I using iloc and slices python to select my interest columns?
type: Question
has answer: http://stackoverflow.com/a/50195444
has title: Removing dataset columns with python slices
tagged with: python
possible better answer: http://stackoverflow.com/a/50195729
accepted answer: http://stackoverflow.com/a/50195444
has answer: http://stackoverflow.com/a/50195729
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/87287937
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50133528
type: Comment
has text: I liked both answers the long(first) one as you were explaining all of the steps, and the short(last) as it was more compressed, although for me more difficult to understand since I'm not that advanced in python.I guess `iters = [(len(group), iter(group)) for group in grouped_dicts]` this is list comperhension? In the last answer I had to to use `for l in zip(itr1, itr2): yield l` as I'm on python 2 but that's not an issue ;) Anyway, do you mind puting both of the versions of you answer, as next person may find it equaly helpfull ;)

http://stackoverflow.com/q/50157748
type: Question
has body: I need to take 3 numbers and print the max, min and middle term. Here's what I wrote: new_list = [] for i in range(3): new_list.append(int(input("Enter a number: "))) x = min(new_list) y = max(new_list) z = print("The max is %d, the middle is %d and the min is é %d." % (y, x , z)) But I don't know how to define z so it can be the middle term. Any help?
answer count: 2
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87333410
has answer: http://stackoverflow.com/a/50157779
has title: Middle Term of List from Inputs
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50158051
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87372982
has text: The capturing group is not necessary, but I thought it would aid readability. I'll adjust `*` to `+`: thanks for your eagle eye.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50177227

http://stackoverflow.com/a/50552474
has comment: http://stackoverflow.com/comment/93743427
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Access to the time_zone is now restricted to paid access keys. I would suggest using GeoTimeZone to map coordinates to a unix time zone and then TimeZoneMapper to map to a .NET time zone.
answers question: http://stackoverflow.com/q/50100800
score: 1
has comment: http://stackoverflow.com/comment/93769355
type: Answer
accepted answer of: http://stackoverflow.com/q/50100800

http://stackoverflow.com/comment/87395098
comment on: http://stackoverflow.com/a/50187397
type: AnswerComment
has text: may I ask what does `if b else 0` mean in the code `return b[0] + 256 * bytes2num(b[1:]) if b else 0`?
score: 0
type: Comment

http://stackoverflow.com/comment/87359472
score: 0
type: AnswerComment
has text: Thanks @Begueradj by giving such a useful information.
type: Comment
comment on: http://stackoverflow.com/a/50169867

http://stackoverflow.com/q/50109197
score: 0
tagged with: python
has title: Represent data as Fourier-transformation or polynomial with high degree?
has comment: http://stackoverflow.com/comment/87236600
has answer: http://stackoverflow.com/a/50273000
has comment: http://stackoverflow.com/comment/87235962
has comment: http://stackoverflow.com/comment/87235811
has body: I am dealing with stelar light curves (.fits-files containing 4000 datapoints of time vs stelar brigthness, see graphic for a few examples with different periodicity). I need to represent/fit these lightcurves in a way that allows me to perform on them unsupervised clustering with machine learning. I got suggested to use either a polynomial representation with a high degree (p=30...up to a few hundreds) or to use fourier transformation on the lightcurves. I found that polynomial fits of numpy.polyfit with a high degree p don't provide good fits and I receive a warning "RankWarning: Polyfit may be poorly conditioned". Maybe I should try Fourier-transformation, but I am not familiar and it sounds complicated. How can/should I represent/fit such data for the sake of machine learning clustering? Can I achieve a good result with np.polyfit with p>30?
type: UnansweredQuestion
tagged with: continuous-fourier
tagged with: cluster-analysis
answer count: 1
tagged with: machine-learning
tagged with: polynomials
type: Question

http://stackoverflow.com/comment/87322699
type: QuestionComment
comment on: http://stackoverflow.com/q/50151785
has text: I've edited the main post!
score: 0
type: Comment

http://stackoverflow.com/comment/87405681
has text: Wouldn't it be easier to port one of them to the other python version?
comment on: http://stackoverflow.com/q/50194169
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87177465
has text: 1) We need a [mcve]. Your code throws syntax and other errors. We can't debug that. 2) Don't compare strings with `is`.
score: 3
comment on: http://stackoverflow.com/q/50080771
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88139479
score: 0
has text: Hey, thanks for your answer. But that's for setting up websocket between my laptop (to act as server) and colab's server and displaying things in the colab website (colab acts as client). But I need to work offline i.e., run both server and client in my machine.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50563569

http://stackoverflow.com/q/50199320
tagged with: image-processing
upvote count: 1
has comment: http://stackoverflow.com/comment/87415324
has body: I tried to run this code it's showing error- Traceback (most recent call last): File "C:\Python36-32\test1.py", line 13, in &lt;module&gt; img_tinted = img * [1, 0.95, 0.9] TypeError: unsupported operand type(s) for *: 'JpegImageFile' and 'float' Here Img_tinted is supposed to change the RGB ratio of the picture. from scipy.misc import imread, imsave, imresize # Read an JPEG image into a numpy array img = imread('assets/cat.jpg') print(img.dtype, img.shape) # Prints "uint8 (400, 248, 3)" img_tinted = img * [1, 0.95, 0.9] # Resize the tinted image to be 300 by 300 pixels. img_tinted = imresize(img_tinted, (300, 300)) # Write the tinted image back to disk imsave('assets/cat_tinted.jpg', img_tinted)
favorite count: 0
has comment: http://stackoverflow.com/comment/87415599
has comment: http://stackoverflow.com/comment/87415346
type: Question
has title: TypeError: unsupported operand type(s) for *: 'JpegImageFile' and 'float'
has comment: http://stackoverflow.com/comment/87417915
has comment: http://stackoverflow.com/comment/87415585
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87416175
has comment: http://stackoverflow.com/comment/87415284
has comment: http://stackoverflow.com/comment/87416163
has comment: http://stackoverflow.com/comment/87418211
tagged with: python
has comment: http://stackoverflow.com/comment/87415567
has comment: http://stackoverflow.com/comment/87415874
has comment: http://stackoverflow.com/comment/87415937
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/42872293
has comment: http://stackoverflow.com/comment/87415634
has comment: http://stackoverflow.com/comment/87415643
downvote count: 0
has comment: http://stackoverflow.com/comment/87415688

http://stackoverflow.com/comment/87464353
type: QuestionComment
comment on: http://stackoverflow.com/q/50223388
has text: Thanks, it works now. Do you know why it labeled the lines with those letters until I fixed the legend command? It's strange since the legend still showed up.
score: 0
type: Comment

http://stackoverflow.com/a/50162641
score: 2
answers question: http://stackoverflow.com/q/50162326
downvote count: 0
has body: Not as elegant as some suggestions, but simple and may work for you? dt = 'dep_time'.zfill(4) dt = dt[:2] + ":" + dt[2:] So for 1 you will get 00:01 and for 613: 06:13 or more succinctly: dt = '{0}:{1}'.format(date_time.zfill(4)[:2], date_time.zfill(4)[2:])
upvote count: 2
type: Answer

http://stackoverflow.com/comment/87385467
has text: import classcard def main(): card1 = Card() card1.deal() print("Your 5 hand card is") for i in card(5): print(card1)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50183106
type: Comment

http://stackoverflow.com/comment/87300724
has text: You can only accept one, so accept the one that's most performant/cleanest/smells nicest... if you STILL can't decide, flip a coin ;)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50139043
type: Comment

http://stackoverflow.com/comment/133131507
score: 0
type: Comment
comment on: http://stackoverflow.com/a/66246240
type: AnswerComment
has text: what are your versions of jupyterlab and ipympl? with jupyterlab 3.6.1 and ipympl 0.9.2 these steps lets me see the plot and I can resize the window, but I can't click the zoom and move buttons

http://stackoverflow.com/a/50107583
downvote count: 4
has body: Thanks for your time. I solve it in an easy way, I make a list List = [(self.chckbox_name.isChecked() , "#name or string I need to be returned if condition is true") , ...etc ] List_of_checked =[] List_of_unchecked = [] for i, v in List: if i == True: List_of_checked.append (v) else: List_of_unchecked.append (v)
accepted answer of: http://stackoverflow.com/q/50077625
score: -3
type: Answer
answers question: http://stackoverflow.com/q/50077625
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/q/50209216
has comment: http://stackoverflow.com/comment/87435429
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/87435860
upvote count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/87435357
has title: Unable to click/ hover over on href button with Selenium
favorite count: 0
has body: I'm trying to click on a button which is located in a sub-menu. Here is the code of the website: I tried many things like first hover and then click, but I got error and I'm not able to click. Here is what I tried: element1 = driver.find_element_by_xpath(&quot;//*[contains(text(), 'Devis')]&quot;) element2 = driver.find_element_by_xpath(&quot;//*[contains(text(), 'Suivi devis')]&quot;) hoverover = ActionChains(driver).move_to_element(element1).move_to_element(element2).click().perform() So I want to hover over DEVIS and then clique on Suivi devis Edit I don't have to click on DEVIS, I just have to hover over with the mouse to open the sub-menus where there is Suivi devis
has comment: http://stackoverflow.com/comment/87436355
score: 1
has comment: http://stackoverflow.com/comment/87435569
tagged with: python
type: Question
tagged with: python-2.7
answer count: 0

pymysql
tags question: http://stackoverflow.com/q/50162167
tags question: http://stackoverflow.com/q/50175109
tags question: http://stackoverflow.com/q/50156520
tag name: pymysql
tags question: http://stackoverflow.com/q/50206630
tags question: http://stackoverflow.com/q/50111706
tags question: http://stackoverflow.com/q/50132493
tags question: http://stackoverflow.com/q/50158598
type: Tag
tags question: http://stackoverflow.com/q/50190682
tags question: http://stackoverflow.com/q/50161231
tags question: http://stackoverflow.com/q/50086142

http://stackoverflow.com/a/50106882
type: Answer
answers question: http://stackoverflow.com/q/50105143
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87231898
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87231555
accepted answer of: http://stackoverflow.com/q/50105143
has comment: http://stackoverflow.com/comment/87231753
has comment: http://stackoverflow.com/comment/87231977
has comment: http://stackoverflow.com/comment/87231432
has body: Check out how DirectoryIterator is implemented. It's a very simple class. ImageDataGenerator#flow_from_directory is just a wrapper to a DirectoryIterator object construction. You don't have to manually specify the labels because DirectoryIterator will automatically assume that each sample is associated with a class named after that sample's parent folder. So, as long as all samples of leaves A are inside the same folder named A and samples of leaves B are inside a different folder, they will be correctly assigned to their respective classes. Furthermore, the iterator's output will already be one-hot encoded, as you defined class_mode as categorical: g = ImageDataGenerator() train = g.flow_from_directory('/path/to/dataset/train/', batch_size=32, target_size=(1100, 180)) x_batch, y_batch = next(train) assert x_batch.shape == (32, 1100, 180, 3) assert y_batch.shape == (32, 2) print(y_batch) [[0. 1.], [1. 0.], [1. 0.], ... [0. 1.]] The classes parameter is not used to set the labels of each sample, but instead to specify a list of sub-folders of directory that should be considered as classes by that iterator (e.g. ['A', 'B']). If the default None is kept, then all sub-folders of directory are considered valid classes, and all images inside them are potential samples for the set. This is useful when you only want to work with a subset of labels, debug your code or hold-off classes. If you wish to override the default labeling, then you can simply replace the content in DirectoryIterator#classes, which contains the class associated with the ith sample at its ith element. For example, let's say you want to add a third class of leaves which doesn't have an associated folder: train = g.flow_from_directory(...) train.classes = np.asarray([0., 1., 2., ..., 0., 1.]) train.class_indices = {'A': 0, 'B': 1, 'C': 2} train.num_classes = 3
score: 1

http://stackoverflow.com/comment/87297027
type: Comment
type: AnswerComment
has text: Server prints: `/usr/lib/python2.7/dist-packages/apt/__init__.pyc`
comment on: http://stackoverflow.com/a/50136104
score: 1

http://stackoverflow.com/comment/87378213
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50179154
type: Comment
has text: @LaurentS a pseudo root account sounds a bit complicated. I would have to exclude that one when displaying the list to avoid confusing the end user. It is possible, but it sounds more complicated than my current solution.

http://stackoverflow.com/comment/87410755
type: QuestionComment
has text: Dear Jpp, Sorry for any inconvenience caused to you. This is the very first post, and I will take note of your suggestion in future posts.
score: 0
comment on: http://stackoverflow.com/q/50191215
type: Comment

http://stackoverflow.com/a/50225479
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87468592
has comment: http://stackoverflow.com/comment/87470761
has comment: http://stackoverflow.com/comment/87469074
has comment: http://stackoverflow.com/comment/87469345
has comment: http://stackoverflow.com/comment/87469185
answers question: http://stackoverflow.com/q/50225178
has comment: http://stackoverflow.com/comment/87469472
type: Answer
accepted answer of: http://stackoverflow.com/q/50225178
has comment: http://stackoverflow.com/comment/87468505
upvote count: 2
score: 2
has body: If I understand the logic of selecting the green lines correctly, there is no need to create a KDTree at each iteration. For each pair (p1, p2) of blue points, the line should be drawn if and only if the following hold: p1 is one of 3 closest neighbors of p2. p2 is one of 3 closest neighbors of p1. dist(p1, p2) &lt; 55. You can create the KDTree once and create a list of green lines efficiently. Here is part of the implementation that returns a list of pairs of indices for points between which the green lines need to be drawn. The runtime is about 0.5 seconds on my machine for 10,000 points. import numpy as np from scipy import spatial data = np.random.randint(0, 1000, size=(10_000, 2)) def get_green_lines(data): tree = spatial.cKDTree(data) # each key in g points to indices of 3 nearest blue points g = {i: set(tree.query(data[i,:], 4)[-1][1:]) for i in range(data.shape[0])} green_lines = list() for node, candidates in g.items(): for node2 in candidates: if node2 &lt; node: # avoid double-counting continue if node in g[node2] and spatial.distance.euclidean(data[node,:], data[node2,:]) &lt; 55: green_lines.append((node, node2)) return green_lines You can proceed to plot green lines as follows: green_lines = get_green_lines(data) fig, ax = plt.subplots() ax.scatter(data[:, 0], data[:, 1], s=1) from matplotlib import collections as mc lines = [[data[i], data[j]] for i, j in green_lines] line_collection = mc.LineCollection(lines, color='green') ax.add_collection(line_collection) Example output:

http://stackoverflow.com/comment/87454727
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50218741
has text: That is coorect. You are counting sentences more than once for maybe all three categories. So if in a sentence there are 5 negative words, The sentence will be added five time.
score: 0

http://stackoverflow.com/q/50207584
has answer: http://stackoverflow.com/a/50208351
has body: Is there a way to extract a subset of columns from a pandas dataframe without specifying all of the columns. e.g. I have dataframe with foll. columns: str_ID, num_ID, 1990, 1991, 1992, 1993, 1994, 1995 and I want to extract columns from 1990 onwards. How do I do that without hard coding it? df.columns.values array(['str_ID', 'num_ID', 1990, 1991, 1992, 1993, 1994, 1995], dtype=object)
tagged with: python
has comment: http://stackoverflow.com/comment/87432480
has comment: http://stackoverflow.com/comment/87432162
has comment: http://stackoverflow.com/comment/87432108
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50207644
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50207644
has title: Extracting columns from pandas dataframe without hard coding
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87432328
has comment: http://stackoverflow.com/comment/87432150
has comment: http://stackoverflow.com/comment/87432085
has comment: http://stackoverflow.com/comment/87432139
possible better answer: http://stackoverflow.com/a/50208351
type: Question

http://stackoverflow.com/comment/87389533
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50186170
has text: Thanks Ernest. This opened up for new logic. However, I would keep the question still open as I am curious to find out if there is a way to get task id, and also for the reason that uniqueness of the uuid is not completely guaranteed (Though I am convinced that the id being not unique is extremely rare case).

http://stackoverflow.com/a/50189329
score: 2
has body: Rather than using datetime.datetime.now() for this sort of thing you can use time.perf_counter(), which is available in Python 3.3+. From the docs: Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid. Also, you can print using a carriage return instead of a newline so that the progress reports are printed on a single line. Here's a brief demo derived from your code. from time import sleep, perf_counter fmt = " Progress: {:&gt;3}% estimated {:&gt;3}s remaining" num = 1000 start = perf_counter() for i in range(1, num + 1): # Simulate doing a few calculations sleep(0.01) stop = perf_counter() remaining = round((stop - start) * (num / i - 1)) print(fmt.format(100 * i // num, remaining), end='\r') print() Depending on your terminal (and Python version) you may also need to add the flush=True keyword arg to the print call in order to get the progress reports to print as they are issued.
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50188907

http://stackoverflow.com/comment/87452088
type: Comment
has text: @e.s. You were faster than my edit :-). I explained in here the reason. I'll edit again to make it more obvious.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50217535

http://stackoverflow.com/q/50144023
has comment: http://stackoverflow.com/comment/87306406
has body: If I have the following code: class foo: def __init__(self): self.w = 5 self.z = 10 def sum(obj,x,y): return obj.x+obj.y f = foo() print sum(foo,'x','y') How would I create a function that takes in two unkown variable names and returns the sum of those variables variables? In this case the example should print 15. EDIT: Typo for the last line it should say print sum(foo,'w','z')
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/2612610
has comment: http://stackoverflow.com/comment/87306408
type: Question
has answer: http://stackoverflow.com/a/50144068
has comment: http://stackoverflow.com/comment/87306362
has title: Have a Function Take a Variable Name of an Object
duplicate of: http://stackoverflow.com/q/2612610
favorite count: 0
score: 0

http://stackoverflow.com/a/50139514
type: Answer
has body: The HTML &lt;script&gt; element is used to embed or reference executable code; this is typically used to embed or refer to JavaScript code. The page you scrape is rendered by JavaScript, the initial HTML contains a &lt;script&gt; tag with images variable that contains URLs of all the pictures. You can either follow Rakesh's approach of extracting the JavaScript object containing URLs with regular expressions or use Requests-HTML that uses Chromium under the hood to render the website as it appears in the browser. You can get all the URLs with the code below: from requests_html import HTMLSession session = HTMLSession() url = 'https://bato.to/chapter/1204541' r = session.get(url) r.html.render() urls = [img.attrs['src'] for img in r.html.find('.item &gt; img')] &gt;&gt;&gt; urls ['https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/57a04a3ce55bd48debf0a486a4c1a48f6380ef9b_1066291_800_1138.png', 'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/a0f75d10919430e6ef25a86c3dcc65f343d8e319_518773_800_1138.png', 'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/575d00ff9ef6873ee9ecfb418e360fe72cc1c594_418309_800_1138.png', ... ] &gt;&gt;&gt; len(urls) 59 The issue of this solution is that it takes a long time to execute. To clarify, .item &gt; img targets all the img elements which are direct children of an element with item class. You can read more about CSS selectors here. You can also use Selenium: from selenium import webdriver browser = webdriver.Chrome() browser.get(url) url_dict = browser.execute_script('return images;') browser.quit() &gt;&gt;&gt; url_dict['1'] 'https://file-comic-99.anyacg.co/uploads/5ae318893532c3405bd86baa/57a04a3ce55bd48debf0a486a4c1a48f6380ef9b_1066291_800_1138.png'
answers question: http://stackoverflow.com/q/50138015
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87302450
has comment: http://stackoverflow.com/comment/87313471
has comment: http://stackoverflow.com/comment/87297860
has comment: http://stackoverflow.com/comment/87302762

http://stackoverflow.com/q/50099179
duplicate of: http://stackoverflow.com/q/976882
has comment: http://stackoverflow.com/comment/87214787
downvote count: 1
favorite count: 0
type: Question
has body: I have a code in Python where at different time steps I'm following a number of different steps. What I want to do is add an extra part in the code where in the first 7 time steps the algorithm will choose randomly a number from an existing set that has 7 different entries (0,1,2,3,4,5,6,7). Essentially what I want to do is choosing without replacement from this set so that at t=7 all the numbers have been chosen once. So at t=0 the set that I need to choose a random element from has 7 elements, at t=1 it has 6 elements etc. Any help would be very much appreciated.
type: UnansweredQuestion
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/976882
has title: Choosing without replacement in python
upvote count: 0
has answer: http://stackoverflow.com/a/50099359
answer count: 1

http://stackoverflow.com/q/50173283
accepted answer: http://stackoverflow.com/a/50173320
tagged with: python
answer count: 6
upvote count: 22
has body: I have a dataframe i want to pop certain number of records, instead on number I want to pass as a percentage value. for example, df.head(n=10) Pops out first 10 records from data set. I want a small change instead of 10 records i want to pop first 5% of record from my data set. How to do this in pandas. I'm looking for a code like this, df.head(frac=0.05) Is there any simple way to get this?
has comment: http://stackoverflow.com/comment/87363687
score: 22
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/75058275
has answer: http://stackoverflow.com/a/77239535
has answer: http://stackoverflow.com/a/61953559
possible better answer: http://stackoverflow.com/a/61953559
has title: Pandas - get first n-rows based on percentage
has comment: http://stackoverflow.com/comment/87363716
tagged with: percentage
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/65522398
has answer: http://stackoverflow.com/a/50173320
has answer: http://stackoverflow.com/a/63377335

http://stackoverflow.com/comment/87351422
has text: A set is a type of list? What do you mean?
comment on: http://stackoverflow.com/q/50166773
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/87212943
type: AnswerComment
comment on: http://stackoverflow.com/a/50097137
type: Comment
has text: Thanks... I am trying to learn people, why do you give mines?
score: 0

http://stackoverflow.com/comment/87216218
score: 0
type: AnswerComment
has text: “you can read off the state changes by skimming the first object in each line” — not true. It would imply that only one object could change state in each line.
type: Comment
comment on: http://stackoverflow.com/a/50091199

http://stackoverflow.com/comment/87381714
comment on: http://stackoverflow.com/q/50181217
type: Comment
type: QuestionComment
score: 0
has text: @csmckelvey https://imgur.com/OdZpEvr

http://stackoverflow.com/q/50136375
tagged with: python
has body: I am designing a ensemble neural network with 3 simple feed-forward NNs. And now I am facing an issue of restoring these 3 neural networks for testing purpose. By now, 3 NN models are created and saved by the saver function. saver = tf.train.Saver() saver.save(sess, save_path=get_save_path(i), global_step=1000) I had successfully saved them into ".checkpoint", ".meta", ".index", and ".data files as shown below. I tried to restored them by using this coding: saver = tf.train.import_meta_graph(get_save_path(i) + '-1000.meta') saver.restore(sess,tf.train.latest_checkpoint(save_dir)) But it only restore the third NN which is network2 for testing. It has affected my result as the algorithm only takes 1 model (network2) and assumes all three NNs model are the same in ensemble function. FYI: My ideal ensemble function: ensemble = (network0 + network1 + network2) / 3 Real outcome: ensemble = (network2 + network2 + network2) / 3 How can I make TF to restore all 3 NN models together?
has title: How to restore multiple neural network models in TensorFlow?
type: UnansweredQuestion
score: 0
tagged with: save
answer count: 1
tagged with: neural-network
tagged with: restore
has answer: http://stackoverflow.com/a/50137953
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/87283473
has text: @Mr.T Sounds like it's because of omitting those column names or your separator.
type: AnswerComment
comment on: http://stackoverflow.com/a/50132440
score: 0
type: Comment

http://stackoverflow.com/comment/138146147
has text: The next problem you will run into is that you are asking `threading.Timer` to call `start` every second, but `start` is... the function where you did that. So it will not only set up that loop, but effectively make a fork bomb.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50093055

http://stackoverflow.com/q/50079415
answer count: 1
tagged with: python
has title: Python PyQt5 - Add rows to table
accepted answer: http://stackoverflow.com/a/50079514
tagged with: qtablewidget
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50079514
score: 0
has body: I have a table created with 2 columns and 0 rows called tableWidget_Events. Here's what the table and grid of buttons look like: Using the value from the spinbox, I want to insert the button text as a row, so if the spinbox = 1 and I click walk, there should be a row created with 1 in the first column and walk in the second column. Here's the code I have to connect the buttons: self.pushButton_SO.clicked.connect(self.add_table) self.pushButton_Walk.clicked.connect(self.add_table) self.pushButton_GB.clicked.connect(self.add_table) self.pushButton_FB.clicked.connect(self.add_table) self.pushButton_PU.clicked.connect(self.add_table) Then the function to add the row: def add_table(self): button = self.sender() # get button text row = self.spinBox_AB_TBL.value() #get value from spinbox rowPosition = self.tableWidget_Events.rowCount() self.tableWidget_Events.insertRow(rowPosition) #insert new row self.tableWidget_Events.setItem(row, 0, QtGui.QTableWidgetItem(self.spinBox_AB_TBL.value())) self.tableWidget_Events.setItem(row, 1, QtGui.QTableWidgetItem(button.text())) The buttons are connected. I can print the button text to the console, and each button click adds a new row. Inserting the text is what I'm hung up on. Thank you.
tagged with: pyqt5
type: Question

http://stackoverflow.com/comment/87307728
type: Comment
type: QuestionComment
score: 0
has text: that's already something :)
comment on: http://stackoverflow.com/q/50106519

http://stackoverflow.com/a/50109615
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87236665
has comment: http://stackoverflow.com/comment/87237022
downvote count: 0
has comment: http://stackoverflow.com/comment/87236658
upvote count: 1
answers question: http://stackoverflow.com/q/50109413
has body: Below are a couple of solutions using minimal data. The main reason your code does not work is you are introducing unnecessary variables first_test and second_test. This assumes, as stated in your question, you wish to test equality of 2 values from your json given 2 parameter inputs. Setup products = [{'id': 545453435453, 'title': "product name", 'fulltitle': "product name"}, {'id': 123454686786, 'title': "product name2", 'fulltitle': "product name3"}] first_value = input('Name of first value: ') second_value = input('Name of second value: ') Solution 1: iteration for product in products: if product[first_value] == product[second_value] : print(product['id']) # Name of first value: title # Name of second value: fulltitle # 545453435453 Solution 2: pandas This involves the 3rd party library pandas, which will be more efficient for repeated calls. import pandas as pd df = pd.DataFrame(products) res = df[df[first_value] == df[second_value]] # Name of first value: title # Name of second value: fulltitle # # fulltitle id title # 0 product name 545453435453 product name
has comment: http://stackoverflow.com/comment/87237028

http://stackoverflow.com/a/50187401
has body: For every widget you create (Button, Frame, ListBox), you can pass keyword arguments to style to widget. This can be a border, a background color, a text color, etc. A full list of these options for the button widget you can see here. For the other widgets, you can select one from this list. So yes you can set the background color easily: send_button = tkinter.Button(top, text="Send", command=send, bg="blue") Most style options (background, foreground, etc...) should work for all widgets
score: 0
answers question: http://stackoverflow.com/q/50187281
type: Answer
accepted answer of: http://stackoverflow.com/q/50187281
type: AcceptedAnswer

http://stackoverflow.com/comment/87464566
type: QuestionComment
type: Comment
has text: You may use `re.finditer`, you know.
comment on: http://stackoverflow.com/q/50223529
score: 0

http://stackoverflow.com/comment/87477576
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50228617
has text: i removed square brackets and checked what is the value of pqr and the answer is this --> <dictionary-itemiterator object at 0x7f90789175d0>

http://stackoverflow.com/comment/87414380
score: 0
comment on: http://stackoverflow.com/q/50194521
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170457/discussion-between-alex-hall-and-pickenpack).

http://stackoverflow.com/comment/87239284
comment on: http://stackoverflow.com/q/50111041
type: Comment
type: QuestionComment
has text: Example URLs: https://pastebin.com/raw/d1epSGcb
score: 0

http://stackoverflow.com/q/50220129
has body: So, I'm taking a list of usernames from a Linux server at school, this top code opens the directory where they are kept and saves it as information #!/usr/bin/env python import subprocess, sys r = subprocess.Popen(['ls','/home/ADILSTU'], stdout=subprocess.PIPE) information = r.stdout.read() print information, str(information) that works just fine and list the users like this... where it list them 1 per line. (there is atleast 100 usernames) ajax2 jjape3 jaxe32 my problem is, I want to create a "look-up" for these usernames, this is my code to search for usernames that only start with the letter j (so should only list jaxe32 from this list) #lookup import re p = re.compile(r'j(?!j)\w*') print p.match(str(information)).group() but when I run this I get this error, and if I get rid of .group() it then just states "none", but no error. So i'm not sure if the list is getting saved to a string right, or if I'm just missing something obvious. I only want to use regular expression for this, not anything else. Traceback (most recent call last): File "getInformation.py", line 11, in &lt;module&gt; print p.match(str(information)).group() AttributeError: 'NoneType' object has no attribute 'group'
tagged with: python
possible better answer: http://stackoverflow.com/a/50220268
has answer: http://stackoverflow.com/a/50220351
has answer: http://stackoverflow.com/a/50220268
type: AnsweredQuestion
score: 0
has title: Python - Understanding Regular Expression
tagged with: regex
has comment: http://stackoverflow.com/comment/87457297
accepted answer: http://stackoverflow.com/a/50220351
type: Question
answer count: 2
tagged with: subprocess

http://stackoverflow.com/q/50138615
tagged with: google-chrome
accepted answer: http://stackoverflow.com/a/50140554
favorite count: 0
has title: WebDriverException: unknown error: cannot find Chrome binary error with Selenium in Python for older versions of Google Chrome
score: 47
has answer: http://stackoverflow.com/a/76105990
type: Question
has comment: http://stackoverflow.com/comment/87295624
has answer: http://stackoverflow.com/a/50140554
possible better answer: http://stackoverflow.com/a/65664901
has answer: http://stackoverflow.com/a/69696348
has answer: http://stackoverflow.com/a/63777842
has answer: http://stackoverflow.com/a/65664901
has answer: http://stackoverflow.com/a/75512340
has answer: http://stackoverflow.com/a/76800891
tagged with: python
has answer: http://stackoverflow.com/a/71444269
has answer: http://stackoverflow.com/a/76792657
has answer: http://stackoverflow.com/a/50138677
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
answer count: 12
upvote count: 47
linked to: http://stackoverflow.com/q/53330322
has answer: http://stackoverflow.com/a/77295291
has body: For compatibility reasons I prefer to use Chrome version 55.0.2883.75 with Chromedriver v. 2.26. I downloaded the older version of chrome from https://www.slimjet.com/chrome/google-chrome-old-version.php and Chromedriver 2.26 from https://chromedriver.storage.googleapis.com/index.html?path=2.26/. I am using the following code to attempt to set my Chrome binary location: from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.binary_location = "C:\\Program Files\\Chrome\\chrome64_55.0.2883.75\\chrome.exe" driver = webdriver.Chrome('chromedriver.exe', chrome_options = options) However, when I attempt to launch the WebDriver Python returns the following error: WebDriverException: unknown error: cannot find Chrome binary (Driver info: chromedriver=2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30),platform=Windows NT 10.0.14393 x86_64) I have tried searching through similar questions and answers, but have not had any luck so far.
has comment: http://stackoverflow.com/comment/87298340
has answer: http://stackoverflow.com/a/70355929
downvote count: 0

http://stackoverflow.com/a/50181241
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50181122
has body: Without any additional information it looks like you have not defined market (and possibly also not items) before calling parse_runners(market, runners) For example: return runners market = "market" items = ["item1","item2","item3"] parse_runners(market, items)
score: 1

http://stackoverflow.com/comment/87221980
comment on: http://stackoverflow.com/q/50102426
has text: Install more RAM chips?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87177400
type: AnswerComment
has text: Does the 'terms' dataframe always have to be equal to or larger than the 'text' dataframe in length? I've been running some tests and it runs into issues when the terms are shorter than the text.
comment on: http://stackoverflow.com/a/50079255
type: Comment
score: 0

http://stackoverflow.com/comment/87321279
comment on: http://stackoverflow.com/q/50151435
type: Comment
type: QuestionComment
score: 0
has text: The form is submitted via GET request (use `params` for your data), but note that there is one more hidden `csrf_token` field.

http://stackoverflow.com/comment/87300644
score: 0
comment on: http://stackoverflow.com/q/50133484
has text: Threads would be another way that you could do this, so `ThreadPoolExecutor` should work.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87239945
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50090421
has text: Continue: `mx = ma.masked_array(x, mask=[1, 0, 0, 0, 1, 0, 0, 1])` `np.gradient(mx.compressed())` and the result is: `array([ 1. , 1.5, 1. , 2.5, 5. ])` which is computed on 5 non masked points. This want work for arrays of rank higher than 1, because it flattens everything to 1D. I think the reason it flattens everything to 1D array is because for any point at each dimension we can either mask value or not, and thus we have a question how to present it and work with it?

http://stackoverflow.com/q/50149995
has answer: http://stackoverflow.com/a/50150225
accepted answer: http://stackoverflow.com/a/50150225
has body: I'm trying to append current price from a web socket to a list so I can format it and use it for some calculations. However it keeps appending items and expanding list. I want to keep only one instance and keep replacing it with new one. Example: res_array = [] bm = None while True: def process_message(msg): global count, res_array, bm res_array.append(msg['c']) return res_array def initiate(): global bm client = Client(api_key="11111111", api_secret="22222222") bm = BinanceSocketManager(client) conn_key = bm.start_symbol_ticker_socket('BNBBTC', process_message) bm.start() initiate() print(res_array)
tagged with: python
has answer: http://stackoverflow.com/a/50150182
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/87318657
has answer: http://stackoverflow.com/a/50150166
possible better answer: http://stackoverflow.com/a/50150166
has title: How to replace old item with new item in a list inside while loop
has comment: http://stackoverflow.com/comment/87318019
has comment: http://stackoverflow.com/comment/87318341
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87492456
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50211223
score: 0
has text: Yeah, probably is the Pi to slow. The DS18B20 temperature sensors saves the temperature on a text file. I would love to have all data and lines on one file. But don't know how to get that

http://stackoverflow.com/comment/87193859
comment on: http://stackoverflow.com/q/50088819
score: 1
type: Comment
type: QuestionComment
has text: wow, okay I was using a old URL's file for some reason, should have noticed that `user_review_list` was missing. Thank you all working now.

http://stackoverflow.com/comment/87260975
type: QuestionComment
comment on: http://stackoverflow.com/q/50121397
type: Comment
score: 0
has text: Try: `pd.DataFrame.from_records({w: model.wv[w] for w in model.wv.vocab}, orient='index')`

http://stackoverflow.com/comment/137806265
type: AnswerComment
score: 1
has text: Added explanation of lambdas in bind functions. Does that make it clearer?
type: Comment
comment on: http://stackoverflow.com/a/50248838

http://stackoverflow.com/comment/87231870
comment on: http://stackoverflow.com/q/50106697
type: QuestionComment
score: 0
has text: It shows the error because it is *trying* to execute the if statement and failing. And I was talking about what is in `items.txt`.
type: Comment

firefox
type: Tag
tags question: http://stackoverflow.com/q/50181286
tags question: http://stackoverflow.com/q/50185236
tag name: firefox
tags question: http://stackoverflow.com/q/50148814
tags question: http://stackoverflow.com/q/50226578
tags question: http://stackoverflow.com/q/50087048

http://stackoverflow.com/q/50105143
answer count: 1
upvote count: 1
has title: How to assign labels to samples produced in ImageDataGenerator
favorite count: 0
type: Question
has body: I'm new to Convolutional Neural Networks and I'm about to build my first ConvNet which is a multi-class image classification ConvNet. Model Description Let's say I have two image folders, one contains few thousands of images of a particular type of leaves (Leaves A) (Image set X) and other folder contain same number of images of similar type of leaves (Leaves B) (Image set Y). So I need to train my model to distinguish those two types. Problem Background Since I have two classes of outputs Leaves A and Leaves B, I have either 0,1 as an output or 1,0 as an output for a given image of Leaves A class or Leaves B class. Leaves A | Leaves B If Input is a Class A Leaf, 1 0 If Input is a Class B Leaf, 0 1 Problem So in order to do that, I have to label my image set X to have output 1,0 and image set Y to have output 0,1. Also since I need to augment images to have more training samples, I used ImageDataGenerator. training_imGen.flow_from_directory( 'path/to/image_folder_X', target_size=(1100,180), batch_size=batchSize, color_mode='rgb', class_mode='categorical' ) But here I cannot assign a label. Not like when I use training_imGen.flow. However I found classes parameter can be called under flow_from_directory, classes: optional list of class subdirectories (e.g. ['dogs', 'cats']). Default: None. If not provided, the list of classes will be automatically inferred from the subdirectory names/structure under directory, where each subdirectory will be treated as a different class (and the order of the classes, which will map to the label indices, will be alphanumeric). But I don't know how to specify two class labels there since I only give the path to image set X folder. Any ideas how to do that? Update training_imGen.flow_from_directory( '/Users/user/database/', target_size=(1100,180), batch_size=batchSize, color_mode='rgb', class_mode='categorical', classes=['Set_A', 'Set_B'] ) Under /Users/user/database/ path, there are two folders called Set_A and Set_B. As I have mention…
tagged with: classification
downvote count: 0
accepted answer: http://stackoverflow.com/a/50106882
tagged with: python
tagged with: keras
has answer: http://stackoverflow.com/a/50106882
type: AnsweredQuestion
tagged with: conv-neural-network
score: 1

http://stackoverflow.com/a/50104646
has comment: http://stackoverflow.com/comment/87226827
has comment: http://stackoverflow.com/comment/87227110
downvote count: 0
has body: I never quite understood the purpose of drawnow. You should get the exact same result just calling your function. Neither drawnow nor its equivalent simply using plt.ion() and plt.draw() or plt.pause() will work in jupyter notebooks. For sure not using the %matplotlib inline backend (because you cannot animate pngs); but also not with the %matplotlib notebook backend due to the event loop which has not been started until the final figure is shown. Options to show an animation in jupyter notebooks are listed in Animation in iPython notebook. The recommended way would be to create a FuncAnimation. The animation from above would then look like %matplotlib notebook import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import numpy as np x = np.random.rand(10, 2) def function_to_draw_figure(i): line.set_data(*x[i,:]) plt.figure() line, = plt.plot([], marker="o") plt.xlim(0, 1) plt.ylim(0, 1) ani = FuncAnimation(plt.gcf(), function_to_draw_figure, frames=len(x), interval=500, repeat=False) plt.show()
upvote count: 1
has comment: http://stackoverflow.com/comment/87226696
accepted answer of: http://stackoverflow.com/q/50103957
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50103957
has comment: http://stackoverflow.com/comment/87227783
has comment: http://stackoverflow.com/comment/87229382
has comment: http://stackoverflow.com/comment/87228440
has comment: http://stackoverflow.com/comment/87227345
type: AcceptedAnswer

http://stackoverflow.com/a/50214154
accepted answer of: http://stackoverflow.com/q/50213782
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87445298
has comment: http://stackoverflow.com/comment/87445621
type: AcceptedAnswer
has body: try to Up the timeout of es.index , because Elasticsearch are limited to 10 secondes of timeout , if on 30 Secondes it will not respond that mean your Host arn't connected or dont respond to the request from elasticsearch import Elasticsearch, RequestsHttpConnection import time import datetime timenow = datetime.datetime.now() es = Elasticsearch(['70.19.172.110:9200'],http_auth=('&lt;username&gt;','&lt;password&gt;')) for x in range(0,5): es.index(index='test', doc_type='json', id=x, body={ 'data1':"Hello World", 'value':325, 'time':timenow, 'timeout':30, # The Time Of timeout you want }) print("Data sent {} ".format(x)) time.sleep(60)
answers question: http://stackoverflow.com/q/50213782
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50162272
tagged with: python
type: Question
has body: I have a dataframe containing open/close, candle color and number of consecutive candles. date open close color run 00:01:00 100 102 g 1 00:02:00 102 104 g 2 00:03:00 104 106 g 3 00:04:00 106 105 r 1 00:05:00 105 101 r 2 00:06:00 101 102 g 1 00:06:00 102 103 g 2 I'm trying to calculate the absolute value of the difference between the open of the first candle in the run and the close of the last candle in the run and apply the difference to each line. The result would look like date open close color run run_length 00:01:00 100 102 g 1 2 # abs(100 - 102) 00:02:00 102 104 g 2 4 # abs(100 - 104) 00:03:00 104 106 g 3 6 # abs(100 - 106) 00:04:00 106 105 r 1 1 # abs(106 - 105) 00:05:00 105 101 r 2 5 # abs(106 - 101) 00:06:00 101 102 g 1 1 # abs(101 - 102) 00:06:00 102 103 g 2 2 # abs(101 - 103) I have read two other posts that come close but don't quite get to the solution I'm looking for: get first and last values in a groupby Pandas number of consecutive occurrences in previous rows I'm using df.groupby((df['color'] != df['color'].shift()).cumsum()) to group the rows by the color of the candle (this is how I calculated the color and the run count) and I can get the first and last values of the group using .agg(['first', 'last']).stack() but this doesn't allow me to apply the difference per line of the original dataframe.
downvote count: 0
answer count: 1
upvote count: 7
favorite count: 0
has title: Pandas difference between first and last grouped by consecutive events
accepted answer: http://stackoverflow.com/a/50162358
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48259470
tagged with: pandas
has answer: http://stackoverflow.com/a/50162358
linked to: http://stackoverflow.com/q/38797271
score: 7

http://stackoverflow.com/comment/87227267
score: 0
comment on: http://stackoverflow.com/a/50104215
type: Comment
has text: Understood, could .str.contains be used here as I'm after partial matches
type: AnswerComment

http://stackoverflow.com/comment/87409671
type: AnswerComment
score: 0
has text: It is not pushed into one channel. It keeps all 3 channels b but having the same values. The 'is_grayscale' can be done similar with 'tf.greater'
type: Comment
comment on: http://stackoverflow.com/a/50181915

http://stackoverflow.com/comment/87404064
type: Comment
has text: Updated the printing part
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50192991

http://stackoverflow.com/comment/87385437
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50184053
has text: Wouldn't you prefer a [for loop?](https://wiki.python.org/moin/ForLoop)

http://stackoverflow.com/comment/87322016
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50151639
has text: @Faibbus you've been sucked into OP next problems. A [mcve] is required in those cases, to avoid debugging the rest of OP code. Don't answer unclear/typo questions like that. vote/flag to close instead

http://stackoverflow.com/q/50204566
tagged with: django
upvote count: 1
tagged with: file-upload
favorite count: 0
has title: Django: writing text from uploaded file to text field
accepted answer: http://stackoverflow.com/a/50204757
type: Question
has answer: http://stackoverflow.com/a/50204757
score: 1
tagged with: python
type: AnsweredQuestion
has body: I have the following model: class Clean(models.Model): name = models.CharField(max_length=100) cv = models.TextField(max_length=10000) cvfile = models.FileField() I am trying to write the contents of cvfile to cv when the user submits the name and file from the form. I'm sure this can be done as the file and text field will be in the same object. The file will always be .txt so I assume a simple .read() can be performed. Should I have a function that the form calls to perform this? If so how can this be done? def writeCV(self): get_text = cvfile.open().read() #write to cv field somehow return self.cv I am using django 1.9 Traceback from Messaoud's answer: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cleaner/clean/add/ Django Version: 1.9 Python Version: 3.6.4 Installed Applications: ['cleaner.apps.CleanerConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python\Python36-32\lib\site-packages\django\views\g…
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50133391
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50133439
tagged with: function
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87284684
has body: def superindex(string, word): return [i for i, ltr in enumerate(string) if ltr == word] I'm a beginner with Python and I would like to know how this look works. How does it create a list? What does i for i do?
upvote count: 1
downvote count: 1
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/50134131
linked to: http://stackoverflow.com/q/22108488
has answer: http://stackoverflow.com/a/50134037
has title: How does this line of code work? (Python, function)
tagged with: python
has answer: http://stackoverflow.com/a/50133578
has comment: http://stackoverflow.com/comment/87284679
answer count: 4
has comment: http://stackoverflow.com/comment/87284692

http://stackoverflow.com/comment/87341629
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50161510
type: Comment
has text: Thanks, this seems to fix the 'keys' but I'm still getting a `ValueError` for the `guide` field: apparently `request.GET.field_name` is not equivalent to `request.GET.guide`?

http://stackoverflow.com/comment/87384568
score: 0
comment on: http://stackoverflow.com/q/50110824
type: Comment
type: QuestionComment
has text: @VMRuiz how can I verify this?

calibration
tag name: calibration
tags question: http://stackoverflow.com/q/50137181
type: Tag

http://stackoverflow.com/a/50218102
answers question: http://stackoverflow.com/q/50218044
score: 0
has body: percent = [33, 44, 55, 66, 77, 88, 99] grade = [] for i in range(0, len(percent)): if percent[i] &gt;= 70 and percent[i] &lt;= 100: grade.append("Grade A") elif percent[i] &gt;= 60 and percent[i] &lt;= 69: grade.append("Grade B") elif percent[i] &gt;= 50 and percent[i] &lt;= 59: grade.append("Grade C") elif percent[i] &gt;= 45 and percent[i] &lt;= 49: grade.append("Grade D") else: grade.append("No grade achieved") print(grade) You were comparing the values against the index of i rather than the percent element at index i. So you were going vs values 0,1,2,3, etc. The above code works as intended
type: Answer

http://stackoverflow.com/a/50086420
has comment: http://stackoverflow.com/comment/87189134
downvote count: 0
has comment: http://stackoverflow.com/comment/87189253
upvote count: 2
answers question: http://stackoverflow.com/q/50086225
has comment: http://stackoverflow.com/comment/87188967
type: Answer
has body: First sort the dataframe by your conditions: df.sort_values(['include', 'Rank'], ascending=[False, True], inplace=True) Then groupby Group and get the top 3 rows for each Group. Also, add a sort_values to have the final dataframe be sorted on Group then on Rank, like so: df.groupby('Group').head(3).sort_values(['Group', 'Rank']) Output: ID Group Rank include 0 1 Group1 1 0 1 2 Group1 2 1 3 4 Group1 4 1 6 7 Group2 3 1 7 8 Group2 4 1 8 9 Group2 5 1
has comment: http://stackoverflow.com/comment/87189226
score: 2

http://stackoverflow.com/comment/87344222
type: Comment
comment on: http://stackoverflow.com/a/50162965
score: 0
type: AnswerComment
has text: ha always fun when you're working with that type of data. I wish I had an answer for you regarding speed of `from_dict` vs. @Wen 's answer. I will do some research and see if I can find an appropriate answer

http://stackoverflow.com/a/50102056
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50101808
type: Answer
has body: You can use recursion. First, create a function that can generate a full combinations for each index of the input: def full_combinations(d, current = []): if len(d) == len(current): yield current else: yield current for i in range(len(d)): if len(set(current+[i])) == len(current)+1: yield from full_combinations(d, current+[i]) combination_list = list(full_combinations([1, 2, 3])) new_results = [[0 if c in i else a for c, a in enumerate([1, 2, 3])] for i in combination_list] full = [a for i, a in enumerate(new_results) if a not in new_results[:i]] Output: [[1, 2, 3], [0, 2, 3], [0, 0, 3], [0, 0, 0], [0, 2, 0], [1, 0, 3], [1, 0, 0], [1, 2, 0]]

http://stackoverflow.com/comment/87282515
comment on: http://stackoverflow.com/q/50130778
score: 0
type: QuestionComment
has text: Downgrade versions of Driver. I think v.33 working perfect
type: Comment

http://stackoverflow.com/comment/87312940
comment on: http://stackoverflow.com/a/50147126
type: AnswerComment
score: 0
type: Comment
has text: would you give the scripts?

http://stackoverflow.com/comment/87309590
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50130315
has text: You need to resize your image to `(image_size,image_size)` before you reshape it.
score: 0

http://stackoverflow.com/a/50148409
answers question: http://stackoverflow.com/q/50148374
has comment: http://stackoverflow.com/comment/87314896
upvote count: 5
score: 5
accepted answer of: http://stackoverflow.com/q/50148374
type: Answer
has comment: http://stackoverflow.com/comment/87315091
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87315582
has body: You can just use indexing by applying a condition statement. cols = ['T1','T2','T3','T4'] df[df[cols] &lt; 0] = -5 Output In [35]: df Out[35]: T1 T2 T3 T4 0 20 -5 4 3 1 85 -5 34 21 2 -5 22 31 75 3 -5 5 7 -5 In your example you're just replacing the value of variable. You need to replace one cell's value using at method. for i in df.iloc[:,df.columns.get_loc("T1"):df.columns.get_loc("T1")+4]&lt;0: for index, j in enumerate(df[i]): if j&lt;0: df.at[index, i] = -5

http://stackoverflow.com/comment/87199088
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50090903
has text: one more thing, it says converted = [row["REGION_ID"], int(row["POPULATION_15"]), NameError: name 'row' is not defined, what should i do about this?
type: Comment

http://stackoverflow.com/q/50120075
type: Question
tagged with: opencv
has title: Google app engine deploy flask app - ImportError: libSM.so.6: cannot open shared object file: No such file or directory
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has comment: http://stackoverflow.com/comment/87258237
has answer: http://stackoverflow.com/a/50120543
answer count: 2
upvote count: 2
score: 2
has body: I am trying to deploy a python flask app to google cloud. Once the app starts running I get the following error: File "/home/vmagent/app/app.py", line 11, in &lt;module&gt; import cv2 File "/env/lib/python3.4/site-packages/cv2/__init__.py", line 9, in &lt;module&gt; from .cv2 import * ImportError: libSM.so.6: cannot open shared object file: No such file or directory Doing some research on the problem, I figured out that this seems to be a problem related to opencv-python and the following line should fixes the issue on linux: sudo apt-get install libsm6 However, since I am using Mac I am unable to use apt-get to install libsm6 locally and since I am deploying using a requirements.txt file which does not accept apt-get I am stuck fixing this. I tried to SSH into the running instance on google cloud, however it does not accept apt-get install libsm6 either, telling me I lack admin rights: E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied) E: Unable to lock the administration directory (/var/lib/dpkg/), are you root? changing directory to root didn't help either. Does anyone know how to fix this? I have also tried python version 3.5 and 3.4 with no luck.
has comment: http://stackoverflow.com/comment/87258406
downvote count: 0
has answer: http://stackoverflow.com/a/50120461
favorite count: 0

site-packages
tags question: http://stackoverflow.com/q/50102968
tag name: site-packages
type: Tag

http://stackoverflow.com/comment/115230674
comment on: http://stackoverflow.com/a/50341520
has text: This assumes that no other column has a genuine "." character.
score: 3
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50134293
tagged with: python
has body: I have a list of numbers and another list of probabilities which corresponds to these numbers. I use numpy.random.choice to create a random 2d array: choice = numpy.random.choice([10, 22, 30], [10, 10], p=[0.45, 0.45, 0.10]) In choiceshould be 45 ones, 45 twos and 10 zeros but after several runs i never get the correct distribution. unique, counts = numpy.unique(choice, return_counts=True) print(dict(zip(unique, counts))) {10: 49, 22: 37, 30: 14} {10: 47, 22: 42, 30: 11} {10: 40, 22: 51, 30: 9} What did i miss?
possible better answer: http://stackoverflow.com/a/50134485
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50134615
tagged with: random
has answer: http://stackoverflow.com/a/50134485
has answer: http://stackoverflow.com/a/50134738
has title: Numpy random choice distribution error
accepted answer: http://stackoverflow.com/a/50134599
has answer: http://stackoverflow.com/a/50134599
answer count: 4
favorite count: 0
tagged with: distribution
type: Question
tagged with: numpy
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/50177146
answers question: http://stackoverflow.com/q/50176861
accepted answer of: http://stackoverflow.com/q/50176861
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/87389460
upvote count: 4
has body: Model performance is dependent on way the data is split and sometimes model does not have ability to generalize. So that's why we need the cross validation. Cross-validation is a vital step in evaluating a model. It maximizes the amount of data that is used to train the model, as during the course of training, the model is not only trained, but also tested on all of the available data. I am wondering whether [X,y] is X_train and y_train or [X,y] should be the whole dataset. [X, y] should be the whole dataset because internally cross validation spliting the data into training data and test data. Suppose you use cross validation with 5 folds (cv = 5). We begin by splitting the dataset into five groups or folds. Then we hold out the first fold as a test set, fit out model on the remaining four folds, predict on the test set and compute the metric of interest. Next, we hold out the second fold as out test set, fit on the remaining data, predict on the test set and compute the metric of interest. By default, scikit-learn's cross_val_score() function uses R^2 score as the metric of choice for regression. R^2 score is called coefficient of determination.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50096784
downvote count: 0
accepted answer: http://stackoverflow.com/a/50097258
upvote count: 1
has answer: http://stackoverflow.com/a/50097258
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50097246
has answer: http://stackoverflow.com/a/50097246
tagged with: django
tagged with: python
has body: I am trying to build a simple web page that queries three tables. There is a Company table that has a one-to-many relationship with a Position table, as well as a one-to-many relationship with a Project table. The goal is to have the page display a given company once, along with all positions and and projects associated with said company. Then, move on to display the next company, any positions held there and projects completed. Below is the closest I've come to getting this right. But, the obvious problem is that if there is more than one project associated with a given company, you'll see that company listed more than once. I'm new to Django, so in the interest of learning, I wanted to beat my own head sufficiently hard before asking for help; but I could really use some fresh ideas at this point. Also: I can see how a nested for loop might work here, but I'm just not clear on how the mechanics of that would work with the query, and then within the template. Models: from django.db import models class Company(models.Model): company_id = models.AutoField(primary_key=True) company_name = models.CharField(max_length=20) company_logo = models.ImageField(upload_to='images/') def __str__(self): return self.company_name class Position(models.Model): position_id = models.AutoField(primary_key=True) position_title = models.CharField(max_length=55) company_id = models.ForeignKey('professional.Company', on_delete=models.CASCADE, blank=True, null=True) begin_date = models.DateField() end_date = models.DateField() def __str__(self): return self.position_title class Project(models.Model): project_id = models.AutoField(primary_key=True) project_name = models.CharField(max_length=55) company_id = models.ForeignKey('professional.Company', on_delete=models.CASCADE, blank=True, null=True) project_description = models.CharField(max_length=500) project_image = models.ImageField(upload_to='images/') def __str__(self): return self.project_name View: from django.views.generic import Templ…
has title: Django: How to iterate over two one-two-many table relationships?
type: AnsweredQuestion
answer count: 2
score: 1

http://stackoverflow.com/a/50179425
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50162787
has body: It looks like you are trying to matrix multiply 'x' with 'weights'. x has a shape of [5741, 20000] for one example, but when you feed examples in batches x will have a shape of [?, 5741, 20000]. Similarly, weights should also have a shape of [?, 20000, 128]. But, from the error, it looks like your weights are still [20000, 128] which tells me that you have some problem in your code which is not transforming the weights variable to shape [?, 20000, 128]. When you can figure this out, the error should go away. The result of matrix multiplication should have a shape of [?, 5741, 128]

http://stackoverflow.com/comment/116536737
has text: Does this answer your question? [Set specific DNS server using dns.resolver (pythondns)](https://stackoverflow.com/questions/3898363/set-specific-dns-server-using-dns-resolver-pythondns)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50168439

http://stackoverflow.com/q/50137442
type: Question
has comment: http://stackoverflow.com/comment/87317419
has comment: http://stackoverflow.com/comment/87295772
has comment: http://stackoverflow.com/comment/87342227
tagged with: owl
has body: UPDATE: I've solved this problem. Using OWL API in Java I manage to retrieve all the axioms in the ontology, among which were all the Equivalent Classes I was looking for. As far as I know, there's no direct way to obtain unamed equivalent classes. This is the code I used: OWLOntologyManager man = OWLManager.createOWLOntologyManager(); o = man.loadOntologyFromOntologyDocument(hp); Stream&lt;OWLLogicalAxiom&gt; logicalAxioms = o.logicalAxioms(); logicalAxioms.forEach(log::println); Question: I have an ontology (Human Phenotype Ontology, or just 'hp') and I need to extract the classes from other ontologies referenced in my ontology inside the "owl:equivalentClass" tag. For instance: For the hp class "HP_0001561", I'd want extracted: BFO_0000051 PATO_0000595 RO_0000052 UBERON_0000173 RO_0002573 PATO_0000460 hp-logical-definitions-subq#during GO_0007565 Here's the class: &lt;!-- http://purl.obolibrary.org/obo/HP_0001561 --&gt; &lt;owl:Class rdf:about="http://purl.obolibrary.org/obo/HP_0001561"&gt; &lt;rdfs:label rdf:datatype="http://www.w3.org/2001/XMLSchema#string"&gt;Polyhydramnios&lt;/rdfs:label&gt; &lt;owl:equivalentClass&gt; &lt;owl:Restriction&gt; &lt;owl:onProperty rdf:resource="http://purl.obolibrary.org/obo/BFO_0000051"/&gt; &lt;owl:someValuesFrom&gt; &lt;owl:Class&gt; &lt;owl:intersectionOf rdf:parseType="Collection"&gt; &lt;rdf:Description rdf:about="http://purl.obolibrary.org/obo/PATO_0000595"/&gt; &lt;owl:Restriction&gt; &lt;owl:onProperty rdf:resource="http://purl.obolibrary.org/obo/RO_0000052"/&gt; &lt;owl:someValuesFrom rdf:resource="http://purl.obolibrary.org/obo/UBERON_0000173"/&gt; &lt;/owl:Restriction&gt; &lt;owl:Restriction&gt; &lt;owl:onProperty rdf:resource="http://purl.obolibrary.org/obo/RO_0002573"/&gt; &lt;owl:someValuesFrom rdf:resource="http://purl.obolibrary.org/obo/PATO_0000460"/&gt; &lt;/owl:Restriction&gt; &lt;owl:Restriction&gt; &lt;owl:onProperty rdf:resource="http://purl.obolibrary.org/obo/hp/hp-logical-definitions-subq#during"/&gt; &l…
type: UnansweredQuestion
tagged with: java
has comment: http://stackoverflow.com/comment/87382146
tagged with: ontology
has comment: http://stackoverflow.com/comment/87301346
tagged with: python
has comment: http://stackoverflow.com/comment/87373521
has comment: http://stackoverflow.com/comment/87297302
has comment: http://stackoverflow.com/comment/87302277
has comment: http://stackoverflow.com/comment/87373059
score: 0
has comment: http://stackoverflow.com/comment/87373158
tagged with: http://stackoverflow.com/tag/rdf
has title: Get equivalence classes from OWL ontologies
answer count: 0
has comment: http://stackoverflow.com/comment/87302169
has comment: http://stackoverflow.com/comment/87373269
has comment: http://stackoverflow.com/comment/87707907
has comment: http://stackoverflow.com/comment/87301865
has comment: http://stackoverflow.com/comment/87453550
has comment: http://stackoverflow.com/comment/87313999
has comment: http://stackoverflow.com/comment/87297734
has comment: http://stackoverflow.com/comment/87381951

http://stackoverflow.com/comment/87497498
type: AnswerComment
has text: Honestly, I don't know it exactly but I bet yes. According the jupyter documentation "Note that the RAM is not released until the kernel is shut-down." it is very likely. There is no reason to keep the Python process and TensorFlow session alive. So the OS once more will probably pick up the pieces and clear the memory.
type: Comment
comment on: http://stackoverflow.com/a/50235440
score: 0

http://stackoverflow.com/comment/87457929
has text: When you have multiple rows with the same Client_IP value, then this column does not identify the rows.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50203341

http://stackoverflow.com/comment/87430661
score: 1
type: Comment
type: QuestionComment
has text: You can remove CountVectorizer all-together. TfidfVectorizer will do that for you.
comment on: http://stackoverflow.com/q/50192763

http://stackoverflow.com/q/50162838
downvote count: 0
has answer: http://stackoverflow.com/a/50162872
has answer: http://stackoverflow.com/a/50162900
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50162985
possible better answer: http://stackoverflow.com/a/50162908
answer count: 4
has title: How to apply a function to a list within a list
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50162908
has body: I have a list and a function: t = [3, [1], [2, [1], [1]]] f = lambda x: x**2 I want the result like this: [9, [1], [4, [1], [1]]] I tried to use map function but it did not seem to work I got a type error when I do this: list(map(f, t))
upvote count: 2
has comment: http://stackoverflow.com/comment/87343608
accepted answer: http://stackoverflow.com/a/50162872

http://stackoverflow.com/comment/87351150
comment on: http://stackoverflow.com/q/50166612
score: 0
type: QuestionComment
type: Comment
has text: If you can tell me why you have this in a try-except clause maybe I can help you out. I really don't think you need any recursion for this. Is it just to verify that the two inputs are valid numbers?

http://stackoverflow.com/comment/87393357
type: Comment
type: QuestionComment
score: 0
has text: Sorry, no. You're trying to run some code when a list item is changed. The other question is trying to run some code when a dict item is changed. Having to pass a reference to `self` to the `MyList` class is a trivial difference that doesn't make your question different from the other question.
comment on: http://stackoverflow.com/q/50188106

http://stackoverflow.com/q/50188106
has body: How to assign values to a slice of some @property of a class, which happens to be a list or numpy.ndarray, so that it's setter is called? Now it seems that assignment to a slice calls only getter. I cannot understand how a slice is handled under the hood in such case. Example code: class MyClass: def __init__(self, a): self.a = a self._a = self.a @property def a(self): return self._a @a.setter def a(self, v): print("I'm called") self._a = v A = MyClass([1, 2, 3]) # prints "I'm called" A.a = [4, 5, 6] # prints "I'm called" A.a[1] = 0 # does not print anything How to make A.a[1] = 0 print "I'm called"?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87393357
type: Question
has comment: http://stackoverflow.com/comment/87393266
tagged with: getter-setter
has comment: http://stackoverflow.com/comment/87393201
tagged with: python
duplicate of: http://stackoverflow.com/q/3137685
tagged with: properties
has title: How to make slicing list @property to call its setter in python
tagged with: slice
linked to: http://stackoverflow.com/q/3137685
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87393155

http://stackoverflow.com/comment/138148294
has text: @MarkusDutschke – What exactly is the difference between `Path(s).rmtree()` and `shutil.rmtree(s)` in this regard?
comment on: http://stackoverflow.com/a/50187147
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87199570
has text: What does `ccm node1 showlog` say?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50089785

http://stackoverflow.com/q/50131032
type: AnsweredQuestion
tagged with: naivebayes
has body: import pandas as pd import numpy from sklearn import cross_validation from sklearn.naive_bayes import GaussianNB fi = "df.csv" # Open the file for reading and read in data file_handler = open(fi, "r") data = pd.read_csv(file_handler, sep=",") file_handler.close() # split the data into training and test data train, test = cross_validation.train_test_split(data,test_size=0.6, random_state=0) # initialise Gaussian Naive Bayes naive_b = GaussianNB() train_features = train.ix[:,0:127] train_label = train.iloc[:,127] test_features = test.ix[:,0:127] test_label = test.iloc[:,127] naive_b.fit(train_features, train_label) test_data = pd.concat([test_features, test_label], axis=1) test_data["p_malw"] = naive_b.predict_proba(test_features) print "test_data\n",test_data["p_malw"] print "Accuracy:", naive_b.score(test_features,test_label) I have written this code to accept input from a csv file with 128 columns where 127 columns are features and the 128th column is the class label. I want to predict probability that the sample belongs to each class (There are 5 classes (1-5)) and print it in for of a matrix and determine the class of sample based on the prediction. predict_proba() is not giving the desired output. Please suggest required changes.
tagged with: python
score: 4
upvote count: 6
accepted answer: http://stackoverflow.com/a/50133061
has title: Multiclass Classification and probability prediction
tagged with: multiclass-classification
type: Question
has comment: http://stackoverflow.com/comment/87283688
downvote count: 2
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50133061
favorite count: 0

http://stackoverflow.com/q/50134468
possible better answer: http://stackoverflow.com/a/65388773
tagged with: image-processing
score: 13
linked to: http://stackoverflow.com/q/2761645
has answer: http://stackoverflow.com/a/65388773
has body: I'm currently working with image processing in python using the scikit-image library. I'm trying to make a binary image using sauvola thresholding with the following code: from PIL import Image import numpy from skimage.color import rgb2gray from skimage.filters import threshold_sauvola im = Image.open("test.jpg") pix = numpy.array(im) img = rgb2gray(pix) window_size = 25 thresh_sauvola = threshold_sauvola(img, window_size=window_size) binary_sauvola = img &gt; thresh_sauvola Which gives the following result: the output is a numpy array with data type of this image is a bool [[ True True True ... True True True] [ True True True ... True True True] [ True True True ... True True True] ... [ True True True ... True True True] [ True True True ... True True True] [ True True True ... True True True]] The problem is that I need to convert this array back to a PIL image using the following line of code: image = Image.fromarray(binary_sauvola) which makes the image look like this: I also tried to change the data type from bool to uint8 but then I'll get the following exception: AttributeError: 'numpy.ndarray' object has no attribute 'mask' So far I haven't found a solution to get a PIL image which looks like the result of the thresholding.
has title: Convert boolean numpy array to pillow image
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87287320
has comment: http://stackoverflow.com/comment/87287569
accepted answer: http://stackoverflow.com/a/50134667
tagged with: python-imaging-library
upvote count: 13
tagged with: scikit-image
tagged with: python
has comment: http://stackoverflow.com/comment/87290348
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50134667
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/87474355
score: 0
type: Comment
has text: @s6hebern you get result of a job before the next job is applied, thus forcing jobs to be done one by one. Simply apply all the jobs, then get all the results
type: AnswerComment
comment on: http://stackoverflow.com/a/50170302

http://stackoverflow.com/comment/87325672
score: 1
has text: `def quit_option(): print ("Good bye!") return quit_option()` infinite recursion
type: QuestionComment
comment on: http://stackoverflow.com/q/50154076
type: Comment

http://stackoverflow.com/q/50190486
has title: Setting different batch size for training and validation using Tensorflow's tf.data API
score: 4
has body: I am migrating from the older queue-based data pipeline to the newer tf.data API. Suppose I have a code like the following, how can I explicitly set different batch sizes for my training and validation iterators. filenames = tf.placeholder(tf.string, shape=[None]) dataset = tf.data.TFRecordDataset(filenames) dataset = dataset.map(...) # Parse the record into tensors. dataset = dataset.repeat() # Repeat the input indefinitely. dataset = dataset.batch(32) iterator = dataset.make_initializable_iterator() # Initialize `iterator` with training data. training_filenames = ["/var/data/file1.tfrecord", "/var/data/file2.tfrecord"] sess.run(iterator.initializer, feed_dict={filenames: training_filenames}) # Initialize `iterator` with validation data. validation_filenames = ["/var/data/validation1.tfrecord", ...] sess.run(iterator.initializer, feed_dict={filenames: validation_filenames}) EDIT: Thank you. Based on the reply, my implementation is as follows: My implementation is like follows, but I'm not able to figure out why I'm getting this error: import tensorflow as tf def _parse(filename, label): image_string = tf.read_file(filename) image_decoded = tf.image.decode_jpeg(image_string) image_resized = tf.image.resize_images(image_decoded, [224, 224]) image_resized.set_shape([224,224,3]) return image_resized, label def input_pipeline(imglist,labellist, batch_size): dataset = tf.data.Dataset.from_tensor_slices((imglist, labellist)) dataset = dataset.map(_parse) # Parse the record into tensors. dataset = dataset.repeat() # Repeat the input indefinitely. dataset = dataset.batch(batch_size) return dataset imglist = glob.glob('/var/temp/*.jpg') train_imgs=imglist[0:100] train_labels = [i for i in range(100)] val_imgs=imglist[200:250] val_labels = [i for i in range(50)] training_batch_size = 4 validation_batch_size = 1 training_ds = input_pipeline(train_imgs, train_labels, training_batch_size) validation_ds = input_pipeline(val_imgs, val_labels, validation_batch_size) handle = tf.pla…
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50191742
downvote count: 0
has answer: http://stackoverflow.com/a/50191742
accepted answer: http://stackoverflow.com/a/50195746
tagged with: tensorflow
favorite count: 0
upvote count: 4
has answer: http://stackoverflow.com/a/50195746
type: Question
answer count: 2
tagged with: python

http://stackoverflow.com/comment/87340948
comment on: http://stackoverflow.com/q/50161070
type: Comment
type: QuestionComment
score: 0
has text: @VikashSingh I would say No, this is not a duplicate, because here we are starting with python dictionaries as apposed to a json file.

http://stackoverflow.com/q/50186541
possible better answer: http://stackoverflow.com/a/50186607
has title: Is there a better way to do 'complex' list comprehension?
tagged with: python
tagged with: list-comprehension
type: AnsweredQuestion
tagged with: performance
score: 0
answer count: 3
has body: I tend to use list comprehension a lot in Python because I think it is a clean way to generate lists, but often I find myself coming back a week later and thinking to myself "What the hell did I do this for?!" and it's a 70+ character nested conditional list comprehension statement. I am wondering if it gets to a certain point if I should break it out into if/elif/else, and the performance impact, if any of doing so. My current circumstance: Returned structure from call is a list of tuples. I need to cast it to a list, some values need to be cleaned up, and I need to strip the last element from the list. e.g. [(val1, ' ', 'ChangeMe', 'RemoveMe), (val1, ' ', 'ChangeMe', 'RemoveMe), (val1, ' ', 'ChangeMe', 'RemoveMe)] So in this case, I want to remove RemoveMe, replace all ' ' with '' and replace ChangeMe with val2. I know it is a lot of changes, but the data I am returned is terrible sometimes and I have no control over what is coming to me as a response. I currently have something like: response = cursor.fetchall() response = [['' if item == ' ' else item if item != 'ChangeMe' else 'val2' for item in row][:-1] for row in response]` Is a nested multi-conditional comprehension statement frowned upon? I know stylistically Python prefers to be very readable, but also compact and not as verbose. Any tips or info would be greatly appreciated. Thanks all!
has answer: http://stackoverflow.com/a/78158076
has answer: http://stackoverflow.com/a/50186607
accepted answer: http://stackoverflow.com/a/50186638
type: Question
has answer: http://stackoverflow.com/a/50186638
tagged with: format

amazon-athena
type: Tag
tags question: http://stackoverflow.com/q/50180425
tag name: amazon-athena

http://stackoverflow.com/comment/87178094
score: 0
has text: It won't train because there's only one input sequence - there's not really anything to train on. I can modify the code and get back to you. Thanks again for taking a look at this!
comment on: http://stackoverflow.com/q/50080512
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51356271
has comment: http://stackoverflow.com/comment/92845719
upvote count: 2
type: Answer
has body: In case any one found this question. The answer provided by the host works, but the idea is wrong. You don't use any RSA keys with HMAC method. The RSA key pair (public and private) are used for asymmetric algorithm while HMAC is symmetric algorithm. In HMAC, the two sides of the communication keep the same secret text(bytes) as the key. It can be a public_cert.pem as long as you keep it secretly. But a public.pem is usually shared publicly, which makes it unsafe.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/116527550
answers question: http://stackoverflow.com/q/50110748

http://stackoverflow.com/q/50112966
tagged with: python-2.7
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Issue with network location printing from arg parser in python
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50113289
tagged with: python
has body: I am trying to give input as network location build but it is printing with extra forward slashes can u please help python file.py --networklocation \network\path\dest\build_1 But when i am printing it in script it is printing as \\network\path\dest\build_1/ but expected is \network\path\dest\build_1 def __parse_args(self): parser = argparse.ArgumentParser(description='network location) parser.add_argument('--networklocation',required=True, type=str ,help="build location ") self._args = parser.parse_args()

http://stackoverflow.com/q/50179792
type: UnansweredQuestion
has body: Thanks in advance for any help....I'm stuck! I am attempting to write a script that will fire up many processes that each do the following: 1. spin up an AWS EC2 Instance 2. execute a script on that instance (script sitting there on AMI) 3. terminate instance when script complete Using separate VMs really is necessary and this is not be a good case for another type of parallelism locally. The script below works but the pool workers stop responding. I get part of the way through the target_cos list and the pool workers do nothing. The process they live in is still running and the VM is still alive on AWS but nothing happens and things appear to be hung. Additionally, when I step through it using a debugger/IDE with a single pool worker it works correctly. When I run it with many workers in the mp pool, they hang after ~2 iterations. import postgresql import boto3 import paramiko import time import os from multiprocessing import Pool def spin_up(target_co): #What would happen with paramiko import here? ec2 = boto3.resource('ec2', region_name="us-west-2") instances = ec2.create_instances(ImageId='AMI-HERE', MinCount=1, MaxCount=1, KeyName="SECRET_KEY", InstanceType="t2.micro", Placement={ 'AvailabilityZone': 'us-west-2c' }, SecurityGroups=[ 'Internal' ] ) i = instances[0] print('WAITING FOR INSTANCE AVAILABILITY....') i.wait_until_running() print('OK.') i.load() k = paramiko.RSAKey.from_private_key_file('KEY_FILE_PATH.pem') c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) success_flag = False attempt_counter = 0 while success_flag == False and attempt_counter &lt; 20: try: c.connect(hostname=i.public_dns_name, username="ubuntu", pkey=k) success_flag = True except: print('SSH Error.....Retrying.') attempt_counter += 1 time.sleep(5) cmd = "python3 PATH_TO_EXECUTABLE_ON_AMI.py --target {} &gt; LOG_FILE_ON_VM".format(target_co) transport = c.get_transport() channel = transport.open_session() channel.exec_command(cmd) while(channel.exit_statu…
upvote count: 1
tagged with: python
tagged with: boto3
has answer: http://stackoverflow.com/a/50225515
tagged with: paramiko
downvote count: 0
answer count: 1
has title: Python multiprocessing children hang -- BOTO3 PARAMIKO
score: 1
favorite count: 0
tagged with: multiprocessing
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87192219
comment on: http://stackoverflow.com/q/50088215
has text: In the first instance, you're just modifying a single DataFrame object instance. This is no different than how vanilla Python works.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50107541
has title: hybrid_property raises a TypeError in if/else
tagged with: python
has answer: http://stackoverflow.com/a/50123115
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87233367
tagged with: sqlalchemy
has body: I'd like to do some formatting on the id in a hybrid property so that numbers under 10 are prefixed with a P0 (P01, P02, 03, etc). The following code is throwing a TypeError: Boolean value of this clause is not defined from the __bool__ method in elements.py. What am I missing? In my models.py: @hybrid_property def conversion_number(self): return 'P0{}'.format(self.id) if self.id &lt; 10 else 'P{}'.format(self.id)
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87232661
type: UnansweredQuestion

http://stackoverflow.com/comment/87238647
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50110615
has text: Well, if it is for mocking that's fine, but normally it is better to implement instances with different behavior with the strategy pattern.
score: 0

http://stackoverflow.com/comment/87442014
comment on: http://stackoverflow.com/q/50212552
score: 0
has text: [This](https://www.oracle.com/corporate/features/understanding-java-9-modules.html) article may shed some light. Have you seen it already?
type: Comment
type: QuestionComment

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/50131042
type: Tag

http://stackoverflow.com/comment/87420315
type: Comment
type: AnswerComment
score: 0
has text: Ok. Thanks again! I don't know if I understand it - so **BeautifulSoup** needs a string, doesn't it?
comment on: http://stackoverflow.com/a/50201797

http://stackoverflow.com/q/50224230
tagged with: assertion
tagged with: thrift-protocol
accepted answer: http://stackoverflow.com/a/50224437
tagged with: python
possible better answer: http://stackoverflow.com/a/50243490
has title: Why Thrift raises AssertionError when requested by multiple threads?
has body: i'm building a kind of simulator that uses thrift protocol. But when im executing multiple threads of my virtual equipments sending messages, the program breaks after a short time by receiving them, think the buffer is overloaded or something like that, or not, so i'm here asking for some help if its possible. Here's the main pieces of my code A class for threading: class ThreadManager (threading.Thread): def __init__(self, name, obj, client, layout): threading.Thread.__init__(self) self.name = name self.obj = obj self.client = client self.layout = layout def run(self): print ("Starting " + self.name) while True: sleep(2) self.obj.auto_gen_msg(self.client, layout=self.layout) The method for generating messages: def auto_gen_msg(self, client, layout='', min_delay=15, max_delay=30): if not layout: msg = self.gen_message(self.draw_random_model()) else: msg = self.gen_message(layout) wait = randint(min_delay, max_delay) sleep(wait) print(self.eqp_type, " delivered a message ...") getattr(client, msg[0])(*msg[1]) The main: def start(layout, equipment, number): try: host = 'localhost' transport = TSocket.TSocket(host, port=9090) transport = TTransport.TBufferedTransport(transport) protocol = TCompactProtocol.TCompactProtocol(transport) client = SuiteService.Client(protocol) transport.open() equips = [Equipment(equipment) for i in range(number)] threads = [ThreadManager(i.eqp_type, i, client, layout) for i in equips] for i in range(len(threads)): threads[i].start() sleep(2) while True: pass transport.close() except Thrift.TException as tx: print ("%s " % (tx.message)) The error haunting me: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Users/lem4fia/Documents/sg/loki/loki-thrift/loki_thrift/loki_thrift/lib/thread_manager.py", line 39, in run self.obj.auto_gen_msg(self.client, layout=self.layout) File "/Users/lem4fia/Documents/sg/loki/loki-thrift/loki_th…
has answer: http://stackoverflow.com/a/50224437
tagged with: thrift
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50243490
type: Question
answer count: 2

http://stackoverflow.com/comment/87462850
type: QuestionComment
has text: @vealkind Have to check the performance after using explode. One of the problem is spike detection is just one such example. I have other functions where statsmodels and scikit-learn libs are used. Explode will probably not help.
comment on: http://stackoverflow.com/q/50215791
type: Comment
score: 0

http://stackoverflow.com/comment/87278476
type: Comment
has text: Thank you @minrk, this way I can recover and associate the `stdout` or any other info I need from the server by adding a `key: value` pair to what is returned by `processmessage()`. What I'm missing is the *streaming* part which is maybe not very clear in my question. For streaming, I mean the *server* keep the clients 'up-to-date' with the processes status, by sending/streaming the processes std-out while a process is still running.
type: AnswerComment
comment on: http://stackoverflow.com/a/50101081
score: 0

http://stackoverflow.com/a/50170401
score: 11
upvote count: 11
has body: When Python constructs the repr of a builtin object such as a list it uses two internal functions: Py_ReprEnter(PyObject *), and Py_ReprLeave(PyObject *). The first of these functions checks we are already handling the repr for the specified object (i.e. looks to see whether it is currently remembering that object). If not it remembers the object and returns 0. In that case the repr code prints the object then calls Py_ReprLeave which removes the object from the set that are currently being tracked. If Py_ReprEnter is already tracking the object it returns non 0 and in that case the list repr code prints [...].
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50170263
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50170263
type: Answer

http://stackoverflow.com/comment/87454985
comment on: http://stackoverflow.com/a/50213290
has text: @trieser Then you will have to provide enough information (code, sample input) for us to replicate your problem. Simply saying "it doesn't work" doesn't give us anything to go on.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/50225054
score: 1
has title: Python executable scripts installed through `console_scripts` using `pip install -e .` can be found in path but not `pip install .`
has answer: http://stackoverflow.com/a/69356374
possible better answer: http://stackoverflow.com/a/69356374
tagged with: command-line
type: Question
has answer: http://stackoverflow.com/a/50225087
answer count: 2
upvote count: 1
tagged with: pip
tagged with: python
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50225087
has body: I have my folder structure like this working folder ├── my_package │ ├── __init__.py │ ├── modules.py ├── scripts │ ├── abc │ └── def └── setup.py and tried to write scripts=[ 'scripts/abc', 'scripts/def' ] in setup.py but my colleague using Windows complained that it was not easy to invoke. Since I want to make my package cross-platform, I tried to follow the instructions of the console_scripts entry point but it seemed to require me to put abc.py and def.py inside my_package. However, I want to keep my folder structure. Therefore I tried to write entry_points={ 'console_scripts': [ 'abc=scripts.abc:main', 'def=scripts.def:main' ]} in setup.py and abc can be invoked if this package is installed using pip install -e . (where . points to working folder), but I cannot invoke it if installed with pip install .. It would report some error: Traceback (most recent call last): File "/Users/xx/.pyenv/versions/3.6.0/bin/abc", line 11, in &lt;module&gt; load_entry_point('my_package==1.0.6', 'console_scripts', 'abc')() File "/Users/xx/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pkg_resources/__init__.py", line 565, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/Users/xx/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2631, in load_entry_point return ep.load() File "/Users/xx/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2291, in load return self.resolve() File "/Users/xx/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2297, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) ModuleNotFoundError: No module named 'scripts' I have no idea what caused this problem. Am I using console_scripts the right way? What is the differences between pip install . and pip install -e .? I have typed python -m site and their paths are the same. BTW, I am using Python 3.6.0 installed locally through pyenv on macOS 10.…
downvote count: 0

http://stackoverflow.com/q/50213230
type: Question
has answer: http://stackoverflow.com/a/50213314
score: -3
has body: I'm trying to create a game that is kind of along the lines of the game mastermind. I have a section where the user has to either guess the number or type "exit" to stop the game. How do i make it so that the code allows both an integer and string input? The code is: PlayerNum = int(input("Type your number in here:")) if PlayerNum == "exit": print "The number was:",RandNum1,RandNum2,RandNum3,RandNum4 print "Thanks for playing! exit() If anyone could help that would be great. Thanks. :D
tagged with: python
has answer: http://stackoverflow.com/a/50213690
has comment: http://stackoverflow.com/comment/87443292
downvote count: 4
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50213680
upvote count: 1
has title: How to make a user input both a string and integer
favorite count: 0

http://stackoverflow.com/q/50210785
has answer: http://stackoverflow.com/a/64572211
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92792036
has body: I build an Inverse Compositional CNN but it reports errors as bellows: ValueError: Variable left_src_tgt_warp/ICSTN/icnv1/weight already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at: I find that using tf.reset_default_graph() can solve this problem. But I do not know where I should add it. for l in range(opt.warpN): with tf.variable_scope("ICSTN", reuse=l &gt; 0) as sc: end_points_collection = sc.original_name_scope + '_end_points' with slim.arg_scope([slim.conv2d, slim.conv2d_transpose], normalizer_fn=slim.batch_norm, weights_regularizer=slim.l2_regularizer(0.05), normalizer_params=batch_norm_params, activation_fn=tf.nn.relu, outputs_collections=end_points_collection): imageWarp = inverse_warp( inputImage, depth, pM, intrinsics, intrinsics_inv) imageWarpAll.append(imageWarp) feat = tf.reshape(imageWarp, [batch_size, H, W, C]) print('feat shape:', feat.get_shape()) print('pM_ini:', pM.get_shape()) with tf.variable_scope("icnv1"): feat = conv2Layer(opt, feat, 4) feat = tf.nn.relu(feat) with tf.variable_scope("icnv2"): feat = conv2Layer(opt, feat, 8) feat = tf.nn.relu(feat) feat = tf.nn.max_pool(feat, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="VALID") feat = tf.reshape(feat, [opt.batch_size, -1]) with tf.variable_scope("fc3"): feat = linearLayer(opt, feat, 48) feat = tf.nn.relu(feat) with tf.variable_scope("fc4"): feat = linearLayer(opt, feat, 6, final=True) dp = tf.reshape(feat, [-1, 6]) print('dp: ', dp.get_shape()) dpM = pose_vec2mat(dp) pM = tf.matmul(dpM, pM) imageWarp = inverse_warp( inputImage, depth, pM, intrinsics, intrinsics_inv) imageWarpAll.append(imageWarp) return imageWarpAll, pM def build_train_graph(): with tf.name_scope("cnn1"):... with tf.name_scope("cnn2"):... with tf.name_scope("Inverse Compositional CNN"):... def train(self, opt): with tf.variable_scope(tf.get_variable_scope()): for i in range(opt.num_gpus): print('gpu:', i) with tf.device('/gpu:%d' % i): self.build_train_graph(L_img_splits[i], R_im…
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50212424
upvote count: 3
answer count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/132872776
linked to: http://stackoverflow.com/q/65401120
has title: TF: how to solve ValueError: Variable ...weight already exists, disallowed. Did you mean to set reuse=True
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/q/50224056
type: Question
has comment: http://stackoverflow.com/comment/87466406
tagged with: discord.py
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
has body: I'm tryna make a discord.py async bot that will award people with brownie points (heh heh) when asked. It's supposed to be a local bot for my friends and me, but I don't want to update every single brownie point of every person into the code every time I restart it. My code is here: import commands import discord from discord.ext.commands import Bot from discord.ext import commands import asyncio import time import random #Here is the basic command: #await client.send_message(message.channel, messsage) #global hub me = 0 discordname = "PRIVATE" Client = discord.Client() client = commands.Bot(command_prefix = "") @client.event async def on_ready(): print ("the brownies are loaded and ready to go!") @client.event async def on_message(message): if message.content.startswith("bb! give"): args = message.content.split(" ") if args[1:][1] == "(my user ID)": global me global discordname me = me + int(args[1:][2]) await client.send_message(message.channel, str(int(args[1:][2])) + " brownie points have been given to " + str(discordname)) if message.content.startswith("bb! brownies"): args = message.content.split(" ") if args[1:][1] == "(my user ID)": await client.send_message(message.channel, str(discordname) + " currently has " + str(me) + " brownie points.") client.run(TOKEN) I wanna make the bot create a new variable each time a user joins the server. However, every attempt I've tried (i.e. pickle module, shelve module...) has turned one of the following consequences: It does nothing It malfunctions It returns an error
accepted answer: http://stackoverflow.com/a/50224398
answer count: 1
has title: How would I make python store the data of multiple people?
has answer: http://stackoverflow.com/a/50224398
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50075118
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50075594
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has body: I am using python 2.7. I am trying to match two values I am having the code something like following a=field [0] ["inv"] ##This is json calling aa=purchase [11] [0] print type(a) print a print type(aa) print aa if aa==a: print "same" else: print "Not same" when I execute the code I am getting following output &lt;type 'str'&gt; 28 &lt;type 'str'&gt; 28 Not same Why I am getting this output.I am having matching values. But why I am getting the output as not same. What is the issue behind this?
has title: Not comparing equal `a==aa` although when printed the output is equal
tagged with: python
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/50075594

http://stackoverflow.com/a/50160067
answers question: http://stackoverflow.com/q/50159602
type: Answer
downvote count: 0
upvote count: 1
has body: Here's one way that could easily be extended to a larger set of dates to match: scalar_date = pd.DataFrame(index=[pd.to_datetime("07-05-2018", format="%d-%m-%Y")]) scalar_date.join(date_buckets. \ set_index('dates'). \ reindex(pd.date_range(date_buckets.dates.min(), \ date_buckets.dates.max()), \ method='bfill')) # buckets # 2018-05-07 1W The idea here is to resize your date_buckets dataframe (using .reindex with method='bfill'), so that you can easily join it to a dataframe with your lookup dates.
score: 1

http://stackoverflow.com/q/50143217
downvote count: 1
score: 2
has comment: http://stackoverflow.com/comment/87306303
tagged with: pytest
upvote count: 3
has comment: http://stackoverflow.com/comment/87305798
has title: How to Parameterize Test Function: Pytest?
answer count: 1
favorite count: 0
type: Question
tagged with: testing
has answer: http://stackoverflow.com/a/54706371
has comment: http://stackoverflow.com/comment/87304622
tagged with: function
has body: How do I pass a list of data, to a Test Function using Pytest? Each Test Case is pretty similar, except for this input parameter. I have tried the following but to no avail: import pytest @pytest.fixture def List_of_Numbers(): list = [1,2,3,4,5,6,7,8] @pytest.parametrize("number", [i for item in list]) def test_eval(number): assert eval(number%2) == 0 pytest output: ==================================== ERRORS ==================================== _________________________ ERROR collecting sample4.py __________________________ sample4.py:8: in &lt;module&gt; @pytest.parametrize("number", [i for item in list]) E AttributeError: module 'pytest' has no attribute 'parametrize' !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!! =========================== 1 error in 0.30 seconds ============================
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87305614
has comment: http://stackoverflow.com/comment/87306119
tagged with: python
has comment: http://stackoverflow.com/comment/87305447

http://stackoverflow.com/comment/87202718
type: Comment
type: QuestionComment
has text: For the sub_titles, you have to expand them all. Use some selenium function to loop and click them including those hidden '24 More Sections' before getting information from the class again.
comment on: http://stackoverflow.com/q/50093119
score: 0

http://stackoverflow.com/q/50214990
upvote count: 2
has comment: http://stackoverflow.com/comment/87447642
accepted answer: http://stackoverflow.com/a/50215546
has comment: http://stackoverflow.com/comment/87446770
tagged with: python
has answer: http://stackoverflow.com/a/50215546
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87446707
has comment: http://stackoverflow.com/comment/87446695
linked to: http://stackoverflow.com/q/7232088
has comment: http://stackoverflow.com/comment/87447486
tagged with: email
has title: Python email body is empty
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87447570
has comment: http://stackoverflow.com/comment/87447247
has body: I'm here to ask you some help. So the thing is, the subject of my email is alright but when I open the email, it's empty and I really can't understand why... Here is my code : from urllib2 import urlopen import smtplib s=smtplib.SMTP('smtp.gmail.com',587) s.starttls() s.ehlo() # now login as my gmail user username='myEmail@gmail.com' password='*****************' s.login(username,password) # the email objects and body replyto='myEmail@gmail.com' sendto=['myEmail@gmail.com'] subject='Mail automatisation' content="This is a test" mailtext='Subject:'+subject+'\n'+content # send the email s.sendmail(replyto, sendto, mailtext) rslt=s.quit() Thanks for you help.
favorite count: 0
type: Question

http://stackoverflow.com/comment/87269263
has text: Note that I'm not responsible for the log of keyring: https://github.com/jaraco/keyring
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50125626
type: Comment

http://stackoverflow.com/comment/87342428
has text: Your code doesn't work correctly with time stamps above 1 minute.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50161586

http://stackoverflow.com/comment/87368740
comment on: http://stackoverflow.com/q/50175817
type: QuestionComment
has text: Just so im understanding the question correctly - You have `clip1` that will be playing (say its background music or something) and then on some event `clip2` should stop `clip1` and play `clip2`'s sound? Is this sounding correct?
type: Comment
score: 1

http://stackoverflow.com/a/50169590
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50166130
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50166130
type: Answer
has body: Are you sure the spider is doing the pagination properly? When you do this: next_page_url = response.xpath('//*[@class="js-course-pagination"]//a[contains(@aria-label,"Next")]/@href').extract() extract() returns a list of results that you are then passing into the url parameter of the Request: yield Request(url=next_page_url, callback=self.parse) But url must be a string or unicode value, so, doing that will generate the following error: TypeError: Request url must be str or unicode, got list: It can be solved by using the extract_first() method, and I would also check that the value is not None: next_page_url = response.xpath('//*[@class="js-course-pagination"]//a[contains(@aria-label,"Next")]/@href').extract_first() if next_page_url: yield Request(url=next_page_url) # parse is the callback by default Please, try this and tell me if it solved your problem
downvote count: 0

tweepy
tags question: http://stackoverflow.com/q/50165767
tags question: http://stackoverflow.com/q/50109749
type: Tag
tags question: http://stackoverflow.com/q/50119211
tags question: http://stackoverflow.com/q/50096703
tags question: http://stackoverflow.com/q/50127690
tags question: http://stackoverflow.com/q/50194013
tag name: tweepy

http://stackoverflow.com/comment/87369673
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50175924
has text: If you knew that N=500, could you implement A > B on the arrays using bit arithmetic and make it O(1)?
type: Comment

http://stackoverflow.com/a/50193970
type: Answer
score: 0
has body: just to give you an idea. it makes sense if your data is not big. import numpy as np x = np.array([[100],[200],[300],[400]]) np.random.shuffle(x) for i in range(0,3): do_something = x[i] print(do_something) or something like this: import numpy as np x = np.array([[100],[200],[300],[400]]) for i in range(10):#epoch: np.random.shuffle(x) do_something = x[:3,:] print(do_something)
answers question: http://stackoverflow.com/q/50180967

http://stackoverflow.com/comment/87356981
type: Comment
has text: I removed the func line. It should be enough to create a tuple for the griddata function.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50169626

http://stackoverflow.com/q/50095916
has title: Page not found (404): No Post matches the given query.
type: Question
has body: I am trying to Create a 'Like' button on a post. a post belongs to a group. However, in my view function, Im getting a 404 error because it cant find the individual post, even though it is in the URL. here are the relevant files: (posts/urls.py): from . import views from django.urls import path app_name = 'posts' urlpatterns = [ path('create/<int:group_id>/', views.create, name='create'), path('edit/<int:group_id>/<int:post_id>/', views.edit, name='edit'), path('delete/<int:group_id>/<int:post_id>/', views.delete, name='delete'), path('like/<int:post_id>/', views.like, name='like'), ] (post/views.py): from django.shortcuts import render, get_object_or_404, redirect from groups.models import Group from .models import Post from .forms import PostForm from django.utils import timezone def like(request, post_id): post = get_object_or_404(Post, pk= post_id) if request.method == 'POST': post.likes_total += 1 return redirect('/groups/index' ) # post.save() else: return render(request, 'groups/detail.html', {'group':group}) (groups/detail html) {% for post in posts %} {{post.title}} {{post.body}} {{post.pub_date_pretty}} {{post.author}} Edit Delete Like ({{post.likes_total}}) {% endfor %} {% csrf_token %} Just don't understand why its not able to grab the post. any help would be really appreciated!
tagged with: django-templates
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/50096172
tagged with: python
score: 0
tagged with: django-views
answer count: 1
tagged with: django-models

http://stackoverflow.com/comment/87189753
type: Comment
score: 0
type: QuestionComment
has text: So what? Let's say the list of functions is called `funcs`. Then you can do `(funcs[1], ({'json':1} ,)`, etc. BTW, you should take a look at https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables
comment on: http://stackoverflow.com/q/50086769

http://stackoverflow.com/q/50195950
tagged with: response
score: 2
answer count: 2
upvote count: 2
linked to: http://stackoverflow.com/q/38239869
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50195965
tagged with: download
type: UnansweredQuestion
has body: I have a FileField with a movie, I'm trying to have the user on a mobile platform (chrome/safari) be able to click a download button and it download it. Currently it opens in a new window no matter what I do. My View def download(request): file_path = 'movie.mp4' if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="video/mp4") response['Content-Disposition: attachment'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 file path is hard coded for testing purposes atm. Everything I read tells me that it's impossible because safari and other mobile browsers view opening a better experience than downloading. I've tried changing mime types and other things.
has answer: http://stackoverflow.com/a/50198169
tagged with: django
tagged with: python
has title: Force download file in a Django Web App on mobile browsers

http://stackoverflow.com/comment/87178926
comment on: http://stackoverflow.com/a/50078237
has text: @ArtemisFowl: you can save what was drawn, but you have to do the work yourself. If all you want is to save and restore what is drawn, you can use the methods of the canvas to get a list of all objects, and from each object you can get all of the options for that object. Just wrap that up into a loop, then write it to a file.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50115225
score: -1
has comment: http://stackoverflow.com/comment/87276240
upvote count: 0
answers question: http://stackoverflow.com/q/50115081
downvote count: 1
has body: Using numpy.where allows you to account for duplicate values, i.e. when more than one country shares the maximum employment. The result will be an array of countries. res = countries[np.where(employment == employment.max())] Since your numeric array consists of rounded percentages, this may well matter.
type: Answer

http://stackoverflow.com/comment/87292090
type: QuestionComment
comment on: http://stackoverflow.com/q/50136944
has text: Welcome to SO. Can you share your existing code, a sample of your input & desired output? This will help us understand your problem better. Also see [mcve].
score: 0
type: Comment

http://stackoverflow.com/q/50090451
has comment: http://stackoverflow.com/comment/87197230
has comment: http://stackoverflow.com/comment/87197430
has answer: http://stackoverflow.com/a/50090623
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87197359
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87197466
has title: Python Text-Based Game with Tkinter
upvote count: 0
type: UnansweredQuestion
score: -2
has body: I participated in a local programming competition yesterday, where I was put on a team of four with members of varying skill levels. We were trying to make a text-based Zork style game, but since UI was one of the categories I was put on creating a GUI which I have no experience with in python. I used Tkinter and got everything mostly working inside the GUI itself, but can't figure out how to get the GUI to interact with the rest of the code. I'm just including the relevant bits here, partially because the rest of the code is quite a mess, with no comments and lots of syntax errors, but I can post it if needed. Here's the code: def pinput(): global e player_input = e.get() print(player_input) def progress(): hallway_1() def hallway_1(): global player_input global prin global e prin.set("You are in a hallway. Yellow lockers line the sides of all walls and you see three doors. One leads into a Library, one to a History classroom, and one to a Math room. You can 1.) Search the hallway or 2.) Procede to one of the rooms.") while player_input != "1" and player_input != "2": #Best guess at a way to get the code to wait for input, actually just causes code to freeze pass if player_input == "1": #Even if 1 is in the entry box beforehand, it never gets here prin.set("You search through the lockers and find 1 health potion.\n Would you like to add it to your inventory? 1.) Yes 2.) No") player_input = "999" def player_attack(): global enemy_hp enemy_hp -= player_strength prin.set("You just attacked the " + enemy_name + "!") def player_block(): global block prin.set("You predict that your enemy is going to attack and decide to block") block = 1 def player_use(): global player_item_use global item_name player_item_use = 100 prin.set("You decide to use one of your items. What do you use?") while player_turn_input != 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10 or 11 or 12 or 13 or 14 or 15 or 16 or 17 or 18 or 19 or 20 or 21 or 22 or 23 or 24 or 25 or 26: player_item_use …
tagged with: python

http://stackoverflow.com/comment/87420139
has text: I'm glad to hear that, can you set this answer as correct answer then?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50157471

http://stackoverflow.com/comment/87521549
has text: well, good luck. for me, this is a major red flag regarding your client's competency as a developer.
comment on: http://stackoverflow.com/q/50214614
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87206098
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50094913
score: 19
has text: Running `b.decode()` with no consideration of the original bytearray's encoding (or whether it even represents encoded Unicode text) is just going to lead to UnicodeDecodeErrors and encoding bugs.

http://stackoverflow.com/comment/87290237
score: 0
comment on: http://stackoverflow.com/q/50117377
type: Comment
type: QuestionComment
has text: Update the question with the error stack trace

http://stackoverflow.com/q/50103957
has answer: http://stackoverflow.com/a/50104041
possible better answer: http://stackoverflow.com/a/50104041
has body: I am trying to plot some data from a camera dynamically using drawnow. However, the dynamic plotting (using matplotlib and drawnow) doesn't seem to be working on jupyter notebook. It's currently working in Pycharm. My code: import matplotlib.pyplot as plt import numpy as np from drawnow import * x = np.random.randn(10, 2) def function_to_draw_figure(): plt.plot(i, j, 'r.') plt.ion() figure() for i, j in x: drawnow(function_to_draw_figure) plt.xlim(-1, 1) plt.ylim(-1, 1) plt.pause(0.5) I would expect this example to plot 10 points dynamically on the same figure (as in pycharm). What actually happens is that multiple figures appear rather than one. Any thoughts why I am not able to do it using jupyter notebook?
accepted answer: http://stackoverflow.com/a/50104646
linked to: http://stackoverflow.com/q/34486642
tagged with: python
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/35532498
answer count: 2
has answer: http://stackoverflow.com/a/50104646
tagged with: matplotlib
tagged with: jupyter-notebook
type: Question
has title: Dynamic plot in python jupyter notebook using drawnow
tagged with: python-3.x

http://stackoverflow.com/comment/87380592
comment on: http://stackoverflow.com/a/50181407
score: 1
has text: But what if I wanted to only predict the value of weight using 10 new data points that aren't from the original dataset?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87380754
has text: @JLPeyret Exactly. In fact, if you read through the source, `AttrDict` doesn't even transform it into a tuple _now_, but only _later_, when you access it via `a.li`. That's why `a['li']` can still work.
comment on: http://stackoverflow.com/a/50181640
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87194315
type: QuestionComment
comment on: http://stackoverflow.com/q/50089135
has text: It's *not* working 100%. `insert_left` and `insert_right` expect a value, not a `Node`, as an argument.
score: 2
type: Comment

http://stackoverflow.com/q/50164751
answer count: 1
has answer: http://stackoverflow.com/a/52993303
type: Question
has body: In my Python script I am trying to set some phone settings through Marionette driver. I am importing the following: from marionette_driver import By from marionette_driver import Wait from marionette import Marionette Then I am attempting to open a client session with the device: client = Marionette('localhost', port=2828) client.start_session() However, I am receiving UnknownCommandException: Traceback (most recent call last): File "xyz.py", line 30, in &lt;module&gt; client.start_session() File "/usr/local/lib/python2.7/dist-packages/marionette_driver/decorators.py", line 26, in _ return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/marionette_driver/marionette.py", line 1243, in start_session body) File "/usr/local/lib/python2.7/dist-packages/marionette_driver/decorators.py", line 26, in _ return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/marionette_driver/marionette.py", line 741, in _send_message self._handle_error(err) File "/usr/local/lib/python2.7/dist-packages/marionette_driver/marionette.py", line 765, in _handle_error raise errors.lookup(error)(message, stacktrace=stacktrace) marionette_driver.errors.UnknownCommandException: WebDriver:NewSession FYI, I am using marionette-driver 1.1.1 Any suggestion regarding resolving this issue will be much appreciated. Edit on 10/26/2018 It is returning a different error message now: $ python Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from marionette import Marionette Traceback (most recent call last): File "./xyz.py", line 7, in &lt;module&gt; from marionette import Marionette File "/usr/local/lib/python2.7/dist-packages/marionette/__init__.py", line 7, in &lt;module&gt; from .marionette_test import ( ImportError: No module named marionette_test
linked to: http://stackoverflow.com/q/52507431
type: UnansweredQuestion
tagged with: firefox-marionette
tagged with: marionette
tagged with: python
has title: How to resolve 'ImportError: No module named marionette_test'
score: 0

http://stackoverflow.com/comment/87553515
comment on: http://stackoverflow.com/q/50202829
type: Comment
has text: See https://code.visualstudio.com/docs/languages/python#_environments and https://code.visualstudio.com/docs/python/environments. Beyond this, there isn't enough information in your post for us to offer any useful suggestions.
type: QuestionComment
score: 0

http://stackoverflow.com/q/50074919
duplicate of: http://stackoverflow.com/q/30763076
has title: Using Python variables in lists
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87166156
tagged with: multiplication
has comment: http://stackoverflow.com/comment/87166147
tagged with: math
has answer: http://stackoverflow.com/a/50074959
accepted answer: http://stackoverflow.com/a/50074959
has comment: http://stackoverflow.com/comment/87167133
tagged with: python
score: -1
tagged with: runtime-error
type: AnsweredQuestion
upvote count: 0
has body: Question 3: Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the N adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? Range of N: 10 &lt;= N &lt;= 50 Dear all, I am dealing with the above mentioned problem. I hope i can request your assistance in helping me with my issue. Here's the code: number = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428280644448664523874930358907296290491560440772390713810515859307960866701724271218839987979087922749219016997208880937766572733300105336788122023542180975125454059475224352584907711670556013604839586446706324415722155397536978179778461740649551492908625…
answer count: 1
linked to: http://stackoverflow.com/q/30763076
downvote count: 1

http://stackoverflow.com/comment/87236144
has text: Oh okay, I updated everything to look more like my real data and then gave an example of what the output should be for that subset.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50108650

http://stackoverflow.com/comment/87239320
has text: You are still getting the ImportError and ModuleNotFoundError even after adding the __init__.py? Can you update your post to show how you added __init__.py and also the updated import codes?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50100767

http://stackoverflow.com/a/50118241
has body: Here's a quick demo that shows how to convert a 1D array of uint8 to a 2D array of uint16. The key function we need here is view. import numpy as np # Make 24 bytes of fake data raw = np.arange(24, dtype=np.uint8) #Convert out = raw.view(np.uint16).reshape(3, 4) print(out) print(out.dtype) output [[ 256 770 1284 1798] [2312 2826 3340 3854] [4368 4882 5396 5910]] uint16 Thanks to Andras Deak for his assistance! If the resulting image doesn't look correct, you may need to swap the byte ordering of the 16 bit integers. You can read about byte ordering in Numpy here. And if that still doesn't look correct, then the data may be organized as two planes, with one plane for the low-order bits of a pixel and the other plane for the high-order bits. That's also easy to deal with, but hopefully it won't come to that. ;)
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50117751
answers question: http://stackoverflow.com/q/50117751
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87296259
has text: Keep in mind that when you set Ref_Readings = Data, you are not copying. You are making it such that Ref_Readings and Data point to the same data structure in memory. This is probably the source of your misunderstanding. Code comments: The of 'print('**************Updated Data')' should go at the end of the if block, after you do the update. You want your prints to be accurate, if you want to leave the print there, make it read "Updating data" so that it's accurate. Also, the print in the else doesn't make sense. You've already checked the dicts at this point, no need for the else.
comment on: http://stackoverflow.com/q/50138831
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87277929
type: QuestionComment
comment on: http://stackoverflow.com/q/50097149
score: 0
has text: okay got it, so just define my model_fn tocreate the lstm rnn using the dynamic_rnn() then decide what to do based on what the mode is? is that fine?
type: Comment

http://stackoverflow.com/q/50108354
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/106784068
has body: I'm trying to get threading to work with a Socket network to accept clients. I had that working fine, but now I have discovered an issue. Here is the code: clients = [] def myFunction(): #Not too relevant I think server.listen(0) conn, addr = server.accept() print(conn) clients.append(conn, addr) threading.Thread(myFunction) threading.Thread(myFunction) input("Hit enter to finish...") print(clients) Now this should return something like this, which it does on all the IDEs I have tried (PyCharm, Sublime text editor, etc.): Hit enter to finish... *2 users connect* 192.168.0.5 # this is the contents of conn 192.168.0.12 *hit enter* 192.168.0.5, 192.168.0.12 However, in Python's own IDLE, the threading seems unable to print anything until I press Enter, with the exact same code, like so: Hit enter to finish... *2 users connect* *hit enter* 192.168.0.5 192.168.0.12 192.168.0.5, 192.168.0.12 This isn't what I want because my code will run in Python IDLE once its finished, so it needs to work here because of this.
possible better answer: http://stackoverflow.com/a/73450108
favorite count: 0
has comment: http://stackoverflow.com/comment/87247883
has comment: http://stackoverflow.com/comment/87234250
type: Question
accepted answer: http://stackoverflow.com/a/50124069
has answer: http://stackoverflow.com/a/73450108
has answer: http://stackoverflow.com/a/50124069
has comment: http://stackoverflow.com/comment/87247867
has comment: http://stackoverflow.com/comment/87234393
has comment: http://stackoverflow.com/comment/106783750
tagged with: python
tagged with: python-idle
type: AnsweredQuestion
answer count: 2
has title: Python IDLE running code differently than other IDEs

http://stackoverflow.com/q/50158962
upvote count: 1
has answer: http://stackoverflow.com/a/50162370
favorite count: 0
linked to: http://stackoverflow.com/q/176011
type: Question
tagged with: python-3.x
has body: Hi I just started learning classes in python and I'm trying to implement an array based list. This is my class and the init constructor. class List: def __init__(self,max_capacity=50): self.array=build_array(max_capacity) self.count=0 However, I wrote a method equals that returns true if the list equals another. However, it always return false. And yes my append method is working. def __eq__(self,other): result=False if self.array==other: result=True else: result=False return result This is how I tested it but it return false? a_list=List() b_list=[3,2,1] a_list.append(3) a_list.append(2) a_list.append(1) print(a_list==b_list) Any help would be appreciated! EDIT: After all the helpful suggestions, I figured out I have to iterate through other and a_list and check the elements.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50159073
tagged with: python
has comment: http://stackoverflow.com/comment/87335780
has comment: http://stackoverflow.com/comment/87335659
has comment: http://stackoverflow.com/comment/87335627
linked to: http://stackoverflow.com/q/9405322
has comment: http://stackoverflow.com/comment/87335696
answer count: 2
score: 1
has title: Why does my equal method always return false?
downvote count: 0

http://stackoverflow.com/a/50222577
has body: Try "conda install -c conda-forge basemap"
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/50215247
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50215247

http://stackoverflow.com/comment/87203456
comment on: http://stackoverflow.com/q/50089785
type: Comment
type: QuestionComment
has text: logs (C:\Users\Admin\.ccm\Tombstone_exp\node1\logs) directory is empty. C:\Users\Admin>ccm node1 showlog C:\Users\Admin>Cannot access file C:\Users\Admin\.ccm\Tombstone_exp\node1\logs\system.log
score: 0

http://stackoverflow.com/comment/87277442
type: Comment
has text: Have you tried running the command with each folder individually? There may be an issue with one .nc file in a specific directory, and this is causing the error?
comment on: http://stackoverflow.com/a/50113202
type: AnswerComment
score: 0

http://stackoverflow.com/a/50219853
has comment: http://stackoverflow.com/comment/87456913
score: 0
has body: The correct way to handle this is with regular expressions. Their is a regex library as part of the standard python library. import re u_input = 'your string' def validate(input): # chars must be different if input[0] == input[-1:]: return False # begin and end with upper or lower a-z with dash in middle pattern = '[a-zA-Z]{1}-[a-zA-Z]{1}' result = re.match(pattern, input) # re.match returns None if no match if not result: return False: else: return True
answers question: http://stackoverflow.com/q/50219683
has comment: http://stackoverflow.com/comment/87457528
has comment: http://stackoverflow.com/comment/87456962
type: Answer

http://stackoverflow.com/a/50190004
downvote count: 1
has comment: http://stackoverflow.com/comment/87397783
type: Answer
score: -1
has body: You should not use the logging package from PyPI but just the built-in logging module: &gt;&gt;&gt; import logging.handlers &gt;&gt;&gt; logging.handlers.WatchedFileHandler &lt;class 'logging.handlers.WatchedFileHandler'&gt;
upvote count: 0
answers question: http://stackoverflow.com/q/50189917
has comment: http://stackoverflow.com/comment/87421608

http://stackoverflow.com/comment/87264742
has text: no, this is not a permissions issue. if it was it would clearly say that in the error text
score: 0
comment on: http://stackoverflow.com/q/50123247
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87239670
has text: @PaulPanzer As it turns out, my helper library did rely on ranges, which is pretty obvious now that I think about it (and obviously I _did_ think about it however many years ago I wrote it…). Anyway, I've now separated it out into its own project and updated it a bit. Although the tests aren't nearly as complete as I'd hoped…
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50110109
type: Comment

http://stackoverflow.com/comment/87422273
type: Comment
type: QuestionComment
has text: So, Python provides a lot of metaprogramming abilities. You can `compile` strings into code objects, execute those code objects, and do all sorts of things. But that is definitely not what you want to do here
comment on: http://stackoverflow.com/q/50201084
score: 0

http://stackoverflow.com/q/50206730
tagged with: pandas
linked to: http://stackoverflow.com/q/59511235
has title: How to check if dask dataframe is empty
tagged with: python
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/87431217
tagged with: dask
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87443137
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50207206
has comment: http://stackoverflow.com/comment/87430495
has body: Is there a dask equivalent of pandas empty function? I want to check if a dask dataframe is empty but df.empty return AttributeError: 'DataFrame' object has no attribute 'empty'
has answer: http://stackoverflow.com/a/50207206
type: Question

http://stackoverflow.com/comment/87396487
comment on: http://stackoverflow.com/q/50189756
score: 1
type: Comment
has text: @AndrasDeak oh i see! Thanks! That solved the problem
type: QuestionComment

http://stackoverflow.com/a/50159595
accepted answer of: http://stackoverflow.com/q/50159205
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50159205
score: 0
has body: If you have just two nexttoken tags in your text then you can use regex to extract the required value. Ex: import re with open(filename, "r") as infile: data = infile.read() c = re.findall("\&lt;nexttoken\&gt;(.*)\&lt;\/nexttoken\&gt;", data) print(c[1]) Output: test2 Note: If your src file is an XML file i highly suggest you use a python xml parser.

http://stackoverflow.com/comment/87184068
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50084136
type: Comment
has text: Well Explained. Thank you!

http://stackoverflow.com/q/50191215
has answer: http://stackoverflow.com/a/50191837
score: 2
type: AnsweredQuestion
answer count: 2
has body: I am new to python and is working on logical statement. My objective is to count the goal score by teams. (i.e. if a team scored a goal, I will assign 1 and the opponent will be assigned -1). Below is the snap shot of the data. Data is below I wrote logical statement as follow: if data['team']== data['hometeam_team1']: data['run_score'] = 1 else: data['run_score'] = -1 but it threw me value error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Can anyone advise? Your help is much appreciated. Thanks Aung
tagged with: pandas
upvote count: 2
has comment: http://stackoverflow.com/comment/87400070
downvote count: 0
favorite count: 0
type: Question
has title: If / Else flow control in pandas dataframe
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87410755
tagged with: if-statement
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50191892
possible better answer: http://stackoverflow.com/a/50191837
has comment: http://stackoverflow.com/comment/87399293
has answer: http://stackoverflow.com/a/50191892
has comment: http://stackoverflow.com/comment/87399573

http://stackoverflow.com/a/50110328
downvote count: 0
has comment: http://stackoverflow.com/comment/87237957
score: 3
type: Answer
has body: curr==2 is a comparison. You probably want curr=2. The second if should be an elif.
has comment: http://stackoverflow.com/comment/87238023
answers question: http://stackoverflow.com/q/50110321
upvote count: 3

http://stackoverflow.com/a/50078352
type: Answer
has body: If your 2D list is A, then # 0-based indexing # assuming you want to take 4th column only when 7th column is `0`. # assuming 7th column contains either '1' or '0' X = [int(row[3]) for row in A if row[6] == '0'] X will be a list such that for each row in your 2D list, only those 4th column values will be included if the corresponding value in 7th column is '0'. This syntax is called List Comprehension and you can read more about it here.
has comment: http://stackoverflow.com/comment/87172909
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50078269
score: 3
answers question: http://stackoverflow.com/q/50078269
upvote count: 3

http://stackoverflow.com/comment/87314871
comment on: http://stackoverflow.com/a/50147944
score: 0
type: Comment
has text: @BishakhaKumari I believe each time you call the render_template() you render the complete page using the given value. So by calling it in the loop you are rendering the page whole page again and again. You have to move the render_template function call outside the for loop. Also you are passing a list into the be printed inside the p tag, which I don't think is what you are looking for. Please do try out my solution and see if it does what you need.
type: AnswerComment

airflow-scheduler
tags question: http://stackoverflow.com/q/50228351
tag name: airflow-scheduler
type: Tag

structured-text
type: Tag
tags question: http://stackoverflow.com/q/50200678
tag name: structured-text

http://stackoverflow.com/comment/87404384
score: 0
has text: @user2100826 I don't think that's the problem, if that was it, then it wouldn't be his current issue, the code would not even work
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50193562

http://stackoverflow.com/comment/87304371
type: QuestionComment
score: 0
has text: Can you supply a sample of your code? This would help to suggest methods to reduce memory footprint.
type: Comment
comment on: http://stackoverflow.com/q/50142997

http://stackoverflow.com/comment/87342796
score: 1
type: Comment
type: QuestionComment
has text: did u just use a reserved python name `time` for the name of the variable?
comment on: http://stackoverflow.com/q/50162459

http://stackoverflow.com/q/50185547
tagged with: loops
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87388128
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50187194
has answer: http://stackoverflow.com/a/50185562
answer count: 2
has body: I need to run the code lines something like this. tweet24042018 = tweets.loc[tweets['date2'] == '24042018'].copy() tweet23042018 = tweets.loc[tweets['date2'] == '23042018'].copy() tweet22042018 = tweets.loc[tweets['date2'] == '22042018'].copy() The function created and tried is like this, for key in collect: ['tweet'+f'{key}'] = tweets.loc[tweets['date2'] == f'{key}'].copy() But, it gives error like, File "&lt;ipython-input-18-3c946d8cc61a&gt;", line 2 ['tweet'+f'{key}'] = tweets.loc[tweets['date2'] == f'{key}'].copy() ^ SyntaxError: can't assign to operator help please
tagged with: for-loop
tagged with: pandas
has title: Dataframe using For Loop in Pandas
score: 1
downvote count: 0

http://stackoverflow.com/comment/87391922
score: 2
comment on: http://stackoverflow.com/q/50187485
type: Comment
type: QuestionComment
has text: Related: [Replace every nth character in a string](https://stackoverflow.com/questions/13668829/replace-every-nth-letter-in-a-string)

http://stackoverflow.com/a/50269769
type: Answer
answers question: http://stackoverflow.com/q/50090868
score: 0
has body: I think all the fellows answered this already. We use mostly lambdas function when we just want to: -create some simple functions that do the work perfectly in a specific place(most of the time hidden inside some other big functions -The lambda function does not have a name -Can be used with some other built-ins functions such as map, list and so forth ... &gt;&gt;&gt; Celsius = [39.2, 36.5, 37.3, 37.8] &gt;&gt;&gt; Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) # mapping the list here &gt;&gt;&gt; print Fahrenheit [102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999] Please visit this webpage , this could be useful.Keep it up !!! https://www.python-course.eu/lambda.php

http://stackoverflow.com/q/50202545
type: Question
has answer: http://stackoverflow.com/a/50203100
has answer: http://stackoverflow.com/a/50202678
possible better answer: http://stackoverflow.com/a/50202678
accepted answer: http://stackoverflow.com/a/50203100
tagged with: python
answer count: 2
has title: Python Grade Book Assignment, writing and reading records, and totals of letter grades, cannot get correct output
type: AnsweredQuestion
score: 0
has body: This is the problem: Create a Python program that allows user enter class name, faculty name, name of each student, and letter grade each student earned. The program should count and display numbers of students who earned As, Bs, Cs, Ds, and Fs. And the program should save all input and output information into a text file named ClassNameGrades.txt. The code I have written so far is below. I am just learning and this is very rudimentary, I apologize. Below that is the output. I don't know why I am getting 2 extra records to pop up. Can someone explain to me what I am doing wrong? The file is created, the input is written into the file, but then it falls apart during the read. def main(): student_num = 0 count = 0 a_total = 0 b_total = 0 c_total = 0 d_total = 0 f_total = 0 student_num = int(input("Enter the number of students you wish to enter grades for: ")) gradefile = open('gradebook.txt', 'w') for count in range(1, student_num + 1): class_name = input('Enter class name: ') faculty_name = input('Enter faculty name: ') student_name = input('Enter student name: ') letter_grade = input('Enter letter grade (A, B, C, D, or F) ') print() if letter_grade.upper() == 'A': a_total += 1 elif letter_grade.upper() == 'B': b_total += 1 elif letter_grade.upper() == 'C': c_total += 1 elif letter_grade.upper() == 'D': d_total += 1 elif letter_grade.upper() == 'F': f_total += 1 else: print('Invalid response') gradefile.write(class_name + '\n') gradefile.write(faculty_name + '\n') gradefile.write(student_name + '\n') gradefile.write(letter_grade + '\n') gradefile.write(str(a_total) + '\n') gradefile.write(str(b_total) + '\n') gradefile.write(str(c_total) + '\n') gradefile.write(str(d_total) + '\n') gradefile.write(str(f_total) + '\n') gradefile.close() gradefile1 = open('gradebook.txt', 'r') class_name = gradefile1.readline() while class_name != '': faculty_name = gradefile1.readline() student_name = gradefile1.readline() letter_grade = gradefile1.readline() class_name = class_name.r…

http://stackoverflow.com/q/50196650
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2318446
tagged with: download
has body: I have been struggling with this for a whole day. I compile a list of URLs that i get by using urllib3 on a webpage(also using BeautifulSoup). The URLs basically point to pdf files that i wanted to automate the download of. What's great is that the pdf links have a beautiful pattern. So i easily use regex to make a list of pdfs that i want to download and ignore the rest. But then that's where the problem starts. The URLs follow the pattern http://www.ti.com/lit/sboa263 NOTE: The last part changes for other files and NO pdf file extension. But if you put this link in your browser you can clearly see it change from that to http://www.ti.com/general/docs/lit/getliterature.tsp?baseLiteratureNumber=sboa263 and that eventually changes to http://www.ti.com/lit/an/sboa263/sboa263.pdf Now i understand you can tell me that "Great, follow this pattern then". But i don't want to because IMO this is not the right way to solve this automation. I want to be able to download the pdf from the first link itself. I have tried response = requests.get(url,allow_redirects=True) which only takes me to the result of the first redirect NOT the last file. Even response.history takes me only to the first redirect. And when i anyway try to download the file there i get a corrupted pdf that wont open. However when i manually pass the final URL just to test the correctness of my file write, i get the actual pdf in perfect order. I don't understand why requests is not able to get to the final URL. My full code is below for your reference - from bs4 import BeautifulSoup import urllib3 import re http = urllib3.PoolManager() url = 'http://www.ti.com/analog-circuit/circuit-cookbook.html' response = http.request('GET', url) soup = BeautifulSoup(response.data) find = re.compile("http://www.ti.com/lit/") download_links = [] for link in soup.find_all('a'): match = re.match(find, link.get('href')) if match: #print(link.get('href')) download_links.append(link.get('href')) To get to the redirected URL i us…
tagged with: http-redirect
has title: Downloading a pdf file from a url that redirects 2 times fails even when using requests.history
accepted answer: http://stackoverflow.com/a/50303036
tagged with: python
has answer: http://stackoverflow.com/a/50303036
has comment: http://stackoverflow.com/comment/87412476
linked to: http://stackoverflow.com/q/4946244
type: AnsweredQuestion
tagged with: urllib3
upvote count: 2
score: 1
answer count: 1
tagged with: python-requests

http://stackoverflow.com/comment/87223943
has text: @Hatt I Have also tried many variations of the code above to try and debug the issue but have come to a dead end
type: QuestionComment
comment on: http://stackoverflow.com/q/50090214
type: Comment
score: 0

http://stackoverflow.com/q/50126234
type: Question
linked to: http://stackoverflow.com/q/41233594
linked to: http://stackoverflow.com/q/49768770
has comment: http://stackoverflow.com/comment/87271000
has comment: http://stackoverflow.com/comment/87271481
type: UnansweredQuestion
tagged with: homebrew
has comment: http://stackoverflow.com/comment/87271380
downvote count: 0
tagged with: pip
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87271814
has body: I've been running Python 3 in Pycharm for a while now, and I tried to install a new module and it failed to install. Specifically it gave me a "Non-zero exit code (1)" and told me to attempt to install it from my terminal using PIP. I have since updated and reinstalled Pycharm and it still will not install new modules. In the terminal, I attempted pip --version The response: -bash: pip: command not found I look up how to install PIP, and try: sudo easy_install pip This is what it said: Searching for pip Reading https://pypi.python.org/simple/pip/ Download error on https://pypi.python.org/simple/pip/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! Couldn't find index page for 'pip' (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/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! No local packages or download links found for pip error: Could not find suitable distribution for Requirement.parse('pip') So I go back to google and do a little more searching and find to try it without the sudo, so easy_install pip Then it gives me this: error: can't create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test- easy-install-2117.pth' The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /Library/Python/2.7/site-packages/ Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferabl…
has comment: http://stackoverflow.com/comment/87271455
linked to: http://stackoverflow.com/q/6012246
answer count: 2
has comment: http://stackoverflow.com/comment/87270721
has answer: http://stackoverflow.com/a/63698332
has comment: http://stackoverflow.com/comment/90797968
has comment: http://stackoverflow.com/comment/87271389
has title: I can't install PIP on MacOS Sierra
linked to: http://stackoverflow.com/q/47997164
score: 1
tagged with: macos
has comment: http://stackoverflow.com/comment/87277279
has answer: http://stackoverflow.com/a/51924231
favorite count: 0

http://stackoverflow.com/comment/87411764
has text: set is faster, or dictionary with number of repetitions
comment on: http://stackoverflow.com/q/50197183
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50085879
upvote count: 3
score: 3
downvote count: 0
has body: After a bit of digging, it seems that it is not trivial to compute per-example gradients in TensorFlow, because this library performs standard back-propagation to compute the gradients (as do other deep learning libraries like PyTorch, Theano and so on), which never actually computes the per-example gradients, it directly obtains the sum of the per-example gradients. Check out this discussion for more details. However, there are some techniques to work around this issue, at least for some use cases. For example, the paper Efficient per-example gradient computation by Ian Goodfellow explains how to efficiently compute per-example vectors containing the sum of squared derivatives. Here is an excerpt from the paper showing the computation (but I highly encourage you read the paper, it is very short): This algorithm is O(mnp) instead of O(mnp²), where m is the number of examples, n is the number of layers in the neural net, and p is the number of neurons per layer. So it is much faster than the naive approach (i.e., performing back-prop once per example), especially when p is large, and even more when using a GPU (which speeds up vectorized approaches by a large factor).
type: Answer
answers question: http://stackoverflow.com/q/50080929

http://stackoverflow.com/a/54238978
downvote count: 0
type: Answer
has body: Before installing some package (pydicom) the installation run just fine. After it I tried to install matplotlib, but I got the same error as yours. I tried conda config --set ssl_verify no but it didn't solve the problem so I set it again to true. Fortunately, I had a virtual environment where I installed my packages. I closed all Anaconda prompts and tried in a new test environment. Magically, the install worked. I came back to my original virtual env and run the install again, and it worked!. It might be that I just had to wait for some time before I could use conda install again. One other thing I could do is remove the package that caused the problem, but I didn't have the chance to try it. If it has anything to do with some virtual environments not being affected, then one possible way to guard against this is to clone the environment before installing any new package. Edit: I tried the same solution but It did not work. But instead of showing the error immediately, it asks me whether I want to proceed. I deactivated the env, and re-opened anaconda prompt, then did the same steps as above and worked again.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50125472

http://stackoverflow.com/q/50162004
has body: I was working on an online tutorial on class in python, then I wanted to try to make a function that print out the value in the return of the other functions. Here is the code: from abc import ABCMeta, abstractmethod class Vehicle(object): __metaclass__ = ABCMeta base_sale_price = 0 wheels = 0 def __init__(self, miles, make, model, year, sold_on): self.miles = miles self.make = make self.model = model self.year = year self.sold_on = sold_on def sale_price(self): if self.sold_on is not None: return 0.0 return 5000.0 * self_wheels def purchase_price(self): if self.sold_on is None: return 0.0 return self.base_sale_price - (.10 * self.miles) def spec(self): x = self.sale_price y = self.purchase_price print "This car should sell at: ", x print "This car should be bought at: ", y @abstractmethod def vehicle_type(): pass class Car(Vehicle): base_sale_price = 8000.0 wheel = 4 def vehicle_type(self): return 'car' class Truck(Vehicle): base_sale_price = 10000.0 wheels = 4 def vehicle_type(self): return 'truck' AE86 = Truck(4, 35000, 'Toyota', 'AE86', 1986, ) print AE86.sale_price() This is what I get: This car should sell at: &lt;bound method Truck.sale_price of &lt;__main__.Truck object at 0x10666da50&gt;&gt; This car should be bought at: &lt;bound method Truck.purchase_price of &lt;__main__.Truck object at 0x10666da50&gt;&gt; What am I doing wrong? how do I make the return value of the methods to show up??
tagged with: class
score: -1
tagged with: printing
accepted answer: http://stackoverflow.com/a/50163154
type: AnsweredQuestion
upvote count: 0
has title: How to print a return value of a method in a class?
has answer: http://stackoverflow.com/a/50163154
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87341934
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/a/50155264
has body: change the name of variable. i mean: bar = locals()['bar'] # KeyError: 'bar' on tmp = locals()['bar'] # 12
type: Answer
answers question: http://stackoverflow.com/q/50155039
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/50122226
favorite count: 0
has comment: http://stackoverflow.com/comment/87262383
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50122378
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50122378
has body: I have a numpy list, type of its element is numpy.float64 and I would like to convert all element of the list to float. This is the print out of the list: [array([ -7.19244777e+24, 3.32768299e-02, -7.19249216e+24], dtype=float32), array([ -8.87044985e+25, 1.46775544e-01, -8.87068228e+25], dtype=float32), array([ 0.61927807, -0.16575921, 0.98002648], dtype=float32), array([ 0.63426137, -0.15838303, 0.97730571], dtype=float32)] I could convert each element from numpy.float to float with following code. mtx = [] for i in range(len(centroids)): row = [] for j in range(len(centroids[i])): row.append(np.asscalar(centroids[i][j])) mtx.append(row) I am wondering is there any one-liner or utility method to convert elements of whole list from numpy.float64 to float ? Same question for string and other data types.
has title: python type convertion over whole numpy array at once
score: 1
has comment: http://stackoverflow.com/comment/87262442
answer count: 1

http://stackoverflow.com/comment/87316607
type: Comment
has text: Maybe this question is for Super User https://superuser.com/
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50149053

http://stackoverflow.com/comment/87261277
score: 9
type: Comment
comment on: http://stackoverflow.com/q/50121703
has text: Turn on some lights.
type: QuestionComment

http://stackoverflow.com/q/50141983
answer count: 4
upvote count: 8
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/64315122
has comment: http://stackoverflow.com/comment/87302747
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63835056
has body: I faced this problem when I installed module matplotlib and wrote this code: import matplotlib.pyplot as plt And then here is the error: "matplotlib.cbook.TimeoutError: LOCKERROR: matplotlib is trying to acquire the lock 'C:\\Users\\Андрей\\.matplotlib\\.matplotlib_lock-*' and has failed. This maybe due to any other process holding this lock. If you are sure no other matplotlib process is running try removing these folders and trying again." So of course if it can not be imported it can not be used.
tagged with: python
has answer: http://stackoverflow.com/a/59858779
has comment: http://stackoverflow.com/comment/87303508
has title: Python - Matplotlib / matplotlib.cbook.TimeoutError: LOCKERROR
has answer: http://stackoverflow.com/a/50486999
score: 7
tagged with: matplotlib
downvote count: 1

http://stackoverflow.com/q/50132734
tagged with: azure
has title: how to extract month and year from a given date in th form of a string
answer count: 1
has comment: http://stackoverflow.com/comment/87283357
has body: good Evening, I have a dataframe which consists of order date, dispatch date each having dates in the format 02-25-2013. I want to extract month and year from these dates and I want to generate new columns in my dataset as Order_Mt, Order_yr, Dispatch_Mt, Dispatch_Yr. I tried to extract by using strptime(). But no use. Can anyone tell me how to do this? Thanks in advance
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87283403
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
linked to: http://stackoverflow.com/q/50128665
has answer: http://stackoverflow.com/a/50133184
has comment: http://stackoverflow.com/comment/87283856
linked to: http://stackoverflow.com/q/32204631
tagged with: python

http://stackoverflow.com/comment/87192812
has text: What empty dataframe are you talking about? What is the expected result?
comment on: http://stackoverflow.com/q/50088353
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87229607
score: 0
has text: Looks like it happens whenever you move the mouse before the turtle has arrived at the cursor position. When you click, you can see the turtle move toward the cursor - if you start moving the mouse before it's arrived at the cursor, it won't draw a line while you're dragging and once you release the mouse button, you'll get that weird jumping behavior.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50105860

http://stackoverflow.com/a/50143321
type: Answer
has body: It sounds like you want: for root_folder in root_dir: for folder in work_dir: os.makedirs(os.path.join(root_folder, folder), exist_ok=True)
score: 0
answers question: http://stackoverflow.com/q/50143212

http://stackoverflow.com/comment/87427000
score: 0
type: AnswerComment
has text: @StrangeRanger Those use the `all` builtin function to check whether all the characters in the message are in the translation dict or in the string of valid morse code characters. If you don't know it, you should read up on `all` and other builtin functions. They are very handy.
type: Comment
comment on: http://stackoverflow.com/a/50193775

http://stackoverflow.com/a/50092613
answers question: http://stackoverflow.com/q/50092497
type: Answer
upvote count: 1
has body: What about: items = {} with open("temp.txt") as f: for line in f: item,cost = line.split('#') cost = float(cost) items[item] = cost Now, you have a dictionary, keyed by item "name" (so they need to be unique in your file, otherwise a dictionary isn't the best structure here) and each value is a float corresponding to the parsed cost. # Print items and cost print(items.items()) #&gt; dict_items([('hammer', 9.95), ('saw', 20.15), ('shovel', 35.4)]) # Print Number of Items print(len(items)) #&gt; 3 # Print Total Cost (unformatted) print(sum(items.values())) #&gt; 65.5 # Print Total Cost (formatted) print("$%.02f" % sum(items.values())) #&gt; $65.50 There are some corner cases you may want to look at to make this solution more robust. For example if the item "name" includes a # sign (i.e. there is more than one # per line), the values aren't properly formatted to be parsed by float, etc.
score: 1
downvote count: 0

http://stackoverflow.com/comment/87454604
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50218405
has text: Interesting +1 , why isn’t _ in the globals() dict?

http://stackoverflow.com/a/50191025
has comment: http://stackoverflow.com/comment/87399606
downvote count: 0
score: 1
upvote count: 1
has body: What you're asking for is the ability to spoof email addresses -- to send mail from your account on your server, and make it look as if it came from someone else. This is a bad idea -- spoofing email addresses will get you quickly blacklisted as a suspected spammer or hacker, and many systems will reject such emails automatically. Instead, just let the email come from the address you're actually using, and in the body of the message put the address of the person the reply should go to.
answers question: http://stackoverflow.com/q/50190681
type: Answer

http://stackoverflow.com/comment/87191471
comment on: http://stackoverflow.com/q/50087103
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by steps?

http://stackoverflow.com/q/50204817
has title: Tensorflow save and load model/estimator
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87427427
has comment: http://stackoverflow.com/comment/87427064
tagged with: tensorflow
type: Question
score: 0
tagged with: mnist
linked to: http://stackoverflow.com/q/50612923
tagged with: python
has body: Im super new to tensorflow, and I`m following the tutorials on its webpage. I already understood the code for the MNIST Dataset tutorial, but I would like to save the model so I can load it afterwards and test it against my own image set. Im tried many ways of saving it but i keep failing. Im talking about this tutorial. Any help will be appreciated! Edit: Everywhere I go, I see a Session variable, but in this example I dont, and that confuses me... Do you know how can I save the model from the tutorial and reuse it?
has comment: http://stackoverflow.com/comment/88258412

http://stackoverflow.com/q/50156293
tagged with: python
has title: pandas create new column referencing certain columns and column headers
has comment: http://stackoverflow.com/comment/87330917
has body: This is my current dataframe. I would like to add two new columns called PriceError and CostError. Price 1 Price2 Cost1 Cost2 %Price %Cost PriceError CostError 1 1 3 6 0 100 2 4 3 3 100 0 df['PriceError'] should equal the following string Price1 is 2 and Price1 is 4. The %Price is 100. df['CostError'] should equal the following string Cost1 is 3 and Cost1 is 6. The %Price is 100. I am only returning those because the other two are below 50% which is my threshold for errors. SO PriceError is hardcoded to "Price1 is df['Price1'] and Price2 is df['Price2'] and the %Price is df['%Price']". I would like to some sort of way to write that PriceError should only look at columns price1, price2, and %price and write the string.
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
has answer: http://stackoverflow.com/a/50157817
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/50101027
favorite count: 0
has body: I have a requirement of tokenizing the words in a sentence based on the specific word list. wordlist = ["nlp - nltk", "CIFA R12 - INV"] Example-input: This is sample text for nlp - nltk CIFA R12 - INV. while using word_tokenize(Exapmle-input), here I need nlp - nltk as one token and CIFA R12 - INV as another token. Is that possible rather than getting nlp - CIFA as different tokens?
type: Question
has answer: http://stackoverflow.com/a/50213085
tagged with: nltk
has title: Tokenize the words based on a list
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: tokenize
answer count: 1
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50213085

http://stackoverflow.com/comment/87391389
has text: Looks great, upvoted it. texplode and anyone else encountering this should however keep in mind that this doesn't have an equal distribution on the shuffle.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50186357
type: AnswerComment

http://stackoverflow.com/comment/87457351
comment on: http://stackoverflow.com/a/50220108
score: 0
type: Comment
has text: If your wifi card support the monitor mode, Yes. You just need to pass the appropriate setting through netsh. Otherwise the problem is in your card.
type: AnswerComment

http://stackoverflow.com/comment/87304665
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50140864
has text: Sorry! The dimensions can change. Updated the post.
type: AnswerComment

http://stackoverflow.com/comment/87209011
type: Comment
type: QuestionComment
has text: Why is that a surprise? Besides the fields, you can attach all kinds of properties, attributes, functions, etc. to a model class, instance, etc.
comment on: http://stackoverflow.com/q/50095511
score: 0

http://stackoverflow.com/comment/87396075
comment on: http://stackoverflow.com/q/50189610
score: 0
type: Comment
type: QuestionComment
has text: `while not vari.startswith('Q'):`. I don't understand the `int` check

http://stackoverflow.com/a/50204836
downvote count: 0
has comment: http://stackoverflow.com/comment/87433061
score: 3
answers question: http://stackoverflow.com/q/50203849
type: Answer
has body: If you don't want to persist the DB data, don't use volumes, so you will have a fresh database everytime you start the container. I guess you need some prepopulated data in your tables, so just build a new DB image copying the data you need. The Docker file could be something like: FROM postgres:9.6-alpine COPY db-data/ /var/lib/postgresql/data In case you need to update the data, mount the db-data/ using -v, change it and rebuild the image. BTW, it would be better to use an automated pipeline to test your builds, using Jenkins, GitLab CI, Travis or whatever solution that suits you. Anyway, you can use docker-compose in your pipeline as well to keep it consistent with your local development environment.
has comment: http://stackoverflow.com/comment/87432820
upvote count: 3
has comment: http://stackoverflow.com/comment/87432493

http://stackoverflow.com/comment/87451012
has text: By what criteria do you want to get `281`? Please put a bit more flesh on the bones of what you have in mind of how identifying 281 is supposed to be done?
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50217001

http://stackoverflow.com/comment/87320662
score: 0
comment on: http://stackoverflow.com/a/50151358
type: Comment
type: AnswerComment
has text: @Aran-Fey made the changes

http://stackoverflow.com/a/50166057
downvote count: 0
has comment: http://stackoverflow.com/comment/87350031
answers question: http://stackoverflow.com/q/50166012
type: Answer
has comment: http://stackoverflow.com/comment/87352593
has body: Just flatMap: myRDD.flatMap(lambda xs: ([x] for x in xs))
score: 2
upvote count: 2

http://stackoverflow.com/comment/87378552
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50118797
has text: @mr4kino So here i have this connecton: [---.---.-.12:47218]<->[---.---.---.188:5228] its using ports 47218 and 5228, how can i tell which one is a service port?
type: Comment

http://stackoverflow.com/comment/87334703
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50158136
has text: Thank you for adding the answer. I have accepted the other answer and already upvoted your answer(feel cant do much now). But your solution also looks neat and while handling with large datasets, I feel your solution will need less CPU cycles as you are not doing any conversions
score: 1

http://stackoverflow.com/comment/87313271
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50147415
has text: I see. The if-else will work regardless of id numbers because it's the first line that is being checked (which will either be 0 or 1).
type: Comment

http://stackoverflow.com/comment/87465161
score: 0
comment on: http://stackoverflow.com/q/50223523
has text: `time.strptime` presumes that `datetime_obj` is a string representing a Gregorian date. Since February doesn't have 30 days this would raise an exception. Are you sure django-jalali is compatible with django-rest-framework? It seems to accept only gregorian date strings as input here.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87246081
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50114235
has text: I am using your function (I have tried both), and then, I do: dfFF['EUR_new'] = dfFF.apply(currency_convertor, axis=1)
score: 0

http://stackoverflow.com/comment/87453815
has text: Added more details to the question. Thanks for pointing that out Bryan!
comment on: http://stackoverflow.com/q/50217481
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87269487
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50125094
has text: @abarnert Increased the buffer to 64K but it's processing about the same as when it was set to 80K. I also commented out the sql writes but it had no affect either.

http://stackoverflow.com/q/50100199
tagged with: django
upvote count: 1
tagged with: python
tagged with: django-rest-framework
has title: how get a csv file and excel formats (xls xlsx,..)with django rest framework
score: 0
has body: I need to limit the API that I've written to get only certain format files. I also need to send my response to Jason. I will send my code and I guess my problem is in serializing.py but I can not Understand where is it when I send CSV file or xls or xlsx return ' "Wrong file type: text/plain"' and now my code : my model : from django.db import models class File(models.Model): file = models.FileField(blank=False, null=False) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) my view: # Create your views here. from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors,status=status.HTTP_400_BAD_REQUEST) and my serializer : class FileSerializer(serializers.ModelSerializer): ALLOWED_TYPES = [ 'text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/json', ] class Meta(): model = File fields = '__all__' def validate_file(self, value): mime = magic.Magic(mime=True) ftype = mime.from_buffer(value.file.read(1024)) if ftype not in self.ALLOWED_TYPES: msg = 'Wrong file type: {}'.format(ftype) raise serializers.ValidationError(msg) value.file.seek() return value and I will thank you if you help me that fix it my python version = 3 and my Django version = 2
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50100244
type: UnansweredQuestion

http://stackoverflow.com/comment/87306133
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50136882
type: QuestionComment
has text: It caches the value of the current loop variable as a default argument. If you don't do that, the `lambda` will only see the last value. In fact, there are *two* loop variables, so the code needs to be `slider.sliderReleased.connect(lambda slider=slider, value_label=value_label: self.slider_released(slider, value_label))`.

http://stackoverflow.com/comment/87190419
score: 0
type: QuestionComment
has text: It's been a while, but I think you can for instance look at the [steepest decent method](https://en.wikipedia.org/wiki/Gradient_descent) which is fairly simple to implement. There's also plenty of python programs out there that implement it.
type: Comment
comment on: http://stackoverflow.com/q/50081980

http://stackoverflow.com/comment/87272058
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50127085
type: QuestionComment
has text: if u want to open an HTML page on checkbox then you can call ajax on the checkbox check.you can see this answer for better refence:-https://stackoverflow.com/questions/23269413/ajax-call-on-checking-a-checkbox

http://stackoverflow.com/comment/87457562
has text: If I _had_ to use sqlite I'd probably go down the path of a single writer process reading from a kafka feed, but I have no idea how successful that would be.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50220147
score: 0