http://stackoverflow.com/q/47507274
upvote count: 4
has title: How to find the same index between two dataframes and combine it to a new dataframe, Python 3
has answer: http://stackoverflow.com/a/47507314
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have two pandas.dataframes df1 and df2. Some of their index are equal. I want to find those index and combine the corresponding rows into a new dataframe. df1 = A B Name apple 1 5 orange 2 6 banana 3 7 df2 = A B Name apple -1 10 audi -2 11 bmw 0 12 banana 2 8 vw -3 6 The new dataframe that I want is: 1) find the rows with the same index; 2) calculate the average value of the corresponding rows in column 'A'. df_new = A_average Name apple 0 banana 2.5 This is because: df1 and df2 both have the index apple and banana. The average value of apple in column 'A' is (1-1)/2=0, and the average value of banana in column 'A' is (3+2)/2=2.5. Do you know how to use Python3 to achieve this? Please note that, in my real application, there can be many more rows than the example I showed above. Thanks!
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: dataframe
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/47507314

http://stackoverflow.com/comment/81818555
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47431402
type: AnswerComment
has text: The difference between `select count(*) from table where something..." and "select count(*) from (select 1 from something where condition=...)`

http://stackoverflow.com/comment/81726311
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47385922
type: QuestionComment
has text: You're lucky then. There is no real logical way to generalise split code on your data. Think about it. When do you expect "Not Available" to show up?

http://stackoverflow.com/q/47476252
upvote count: 0
has comment: http://stackoverflow.com/comment/81907113
tagged with: function
downvote count: 1
answer count: 1
has title: Python function for plotting a heatmap
favorite count: 0
type: Question
has body: I'm having a hard time making a function that plots a Heatmap when I call it for several variables. Here's what I managed to do so far, which works very well, but how can I make it into a function? df = pd.DataFrame(columns=['ypos', 'xpos', 'val']) df.loc[0] = [1,1,MD.at[0,"VarName[1][1]"]] df.loc[1] = [1,2,MD.at[0,"VarName[1][2]"]] df.loc[2] = [1,3,MD.at[0,"VarName[1][3]"]] df.loc[3] = [1,4,MD.at[0,"VarName[1][4]"]] df.loc[4] = [2,1,MD.at[0,"VarName[2][1]"]] df.loc[5] = [2,2,MD.at[0,"VarName[2][2]"]] df.loc[6] = [2,3,MD.at[0,"VarName[2][3]"]] df.loc[7] = [2,4,MD.at[0,"VarName[2][4]"]] df.loc[8] = [3,1,MD.at[0,"VarName[3][1]"]] df.loc[9] = [3,2,MD.at[0,"VarName[3][2]"]] df.loc[10] = [3,3,MD.at[0,"VarName[3][3]"]] df.loc[11] = [3,4,MD.at[0,"VarName[3][4]"]] df.loc[12] = [4,1,MD.at[0,"VarName[4][1]"]] df.loc[13] = [4,2,MD.at[0,"VarName[4][2]"]] df.loc[14] = [4,3,MD.at[0,"VarName[4][3]"]] df.loc[15] = [4,4,MD.at[0,"VarName[4][4]"]] print(df) ax = sns.heatmap(df.pivot('ypos', 'xpos', 'val'), annot=True) ax.invert_yaxis() Please note that VarName1 ... VarName[4][4] is the header name of each column in the dataset. I'd really appreciate your help!!
has answer: http://stackoverflow.com/a/47535367
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: heatmap

python
tags question: http://stackoverflow.com/q/47510581
tags question: http://stackoverflow.com/q/47382800
tags question: http://stackoverflow.com/q/47508939
tags question: http://stackoverflow.com/q/47463118
tags question: http://stackoverflow.com/q/47410643
tags question: http://stackoverflow.com/q/47479480
tags question: http://stackoverflow.com/q/47508516
tags question: http://stackoverflow.com/q/47511055
tags question: http://stackoverflow.com/q/47405236
tags question: http://stackoverflow.com/q/47401262
tags question: http://stackoverflow.com/q/47416625
tags question: http://stackoverflow.com/q/47479980
tags question: http://stackoverflow.com/q/47460570
tags question: http://stackoverflow.com/q/47460399
tags question: http://stackoverflow.com/q/47536458
tags question: http://stackoverflow.com/q/47486024
tags question: http://stackoverflow.com/q/47413992
tags question: http://stackoverflow.com/q/47385812
tags question: http://stackoverflow.com/q/47514666
tags question: http://stackoverflow.com/q/47484639
tags question: http://stackoverflow.com/q/47529684
tags question: http://stackoverflow.com/q/47440941
tags question: http://stackoverflow.com/q/47419371
tags question: http://stackoverflow.com/q/47401706
tags question: http://stackoverflow.com/q/47444272
tags question: http://stackoverflow.com/q/47419199
tags question: http://stackoverflow.com/q/47471658
tags question: http://stackoverflow.com/q/47508349
tags question: http://stackoverflow.com/q/47535099
tags question: http://stackoverflow.com/q/47457633
tags question: http://stackoverflow.com/q/47397717
tags question: http://stackoverflow.com/q/47502317
tags question: http://stackoverflow.com/q/47489498
tags question: http://stackoverflow.com/q/47498748
tags question: http://stackoverflow.com/q/47523760
tags question: http://stackoverflow.com/q/47524492
tags question: http://stackoverflow.com/q/47403771
tags question: http://stackoverflow.com/q/47434224
tags question: http://stackoverflow.com/q/47478684
tags question: http://stackoverflow.com/q/47390843
tags question: http://stackoverflow.com/q/47428173
tags question: http://stackoverflow.com/q/47385313
tags question: http://stackoverflow.com/q/47417008
tags question: http://stackoverflow.com/q/47531948
tags question: http://stackoverflow.com/q/47423878
tags question: http://stackoverflow.com/q/47429354
tags question: http://stackoverflow.com/q/47474891
tags question: http://stackoverflow.com/q/47492974
tags question: http://stackoverflow.com/q/47421454
tags question: http://stackoverflow.com/q/47419036
tags question: http://stackoverflow.com/q/47502640
tags question: http://stackoverflow.com/q/47407131
tags question: http://stackoverflow.com/q/47528539
tags question: http://stackoverflow.com/q/47474002
tags question: http://stackoverflow.com/q/47537538
tags question: http://stackoverflow.com/q/47512770
tags question: http://stackoverflow.com/q/47481909
tags question: http://stackoverflow.com/q/47433921
tags question: http://stackoverflow.com/q/47385700
tags question: http://stackoverflow.com/q/47529937
tags question: http://stackoverflow.com/q/47390305
tags question: http://stackoverflow.com/q/47479496
tags question: http://stackoverflow.com/q/47483587
tags question: http://stackoverflow.com/q/47438289
tags question: http://stackoverflow.com/q/47407537
tags question: http://stackoverflow.com/q/47415039
tags question: http://stackoverflow.com/q/47500832
tags question: http://stackoverflow.com/q/47488859
tags question: http://stackoverflow.com/q/47499986
tags question: http://stackoverflow.com/q/47475204
tags question: http://stackoverflow.com/q/47486683
tags question: http://stackoverflow.com/q/47399794
tags question: http://stackoverflow.com/q/47526726
tags question: http://stackoverflow.com/q/47531936
tags question: http://stackoverflow.com/q/47499284
tags question: http://stackoverflow.com/q/47401311
tags question: http://stackoverflow.com/q/47534108
tags question: http://stackoverflow.com/q/47459054
tags question: http://stackoverflow.com/q/47448236
tags question: http://stackoverflow.com/q/47486898

http://stackoverflow.com/comment/81867357
has text: anyway really. I just want the system to read the text file and take those text entries and check timestamps of each file list in text file.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47456261

http://stackoverflow.com/q/47392526
linked to: http://stackoverflow.com/q/22952026
accepted answer: http://stackoverflow.com/a/47392833
tagged with: python-module
tagged with: python
linked to: http://stackoverflow.com/q/8122734
has answer: http://stackoverflow.com/a/47392833
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81738065
has comment: http://stackoverflow.com/comment/81738181
answer count: 1
tagged with: file
has body: I have a problem understanding why reload() doesn't work properly in the code below: # Create initial file content f = open('some_file.py', 'w') f.write('message = "First"\n') f.close() import some_file print(some_file.message) # First # Modify file content f = open('some_file.py', 'w') f.write('message = "Second"\n') f.close() import some_file print(some_file.message) # First (it's fine) reload(some_file) print(some_file.message) # First (not Second, as expected) If I change the file some_file.py manually with an external editor (while the program is running) then everything works as expected. So I guess it may have something to do with syncing. Environment: Linux, Python 2.7.
type: Question
has title: Module reload doesn't work as expected

http://stackoverflow.com/comment/81790865
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47418227
has text: @wim Yea I looked at the question that mine was marked a duplicate of (I did extensive google searching, I swear!) Adding the # pylint: disable=invalid-name seems to do the trick. I will make pylint do my bidding
score: 0

http://stackoverflow.com/comment/81781784
has text: we can't save anything on remote machine, hence was wondering if we can do it just by login into remote and using some exec_command
comment on: http://stackoverflow.com/a/47414016
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47475233
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47475640
has title: Update selected fields in MongoDB with Pymongo
tagged with: python
type: UnansweredQuestion
has body: I want my python (scrapy) script to : Insert document in my db if url doesn't not exist Update only url field if document exists and don't update the other fields. My script works partially because it inserts a new document if url doesn't exist (that i want) but it updates all the other fields if the document exists (i don't want). Can you help ? here is a sample : def process_item(self, item, spider): for data in item: if not data: raise DropItem("Missing data!") self.collection.update({'userurl': item['userurl']}, dict(item), upsert=True) return item Thx !
tagged with: mongodb
tagged with: pymongo
downvote count: 0
score: 1
upvote count: 1
tagged with: scrapy
answer count: 1

jhipster
tag name: jhipster
type: Tag
tags question: http://stackoverflow.com/q/47397656

http://stackoverflow.com/q/47535872
tagged with: python
has body: I have a very large and also sparse matrix (531K x 315K), the number of total cells is ~167 Billion. The non-zero values are only 1s. Total number of non-zero values are around 45K. Is there an efficient NMF package to solve my problem? I know there are couple of packages for that and they are working well only for small size of data matrix. Any idea helps. Thanks in advance.
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/82028906
tagged with: matrix-factorization
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47536681
has title: Very Large and Very Sparse Non Negative Matrix factorization
has comment: http://stackoverflow.com/comment/82029931
has answer: http://stackoverflow.com/a/47536681
answer count: 1
downvote count: 1
score: 8
favorite count: 0
type: Question
upvote count: 9
tagged with: nmf
tagged with: bigdata

http://stackoverflow.com/comment/81743175
has text: Py2 and Py3 mean very different things with `int`. You can always look at the source code to see how the different structures are implemented. Py2 `int` is a fixed-size structure, while Py3 `int` is definitely not.
comment on: http://stackoverflow.com/q/47395007
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47501048
type: Answer
answers question: http://stackoverflow.com/q/47500081
has body: If you need to add a single row: In [136]: dFrame.loc[len(dFrame)] = row In [137]: dFrame Out[137]: Amenity Area Daily Latitude Longitude Monthly Name Weekly Yearly 0 NA NA NA NA NA NA NA NA NA NOTE: usually it's much better, faster, less memory consuming (it depends...) to collect the data first into list of lists and then to call pd.DataFrame() constructor once: In [138]: data = [row, np.arange(9)] In [139]: cols = 'Amenity Area Daily Latitude Longitude Monthly Name Weekly Yearly'.split() In [140]: df = pd.DataFrame(data, columns=cols) In [141]: df Out[141]: Amenity Area Daily Latitude Longitude Monthly Name Weekly Yearly 0 NA NA NA NA NA NA NA NA NA 1 0 1 2 3 4 5 6 7 8
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47500081

http://stackoverflow.com/q/47420211
accepted answer: http://stackoverflow.com/a/47491454
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47491454
has body: I tried to import ndimage package from SciPy to use the maximum filter in it. However, it seems SciPy is missing this part. I got this error: from scipy.linalg import _fblas ImportError: DLL load failed: The specified module could not be found. I even tried these as well (separately): import scipy.ndimage from scipy.ndimage.filters import maximum_filter import ndimage form scipy But I still get the same error. The complete error is: Traceback (most recent call last): File "C:\Users\Programs\PyCharm\PyCharm Community Edition 2017.2.4\helpers\pydev\pydevd.py", line 1599, in &lt;module&gt; globals = debugger.run(setup['file'], None, None, is_module) File "C:\Users\Programs\PyCharm\PyCharm Community Edition 2017.2.4\helpers\pydev\pydevd.py", line 1026, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Users\Programs\PyCharm\PyCharm Community Edition 2017.2.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/Desktop/Test_2/test.py", line 2, in &lt;module&gt; import scipy.ndimage File "C:\Users\Programs\Python 3.6\lib\site-packages\scipy\ndimage\__init__.py", line 161, in &lt;module&gt; from .filters import * File "C:\Users\Programs\Python 3.6\lib\site-packages\scipy\ndimage\filters.py", line 37, in &lt;module&gt; from scipy.misc import doccer File "C:\Users\Programs\Python 3.6\lib\site-packages\scipy\misc\__init__.py", line 67, in &lt;module&gt; from scipy.interpolate._pade import pade as _pade File "C:\Users\Programs\Python 3.6\lib\site-packages\scipy\interpolate\__init__.py", line 175, in &lt;module&gt; from .interpolate import * File "C:\Users\Programs\Python 3.6\lib\site-packages\scipy\interpolate\interpolate.py", line 20, in &lt;module&gt; import scipy.linalg File "C:\Users\Programs\Python 3.6\lib\site-packages\scipy\linalg\__init__.py", line 186, in &lt;module&gt; from .misc import * File "C:\Users\Programs\Python 3.6\lib\site-packages\scipy\linal…
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
tagged with: python
has title: ndimage is not in SciPy
tagged with: scipy
has comment: http://stackoverflow.com/comment/81797571
has comment: http://stackoverflow.com/comment/81795431
tagged with: python-import
has comment: http://stackoverflow.com/comment/81815638
upvote count: 3

http://stackoverflow.com/q/47524720
has comment: http://stackoverflow.com/comment/82005621
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82005853
has answer: http://stackoverflow.com/a/47524873
possible better answer: http://stackoverflow.com/a/75404154
has comment: http://stackoverflow.com/comment/82005665
has comment: http://stackoverflow.com/comment/82005813
tagged with: python
has comment: http://stackoverflow.com/comment/82005736
tagged with: flask
accepted answer: http://stackoverflow.com/a/47524873
has body: In my Flask/SQLAlchemy project, I have an index table called Styles_Index, which has a corresponding table object that I query on. The schema in sqlite3 looks like CREATE TABLE Styles_Index ( beer_id integer not null, style_id integer not null, primary key (beer_id, style_id) ); And the object in python looks like class Styles_Index(db.Model): beer_id = db.Column(db.Integer, db.ForeignKey('beers.id'), primary_key = True) style_id = db.Column(db.Integer, db.ForeignKey('styles.id'), primary_key = True) When I try to join the table onto another that shares a common key via the SQLAlchemy BaseQuery.join(), it creates a query: SELECT styles__index.id AS styles__index_id, styles__index.beer_id AS styles__index_beer_id, styles__index.style_id AS styles__index_style_id FROM styles__index JOIN styles ON styles__index.style_id = styles.id LIMIT ? OFFSET ? where Styles_Index has two underscores instead of one. Is this an intentional design choice due to the _ wildcard character in SQL? Is there a better way to write this query, without resorting to writing raw SQL?
has title: SQLAlchemy changing table name to have two underscores
type: AnsweredQuestion
score: 2
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/75404154
tagged with: sqlite
downvote count: 0

http://stackoverflow.com/a/47536696
upvote count: 8
has body: You seem to be confusing buckets, folders, and object keys. Your code should look something like this (where key contains both the folder and file name, and bucket contains only the S3 bucket name): obj = s3.get_object(Bucket='bucketname', Key='folder1/folder2/filename.csv')
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47536489
has comment: http://stackoverflow.com/comment/111513671
score: 8

http://stackoverflow.com/a/47400827
has comment: http://stackoverflow.com/comment/81837961
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: In operating systems with shell filename expansion, you might be able to use the shell's file expansion ability. For example: uncompyle6 -o /tmp/unc6 myfiles/*.pyc If you need something fancier or more control, you could always write some code that does the fancier expansion. Here is the above done in POSIX shell filtering out the single file myfiles/huge.pyc: cd myfiles for pyc in *.pyc; do if $pyc != huge.pyc ; then uncompyle -o /tmp/unc $pyc fi done Note: It seems this question was also asked in Issue on output directory while executing commands with windows batch command "FOR /R"
has comment: http://stackoverflow.com/comment/81755293
accepted answer of: http://stackoverflow.com/q/47397711
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47397711

http://stackoverflow.com/q/47441971
has comment: http://stackoverflow.com/comment/81839272
has comment: http://stackoverflow.com/comment/81839529
has title: I want to print False values in my function
duplicate of: http://stackoverflow.com/q/33989155
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81839038
answer count: 0
has comment: http://stackoverflow.com/comment/81839116
has comment: http://stackoverflow.com/comment/81839138
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
has body: li=[4,6,8,3,7] def even(x): if x%2==0: return False else: return True a=filter(even,li) print(a) print(list(a)) In this program, I can easily print the True values, but I want to print the False values without changed my function. How can I do that?
linked to: http://stackoverflow.com/q/33989155
tagged with: python
has comment: http://stackoverflow.com/comment/81839692
type: UnansweredQuestion

http://stackoverflow.com/q/47495048
tagged with: ubuntu
has answer: http://stackoverflow.com/a/47495222
accepted answer: http://stackoverflow.com/a/47495265
tagged with: opencv
type: AnsweredQuestion
score: 3
tagged with: face-detection
upvote count: 3
linked to: http://stackoverflow.com/q/60191711
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47495265
answer count: 2
has title: Crop multiple faces from a picture using opencv and store them in a folder
has body: I am a beginner to opencv and I have tried to crop a single face from a picture for my project but couldn't crop all the faces from the picture. What can be done to detect all the faces and crop them to move to a folder? taking images from the input folder and posting the cropped image to the output folder. import numpy as np import cv2 import os, os.path #multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml face_cascade = cv2.CascadeClassifier('faces.xml') #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml eye_cascade = cv2.CascadeClassifier('eye.xml') DIR = 'input' numPics = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))]) for pic in range(1, (numPics+1)): img = cv2.imread('input/'+str(pic)+'.jpg') height = img.shape[0] width = img.shape[1] size = height * width if size &gt; (500^2): r = 500.0 / img.shape[1] dim = (500, int(img.shape[0] * r)) img2 = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) img = img2 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) eyesn = 0 for (x,y,w,h) in faces: imgCrop = img[y:y+h,x:x+w] #cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: #cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) eyesn = eyesn +1 if eyesn &gt;= 2: cv2.imwrite("output/crop"+str(pic)+".jpg", imgCrop) #cv2.imshow('img',imgCrop) print("Image"+str(pic)+" has been processed and cropped") k = cv2.waitKey(30) &amp; 0xff if k == 27: break #cap.release() print("All images have been processed!!!") cv2.destroyAllWindows() cv2.destroyAllWindows() How to crop all faces from a picture to save in a folder?
possible better answer: http://stackoverflow.com/a/47495222
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/82034844
has text: Using `axis=-1` goes in the direction of the columns, and if each row is a sample, then individual samples would be normalized - no?
score: 0
comment on: http://stackoverflow.com/q/47538391
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47516838
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/81989683
has comment: http://stackoverflow.com/comment/81989640
answer count: 4
has body: I have a text file with data. In each line there is one or two words and one number, so the problem is, that sometimes there are 2 columns and sometimes 3. aaa bbb 4 ccc 10 ddd eee 3 fff 5 I only need those numbers. How to copy them to a list in Python? I tried with file = open("data.txt","r") data = file.readlines() result = [] for line in data: result.append(line.split(' ')[-1]) file.close() But I don't know how to get rid of '\n' in the end of number? Because when I change result.append(line.split(' ')[-1]) to result.append(int(line.split(' ')[-1])), it doesn't work. Is there a better way?
has answer: http://stackoverflow.com/a/47517756
has answer: http://stackoverflow.com/a/47516894
has title: How to read values from the last column from a file with different number of columns?
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47517220
has comment: http://stackoverflow.com/comment/81991441
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47516937

http://stackoverflow.com/comment/81722383
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47384763
type: QuestionComment
has text: Try `for i in range(len(S) -1):`. In `and S[i+1] != " ":` you're attempting to access the `i+1` index... Well when you get to the very end of that loop, `i+1` overshoots the end of the list.

http://stackoverflow.com/comment/81811149
comment on: http://stackoverflow.com/a/47427036
has text: Thanks @ClémentDenoix. I will try
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81905974
has text: @PiyushDas I've made edits to clarify my question. Hope you could provide some insights on it.
comment on: http://stackoverflow.com/q/47464004
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82011677
comment on: http://stackoverflow.com/a/47527692
has text: This exactly what I don't want, just like my NOTICE says, this captures the ENTIRE output, and then prints it when it is done, I want to be able to print in a "live" manner
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47473037
tagged with: beautifulsoup
has title: How to pass emoji scraping a text in phyton with bs4
has answer: http://stackoverflow.com/a/47480098
tagged with: python
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has body: I'm creating a scraper that scrapes all the comments in a URL page and I'm saving the text in a txt file (1 comment = 1 txt). Now I'm having a problem when there are some emoji in the text of a comment. In fact, the program stops and says "UnicodeEncodeError: 'charmap' codec can't encode the character". How can I pass this problem? (I'm using bs4) The structure of the code is like this: q=requests.get(url) soup=BeautifulSoup(q.content, "html.parser") x=soup.find("a", {"class":"comments"}) y=x.find_all("div", {"class":"blabla"}) i=0 for item in y: name=str(i) comment=item.find_all("p") out_file=open('%s.txt'%CreatorName, "w") out_file.write(str(comment) out_file.close i=i+1 Thanks to everyone.
has comment: http://stackoverflow.com/comment/81900554
tagged with: emoji

http://stackoverflow.com/q/47410243
has title: django - cannot login after create custom user model
answer count: 2
has answer: http://stackoverflow.com/a/47422631
type: UnansweredQuestion
tagged with: django-custom-user
downvote count: 0
tagged with: django
upvote count: 1
linked to: http://stackoverflow.com/q/1769403
favorite count: 0
type: Question
has body: I created my own user model and usermanager model. Then I tried to create a supersuser and get "Superuser created successfully." However, when I tried to login with all the info, it failed. Then I added a line of code to print my password while creating. The result matches with my password.I am pretty sure the server is using the custom model because: The required fields changes according to my code If I remove one necessary field from the required fields, I get an error about "TypeError: create_superuser() missing 1 required positional argument:" which is expected, so it is in the right way I used .count() method to get the user in the database and i can see the amount increase with 1 after I created one Here is my code: class UserManager(BaseUserManager): def create_user(self, username,email,password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.username = username user_obj.save(using=self.db) return user_obj def create_superuser(self, username, email, password): print("Super user created, with password" + password) return self.create_user( username=username, email=email, password=password, ) class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) email = models.EmailField(blank=True, unique=True) created_time = models.TimeField(auto_now=True) active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() I really appreciate if anybody can give me any idea. Totally get lost.
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47410439

http://stackoverflow.com/a/47496126
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47495956
has comment: http://stackoverflow.com/comment/81947620
has comment: http://stackoverflow.com/comment/81947608
type: Answer
has body: So after I went over a big piece of the unittest code I found a solution! The TestCase class has an _outcome attribute. The _outcome has a list type attribute called errors. errors[0][1] is a tuple that is exactly like the sys.exc_info() output that contains the traceback. So now that I have this tuple that I can use in traceback.format_exception() just like traceback.format_exc() uses it and problem solved. def tearDown(self): try: etype, value, tb = self._outcome.errors[0][1] trace = ''.join(traceback.format_exception(etype=etype, value=value, tb=tb, limit=None)) date = '{date}\n'.format(date=str(datetime.datetime.now())) name = '\n' + self._testMethodName + '-\n' with open(self.logger, 'a') as doc: doc.write(name + date + trace) except: pass
answers question: http://stackoverflow.com/q/47495956
upvote count: 2
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/81938656
comment on: http://stackoverflow.com/q/47491390
type: Comment
type: QuestionComment
has text: strange... maybe ditch the trailing slash: `url_prefix='/verificator'` in the Blueprint instantiation (that is how I always define them)
score: 1

http://stackoverflow.com/a/47520474
answers question: http://stackoverflow.com/q/47519841
has comment: http://stackoverflow.com/comment/81997540
downvote count: 0
score: 1
upvote count: 1
has body: It's a function of time, not of x. [y(t) not y(x)]. In other words, call evalPoly(coefsY, times) instead of evalPoly(coefsY, xs). def trajectoryNoDrag(angleDeg,veloc,x0,y0): #Y values messed up """ @function: trajectoryNoDrag @params: angleDeg (float); the angle of launch veloc (float); the initial velocity, x and y components x0 (float); the initial X pos y0 (float); the initial Y pos @returns: times (np.array); the time intervals xs (np.array); the x values ys (np.array); the y values @purpose: Simulate the trajectory of an arrow """ coefsX, coefsY = arrowPolys(angleDeg, veloc, x0, y0) #Store the coefs duration = quadSolve(coefsY)[0] #flight duration tinc = duration * NUM_PER_SEC #the incerments times = np.linspace(0,duration,tinc) #The times xs = np.linspace(x0, coefsX[1] * duration, tinc) #The x values # your polynomial evaluation below is a function of time. ys = evalPoly(coefsY, times) return times, xs, ys #-- End of File --#
has comment: http://stackoverflow.com/comment/81997506
accepted answer of: http://stackoverflow.com/q/47519841
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/82028572
type: Comment
score: 0
type: AnswerComment
has text: This works great. Is there a simple way to place the month ticks with month labels on the x axis instead of Julian days?
comment on: http://stackoverflow.com/a/47513899

http://stackoverflow.com/comment/81920145
has text: Just added an explanation to give you a better idea.
score: 0
comment on: http://stackoverflow.com/a/47482363
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47471323
answers question: http://stackoverflow.com/q/47471261
has comment: http://stackoverflow.com/comment/81898184
has comment: http://stackoverflow.com/comment/81897275
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81898089
downvote count: 0
has body: A single equal sign, that is, =, is used for variable assignment. For comparison, you must use double equals ==. So replace your if line with this: if (b==False): In addition to this, the parentheses in Python are unnecessary. You could write: if b == False: And it would still work. Since b is a boolean value (True or False), you can also do if not b:
has comment: http://stackoverflow.com/comment/81897610

http://stackoverflow.com/q/47420926
answer count: 2
has comment: http://stackoverflow.com/comment/81796618
accepted answer: http://stackoverflow.com/a/47421220
has comment: http://stackoverflow.com/comment/81796172
downvote count: 0
has comment: http://stackoverflow.com/comment/81796184
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47421220
has title: Python regex preference if multiple matches
linked to: http://stackoverflow.com/q/4697882
has comment: http://stackoverflow.com/comment/81796857
has comment: http://stackoverflow.com/comment/81796690
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81796494
type: AnsweredQuestion
has body: I am searching for city names in a string: mystring = 'SDM\Austin' city_search = r'(SD|Austin)' mo_city = re.search(city_search,mystring,re.IGNORECASE) city = mo_city.group(1) print(city) This will return city as 'SD'. Is there a way to make 'Austin' the preference? Switching the order to (Austin|SD) doesn't work. The answer is the same as How can I find all matches to a regular expression in Python?, but the use case is a little different since one match is preferred.
possible better answer: http://stackoverflow.com/a/47421662
has answer: http://stackoverflow.com/a/47421662
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81796204
has comment: http://stackoverflow.com/comment/81796672
has comment: http://stackoverflow.com/comment/81796791

http://stackoverflow.com/a/47473249
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81902540
has body: One possible solution is my replacing wildcard from all the other elements present and then merge them i.e Data : edf = pd.DataFrame.from_dict([ { 'name' : 'Boson', 'type' : 'Material' }, { 'name' : 'Atman', 'type' : 'Ideal' }, ]) rdf = pd.DataFrame.from_dict([ { 'action' : 'recognize', 'entity_type' : 'ALL'}, { 'action' : 'disdain', 'entity_type' : 'Material'}, { 'action' : 'worship', 'entity_type' : 'Ideal'}, ]) Preprocessing : mask = rdf['entity_type']=='ALL' # Join all the elements from `edf['type']` with `;` since you might have `,`s in types and we need to use set to get rid of duplicates (Thank you @John ) all_ = ';'.join(set(edf['type'])) # all_ : Material,Ideal # Replace all by newly obatined string rdf['entity_type'] = np.where(mask,all_,rdf['entity_type']) rdf action entity_type 0 recognize Material;Ideal 1 disdain Material 2 worship Ideal # Split and stack so we can make `entity_type` one dimensional rdf = rdf.set_index('action')['entity_type'].str.split(';',expand=True)\ .stack().reset_index('action').rename(columns={0:'type'}) rdf action type 0 recognize Material 1 recognize Ideal 0 disdain Material 0 worship Ideal Merge: ndf = edf.merge(rdf,on='type').rename(columns={'action':'recommendation'}) ndf name type recommendation 0 Boson Material recognize 1 Boson Material disdain 2 Atman Ideal recognize 3 Atman Ideal worship Sample run on different dataframes : edf = pd.DataFrame.from_dict([ { 'name' : 'Boson', 'type' : 'Material' }, { 'name' : 'Atman', 'type' : 'Ideal' }, { 'name' : 'Chaos', 'type' : 'Void, but emphasized' }, { 'name' : 'Tohuwabohu', 'type' : 'Void' }, ]) rdf = pd.DataFrame.from_dict([ { 'action' : 'recognize', 'entity_type' : 'ALL'}, { 'action' : 'disdain', 'entity_type' : 'Material'}, { 'action' : 'worship', 'entity_type' : 'Ideal'}, { 'action' : 'drink', 'entity_type' : 'ALL'} ]) Then: mask = rdf['entity_type']=='ALL' all_ = ';'.join(set(edf['type'])) rdf['entity_type'] = np.where(mask,all_,rdf['entity_type']) rdf = rdf.set_index('actio…
has comment: http://stackoverflow.com/comment/81902340
accepted answer of: http://stackoverflow.com/q/47472207
has comment: http://stackoverflow.com/comment/81902207
has comment: http://stackoverflow.com/comment/81921844
has comment: http://stackoverflow.com/comment/81903205
has comment: http://stackoverflow.com/comment/81922149
has comment: http://stackoverflow.com/comment/81902691
has comment: http://stackoverflow.com/comment/81922177
answers question: http://stackoverflow.com/q/47472207
type: Answer
has comment: http://stackoverflow.com/comment/81903145
has comment: http://stackoverflow.com/comment/81970051
upvote count: 3
score: 3

http://stackoverflow.com/comment/81750285
score: 0
comment on: http://stackoverflow.com/q/47398264
has text: Yes, looks like I had different numpy versions even though I had updated ... needed to restart the kernel. I sure feel stupid now, thanks for the support
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47525204
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82021087
downvote count: 0
has comment: http://stackoverflow.com/comment/82021233
favorite count: 0
accepted answer: http://stackoverflow.com/a/47525331
type: Question
has answer: http://stackoverflow.com/a/47525331
has body: I am trying to read contents of a CSV file but I get NAN for some 'reviewtext' field. I have attached my csv file. When data.head() reads all values from the file but when I try to read only specific fields with revs.head() , it gives me an error. revs.head()Image data.head()Image import pandas as pd data = pd.read_csv('Review_50.csv',sep='|',error_bad_lines=False) print data.head() revs = data.loc[:,['r_name','reviewtext','date']] print revs.head()` Reviews_50.csv
has title: Reading specific fields from a CSV file
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82006553
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82021572

http://stackoverflow.com/comment/81867250
type: AnswerComment
comment on: http://stackoverflow.com/a/47456431
score: 0
type: Comment
has text: That's great thank you. Small followups: The week should start on Sunday as the first row relates to a Sunday. Also, is it possible to only have the legend in the top subplot?

http://stackoverflow.com/a/56993693
upvote count: 1
type: AcceptedAnswer
has body: I actually found this problem as well. There is a bug in the tensorflow platform. You can solve by changing the get_step_input_shape function in the recurrent.py file. Just add [0] to the end of this line: nest.map_structure(get_input_spec, input_shape))
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47520135
answers question: http://stackoverflow.com/q/47520135
downvote count: 0

http://stackoverflow.com/comment/81868503
comment on: http://stackoverflow.com/a/47456102
score: 0
type: Comment
has text: Have you opened up the firewall on the port?, flask run their own web server so apache works as a proxy.
type: AnswerComment

http://stackoverflow.com/q/47520890
has comment: http://stackoverflow.com/comment/81998493
upvote count: 0
downvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/81998434
favorite count: 0
has answer: http://stackoverflow.com/a/47521032
type: Question
has comment: http://stackoverflow.com/comment/81998454
tagged with: numpy
has title: Error "can't multiply sequence by non-int of type 'float'"
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/81998583
tagged with: python
has body: In the following code, when I try to run the line "x01 = rk4(x01,t1[-1],h1,fallParabola)," an error pops up saying "can't multiply sequence by non-int of type 'float'." I am wondering why this is, as I thought that multiplying every term in a numpy array by a number multiplied every term in the array by that number. **slope1 and intercept1 are already defined elsewhere, so that is not an issue def rk4(f,t,h,g): k1 = h*g(t,f) k2 = h*g(t+0.5*h, f+0.5*k1) k3 = h*g(t+0.5*h, f+0.5*k2) k4 = h*g(t+h, f+k3) return f + k1/6. + k2/3. + k3/3. + k4/6. def fallParabola(t,f): g = 10 px = f[0] py = f[1] vx = f[2] vy = f[3] slope = slope1 * (px-shift1) theta = sp.arctan(np.abs(slope)) acc = np.array([vx,vy,g*sp.sin(theta)*sp.cos(theta), g*sp.sin(theta)*sp.sin(theta)]) return acc,slope x01 = np.array([0.0,intercept1,0.0,0.0]) t01 = 0. px1 = [x01[0],] py1 = [x01[1],] vx1 = [x01[2],] vy1 = [x01[3],] t1 = [t01,] h1 = 0.1 while py1[-1] &gt; 0: x01 = rk4(x01,t1[-1],h1,fallParabola) px1.append(x01[0]) py1.append(x01[1]) vx1.append(x01[2]) vy1.append(x01[3]) t1.append(t1[-1]+h1)

http://stackoverflow.com/comment/81755048
has text: @cᴏʟᴅsᴘᴇᴇᴅ nope , you can add to yours my friend ~let us make this site clear and straightforward to the answer :-)
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47400290

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/47384090
tags question: http://stackoverflow.com/q/47454771
tags question: http://stackoverflow.com/q/47441239
tags question: http://stackoverflow.com/q/47435751
tags question: http://stackoverflow.com/q/47418616
tags question: http://stackoverflow.com/q/47471817
tags question: http://stackoverflow.com/q/47392733
tags question: http://stackoverflow.com/q/47397117
tags question: http://stackoverflow.com/q/47446612
tags question: http://stackoverflow.com/q/47406740
tags question: http://stackoverflow.com/q/47538602
tags question: http://stackoverflow.com/q/47445767
tags question: http://stackoverflow.com/q/47501469
tags question: http://stackoverflow.com/q/47439243
tags question: http://stackoverflow.com/q/47424820
tags question: http://stackoverflow.com/q/47481714
tags question: http://stackoverflow.com/q/47461231
tags question: http://stackoverflow.com/q/47431178
tags question: http://stackoverflow.com/q/47396221
tags question: http://stackoverflow.com/q/47408223
tags question: http://stackoverflow.com/q/47384084
tags question: http://stackoverflow.com/q/47526387
tags question: http://stackoverflow.com/q/47450399
tags question: http://stackoverflow.com/q/47426979
tags question: http://stackoverflow.com/q/47420510
tags question: http://stackoverflow.com/q/47531854
tags question: http://stackoverflow.com/q/47466151
tags question: http://stackoverflow.com/q/47415600
tags question: http://stackoverflow.com/q/47496882
tags question: http://stackoverflow.com/q/47509358
tags question: http://stackoverflow.com/q/47404084
tags question: http://stackoverflow.com/q/47472199
type: Tag
tags question: http://stackoverflow.com/q/47445727

http://stackoverflow.com/a/47484863
answers question: http://stackoverflow.com/q/47484753
has body: replace n with n+1 n = 6 for i in range(n+1): print(' '*(n-i) + '#' * i)
score: 0
type: Answer

http://stackoverflow.com/q/47506700
tagged with: python-3.x
has title: the OK button can't be click - why?
linked to: http://stackoverflow.com/q/10629815
has answer: http://stackoverflow.com/a/47507043
answer count: 5
has comment: http://stackoverflow.com/comment/81969505
has comment: http://stackoverflow.com/comment/81969359
has answer: http://stackoverflow.com/a/47533141
tagged with: python
tagged with: webdriver
has answer: http://stackoverflow.com/a/47506914
tagged with: selenium-webdriver
type: Question
score: 0
linked to: http://stackoverflow.com/q/17676036
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47508494
linked to: http://stackoverflow.com/q/43868009
has comment: http://stackoverflow.com/comment/81973938
has answer: http://stackoverflow.com/a/47507333
linked to: http://stackoverflow.com/q/32858434
has body: The below is the id of the "Ok" button inside the popup window , just wanted to say that i was able to sendkeys and ENTER for another field inside the same popup window : OK button The exception i'm getting is: selenium.common.exceptions.ElementNotInteractableException: Message: Cannot click on element Also adding the actual GUI : actual window The code is below: def create_new_customer_iden(): browser.find_element_by_css_selector("#customer_care_app_tab &gt; tbody &gt; tr &gt; td:nth-child(2)").click() browser.find_element_by_css_selector("#add_customer &gt; td:nth-child(2)").click() browser.find_element_by_id("go_srch_button").click() random_number=random.randrange (10000, 99999) statement ='INSERT INTO sa_customer(CUSTOMER_NO, CUSTOMER_NAME) VALUES(:1, :2)' cursor.execute(statement,(random_number,random_number)) connection.commit() browser.find_element_by_name("popup_search_init_customer_id").send_keys(random_number) browser.find_element_by_name("popup_search_init_customer_id").send_keys(Keys.ENTER) # works great until here browser.find_element_by_id("ok_button").click() i found another issue : if i'm adding the below lines of code : button=browser.find_element_by_id ("ok_button") print(button) button.click() The print gives me this element: selenium.webdriver.remote.webelement.WebElement (session="75fba3d3-bef4-4800-a03d-bfbfcf831209", element="4d27c723-ed64-40a5-9da0-102a52f4d910") BUT the last line of code throws me the below exception : selenium.common.exceptions.ElementNotInteractableException: Message: Cannot click on element WHICH means that i need to find a subtitute to the click() operation. Any suggestions ???

http://stackoverflow.com/comment/81767139
comment on: http://stackoverflow.com/q/47406911
type: Comment
has text: @schwobaseggl Hah! True. The only other way is to use a try-except.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82018104
has text: I now added it as an answer as well. So if it answered your question well enough feel free to accept :)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47529887
score: 0

http://stackoverflow.com/q/47480456
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/81927302
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81916528
type: Question
has comment: http://stackoverflow.com/comment/81916447
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81917999
tagged with: python
has comment: http://stackoverflow.com/comment/81915792
has body: Recently, I've been stuck with a issue that is probably very simple to solve, but after losing hours trying to do it I've decided to ask for help. So, I have these 2 dataframes: df = pd.DataFrame({ 'AlleleID': [1, 2, 3, 4], 'Name': ['a', 'b', 'c', 'd'], 'VariationID':[[1,5,6],[2],[3,7],[4]] }) df_reviews = pd.DataFrame({ 'VariationID': [1, 1, 1, 2, 3, 3, 4, 5, 5, 6, 7], 'Stars': [1, 0, 1, 1, 1, 0, 4, 3, 1, 1, 0], 'Source': ['literature', 'clinical', 'inlab', 'inlab', 'literature', 'clinical', 'inlab', 'inlab', 'inlab',\ 'literature', 'literature'] }) The intent is for this to be applied to much larger datasets. I create as many columns as I will need to, and I fill them with zeros, adding them to the df dataset. For each row in the df_reviews dataset, I want to use the value of the VariationID column to know which row in the df dataset this one is referring to, then I want to use the other two elements of the row (the number of starts and the source) to know which column in the df I am referring to. Then I just want to increment the value by one. The goal is just to count how many entries with the different combinations of "Stars" and "Source" exist in the df_reviews dataframe for each different "AlleleID" in df, but each row in df can be connected to multiple different rows in df_reviews, since it has a list of VariationIDs. I used the following code, and I got the error "KeyError: True" star_values = df_reviews['Stars'].unique() source_values = df_reviews['Source'].unique() col_names = [] for e in star_values: for f in source_values: col_name = 'reviews_stars_%s_source_%s' % (e, f) col_names.append(col_name) col_name = 'reviews_stars_%s' % (e) col_names.append(col_name) for name in col_names: df[name] = np.zeros(len(df), dtype = int) for row in df_reviews.itertuples(index = False, name = None): col_name = 'reviews_stars_%s_source_%s' % (row[0], row[1]) df.loc[row[2] in df.VariationID,col_name] +=1 print(df) So, what I need, pretty much, is an efficient and fast wa…
has title: Python Pandas Dataframe selection using the "in" operator
has comment: http://stackoverflow.com/comment/81916420

http://stackoverflow.com/q/47503300
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47508568
has comment: http://stackoverflow.com/comment/81963426
tagged with: python
tagged with: web-crawler
upvote count: 6
type: Question
tagged with: google-crawlers
has title: Google Trend Crawler code 429 error
tagged with: google-api
answer count: 1
score: 6
tagged with: google-trends
downvote count: 0
has comment: http://stackoverflow.com/comment/81962610
accepted answer: http://stackoverflow.com/a/47508568
favorite count: 0
has body: I am new to python and using unofficial pytrends API to crawl Google Trend. I have 2000+ keywords as DNA list and try to crawl data. When I run this code, it appears with "Google returned a response with code 429" even though I added time.sleep(1). Can anyone help me with this problem? below is my code #DNA has 2000+ lists from pytrends.request import TrendReq import pandas as pd import xlsxwriter import time pytrends = TrendReq(hl='en-US,tz=360') Data = pd.DataFrame() #Google Trend Crawler for i in range(DNA[i]): time.sleep(1) kw_list = [DNA[i]] pytrends.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='', gprop='') df = pd.DataFrame(pytrends.interest_over_time()) #Setting a Google Trend Dates if(i==0): Googledate = pd.DataFrame(pytrends.interest_over_time()) Data['Date'] = Googledate.index Data.set_index('Date', inplace=True) #results if(df.empty == True): Data[DNA[i]] = "" else: df.index.name = 'Date' df.reset_index(inplace=True) Data[DNA[i]] = df.loc[:, DNA[i]] Data

http://stackoverflow.com/q/47413250
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47413916
has title: Trigger AWS Lambda through API Gateway using Proxy Integration
has answer: http://stackoverflow.com/a/47413916
has body: I am just getting started with AWS and have made a basic calculator in AWS Lambda as below: import json def lambda_handler(event, context): op1 = event.get('op1',0) op2 = event.get('op2',0) operator = event.get('op', None) if op1 == 0 or op2 == 0 or operator == None: result = 'Please enter valid input data' ret_code = 219 else: if operator in {'add', 'plus', '+'}: result = op1 + op2 ret_code = 278 elif operator in {'subtract', 'minus', '-'}: result = op1 - op2 ret_code = 278 elif operator in {'multiply', '*'}: result = op1 * op2 ret_code = 278 elif operator in {'divide', '/'}: result = op1 / op2 ret_code = 278 else: result = 'Please enter valid operator' ret_code = 219 return { 'isBase64Encoded': False, 'statusCode': ret_code, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps(result) } This function works fine when I test Lambda using the following { "op1": 7, "op2": 9, "op": "divide" } I then made an API in Amazon API Gateway and configured it to use Lambda Proxy integration, as shown in API Setup. However, now when I try and trigger the AWS Lambda through a PUT or POST through the same input data as before, I get a 219 error which means that the data isn't being passed into the Lambda event but instead Lambda is using the default zeros, giving the error. The response that I get from API Gateway is as follows: Execution log for request test-request Tue Nov 21 12:19:34 UTC 2017 : Starting execution for request: test-invoke-request Tue Nov 21 12:19:34 UTC 2017 : HTTP Method: PUT, Resource Path: / Tue Nov 21 12:19:34 UTC 2017 : Method request path: {} Tue Nov 21 12:19:34 UTC 2017 : Method request query string: {} Tue Nov 21 12:19:34 UTC 2017 : Method request headers: {} Tue Nov 21 12:19:34 UTC 2017 : Method request body before transformations: { "op1": 7, "op2": 9, "op": "divide" } Tue Nov 21 12:19:34 UTC 2017 : Endpoint request URI: https://lambda.eu-west-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-west-2:*:function:newCalc/invocations Tu…
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: python
tagged with: aws-api-gateway
tagged with: amazon-web-services
answer count: 1
tagged with: aws-lambda

http://stackoverflow.com/comment/81929596
comment on: http://stackoverflow.com/q/47487037
type: Comment
type: QuestionComment
has text: Do you want to upload image one by one and edit image one by one? Or want to upload multiple image at a time?
score: 0

http://stackoverflow.com/comment/82057409
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47521215
type: Comment
has text: Tried it, but it doesn't seem to work. Also, I do not want to add any accelerator string, just simply highlight the ampersand, which the paragraph you quoted does not into further. Thanks for the try, and the reason I did not provide a complete working example is that I felt that this was not necessary as I had hoped this specific edge case would have been encountered by someone else already (and thus would hopefully be easily resolvable).

http://stackoverflow.com/q/47409235
has answer: http://stackoverflow.com/a/47409313
has body: I have a problem on right now. I have a google spreadsheet that is responses of the questionnaire.I want to count how many men score points(5,4,3,2,1 points) for the traffic of this place and so do women. like this. How can I do ?By the way I used google api on django #All responses save in data data = pd.DataFrame(sheet.get_all_records()) #get data of traffic data['trafic'] #['5','4','3','4','2'] #get data of gender data['gender'] #['woman','man','woman','woman','man']
tagged with: python
type: AnsweredQuestion
tagged with: google-sheets
accepted answer: http://stackoverflow.com/a/47409313
answer count: 1
has title: Compare two rows on the google spreadsheet django
type: Question
score: 0

http://stackoverflow.com/comment/81935053
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47489905
has text: Can you provide a self-contained example that actually demonstrates that it fails with the `int` and works with the `//`?

http://stackoverflow.com/comment/81837349
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47441191

http://stackoverflow.com/q/47482321
has answer: http://stackoverflow.com/a/47533965
has body: I'm wondering how to use Service Account on Google App Engine standard environment. I wrote some codes like below to access BigQuery with a proper JSON key file. from google.cloud import bigquery .... bigquery_client = bigquery.Client.from_service_account_json(proper_path_to_json_key) list(bigquery_client.list_datasets()) The code works OK when I run it on a local Python interpreter but results miserably failed with the following error when it runs on local dev_appserver.py. TransportError: ('Connection aborted.', error(13, 'Permission denied')) When it runs on GAE, it still fails but its error message is like below. TransportError: ('Connection broken: IncompleteRead(208 bytes read)', IncompleteRead(208 bytes read)) I think this error is caused by GAE's restriction on outbound traffic described here https://cloud.google.com/appengine/docs/standard/python/issue-requests but I have no idea how to resolve it. What is the best way to use Service Account on GAE environment?
favorite count: 0
type: Question
tagged with: google-cloud-platform
downvote count: 0
type: UnansweredQuestion
has title: How to use service account in Python on GAE?
answer count: 1
tagged with: google-app-engine
upvote count: 3
score: 3
tagged with: service-accounts
tagged with: python

http://stackoverflow.com/q/47487523
tagged with: python
has body: First, Below is the sample line from ASM file which contains 1-2 millions lines like this: .text:0040120F 03 CA add ecx, edx .text:00401211 89 48 3C mov [eax+3Ch], ecx .text:00401214 8B 0D C4 7E 58 00 mov ecx, dword_587EC4 I want to count the Header(text) and Segments(add, mov) in each file in Spark for fast processing. I've read documentations/articles but didn't found any techniques to analyze files line by line to count only these headers, segments. After Processing the result should be: 'text': 3, 'add': 1, 'mov': 2 Is there anyway to extract only these parts from assembly files In Spark?
accepted answer: http://stackoverflow.com/a/47491758
has answer: http://stackoverflow.com/a/47491758
favorite count: 0
tagged with: scala
answer count: 1
has comment: http://stackoverflow.com/comment/81930087
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81931276
type: Question
has comment: http://stackoverflow.com/comment/81930789
type: AnsweredQuestion
score: 0
tagged with: assembly
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/81930242
has title: How to process ASM files in Spark (Python/Scala)

http://stackoverflow.com/a/47466675
downvote count: 0
has body: Try this: dict1 = {1:'a', 2:'b', 3:'c'} dict2 = {1:'d', 2:'e'} # Change the name of a key # Note this will delete the keys 1 and 2 in dict2 dict2[4] = dict2.pop(1) # Return the corresponding value dict2[5] = dict2.pop(2) # Merging the two dicts (works in Python 3.5+) result = {**dict1, **dict2} &gt;&gt;&gt; result {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} Alternatively, if you want to keep dict2 unchanged: dict1 = {1:'a', 2:'b', 3:'c'} dict2 = {1:'d', 2:'e'} for i, k in enumerate(dict2, start=len(dict1) + 1): dict1[i] = dict2[k] &gt;&gt;&gt; dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
answers question: http://stackoverflow.com/q/47466466
has comment: http://stackoverflow.com/comment/81887846
type: Answer
has comment: http://stackoverflow.com/comment/81887941
score: 2
upvote count: 2

http://stackoverflow.com/q/47429354
score: 1
accepted answer: http://stackoverflow.com/a/48944400
has title: tensorflow gpu failed init from systemd service
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52521893
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/52521893
answer count: 2
tagged with: gunicorn
linked to: http://stackoverflow.com/q/52039439
downvote count: 0
has answer: http://stackoverflow.com/a/48944400
upvote count: 1
tagged with: python
tagged with: flask
tagged with: systemd
type: AnsweredQuestion
has body: I'm trying to host flask API which is using tensorflow libraries.I installed tensorflow gpu library with CUDA and cudnn libraries.I manually checked with the following command which is working fine. /captcha/env/bin/gunicorn captcha:app -b 0.0.0.0:5124 -k gevent --worker-connections 1000 But when i add this systemd service im getting a tensorflow gpu error systemd service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] PIDFile=/run/gunicorn/pid User=root Group=root WorkingDirectory=/captcha/env ExecStart=/captcha/env/bin/gunicorn captcha:app -b 0.0.0.0:5124 -k gevent --worker-connections 1000 ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID PrivateTmp=true [Install] WantedBy=multi-user.target Error text in Log file: Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/install_sources#common_installation_problems for some common reasons and solutions. Include the entire stack trace above this error message when asking for help. Can anyone point me where I'm doing wrong?

http://stackoverflow.com/q/47530191
score: 1
linked to: http://stackoverflow.com/q/448271
tagged with: python
has title: Importing files in different directories in Python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47530371
possible better answer: http://stackoverflow.com/a/47530371
answer count: 2
tagged with: python-import
has body: I have a directory structure like this: dir/ frontend.py dir1/main.py dir2/backend.py How do I import backend in main in Python? How do I import frontend in main in Python? Have tried all the answers on Stackoverflow. Nothing seems to work.
tagged with: relative-import
downvote count: 0
tagged with: directory-structure
has comment: http://stackoverflow.com/comment/82016945
has comment: http://stackoverflow.com/comment/82017489
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/49608227
accepted answer: http://stackoverflow.com/a/49608227

http://stackoverflow.com/comment/81741859
type: Comment
has text: Well `yield` does create a generator so I'm not sure I understand the distinction you make. Of course you could trivially use a generator expression instead like `return (transform_2(transform_1(line)) for line in in_f)`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47394322

http://stackoverflow.com/comment/81845231
score: 0
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ The first row is on Sunday, then Monday and so on.
comment on: http://stackoverflow.com/q/47444578

flask
tags question: http://stackoverflow.com/q/47534219
tags question: http://stackoverflow.com/q/47454315
tags question: http://stackoverflow.com/q/47524720
tags question: http://stackoverflow.com/q/47461470
tags question: http://stackoverflow.com/q/47487850
tags question: http://stackoverflow.com/q/47433307
tags question: http://stackoverflow.com/q/47387012
tags question: http://stackoverflow.com/q/47445249
tags question: http://stackoverflow.com/q/47425271
tags question: http://stackoverflow.com/q/47519491
tags question: http://stackoverflow.com/q/47448097
tags question: http://stackoverflow.com/q/47384600
tags question: http://stackoverflow.com/q/47465163
tags question: http://stackoverflow.com/q/47518985
tags question: http://stackoverflow.com/q/47415828
tags question: http://stackoverflow.com/q/47532207
tags question: http://stackoverflow.com/q/47441899
tags question: http://stackoverflow.com/q/47530089
tags question: http://stackoverflow.com/q/47445043
tags question: http://stackoverflow.com/q/47404633
tags question: http://stackoverflow.com/q/47498415
tags question: http://stackoverflow.com/q/47504282
tags question: http://stackoverflow.com/q/47454113
tags question: http://stackoverflow.com/q/47444541
tags question: http://stackoverflow.com/q/47480045
tags question: http://stackoverflow.com/q/47481819
tags question: http://stackoverflow.com/q/47517333
tags question: http://stackoverflow.com/q/47443283
tags question: http://stackoverflow.com/q/47539265
tags question: http://stackoverflow.com/q/47482842
tags question: http://stackoverflow.com/q/47446008
tags question: http://stackoverflow.com/q/47464961
tags question: http://stackoverflow.com/q/47443370
tags question: http://stackoverflow.com/q/47407933
tags question: http://stackoverflow.com/q/47393181
tags question: http://stackoverflow.com/q/47389808
tags question: http://stackoverflow.com/q/47443714
tags question: http://stackoverflow.com/q/47449444
tags question: http://stackoverflow.com/q/47497930
tags question: http://stackoverflow.com/q/47453179
tags question: http://stackoverflow.com/q/47468835
tags question: http://stackoverflow.com/q/47502006
tags question: http://stackoverflow.com/q/47481853
tags question: http://stackoverflow.com/q/47433061
tags question: http://stackoverflow.com/q/47538967
tags question: http://stackoverflow.com/q/47480354
tags question: http://stackoverflow.com/q/47478913
tags question: http://stackoverflow.com/q/47474571
tags question: http://stackoverflow.com/q/47437704
tags question: http://stackoverflow.com/q/47420805
tags question: http://stackoverflow.com/q/47403435
tags question: http://stackoverflow.com/q/47473531
tags question: http://stackoverflow.com/q/47533601
tags question: http://stackoverflow.com/q/47490789
tags question: http://stackoverflow.com/q/47405339
tags question: http://stackoverflow.com/q/47467658
tags question: http://stackoverflow.com/q/47385053
tags question: http://stackoverflow.com/q/47491390
tags question: http://stackoverflow.com/q/47524285
tags question: http://stackoverflow.com/q/47485759
tags question: http://stackoverflow.com/q/47525351
tags question: http://stackoverflow.com/q/47425601
tags question: http://stackoverflow.com/q/47396941
tag name: flask
tags question: http://stackoverflow.com/q/47509920
tags question: http://stackoverflow.com/q/47386568
tags question: http://stackoverflow.com/q/47429354
tags question: http://stackoverflow.com/q/47526946
tags question: http://stackoverflow.com/q/47408551
tags question: http://stackoverflow.com/q/47425595
tags question: http://stackoverflow.com/q/47540445
tags question: http://stackoverflow.com/q/47413300
tags question: http://stackoverflow.com/q/47462540
tags question: http://stackoverflow.com/q/47511303
tags question: http://stackoverflow.com/q/47511463
tags question: http://stackoverflow.com/q/47501776
tags question: http://stackoverflow.com/q/47504547
tags question: http://stackoverflow.com/q/47442632
tags question: http://stackoverflow.com/q/47495775
tags question: http://stackoverflow.com/q/47390874

django
tags question: http://stackoverflow.com/q/47526570
tags question: http://stackoverflow.com/q/47465726
tags question: http://stackoverflow.com/q/47528938
tags question: http://stackoverflow.com/q/47538318
tags question: http://stackoverflow.com/q/47446612
tags question: http://stackoverflow.com/q/47473356
tags question: http://stackoverflow.com/q/47538602
tags question: http://stackoverflow.com/q/47538292
tags question: http://stackoverflow.com/q/47512227
tags question: http://stackoverflow.com/q/47530422
tags question: http://stackoverflow.com/q/47466491
tags question: http://stackoverflow.com/q/47387266
tags question: http://stackoverflow.com/q/47403118
tags question: http://stackoverflow.com/q/47517909
tags question: http://stackoverflow.com/q/47511076
tags question: http://stackoverflow.com/q/47454091
tags question: http://stackoverflow.com/q/47534145
tags question: http://stackoverflow.com/q/47415600
tags question: http://stackoverflow.com/q/47483184
tags question: http://stackoverflow.com/q/47529218
tags question: http://stackoverflow.com/q/47428004
tags question: http://stackoverflow.com/q/47460570
tags question: http://stackoverflow.com/q/47471658
tags question: http://stackoverflow.com/q/47436534
tags question: http://stackoverflow.com/q/47467395
tags question: http://stackoverflow.com/q/47448510
tags question: http://stackoverflow.com/q/47501469
tags question: http://stackoverflow.com/q/47421708
tags question: http://stackoverflow.com/q/47533323
tags question: http://stackoverflow.com/q/47472708
tags question: http://stackoverflow.com/q/47406557
tags question: http://stackoverflow.com/q/47474228
tags question: http://stackoverflow.com/q/47439243
tags question: http://stackoverflow.com/q/47525872
tags question: http://stackoverflow.com/q/47502752
tags question: http://stackoverflow.com/q/47410243
tags question: http://stackoverflow.com/q/47527443
tags question: http://stackoverflow.com/q/47444179
tags question: http://stackoverflow.com/q/47397059
tags question: http://stackoverflow.com/q/47496882
tags question: http://stackoverflow.com/q/47487578
tags question: http://stackoverflow.com/q/47476811
tags question: http://stackoverflow.com/q/47455268
tags question: http://stackoverflow.com/q/47429486
tags question: http://stackoverflow.com/q/47417158
tags question: http://stackoverflow.com/q/47389649
tags question: http://stackoverflow.com/q/47435824
tags question: http://stackoverflow.com/q/47393433
tags question: http://stackoverflow.com/q/47536176
tags question: http://stackoverflow.com/q/47433677
tags question: http://stackoverflow.com/q/47531258
tags question: http://stackoverflow.com/q/47509857
tags question: http://stackoverflow.com/q/47408081
tags question: http://stackoverflow.com/q/47407225
tags question: http://stackoverflow.com/q/47398975
tags question: http://stackoverflow.com/q/47455692
tags question: http://stackoverflow.com/q/47495215
tags question: http://stackoverflow.com/q/47399613
tags question: http://stackoverflow.com/q/47408001
tags question: http://stackoverflow.com/q/47504564
tags question: http://stackoverflow.com/q/47454273
tags question: http://stackoverflow.com/q/47384176
tags question: http://stackoverflow.com/q/47537675
tags question: http://stackoverflow.com/q/47433100
tags question: http://stackoverflow.com/q/47461225
tags question: http://stackoverflow.com/q/47477360
tags question: http://stackoverflow.com/q/47462085
tags question: http://stackoverflow.com/q/47389598
tags question: http://stackoverflow.com/q/47431178
tags question: http://stackoverflow.com/q/47475969
tags question: http://stackoverflow.com/q/47523686
tags question: http://stackoverflow.com/q/47422491
tags question: http://stackoverflow.com/q/47430027
tags question: http://stackoverflow.com/q/47397323
tags question: http://stackoverflow.com/q/47465437
tags question: http://stackoverflow.com/q/47483015
tags question: http://stackoverflow.com/q/47533450
tags question: http://stackoverflow.com/q/47513066
tags question: http://stackoverflow.com/q/47426314
tags question: http://stackoverflow.com/q/47419655

pyqt
type: Tag
tags question: http://stackoverflow.com/q/47413307
tags question: http://stackoverflow.com/q/47503984
tags question: http://stackoverflow.com/q/47539035
tags question: http://stackoverflow.com/q/47446217
tags question: http://stackoverflow.com/q/47415244
tags question: http://stackoverflow.com/q/47455234
tags question: http://stackoverflow.com/q/47449925
tags question: http://stackoverflow.com/q/47503531
tags question: http://stackoverflow.com/q/47512508
tags question: http://stackoverflow.com/q/47491386
tags question: http://stackoverflow.com/q/47395529
tags question: http://stackoverflow.com/q/47482998
tags question: http://stackoverflow.com/q/47475224
tags question: http://stackoverflow.com/q/47441374
tags question: http://stackoverflow.com/q/47393609
tags question: http://stackoverflow.com/q/47532133
tags question: http://stackoverflow.com/q/47405395
tags question: http://stackoverflow.com/q/47519734
tags question: http://stackoverflow.com/q/47393597
tags question: http://stackoverflow.com/q/47468901
tag name: pyqt
tags question: http://stackoverflow.com/q/47431119
tags question: http://stackoverflow.com/q/47448063
tags question: http://stackoverflow.com/q/47434489
tags question: http://stackoverflow.com/q/47497383
tags question: http://stackoverflow.com/q/47404344
tags question: http://stackoverflow.com/q/47384116
tags question: http://stackoverflow.com/q/47417913
tags question: http://stackoverflow.com/q/47417354
tags question: http://stackoverflow.com/q/47384578
tags question: http://stackoverflow.com/q/47529864
tags question: http://stackoverflow.com/q/47517925
tags question: http://stackoverflow.com/q/47529509
tags question: http://stackoverflow.com/q/47503169
tags question: http://stackoverflow.com/q/47513314
tags question: http://stackoverflow.com/q/47480516

http://stackoverflow.com/comment/81947462
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47496129
has text: use `root.after(milliseconds, function_name)` instead of `while` loops.
type: QuestionComment

http://stackoverflow.com/q/47502624
has answer: http://stackoverflow.com/a/47507319
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47381824
accepted answer: http://stackoverflow.com/a/47517582
possible better answer: http://stackoverflow.com/a/47507319
has answer: http://stackoverflow.com/a/47517582
tagged with: python
has comment: http://stackoverflow.com/comment/81966373
has title: Turtle Graphics - Retrieve Color of Overlapping Shapes
type: Question
has body: I have a red star partially inscribed within a purple square that contains an orange circle. I am extracting the color of the point that the user clicks on. When I click on the circle inside the square, the color that is returned is purple, not orange. The program also returns purple when I click on the part of the red star that is inside the square. How can I rectify this issue? Thank you. import turtle def border(height,color): height = float(height) length = height *(1.9) length = round(length,2) # Draws a rectangle. turtle.begin_fill() turtle.color(color) turtle.down() turtle.forward(length) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.forward(length) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.end_fill() def big_shape(vertices, steps, length): turtle.color("red") turtle.begin_fill() for i in range(vertices): turtle.forward(length) turtle.right(steps*360.0/vertices) turtle.end_fill() def textbox_click(rawx,rawy): turtle.up() turtle.setposition(rawx,rawy) turtle.down() rawy = -rawy canvas = turtle.getcanvas() canvas.pack(fill="both", expand=True) ids = canvas.find_overlapping(rawx, rawy, rawx, rawy) if ids: # if list is not empty index = ids[0] color = canvas.itemcget(index, "fill") if color != '': print(color.lower()) def getcoordinates(): turtle.onscreenclick(turtle.goto) turtle.onscreenclick(modifyglobalvariables) # Here's the change! turtle.onscreenclick(textbox_click) def modifyglobalvariables(rawx,rawy): global xclick global yclick xclick = int(rawx//1) yclick = int(rawy//1) print(xclick) print(yclick) def main(): border(150,"purple") turtle.begin_fill() turtle.down() turtle.color("purple") turtle.up() # Creates the big shape x1=150 y1=3 turtle.setposition(x1,y1) big_shape(5,2,50) turtle.begin_fill() turtle.down() turtle.up() # Circle x1=70 y1=-107 turtle.setposition(x1,y1) turtle.begin_fill() turtle.circle(50) turtle.color("orange") turtle.end_fill() getcoordinates() turtle.done() main()
score: 0
answer count: 2
tagged with: tkinter
tagged with: turtle-graphics

http://stackoverflow.com/comment/81978162
type: AnswerComment
has text: @CHANDRAMURUGAN What does `df['Name'].isnull().sum()` display?
score: 0
comment on: http://stackoverflow.com/a/47511103
type: Comment

http://stackoverflow.com/comment/82000149
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/145270/calling-c-c-from-python
comment on: http://stackoverflow.com/q/47520712
score: 1

http://stackoverflow.com/a/47499051
upvote count: 9
has comment: http://stackoverflow.com/comment/81953734
type: Answer
has comment: http://stackoverflow.com/comment/81953694
answers question: http://stackoverflow.com/q/47498920
score: 9
has body: Or something like .values and .values.T df1=df.set_index('ID') df1.values+df1.values.T Out[626]: array([[ 8, 7, 4, 6, 13, 9, 7], [ 7, 6, 3, 5, 12, 8, 6], [ 4, 3, 0, 2, 9, 5, 3], [ 6, 5, 2, 4, 11, 7, 5], [13, 12, 9, 11, 18, 14, 12], [ 9, 8, 5, 7, 14, 10, 8], [ 7, 6, 3, 5, 12, 8, 6]], dtype=int64) More info : pd.DataFrame(data=df1.values+df1.values.T,index=df.index,columns=df.index) Out[627]: ID a b c d e f g ID a 8 7 4 6 13 9 7 b 7 6 3 5 12 8 6 c 4 3 0 2 9 5 3 d 6 5 2 4 11 7 5 e 13 12 9 11 18 14 12 f 9 8 5 7 14 10 8 g 7 6 3 5 12 8 6
downvote count: 0
has comment: http://stackoverflow.com/comment/81954656

kivy-language
tags question: http://stackoverflow.com/q/47416625
type: Tag
tags question: http://stackoverflow.com/q/47526503
tags question: http://stackoverflow.com/q/47416081
tags question: http://stackoverflow.com/q/47481919
tags question: http://stackoverflow.com/q/47489567
tags question: http://stackoverflow.com/q/47419232
tags question: http://stackoverflow.com/q/47399358
tags question: http://stackoverflow.com/q/47434756
tags question: http://stackoverflow.com/q/47514431
tags question: http://stackoverflow.com/q/47499851
tag name: kivy-language
tags question: http://stackoverflow.com/q/47486533
tags question: http://stackoverflow.com/q/47409112
tags question: http://stackoverflow.com/q/47524060
tags question: http://stackoverflow.com/q/47451868
tags question: http://stackoverflow.com/q/47534067
tags question: http://stackoverflow.com/q/47387293
tags question: http://stackoverflow.com/q/47473390
tags question: http://stackoverflow.com/q/47389711
tags question: http://stackoverflow.com/q/47396563
tags question: http://stackoverflow.com/q/47525588
tags question: http://stackoverflow.com/q/47487038
tags question: http://stackoverflow.com/q/47481540
tags question: http://stackoverflow.com/q/47455600
tags question: http://stackoverflow.com/q/47499259

http://stackoverflow.com/q/47402773
score: 0
tagged with: typeerror
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/81759843
type: Question
tagged with: numpy
tagged with: pearson
has body: This will be maybe quite personal question but I don't know who to ask I hope somebody can help and don't skip me THANKS!. I have installed python using Anaconda and using Jupyter notebook. I have 2 csv files of data. products.head() ID_FUPID FUPID 0 1 674563 1 2 674597 2 3 674606 3 4 694776 4 5 694788 Products contain id of product and product number. ratings.head() ID_CUSTOMER ID_FUPID RATING 0 1 216 1 1 2 390 1 2 3 851 5 3 4 5897 1 4 5 9341 1 Ratings containt id of customer, productID and Rating which customer give to product. I have created table as: M = ratings.pivot_table(index=['ID_CUSTOMER'],columns=['ID_FUPID'],values='RATING') Which is showing data correctly in matrix with productID= columns and customerID as rows. I wanted to count pearson colleration between products so here is the pearson function: def pearson(s1, s2): import numpy as np """take two pd.series objects and return a pearson correlation""" s1_c = s1 - s1.mean() s2_c = s2 - s2.mean() return np.sum(s1_c * s2_c) / np.sqrt(np.sum(s1_c ** 2) * np.sum(s2_c ** 2)) When I'm trying to count pearson(M['17'], M['21']) I got following errors: 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) 2441 try: -&gt; 2442 return self._engine.get_loc(key) 2443 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: '17' 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() p…
tagged with: python
accepted answer: http://stackoverflow.com/a/47403884
has title: Numpy TypeError: an integer is required
has answer: http://stackoverflow.com/a/47403884
type: AnsweredQuestion

http://stackoverflow.com/q/47423359
has comment: http://stackoverflow.com/comment/81801895
has comment: http://stackoverflow.com/comment/86744825
score: 0
answer count: 0
has title: pip install ez-setup is giving python setup.py egg_info error
tagged with: pip
type: Question
type: UnansweredQuestion
has body: I'm running into the following error when trying to run pip install ez_setup: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/wb/z3f0rbyx7pj5zz_3pj5dkq5h0000gp/T/pip-build-HZDM61/ez-setup/ Whenever I run pip install -U pip setuptools, it says that everything is up to date Anyone know how I can fix this?
tagged with: python

http://stackoverflow.com/q/47480357
has comment: http://stackoverflow.com/comment/81915611
answer count: 0
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I've got the following data set - The issue with this data set is the cols F:J aren't consistent as you can see the days are upper case for 2 columns and lower case for the other. The desired output is below: I did originally post this question in a different post but once I noticed the discrepancies I was advised to ask the question again in a new post - Best way to Pivot/Rotate Data Set
linked to: http://stackoverflow.com/q/47478559
has comment: http://stackoverflow.com/comment/81915555
type: UnansweredQuestion
tagged with: python
has title: Transpose and Pivot with conditions
tagged with: python-2.7

http://stackoverflow.com/q/47529558
tagged with: matplotlib
downvote count: 0
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/47532603
has body: I am working on a project on which I want to select an area on an image in order to do some treatments on this area. So I found this wonderful tool RectangleSelector of matplotlib. But what I want is setting the rectangle at an initial position on the image, instead of waiting for the user clicking a first area (for example a rectangle of 10x10 pixels on top/left of the image). At first I thought I have to use state_modifier_keys but it doesn't seem to be this. So, is it possible ? An example (with plots but it is the same question) can be: from __future__ import print_function from matplotlib.widgets import RectangleSelector import numpy as np import matplotlib.pyplot as plt def line_select_callback(eclick, erelease): 'eclick and erelease are the press and release events' x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print("(%3.2f, %3.2f) --&gt; (%3.2f, %3.2f)" % (x1, y1, x2, y2)) print(" The button you used were: %s %s" % (eclick.button, erelease.button)) def toggle_selector(event): print(' Key pressed.') if event.key in ['Q', 'q'] and toggle_selector.RS.active: print(' RectangleSelector deactivated.') toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.RS.active: print(' RectangleSelector activated.') toggle_selector.RS.set_active(True) fig, current_ax = plt.subplots() # make a new plotting range N = 100000 # If N is large one can see x = np.linspace(0.0, 10.0, N) # improvement by use blitting! plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5) plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3) print("\n click --&gt; release") # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector(current_ax, line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.connect('key_press_event', toggle_sele…
tagged with: python
score: 4
type: AnsweredQuestion
has title: Matplotlib rectangleSelector - Set initial position
possible better answer: http://stackoverflow.com/a/69032608
accepted answer: http://stackoverflow.com/a/47532603
tagged with: rectangles
has answer: http://stackoverflow.com/a/69032608

http://stackoverflow.com/comment/82035882
score: 0
has text: It's not entirely clear to me what you are trying to do. As a general rule, message brokers are not to be used for file transfer. Indeed, any message larger than around 100K tends to gum things up. So- is this a message broker problem, or a Python problem? My thought: create messages pointing to the location of the files, and then your consumers perform the task directed at them via the messages.
type: QuestionComment
comment on: http://stackoverflow.com/q/47539357
type: Comment

http://stackoverflow.com/q/47507379
has body: According to cloud datastore documentation for field type TextProperty there shouldn't be any restriction on size but in my case it's giving below error for string size equal to The value of property "{my_field_name}" is longer than 1048487 bytes Below is my entity class class History(ndb.Model): user_mail = ndb.StringProperty() json_string = ndb.TextProperty(indexed=False) updated_date = ndb.DateTimeProperty() This is function from where I am trying to store the entity def store_user_mail(user_email, json_object): # string size for which this is creating problem is around 1.56Mb print(sys.getsizeof(json.dumps(json_object))) user_mail_obj = History() user_mail_obj.user_mail = user_email user_mail_obj.json_string = json.dumps(json_object) user_mail_obj.updated_date = datetime.datetime.utcnow() user_mail_obj.put() Also I have tried compression of the json string before storing but that would create problem for us because we want to store this as text property not as binary data. Also point is as my json_string field is TextProperty type it should be stored without any issue irrespective of size of string. Have already spent a lot of time figuring out solution. Is there something which I am doing wrong here or is this bug with NDB or datastore and if that's the case what can be a good solution ?
has comment: http://stackoverflow.com/comment/81971534
favorite count: 0
has title: PYTHON-The value of property "{field_name}" is longer than 1048487 bytes for TextProperty in datastore
has answer: http://stackoverflow.com/a/47559435
possible better answer: http://stackoverflow.com/a/47559435
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47518816
has comment: http://stackoverflow.com/comment/82005747
downvote count: 0
has comment: http://stackoverflow.com/comment/81971597
has comment: http://stackoverflow.com/comment/81971292
has comment: http://stackoverflow.com/comment/81971476
type: Question
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/47518816
tagged with: google-cloud-datastore
tagged with: google-app-engine
tagged with: app-engine-ndb
tagged with: python

http://stackoverflow.com/q/47428016
type: Question
has comment: http://stackoverflow.com/comment/81810842
score: 0
has comment: http://stackoverflow.com/comment/81810730
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81810704
has comment: http://stackoverflow.com/comment/81814068
has title: Memory Issue While reading zip file from S3 using Python(boto3 package)
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/81810770
has body: Please find the code snippet s3_resource = boto3.resource('s3', aws_access_key_id = 'XXXXXXX', aws_secret_access_key = 'XXXXX') file = s3_resource.Object('xxxxxx',filePath).get() with io.BytesIO(file['Body'].read()) as t: t.seek(0) with ZipFile(t, 'r') as myzip: The file is a compressed zip file. I am getting memory error at (with io.BytesIO(file['Body'].read()) as t:) Is there an efficient was of reading the compressed zip file from S3 using boto3 package in python
tagged with: python
has comment: http://stackoverflow.com/comment/81810496
tagged with: boto3

http://stackoverflow.com/q/47529094
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has title: cvs merge error
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82015924
has body: I have a csv data (converted from xlsx to csv but with wordwrap, don't know how to get every xlsx-row as csv-line without wordwrap of cells) like this: 1099411,wlan: Possible leakage of original sequence numbers and source address of probe request frames affecting user privacy (Applicable to Android O or later) [FW],WConnect,WLAN Embedded SW,High,AdjacentNetwork,CWE-330 Use of Insufficiently Random Values,"The original mac spoofing feature does not use the following in probe request frames: (a) randomized sequence numbers and (b) randomized source address for cfg80211 scan, vendor scan and pno scan which may affect user privacy.","Turn ON the Wi-Fi and sniff the probe requests to find out the following: (a) incremental (non-randomized) sequence numbers and (b) original MAC address of the device",Publicly known,None,None,"Mac randomization refers to the randomization of probe request source address and sequence numbers. This change implements Mac randomization to randomize probe request&amp;#39;s source MAC address and sequence number in host, vendor and pno scans to maintain / improve user&amp;#39;s privacy. The change requires the framework (Android O or later) to actually set this feature","wlan_framegen.c wlan_framegen.h wlan_mgmt_local_txrx.c wlan_mgmt_local_txrx.h wlan_rtt.c wlan_rtt.h wlan_scan.c wlan_scan_priv.h wlan_scan_sm.c wlan_vdev_keepalive.c",None,None 1079713,Buffer overflow vulnerability in ioctl V4L2_CID_PRIVATE_IRIS_SET_SPURTABLE,WConnect,FMHost,High,Local,CWE-120 Buffer Copy Without Checking Size of Input ('Classic Buffer Overflow'),"If larger than expected data is set by the user in SpurTableFile.txt, during the copy_from_user call in ioctl V4L2_CID_PRIVATE_IRIS_SET_SPURTABLE, a buffer overflow in kernel memory occurs.","1. Configure /etc/fm/SpurTableFile.txt file with more than expected data. 2. Launch FM app.","CVE-2016-5345, ANDROID-32639452 Reported by Aravind Machiry, an external researcher, to ASUS, who reported it to us. We thank them for …
has answer: http://stackoverflow.com/a/47531964
upvote count: 0
has comment: http://stackoverflow.com/comment/82015633
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82014923
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82014621
has comment: http://stackoverflow.com/comment/82016358

http://stackoverflow.com/q/47454039
has comment: http://stackoverflow.com/comment/81862775
score: -2
has comment: http://stackoverflow.com/comment/81862872
tagged with: python
has body: So far, I have the generator working but I can't get the tkinter to display the variable for the generated password, it only comes up in the console. Once I have the password checker working as well, I need that to be able to change variable as well, please help, here is a copy of my code from tkinter import * import tkinter as tk from tkinter import font as tkfont import random import time global strength global gen strength = 0; gen = '[password will be here]'; global mypw mypw = ''; def generate(): alphabet = "abcdefghijklmnopqrstuvwxyz" pw_length = 8 mypw = "" for i in range(pw_length): next_index = random.randrange(len(alphabet)) mypw = mypw + alphabet[next_index] # replace 1 or 2 characters with a number for i in range(random.randrange(1,3)): replace_index = random.randrange(len(mypw)//2) mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:] # replace 1 or 2 letters with an uppercase letter for i in range(random.randrange(1,3)): replace_index = random.randrange(len(mypw)//2,len(mypw)) mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:] print(mypw) gen = mypw; class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne, PageTwo): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. frame.grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage") def show_fr…
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81862637
has title: Trying to code a password checker and generator using Tkinter
answer count: 1
downvote count: 3
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47454733
accepted answer: http://stackoverflow.com/a/47454733
type: Question

http://stackoverflow.com/comment/81796274
has text: Circular import is happening! Putting import statement inside a function is called "defer importing".
type: QuestionComment
comment on: http://stackoverflow.com/q/47421003
score: 0
type: Comment

http://stackoverflow.com/comment/81804023
type: AnswerComment
comment on: http://stackoverflow.com/a/47424477
type: Comment
has text: I am trying to replicate this [code](https://stackoverflow.com/questions/42192133/embedding-matplotlib-live-plot-data-from-arduino-in-tkinter-canvas ) only Id like to have it in a class type format.
score: 0

http://stackoverflow.com/q/47397919
type: UnansweredQuestion
has body: I have a special URL where my code is halting for hours (more than 3 hours). I can't seem to understand why it would do that. The URL is http://www.etudes.ccip.fr/maintenance_site.php. Direct requests.get() works instantaneously but whenever I have an HTTPAdapter, the code seems to sleep almost indefinitely import requests from requests.adapters import HTTPAdapter url = 'http://www.etudes.ccip.fr/maintenance_site.php' session = requests.Session() session.mount('http://', HTTPAdapter(max_retries=2)) session.get(url, timeout=2)
score: 18
tagged with: python
has answer: http://stackoverflow.com/a/47462182
upvote count: 18
has comment: http://stackoverflow.com/comment/81869810
answer count: 3
tagged with: urllib3
downvote count: 0
has answer: http://stackoverflow.com/a/47457580
tagged with: python-requests
has title: Python requests with HTTPAdapter is halting for hours
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81860643
has answer: http://stackoverflow.com/a/47453480

http://stackoverflow.com/a/47496509
has body: Maybe all you need is to drop the duplicate index after concatenating by keeping only the first one i.e alldates = pd.concat([dates1,dates2,dates3,dates4], axis=0).dropna() alldates = alldates.loc[~alldates.index.duplicated(keep='first')] print(alldates) month day year 0 4 20 2009 1 4 20 9 2 4 20 9 3 4 3 9 4 Mar 20 2009 5 Mar 20 2009 6 Mar 20 2009 7 Mar 20 2009 8 Mar 20 2009 In case you are trying to fill the nan values from other dataframes then you can use adf = df.fillna(df2) For more than two dataframes l = [dates1,dates2] for i in range(len(l)-1): ndf = l[i] ndf = ndf.fillna(l[i+1])
answers question: http://stackoverflow.com/q/47496261
has comment: http://stackoverflow.com/comment/81948273
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81948792
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81948417
accepted answer of: http://stackoverflow.com/q/47496261
type: Answer

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

http://stackoverflow.com/q/47499665
accepted answer: http://stackoverflow.com/a/47499873
has answer: http://stackoverflow.com/a/47540981
possible better answer: http://stackoverflow.com/a/47540981
type: Question
has title: Pygame sprites escaping border
has comment: http://stackoverflow.com/comment/81955036
answer count: 2
has answer: http://stackoverflow.com/a/47499873
tagged with: python
tagged with: pygame
has body: I am making a survival-based rpg game, but when I move the player sprite it would move out of the wall. I implemented a basic function to prevent this from happening, and it works. if player.rect.x&lt;0: player.rect.x=0 if player.rect.x&gt;total_level_width: player.rect.x=total_level_width if player.rect.y&lt;0: player.rect.y=0 if player.rect.y&gt;total_level_height: player.rect.y=total_level_height It prevents the player sprite from moving out of the walls, but the sprite can still pass through the bottom and right walls. Any help is welcome! Thank you! Full code: import pygame import random black=(0,0,0) white=(255,255,255) green=(0,128,0) skin=(255,224,189) class Player(pygame.sprite.Sprite): def __init__(self,x,y): super(Player,self).__init__() self.image=pygame.Surface([25, 25]) self.image.fill(skin) self.rect=self.image.get_rect() self.rect.x=x self.rect.y=y self.change_x=0 self.change_y=0 self.speed=7 def changespeed(self,x,y): self.change_x += x self.change_y += y def update(self): self.rect.x += self.change_x self.rect.y += self.change_y class Tree(pygame.sprite.Sprite): def __init__(self,x,y): super(Tree,self).__init__() self.image=pygame.Surface([40, 40]) pygame.draw.circle(self.image,green,(x,y),30,10) self.image.fill(green) self.rect=self.image.get_rect() self.rect.x=x self.rect.y=y self.wood=20 def update(self): pass class Camera(object): def __init__(self,camera_func,width,height): self.camera_func=camera_func self.state=pygame.Rect(0,0,width,height) def apply(self,target): return target.rect.move(self.state.topleft) def update(self,target): self.state=self.camera_func(self.state,target.rect) def complex_camera(camera, target_rect): l,t,_, _=target_rect _,_, w, h=camera l,t,_,_=-l+screen_width/2, -t+screen_height/2, w, h l = min(0, l) l = max(-(camera.width-screen_width), l) t = max(-(camera.height-screen_height), t) t = min(0, t) return pygame.Rect(l, t, w, h) pygame.init() screen_width=800 screen_height=600 screen=pygame.display.set_mode([screen_wid…
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47469961
type: Answer
has body: You run python waf configure to configure the project. After that a variant is build with the commands build_a and build_b def configure(ctx): load('compiler_c') def build(bld): if not bld.variant: bld.fatal('call "waf build_a" or "waf build_b", and try "waf --help"') if bld.variant == 'a': bld.program(source='a.c', target='app', includes='.') elif bld.variant == 'b': bld.program(source='b.c', target='app', includes='.') else: bld.fatal('"') # create build and clean commands for each build context from waflib.Build import BuildContext, CleanContext for x in 'a b'.split(): for y in (BuildContext, CleanContext): name = y.__name__.replace('Context','').lower() class tmp(y): __doc__ = '''executes the {} of {}'''.format(name, x) cmd = name + '_' + x variant = x
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47396160
accepted answer of: http://stackoverflow.com/q/47396160
upvote count: 1
score: 1

unicode
tags question: http://stackoverflow.com/q/47394521
tags question: http://stackoverflow.com/q/47417345
tags question: http://stackoverflow.com/q/47481479
tag name: unicode
type: Tag
tags question: http://stackoverflow.com/q/47397583
tags question: http://stackoverflow.com/q/47492546
tags question: http://stackoverflow.com/q/47459441
tags question: http://stackoverflow.com/q/47469201
tags question: http://stackoverflow.com/q/47450032
tags question: http://stackoverflow.com/q/47485684
tags question: http://stackoverflow.com/q/47434283

http://stackoverflow.com/q/47413341
has body: Let's say I have two list of dictionary like below: FeeDict = [{u'100': u'Booking Fee'}, {u'101': u'Penalty Fee'}] ChargeObj = ([{'ChargeAmount': 50.0, 'KeyCharge': u'101'}, {'ChargeAmount': 150.0, 'KeyCharge': u'100'}], [{'PromotionAmount': 0.0, 'KeyCharge': u'101'}, {'PromotionAmount': 0.0, 'KeyCharge': u'100'}], [{'TotalCharge': 200.0, 'TotalPromotion': 0.0}]) I tried to get key value of both variables and arrange it just like below: Booking Fee : 150.0 Penalty Fee : 50.0 So I tried my code in jinja2 like this: &lt;table&gt; {% for row in ChargeObj %} {% set key = row[0]['KeyCharge']|string %} &lt;!-- 100 or 101 --&gt; {% set desc = FeeDict[0][key] %} &lt;!-- Booking Fee or Penalty Fee --&gt; {% set amt = row[0]['ChargeAmount'] %} &lt;tr&gt; &lt;td&gt;{{desc}}&lt;/td&gt; &lt;td&gt;{{amt}}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; The problem is that FeeDict[0][key] not return a value as I expected above. However, it will return value if I assigned fixed key to it say FeeDict[0]['100'], but why not key from FeeDict ? I thought probably that key required be to a string not number so I tried row[0]['KeyCharge']|string but still not help. What's wrong with that? How can I fix it? Thanks
has comment: http://stackoverflow.com/comment/81781210
tagged with: jinja2
has comment: http://stackoverflow.com/comment/81781366
has comment: http://stackoverflow.com/comment/81786295
has comment: http://stackoverflow.com/comment/81781623
tagged with: python
type: Question
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81781635
has title: Cannot get Key Value of Dictionary in Jinja2 Template
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81781460
has comment: http://stackoverflow.com/comment/81781834

http://stackoverflow.com/a/47511134
answers question: http://stackoverflow.com/q/47510091
type: Answer
has body: This is the python script to do that . import re data=open("myfile.txt","r").read() listinput=['a','b','c'] for i in listinput: changed_data=re.sub("x file",i+" file",data) fp2=open("myfile"+i+".txt","w") fp2.write(changed_data) fp2.close()
accepted answer of: http://stackoverflow.com/q/47510091
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/47385352
has title: Should you deploy django with wsgi?
possible better answer: http://stackoverflow.com/a/47385482
answer count: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81723934
has answer: http://stackoverflow.com/a/47385482
has answer: http://stackoverflow.com/a/47389227
favorite count: 0
type: Question
tagged with: network-programming
tagged with: server
has comment: http://stackoverflow.com/comment/81746360
tagged with: wsgi
downvote count: 0
tagged with: django
tagged with: python
has body: Do you need to deploy django with wsgi? I am running Django on a Docker instance and it seems like often the recommended solution is just to use Django's development server, i.e. the command python manage.py runserver. When exactly is a web server such as wsgi needed -- and in this instance, in a containerized application, is the django development server enough for production applications?
accepted answer: http://stackoverflow.com/a/47385443
has answer: http://stackoverflow.com/a/47385443
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/47495089
has body: Here you have an recursive approach for this equation, to give you an idea what I meant in my comment. class Slope: def __init__(self, timestamp, slope): self.timestamp = timestamp self.slope = slope def find_slope(slopes, slope, step_size, until): if slope.timestamp &gt; until: return slopes current_y = slope.slope + step_size * slope.slope slope = Slope(slope.timestamp + 1, current_y) slopes.append(slope) return find_slope(slopes, slope, step_size, until) if __name__=="__main__": initial_slope = Slope(0, 1) for current in find_slope([], initial_slope, 1, 3): print("slope: {slope}, timestamp: {timestamp}".format(**current.__dict__)) But there multiple ways to solve this problem e.g. with a while or a for loop. I also have to admit you could write a shorter version but I think the verbosity helps you better understand. Edit Your eyes should focus on that function... def find_slope(slopes, slope, step_size, until): if slope.timestamp &gt; until: return slopes current_y = slope.slope + step_size * slope.slope slope = Slope(slope.timestamp + 1, current_y) slopes.append(slope) return find_slope(slopes, slope, step_size, until) This is a recursive call or simpler a function that calls itself as long as a certain point is reached here it is if slope.timestamp &gt; until. The first call is with my initial_slope (step_size and until are just constants). The line current_y = slope.slope + step_size * slope.slope calculates the new slope value. Then I create a slope instance with the new slope value and updated time and add it to a list. The slope instance, the slope list and the constants are passed into the next step with a self call of the function return find_slope(slopes, slope, step_size, until). The return is needed to not only go down the ladder and collect new slopes but also return back to the start so the caller can receive it. You can call the recursive function with slopes = find_slope([], initial_slope, 1, 3) and get a list of slopes back. I initialized it with …
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/81948352
has comment: http://stackoverflow.com/comment/81947016
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47494670

pandas
tags question: http://stackoverflow.com/q/47403696
tags question: http://stackoverflow.com/q/47416113
tags question: http://stackoverflow.com/q/47425428
tags question: http://stackoverflow.com/q/47459474
tags question: http://stackoverflow.com/q/47436867
tags question: http://stackoverflow.com/q/47501684
tags question: http://stackoverflow.com/q/47470501
tags question: http://stackoverflow.com/q/47515357
tags question: http://stackoverflow.com/q/47445364
tags question: http://stackoverflow.com/q/47463481
tags question: http://stackoverflow.com/q/47536793
tags question: http://stackoverflow.com/q/47384019
tags question: http://stackoverflow.com/q/47382887
tags question: http://stackoverflow.com/q/47525521
tags question: http://stackoverflow.com/q/47507405
tags question: http://stackoverflow.com/q/47515485
tags question: http://stackoverflow.com/q/47535547
tags question: http://stackoverflow.com/q/47511511
tags question: http://stackoverflow.com/q/47383980
tags question: http://stackoverflow.com/q/47457312
tags question: http://stackoverflow.com/q/47417432
tags question: http://stackoverflow.com/q/47510766
tags question: http://stackoverflow.com/q/47421043
tags question: http://stackoverflow.com/q/47480262
tags question: http://stackoverflow.com/q/47392758
tags question: http://stackoverflow.com/q/47484166
tags question: http://stackoverflow.com/q/47455709
tags question: http://stackoverflow.com/q/47499676
tags question: http://stackoverflow.com/q/47475618
tags question: http://stackoverflow.com/q/47402773
tags question: http://stackoverflow.com/q/47523960
tags question: http://stackoverflow.com/q/47480276
tags question: http://stackoverflow.com/q/47505790
tags question: http://stackoverflow.com/q/47522665
tags question: http://stackoverflow.com/q/47441456
tags question: http://stackoverflow.com/q/47477722
tags question: http://stackoverflow.com/q/47465609
tags question: http://stackoverflow.com/q/47523741
tags question: http://stackoverflow.com/q/47495896
tags question: http://stackoverflow.com/q/47517983
tags question: http://stackoverflow.com/q/47518628
tags question: http://stackoverflow.com/q/47427314
tags question: http://stackoverflow.com/q/47400775
tags question: http://stackoverflow.com/q/47437966
tags question: http://stackoverflow.com/q/47481944
tags question: http://stackoverflow.com/q/47406787
tags question: http://stackoverflow.com/q/47461781
tags question: http://stackoverflow.com/q/47440077
tags question: http://stackoverflow.com/q/47441147
tags question: http://stackoverflow.com/q/47444332
tags question: http://stackoverflow.com/q/47498667
tags question: http://stackoverflow.com/q/47482009
tags question: http://stackoverflow.com/q/47518403
tags question: http://stackoverflow.com/q/47420629
tags question: http://stackoverflow.com/q/47392579
tags question: http://stackoverflow.com/q/47413540
tags question: http://stackoverflow.com/q/47447589
tags question: http://stackoverflow.com/q/47386523
tags question: http://stackoverflow.com/q/47511048
tags question: http://stackoverflow.com/q/47514330
tags question: http://stackoverflow.com/q/47515899
tags question: http://stackoverflow.com/q/47540548
tags question: http://stackoverflow.com/q/47531615
tags question: http://stackoverflow.com/q/47505092
tags question: http://stackoverflow.com/q/47383584
tags question: http://stackoverflow.com/q/47493007
tags question: http://stackoverflow.com/q/47490576
tags question: http://stackoverflow.com/q/47470441
tags question: http://stackoverflow.com/q/47491733
tags question: http://stackoverflow.com/q/47405541
tags question: http://stackoverflow.com/q/47395061
tags question: http://stackoverflow.com/q/47480846
tags question: http://stackoverflow.com/q/47439943
tags question: http://stackoverflow.com/q/47496511
tags question: http://stackoverflow.com/q/47461927
tags question: http://stackoverflow.com/q/47444958
tags question: http://stackoverflow.com/q/47516935
tags question: http://stackoverflow.com/q/47469996
tags question: http://stackoverflow.com/q/47529735
tags question: http://stackoverflow.com/q/47424075

http://stackoverflow.com/a/47613826
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47509597
has body: In case you are using discord.py, check out this example scripts: https://github.com/Rapptz/discord.py/blob/async/examples/reply.py @client.event async def on_message(message): if message.content.startswith('!hello'): msg = 'Hello {0.author.mention}'.format(message) await client.send_message(message.channel, msg) If you want to add more commands it would be better to use the @*.command() decorator, see the other examples for that. Basically the decorator version for the example above should look like this: bot = commands.Bot(command_prefix='!') @bot.command(pass_context=True) async def hello(ctx): """Answers a !hello command""" msg = 'Hello {0.author.mention}'.format(ctx.message) await bot.say(msg)
score: 0
answers question: http://stackoverflow.com/q/47509597

http://stackoverflow.com/comment/81873810
type: QuestionComment
comment on: http://stackoverflow.com/q/47459303
has text: Why when you do the lookups on `[1, 3, 5]` is the expected result `[1, 3, 3]` instead of `[0, 2, 2]`? We normally use zero-based indexing in Python.
score: 0
type: Comment

http://stackoverflow.com/q/47472489
has title: Python - ffmpeg (commands to start, stop recording)
score: 1
downvote count: 0
answer count: 1
tagged with: cmd
upvote count: 1
tagged with: command
favorite count: 0
type: Question
tagged with: ffmpeg
accepted answer: http://stackoverflow.com/a/47473075
has answer: http://stackoverflow.com/a/47473075
tagged with: python
type: AnsweredQuestion
has body: I need a programme that would open cmd and have a command to start recording in cmd and to stop recording in cmd import win32com.client from datetime import datetime import time shell = win32com.client.Dispatch("WScript.Shell") shell.run("cmd") #run's command panel shell.AppActivate("cmd") time.sleep(3) #wait's 3 seconds shell.SendKeys('ffmpeg -y -f dshow -i video="Logitech HD Webcam C270" kamera.mp4') #type's in cmd the following (start's recording) time.sleep(3) shell.SendKeys("{ENTER}") #enter is pressed in cmd time.sleep(6) shell.SendKeys('exit') shell.SendKeys("{ENTER}") #here is a problem, the proggrame wont shutdown after 6 sec I could use -t 00:00:03 in ffmpeg, but I need to close the programme by command

http://stackoverflow.com/a/47458902
upvote count: 1
downvote count: 1
has body: I think Pip installed your package for Python3. That's why your python can't find Numpy If you want to use NumPy for Python2 you must install directly 1.13.3 cp27 version, or you must install Python3. You can check NumPy and Python versions here. https://pypi.python.org/pypi/numpy My personal advice is to use Python3. It's not a good time to use Python2 I think. You can check some resources https://wiki.python.org/moin/Python2orPython3 http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html https://www.activestate.com/blog/2017/01/python-3-vs-python-2-its-different-time
type: Answer
has comment: http://stackoverflow.com/comment/81872605
has comment: http://stackoverflow.com/comment/81872861
score: 0
answers question: http://stackoverflow.com/q/47458833

http://stackoverflow.com/a/47515348
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47515111
has body: Can be solved f.e. like this: use an innner list that you fill and return it: def collataz(number): def collataz(number, all_nums): # if you ever encounter a number that does not converge to 1 # you'll get no output and will miss the chance to get famous # this will run till 1 then return the list. But thats what it # is about (the conjecture) while True: all_nums.append(number) if number % 2 == 0 : number = number //2 elif number % 2 ==1 : number = 3 * number + 1 if number == 1: all_nums.append(1) return all_nums rv = [] # start with empty list and collataz(number,rv) # run the inner func return rv # return list print('enter any number...!') number=int(input()) alls = collataz(number) print(alls) Output (for 678 as input): [678, 339, 1018, 509, 1528, 764, 382, 191, 574, 287, 862, 431, 1294, 647, 1942, 971, 2914, 1457, 4372, 2186, 1093, 3280, 1640, 820, 410, 205, 616, 308, 154, 77, 232, 116, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] You cannot run it for all numberts till infinity - reason being : limitation by usable numbers (int,long, ...) possible in python with give you a hard maximal bound of "intermediate" numbers the conjecture may be able to reach limitation by your lifetime - theres bound to be more numbers to check then you have nanoseconds times atoms in you limitation by your PCs ram, energy etc. You can try it for many numbers: aVeryHighNumber = 1000000 alltimesMax = (1,[1]) for numbr in range(2,aVeryHighNumber): alls = collataz(numbr) print(alls) You also could store the result in a dictionary but somewhen the resources of your PC will be full. The fun part about collatz is, that the longest "row" is not nessessarily the one from the highest number. Try 837799 - wich is by some reported as longest below 1000000 starting value which is mostly of interest because of (https://projecteuler.net/problem=14)

http://stackoverflow.com/a/65453488
type: Answer
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47540607
has body: Not an issue with yours but I was getting an error using uppercase characters in my db file name. Changed it and fixed this issue... Worth a try for others! sqlite3.connect('lowercase_name.db')

http://stackoverflow.com/comment/82028209
comment on: http://stackoverflow.com/q/47535605
type: Comment
type: QuestionComment
has text: Sorry my initial post was not clear enough, I updated it. TL/DR: I want to use --keepdb to avoid creating the database each time.
score: 1

http://stackoverflow.com/a/47416867
has comment: http://stackoverflow.com/comment/81791699
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81787726
has comment: http://stackoverflow.com/comment/81787966
has body: If I understand you correctly, you want to gather the names of the groups of all q objects that have a group attribute. If so, the following code will work by splitting the desired operation into two readable steps: my_list = list() for q in queryset_for_table: group = getattr(q, 'group', None) if group is not None: my_list.append(group.name) If all q objects have a group attribute, you could also use: my_list = list() for q in queryset_for_table: my_list.append(q.group.name) For arbitrary nested attributes the following should work: def get_nested_attributes(object, attributes): for attribute in attributes: objects = [getattr(o, attribute, None) for o in objects] return objects my_list = get_nested_attrs(queryset_for_table, ('group', 'name')) This solution iterates over the attributes. You start with your queryset, then get the groups, then get the group names.
has comment: http://stackoverflow.com/comment/81787610
accepted answer of: http://stackoverflow.com/q/47416747
type: Answer
answers question: http://stackoverflow.com/q/47416747

http://stackoverflow.com/a/47459144
has body: While looping in data[key] you can get value with data[key][item]: data = { "ID_54321": { "Name": "John Doe", "Email": "jdoe@gmail123.com", "Q1": "3" } } for key in data: for item in data[key]: print data[key][item]
type: Answer
accepted answer of: http://stackoverflow.com/q/47459088
answers question: http://stackoverflow.com/q/47459088
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47438702
type: Answer
has body: I believe your print statement was originally out of alignment, as it was not getting picked up by your if statement. Also your &amp; should be and: def main(): name = input("Enter Your Name:") name2 = input ("Enter Your Name:") if (name == 'Mark') and (name2 == 'John'): print("Your Name is correct") main()
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47438568
score: 1
answers question: http://stackoverflow.com/q/47438568

http://stackoverflow.com/a/47732558
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/82429467
score: 4
has body: Uninstalling and doing a clean install of homebrew will fix the issue.
answers question: http://stackoverflow.com/q/47513024
has comment: http://stackoverflow.com/comment/82428177
downvote count: 1
has comment: http://stackoverflow.com/comment/83712952

http://stackoverflow.com/comment/82020481
score: 0
type: AnswerComment
has text: But whenever there is an answer from you guys I will never forget that. It hits so hard how much I dont know : )
type: Comment
comment on: http://stackoverflow.com/a/47531970

http://stackoverflow.com/comment/81884006
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47459388
has text: What's in the console, any JS errors?

http://stackoverflow.com/q/47460524
has answer: http://stackoverflow.com/a/47461902
type: Question
type: UnansweredQuestion
tagged with: procedural-programming
tagged with: python
score: 0
has body: I've written the following: screenState = screenGrab(workingDirectory + '/Screenshots') Which calls this subroutine: def screenGrab(directory): """ Takes a screenshot of an area of the screen. :params: directory : directory to save screenshot in """ box = (x_pad + 1, y_pad + 1, x_pad + 961, y_pad + 641) im = ImageGrab.grab(box) im.save(directory + '/full_snap__' + str(int(time.time())) + '.png', 'PNG') And when I attempt to run the code I get the following error: TypeError: screenGrab() takes 0 positional arguments but 1 was given I'm unsure as to why this error is occurring.
has title: screenGrab() takes 0 positional arguments but 1 was given
answer count: 1
has comment: http://stackoverflow.com/comment/81878349
has comment: http://stackoverflow.com/comment/81876938
has comment: http://stackoverflow.com/comment/81878543

http://stackoverflow.com/comment/81885529
score: 1
has text: So, `"Hello, World!"` would just be an instance of the class, `String`?
comment on: http://stackoverflow.com/q/47465305
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82043942
type: Comment
type: QuestionComment
has text: Apologies. I was unfamiliar with the concept of a working example, especially since I have no such working code. I've looked into meshgrid and I'm updating my code
comment on: http://stackoverflow.com/q/47539760
score: 0

http://stackoverflow.com/comment/81954735
comment on: http://stackoverflow.com/q/47487763
type: QuestionComment
has text: @hpaulj Yes, Like you said the problem is the assignment to the data.train.images. Went through the tensorflow source code, cant change the array. Thanks anyways.
score: 0
type: Comment

http://stackoverflow.com/comment/81837446
type: AnswerComment
has text: @juanpa.arrivillaga Changed to `C#`; And I guess writing OO code in C is possible, but it would be quite hard, wouldn't it? The language isn't designed that way.
comment on: http://stackoverflow.com/a/47441162
type: Comment
score: 0

http://stackoverflow.com/comment/81768474
type: Comment
type: QuestionComment
has text: Will be work `print('\a')` but required run code on `system`(`CMD`) not `IDLE`, on CMD `C:\PythonXX\python.exe path_of_your_script\your_awesome.py`
comment on: http://stackoverflow.com/q/47406496
score: 0

http://stackoverflow.com/a/47502606
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47502554
has body: Probably not if you fopen. What I use for logs is file_put_contents( $filename, $data, FILE_APPEND|LOCK_EX); That way you don't have an open resource handle, and it will create a file if no exists when it goes to write. I tried it once with fwrite with about 15 different processes all logging stuff, wound up with half a file of NUL crap in it. So then I started using this. http://php.net/manual/en/function.file-put-contents.php FILE_USE_INCLUDE_PATH Search for filename in the include directory. See include_path for more information. FILE_APPEND If file filename already exists, append the data to the file instead of overwriting it. LOCK_EX Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x".
downvote count: 0
score: 1

http://stackoverflow.com/comment/82199220
type: Comment
type: QuestionComment
has text: I actually left it in the background for pretty long time, but nothing ever changed.
score: 0
comment on: http://stackoverflow.com/q/47506622

http://stackoverflow.com/q/47532112
possible better answer: http://stackoverflow.com/a/47532612
favorite count: 0
has answer: http://stackoverflow.com/a/47609302
type: Question
has answer: http://stackoverflow.com/a/47532612
linked to: http://stackoverflow.com/q/12080552
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82020702
has answer: http://stackoverflow.com/a/47538885
type: AnsweredQuestion
answer count: 3
has title: Text-Based Pokemon Game: How do I implement an evolution system?
score: 1
downvote count: 0
has body: I have starting working on this Text-Based Pokemon game and I am stuck on trying to figure an evolution system that can change one class object into another class object, if that makes sense. I've attempted to do this just by simply making the class object equal to the one I want to change: # Trainer new_trainer = Trainer('Trainer', 'Male') # Test pokemon (the parameter is just a level value) bulbasaur = Bulbasaur(10) ivysaur = Ivysaur(20) # Adding pokemon to party new_trainer.add_pokemon(bulbasaur) new_trainer.add_pokemon(ivysaur) # Display pokemon lists print(new_trainer.pokemon_list) new_trainer.display_party() # Attempting to 'evolve' bulbasuar bulbasaur = Ivysaur(bulbasaur.lvl) # Displaying results again to see if it worked print(new_trainer.pokemon_list) new_trainer.display_party() But by looking at the output, it shows that nothing has happened: Bulbasaur was added to your party! Ivysaur was added to your party! [&lt;__main__.Bulbasaur object at 0x0000023587EDA080&gt;, &lt;__main__.Ivysaur object at 0x0000023587EDA0F0&gt;] 1. Bulbasaur 2. Ivysaur [&lt;__main__.Bulbasaur object at 0x0000023587EDA080&gt;, &lt;__main__.Ivysaur object at 0x0000023587EDA0F0&gt;] 1. Bulbasaur 2. Ivysaur EDIT: It turns that that the variable value DOES indeed change, but I simply need to update the Trainer's pokemon list. However, I am still unsure on how to do this. The display_party function in the Trainer class looks like this: def display_party(self): # Displays pokemon party list if not self.pokemon_list: return print("There are no pokemon in your party.") else: for pokemon in range(len(self.pokemon_list)): print("{0}. {1}".format(pokemon + 1, self.pokemon_list[pokemon].name)) I was just thinking of adding an update_party function, which goes into the list, deletes the old value and inserts the new value, but how will it know what value to delete? Perhaps there is a better way to do this? And sorry if my question doesn't include that much information, I will add more of my code…
accepted answer: http://stackoverflow.com/a/47609302

http://stackoverflow.com/a/47391255
has comment: http://stackoverflow.com/comment/112713959
has body: You don't need to loop over filenames and plots, only need to select the next plot in the list. for i, filename in enumerate(file_list): p = ax_list[i]: x,y = load_file(filename) p.plot(x, y, label=l, #I assign labels from a list beforehand, as well as colors color=c, linewidth=0.5, ls='-') plt.plot() You can also replace fig = plt.figure() ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) ax_list=[ax1, ax2, ax3, ax4] with just fig, ax_list = plt.subplots(2, 2) ax_list = ax_list.flatten() To get a simple 2x2 grid.
has comment: http://stackoverflow.com/comment/81735933
answers question: http://stackoverflow.com/q/47391136
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/112783666
has comment: http://stackoverflow.com/comment/81736162
type: Answer
accepted answer of: http://stackoverflow.com/q/47391136

http://stackoverflow.com/q/47409266
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47423784
downvote count: 1
favorite count: 0
type: Question
has body: I've been racking my brain trying to do the following task (Just to keep simple). First image you have an array like this: import numpy as np numbers = np.arange(0,12) Then, I'd like to take random sample for that array. Assume you are interested to partition in 4 equal parts. Here I have my first problem. How you can get 4 or more equal partitions using pyspark in a automated way? (The brute force looks like this) rdd = sc.parallelize(numbers) rdd_sampled_1 = rdd.sample(False, 0.25) rdd_sampled_2 = rdd.sample(False, 0.25) rdd_sampled_3 = rdd.sample(False, 0.25) rdd_sampled_4 = rdd.sample(False, 0.25) The output should look like this: rdd_sample_1 = [3 2 7] rdd_sample_1 = [1 4 8] rdd_sample_3 = [9 5 10] rdd_sample_4 = [11 6 0] Afterwards, I'd like to sum all this partials samples using map function. The should look like this: collect_sample_1 = [12] collect_sample_2 = [13] collect_sample_3 = [24] collect_sample_4 = [17] How you can do this using pyspark?
has title: How to sum all Rdd samples in parallel with Pyspark
tagged with: apache-spark-sql
score: 0
tagged with: apache-spark

mysql
tags question: http://stackoverflow.com/q/47481714
tags question: http://stackoverflow.com/q/47510581
tags question: http://stackoverflow.com/q/47525872
tags question: http://stackoverflow.com/q/47387273
tags question: http://stackoverflow.com/q/47440757
tags question: http://stackoverflow.com/q/47499032
tags question: http://stackoverflow.com/q/47397521
tags question: http://stackoverflow.com/q/47508523
type: Tag
tags question: http://stackoverflow.com/q/47383886
tags question: http://stackoverflow.com/q/47471970
tags question: http://stackoverflow.com/q/47458722
tags question: http://stackoverflow.com/q/47428864
tags question: http://stackoverflow.com/q/47452697
tag name: mysql
tags question: http://stackoverflow.com/q/47502008
tags question: http://stackoverflow.com/q/47454771
tags question: http://stackoverflow.com/q/47424775
tags question: http://stackoverflow.com/q/47508868
tags question: http://stackoverflow.com/q/47505706
tags question: http://stackoverflow.com/q/47412540
tags question: http://stackoverflow.com/q/47438397
tags question: http://stackoverflow.com/q/47517050
tags question: http://stackoverflow.com/q/47492752
tags question: http://stackoverflow.com/q/47426595
tags question: http://stackoverflow.com/q/47527443
tags question: http://stackoverflow.com/q/47382916
tags question: http://stackoverflow.com/q/47536176
tags question: http://stackoverflow.com/q/47484974
tags question: http://stackoverflow.com/q/47408001
tags question: http://stackoverflow.com/q/47474986
tags question: http://stackoverflow.com/q/47410893
tags question: http://stackoverflow.com/q/47384746
tags question: http://stackoverflow.com/q/47416893
tags question: http://stackoverflow.com/q/47415989
tags question: http://stackoverflow.com/q/47500241
tags question: http://stackoverflow.com/q/47491593
tags question: http://stackoverflow.com/q/47422617
tags question: http://stackoverflow.com/q/47461721
tags question: http://stackoverflow.com/q/47498458
tags question: http://stackoverflow.com/q/47452952
tags question: http://stackoverflow.com/q/47438715
tags question: http://stackoverflow.com/q/47478913
tags question: http://stackoverflow.com/q/47514886
tags question: http://stackoverflow.com/q/47387012
tags question: http://stackoverflow.com/q/47434920
tags question: http://stackoverflow.com/q/47419943
tags question: http://stackoverflow.com/q/47487329
tags question: http://stackoverflow.com/q/47406919
tags question: http://stackoverflow.com/q/47498950
tags question: http://stackoverflow.com/q/47512227
tags question: http://stackoverflow.com/q/47503739
tags question: http://stackoverflow.com/q/47421646

http://stackoverflow.com/comment/81805451
comment on: http://stackoverflow.com/a/47425226
score: 1
has text: 1. Any -- so typically the newest. 2. No. 3. You don't need to remove your original install; the installer should add the new one.
type: Comment
type: AnswerComment

tensorflow
tags question: http://stackoverflow.com/q/47459299
tags question: http://stackoverflow.com/q/47414371
tags question: http://stackoverflow.com/q/47509504
type: Tag
tags question: http://stackoverflow.com/q/47511726
tags question: http://stackoverflow.com/q/47429267
tags question: http://stackoverflow.com/q/47383336
tags question: http://stackoverflow.com/q/47512355
tags question: http://stackoverflow.com/q/47448327
tags question: http://stackoverflow.com/q/47417060
tags question: http://stackoverflow.com/q/47430437
tags question: http://stackoverflow.com/q/47493392
tags question: http://stackoverflow.com/q/47390473
tags question: http://stackoverflow.com/q/47393788
tags question: http://stackoverflow.com/q/47442792
tags question: http://stackoverflow.com/q/47490494
tags question: http://stackoverflow.com/q/47443880
tags question: http://stackoverflow.com/q/47495190
tags question: http://stackoverflow.com/q/47525680
tags question: http://stackoverflow.com/q/47491262
tags question: http://stackoverflow.com/q/47477314
tags question: http://stackoverflow.com/q/47400126
tags question: http://stackoverflow.com/q/47385841
tags question: http://stackoverflow.com/q/47519353
tags question: http://stackoverflow.com/q/47506622
tags question: http://stackoverflow.com/q/47506607
tags question: http://stackoverflow.com/q/47477065
tags question: http://stackoverflow.com/q/47394731
tags question: http://stackoverflow.com/q/47516046
tags question: http://stackoverflow.com/q/47470304
tags question: http://stackoverflow.com/q/47413054
tags question: http://stackoverflow.com/q/47403336
tags question: http://stackoverflow.com/q/47451767
tags question: http://stackoverflow.com/q/47464272
tags question: http://stackoverflow.com/q/47425746
tags question: http://stackoverflow.com/q/47462962
tags question: http://stackoverflow.com/q/47473442
tags question: http://stackoverflow.com/q/47457344
tags question: http://stackoverflow.com/q/47482493
tags question: http://stackoverflow.com/q/47537821
tags question: http://stackoverflow.com/q/47529792
tags question: http://stackoverflow.com/q/47475916
tags question: http://stackoverflow.com/q/47481748
tags question: http://stackoverflow.com/q/47479587
tags question: http://stackoverflow.com/q/47415828
tags question: http://stackoverflow.com/q/47426044
tags question: http://stackoverflow.com/q/47394104
tags question: http://stackoverflow.com/q/47531328
tags question: http://stackoverflow.com/q/47461331
tags question: http://stackoverflow.com/q/47519104
tags question: http://stackoverflow.com/q/47384632
tags question: http://stackoverflow.com/q/47394941
tags question: http://stackoverflow.com/q/47515470
tags question: http://stackoverflow.com/q/47516111
tags question: http://stackoverflow.com/q/47474072
tags question: http://stackoverflow.com/q/47393251
tags question: http://stackoverflow.com/q/47500342
tags question: http://stackoverflow.com/q/47411383
tags question: http://stackoverflow.com/q/47487763
tags question: http://stackoverflow.com/q/47532162
tags question: http://stackoverflow.com/q/47426233
tags question: http://stackoverflow.com/q/47498748
tags question: http://stackoverflow.com/q/47499284
tags question: http://stackoverflow.com/q/47498307
tags question: http://stackoverflow.com/q/47462114
tags question: http://stackoverflow.com/q/47417897
tags question: http://stackoverflow.com/q/47406906
tags question: http://stackoverflow.com/q/47394761
tags question: http://stackoverflow.com/q/47481138
tags question: http://stackoverflow.com/q/47535920
tags question: http://stackoverflow.com/q/47535940
tags question: http://stackoverflow.com/q/47493423
tags question: http://stackoverflow.com/q/47428336
tags question: http://stackoverflow.com/q/47456415
tags question: http://stackoverflow.com/q/47519802
tags question: http://stackoverflow.com/q/47431777
tags question: http://stackoverflow.com/q/47387555
tags question: http://stackoverflow.com/q/47456848
tags question: http://stackoverflow.com/q/47447183
tags question: http://stackoverflow.com/q/47457501

http://stackoverflow.com/a/63233650
has body: Although I'm too late to the party, on Google's Facenet (89MB), I have got some interesting results as follows, I tried every option mentioned in the above answers, But found out that Keras in Tensorflow is slightly faster than vanilla Keras, and the results might be better on a stronger CPU. My laptop is really old, with a configuration of 4th gen i5 (4120U), 8GB 1600MHz DDR3, and a normal SATA SSD, and I'm using Tensorflow 1.15.2 CPU version. # Old method -- 16 to 17 seconds from keras import backend as K K.clear_session() model = load_model('models/facenet_v1.h5', compile=False) #------------------------------------------------------ # Method 1 -- 16 to 18 seconds from keras import backend as K K.clear_session() with open('models/facenet_v1.json', 'r') as j: json_model = j.read() model = model_from_json(json_model) model.load_weights('models/facenet_v1_weights.h5') #------------------------------------------------------ # Method 2 -- 9 to 11 seconds -&gt; Best tf.keras.backend.clear_session() model = tf.keras.models.load_model('models/facenet_v1.h5', compile=False) And apart from this definitely, you'll get much better results if you have a GPU.
answers question: http://stackoverflow.com/q/47455397
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/81835109
type: QuestionComment
has text: That gives `False`! Why is that?
type: Comment
comment on: http://stackoverflow.com/q/47440077
score: 0

http://stackoverflow.com/a/47435389
has comment: http://stackoverflow.com/comment/81837076
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81841844
has comment: http://stackoverflow.com/comment/81832195
has comment: http://stackoverflow.com/comment/81842554
has body: df.T is a different object. The changes you make will not be reflected in the original df. Where is it? Since there is no variable pointing to it, either it has already been collected by the garbage collector or it is waiting to be collected. You cannot access it. What you can do is to create a new variable transposed = df.T transposed['C'] = 3 transposed Out: 0 1 2 3 C A 1 2 3 4 3 B 1 3 4 7 3 The same thing happens when you call any method that returns a new DataFrame. df.drop(0)['C'] = 2, df.reset_index()['C'] = 3 or df.drop_duplicates()['C'] = 3. The original DataFrame always stays the same. There is another DataFrame created with that exact row assigned to it but it becomes inaccessible as soon as you execute that statement because you don't have any variables pointing to it. For CPython's garbage collection, there is some useful information here. Edit from @Bharath: (an explanation given by one of my teachers) T returns a copy. That means new memory is allocated to store the new object. If you look up python garbage collection you’ll find that each object in memory keeps a counter of how many pointers are pointing to it. When the garbage collection is run, it will find this object in memory and see that it has zero pointers. Because it has zero pointers the garbage collection will reclaim the memory and the object is gone forever. So it is recommended to keep a single pointer pointing to the object by assigning to a name (or variable).
has comment: http://stackoverflow.com/comment/81842133
has comment: http://stackoverflow.com/comment/81826913
has comment: http://stackoverflow.com/comment/81837018
has comment: http://stackoverflow.com/comment/81827285
has comment: http://stackoverflow.com/comment/81836958
type: Answer
has comment: http://stackoverflow.com/comment/81841412
accepted answer of: http://stackoverflow.com/q/47435152
has comment: http://stackoverflow.com/comment/81827322
has comment: http://stackoverflow.com/comment/81824881
has comment: http://stackoverflow.com/comment/81843095
has comment: http://stackoverflow.com/comment/81825035
has comment: http://stackoverflow.com/comment/81837419
has comment: http://stackoverflow.com/comment/81837140
has comment: http://stackoverflow.com/comment/81828930
upvote count: 2
answers question: http://stackoverflow.com/q/47435152
score: 2
has comment: http://stackoverflow.com/comment/81826338
has comment: http://stackoverflow.com/comment/81826816
has comment: http://stackoverflow.com/comment/81833016
has comment: http://stackoverflow.com/comment/81837224
downvote count: 0
has comment: http://stackoverflow.com/comment/81826492

http://stackoverflow.com/comment/81782669
type: Comment
has text: The actual samples buffer, however, is the one in `shuffle` (which, if you don't want to have shuffling, can be replaced by another `prefetch()`).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47414078

relational-database
type: Tag
tag name: relational-database
tags question: http://stackoverflow.com/q/47540607

http://stackoverflow.com/q/47462568
has comment: http://stackoverflow.com/comment/81883818
has comment: http://stackoverflow.com/comment/81883591
accepted answer: http://stackoverflow.com/a/47462608
favorite count: 0
has answer: http://stackoverflow.com/a/47462608
type: Question
has comment: http://stackoverflow.com/comment/81883725
tagged with: reshape
has comment: http://stackoverflow.com/comment/81881024
tagged with: python
score: 4
upvote count: 4
tagged with: numpy
possible better answer: http://stackoverflow.com/a/56798188
has title: Numpy reshape preserving some dimensions
type: AnsweredQuestion
has body: I want this # assume each 2x2 as assigned number on right [[[False True] # 1 [False False]] [[False False] # 2 [False True]] [[ True False] # 3 [False False]] [[False True] # 4 [False False]]] to be reshape into [[[[False True False False] [False False False True] [ True False False True] [False False False False]]]] as in [[[[False True | False False] # 1 | 2 [False False | False True] ___ ___ ---------- ----------- [ True False | False True] # 3 | 4 [False False | False False]]]] but I get when using arr.reshape(1,1,4,4) [[[[False True False False] # 1 flat [False False False True] # 2 flat [ True False False False] # 3 flat [False True False False]]]] # 4 flat Notice that each 2x2 is flattened. I want numpy to reshape such that 2x2 remains the same while the dimensions before that are adjusted. How do I do it? EDIT: shape of arr is m,n,r and m could be odd EDIT2: Case 9x2x2 into 1x1x6x6 What I have: [[[False False] [False True]] [[False False] [False True]] [[ True False] [False False]] [[False False] [False True]] [[False False] [ True False]] [[False False] [ True False]] [[False True] [False False]] [[False False] [ True False]] [[ True False] [False False]]] Expected: [[[[False False | False False | True False] [False True | False True | False False] ----------- ----------- ---------- [False False | False False | False False] [False True | True False | True False] ---------- ----------- ----------- [False True | False False | True False] [False False | True False | False False]]]] What I got: [[[[False False False True False False] # 1 flattened; half of 2 [False True True False False False] # rem half of 2; flattened 3 [False False False True False True] # ... [False False False True False False] [False False True False False True] [False False True False False False]]]]
answer count: 2
has answer: http://stackoverflow.com/a/56798188
downvote count: 0

http://stackoverflow.com/q/47443357
tagged with: python
has body: After a lot of searching and being unable to find an answer i choose to place my question here. How do i fit an exponential function in the form of y=(1/A)e^(-x/A) to the shown data and plot this function? I still need some getting used to fitting in Python. Help will be more than appreciated! Thank you in advance.
has comment: http://stackoverflow.com/comment/81841877
has comment: http://stackoverflow.com/comment/81842314
has title: Python | Plotting & fitting a data fit in the form (1/A)e^(-x/A) in which A is a constant
downvote count: 0
has answer: http://stackoverflow.com/a/47444527
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47447698
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
tagged with: trendline
answer count: 2
has comment: http://stackoverflow.com/comment/81842178
tagged with: exponential
type: UnansweredQuestion

http://stackoverflow.com/comment/81934632
comment on: http://stackoverflow.com/a/47486080
score: 1
type: AnswerComment
has text: I found a solution that works but does not seem to be very elegant: I added `import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'MyApp'))` in test_app.py before importing 'app.py'. Is there a more elegant way?
type: Comment

http://stackoverflow.com/comment/81963720
has text: Or here: https://stackoverflow.com/questions/6558765/how-do-you-see-the-entire-command-history-in-interactive-python
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47503901

http://stackoverflow.com/comment/81969404
type: AnswerComment
comment on: http://stackoverflow.com/a/47506766
score: 0
has text: Thanks guys, I'm new to nparray but need a quick manipulation. it's working like a charm!
type: Comment

http://stackoverflow.com/comment/81914710
comment on: http://stackoverflow.com/q/47479919
has text: please [edit] or delete your question. So far it attracted 2 guessed-wrong answers. Cannot reproduce your issue
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47499843
has body: inv_len = len(deadBody) This is equal to the length of deadBody. Just use something that empties dead body and if you want to add them to your inventory. Such as: player_inv.extend(deadBody) deadBody.clear() #deadBody is now an empty list
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47499544

proxy
tags question: http://stackoverflow.com/q/47396311
tags question: http://stackoverflow.com/q/47524816
tags question: http://stackoverflow.com/q/47399472
tags question: http://stackoverflow.com/q/47499986
tags question: http://stackoverflow.com/q/47441351
type: Tag
tags question: http://stackoverflow.com/q/47496039
tag name: proxy
tags question: http://stackoverflow.com/q/47499686
tags question: http://stackoverflow.com/q/47414022
tags question: http://stackoverflow.com/q/47528645

http://stackoverflow.com/q/47390142
has comment: http://stackoverflow.com/comment/81735650
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/81737328
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81741455
tagged with: python
type: UnansweredQuestion
answer count: 1
favorite count: 0
has body: I've a Python script which Download files from a number of resources, then these files are uploaded in Google Cloud Storage Bucket after some processing, From there these files are loaded in Relevent BigQuery Tables. i have a cronjob running this script every 15 minutes, works perfectly, but some times, like once in a week , i face a problem with only one file out of 16. Issue is that everything seems perfect from script's log. file get downloaded processed uploaded to a bucket loaded into Bigquery. When i check job resources from Google rest v2 jobs get (https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get) status is 200 OK and "outputRows": 584, but Data is not in BigQuery Table when i re upload that file in my resource from where the file is downloaded then file get uploaded and data can be seen in BigQuery Table. Can any one Help me out with this?
has answer: http://stackoverflow.com/a/47403580
has title: BigQuery: Jobs resource are 200 OK and "outputRows": 584, but Data is not in BigQuery Table
type: Question
tagged with: google-cloud-platform
score: 3

http://stackoverflow.com/a/47445774
has comment: http://stackoverflow.com/comment/81847210
score: 2
has body: Your problem is that you're trying to use x0 for two incompatible purposes at the same time: loop control and the current guess at the root. Try separating those purposes into different variables. guess0 = -6 while(guess0 &lt; 5): guess0 += 1 x0 = guess0 print("The value of x0 is: ",x0) ... Even better, use a for loop; they're designed for exactly this problem: for guess0 in (-5, 6): x0 = guess0 print("The value of x0 is: ",x0) ...
has comment: http://stackoverflow.com/comment/81847171
type: Answer
answers question: http://stackoverflow.com/q/47445678
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47445678
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47475154
answer count: 3
tagged with: ansible
score: 3
upvote count: 3
downvote count: 0
tagged with: https
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47478588
has title: Ansible for Windows: WinRM HTTPS setup
has answer: http://stackoverflow.com/a/65317926
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83223465
has comment: http://stackoverflow.com/comment/81905860
tagged with: ssl
tagged with: python
tagged with: winrm
has body: I have some Ansible playbooks I want to run against some Windows hosts. I've followed the various Ansible guides for setting up WinRM and they have worked fine, but the default setups are very insecure and I want something more production ready. However, the instructions for how to do this are incredibly sparse. So far I've done the following: On my Windows box: Enabled WinRM using the supplied ConfigureRemotingForAnsible.ps1 script Configured target machine to to use a valid cert on HTTPS/5986 rather than the self-signed one generated by the above script Enabled both Kerberos and CredSSP auth methods on the target machine in WinRM. Some of my role steps require CredSSP to work reliably. So far so good, the Windows side seems to work fine. However, getting Ansible to connect is proving a nightmare. I can't figure out how to get Ansible to trust the HTTPS cert on the target despite adding it. On my Centos 7 'push box' I've done the following: Install Ansible and pip with the pywinrm, requests_kerberos and requests_credssp modules Added my CA certificate to both /etc/pki/tls/certs and /etc/pki/ca-cert Set my inventory to the following: ansible_user=ADMINISTRATOR@DOMAIN.COM ansible_password=Password1 ansible_port=5986 ansible_connection=winrm ansible_winrm_scheme=https /#ansible_winrm_server_cert_validation=ignore ansible_winrm_transport=credssp With certification validation turned on the connection fails with the following error: fatal: [host.domain.com]: UNREACHABLE! => { "changed": false, "msg": "credssp: HTTPSConnectionPool(host='host.domain.com', port=5986): Max retries exceeded with url: /wsman (Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),))", "unreachable": true} With cert validation turned off it works fine. So my question: How do I get Ansible to trust my CA cert?
has answer: http://stackoverflow.com/a/59844436

http://stackoverflow.com/a/47535806
has body: drop all the collections of the test database after tests. in this way, the db doesn't need to be recreated, and the db is empty after tests. for the problem of test database name, it is described in django doc: https://docs.djangoproject.com/en/1.8/topics/testing/overview/#the-test-database you could create your own test runner to replace your script: django unit tests without a db
has comment: http://stackoverflow.com/comment/82028803
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47535605
has comment: http://stackoverflow.com/comment/82029647
type: Answer
answers question: http://stackoverflow.com/q/47535605
has comment: http://stackoverflow.com/comment/82029162
has comment: http://stackoverflow.com/comment/82028490
upvote count: 2
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47643057
type: Answer
has body: I finally settled for something else, as Blorgbeard suggested _databases = {} def register(dbname="default"): def wrapper(klass): _databases[dbname] = klass return klass return wrapper def get_db(name="default"): return _databases[name] And the user only needs to declare @register() class SqliteDatabase: def __get__(self, index): # retrieve data if data is None: raise KeyError(index) return data This way, anybody can declare as many as databases as they want. If you have improvements over this version, I'll gladly take them.
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47517595

http://stackoverflow.com/comment/82015318
comment on: http://stackoverflow.com/q/47527735
type: Comment
type: QuestionComment
score: 0
has text: on question 1. your code does not understand order, unless you tell it what order you want, perhaps some sorting function is suitable.

http://stackoverflow.com/comment/81848635
score: 0
has text: thanks alot!, i never considered the replace() function
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47446659

http://stackoverflow.com/a/47426524
has comment: http://stackoverflow.com/comment/81807834
has body: I think your indents are incorrect. See if this is what you are looking for: for k, v in AND_List.items(): for j, i in list2.items(): if j in v: DictList.setdefault(k, []).append(float(i)) for k, i in DictList.iteritems(): avgDict[k] = sum(i)/float(len(i)) print avgDict
has comment: http://stackoverflow.com/comment/81827240
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47426431
score: 1
type: Answer

http://stackoverflow.com/a/47448729
score: 0
has body: You can use ps and grep to find the process: ps aux | grep runserver then kill it by: kill the_pid I mean you can write this to a shell script, then invoke it.
type: Answer
answers question: http://stackoverflow.com/q/47448510

http://stackoverflow.com/a/49090232
score: 2
upvote count: 2
downvote count: 0
has body: If you want the elements in ypos to be placed at the x index where each element's index in ypos should correspond with the same y index's element: Initialize x to the required size using all null values. Iterate through the zipped y and ypos elements to fill in each corresponding y element into x. Iterate through x and replace each remaining null value with z values where each replacement will choose from z in increasing order. y = [11, 13, 15] z = [12, 14] ypos = [1, 5, 3] x = [None] * (len(y) + len(z)) for x_ypos, y_elem in zip(ypos, y): x[x_ypos - 1] = y_elem z_iter = iter(z) x = [next(z_iter) if i is None else i for i in x] # x -&gt; [11, 12, 15, 14, 13]
answers question: http://stackoverflow.com/q/47443332
type: Answer

http://stackoverflow.com/comment/82038775
score: 0
comment on: http://stackoverflow.com/q/47533291
has text: did you try `VideoCapture(0)` or `VideoCapture(1)`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47540996
accepted answer of: http://stackoverflow.com/q/47523856
has body: I think you should use @api.multiinstead of @api.model, since you are computing the values. Also, replace self with record, like so: @api.multi @api.depends('order_picking', 'order_picking.isbn', 'contract_worksheet') def accounting_scenarios(self): for record in self: if record.state == 'awaitingraw': record.isbn.printer_wip_account.debit = record.contract_worksheet.total_alles
answers question: http://stackoverflow.com/q/47523856
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82039299
has comment: http://stackoverflow.com/comment/82039368
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47540148
tagged with: aws-lambda
type: Question
tagged with: alexa-skills-kit
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
has title: Alexa won't recognize valid json feed
has comment: http://stackoverflow.com/comment/82037556
tagged with: python
has comment: http://stackoverflow.com/comment/82044444
score: 0
has comment: http://stackoverflow.com/comment/82037557
answer count: 0
tagged with: rss
has body: Error: There was an error parsing the feed. Please ensure that the feed is valid JSON or RSS. For the flash briefing skill I can't get Alexa to recognize my Lambda function return as valid JSON. When I call API gateway on this Lambda function it returns valid JSON. Why won't Alexa recognize it? I've read over the feed guildlines here and have come up short. import json def lambda_handler(event, context): js = [ { "uid": "EXAMPLE_CHANNEL_MULTI_ITEM_JSON_TTS_1", "updateDate": "2016-04-10T00:00:00.0Z", "titleText": "Multi Item JSON (TTS)", "mainText": "This channel has multiple TTS JSON items. This is the first item.", "redirectionUrl": "https://www.amazon.com" }, { "uid": "EXAMPLE_CHANNEL_MULTI_ITEM_JSON_TTS_2", "updateDate": "2016-04-10T00:00:00.0Z", "titleText": "Multi Item JSON (TTS)", "mainText": "This channel has multiple TTS JSON items. This is the second item.", "redirectionUrl": "https://www.amazon.com" } ] js = json.dumps(js) return js returned string "[{\"mainText\": \"This channel has multiple TTS JSON items. This is the first item.\", \"redirectionUrl\": \"https://www.amazon.com\", \"uid\": \"EXAMPLE_CHANNEL_MULTI_ITEM_JSON_TTS_1\", \"titleText\": \"Multi Item JSON (TTS)\", \"updateDate\": \"2016-04-10T00:00:00.0Z\"}, {\"mainText\": \"This channel has multiple TTS JSON items. This is the second item.\", \"redirectionUrl\": \"https://www.amazon.com\", \"uid\": \"EXAMPLE_CHANNEL_MULTI_ITEM_JSON_TTS_2\", \"titleText\": \"Multi Item JSON (TTS)\", \"updateDate\": \"2016-04-10T00:00:00.0Z\"}]" I have "validated" this output as valid JSON using this online tool. If anyone has a properly formatted JSON feed that has been accepted by Amazon please paste that code below.
has comment: http://stackoverflow.com/comment/82037915

android
tags question: http://stackoverflow.com/q/47496992
tags question: http://stackoverflow.com/q/47407680
tags question: http://stackoverflow.com/q/47396126
tags question: http://stackoverflow.com/q/47535900
tags question: http://stackoverflow.com/q/47479496
tags question: http://stackoverflow.com/q/47400957
tags question: http://stackoverflow.com/q/47396382
tags question: http://stackoverflow.com/q/47450877
tags question: http://stackoverflow.com/q/47510030
tags question: http://stackoverflow.com/q/47481902
tag name: android
tags question: http://stackoverflow.com/q/47505747
type: Tag
tags question: http://stackoverflow.com/q/47426618

http://stackoverflow.com/comment/91466634
score: 0
type: AnswerComment
has text: Is there any document for this behavior?
type: Comment
comment on: http://stackoverflow.com/a/51342468

http://stackoverflow.com/a/47442977
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47442953
score: 1
has body: From retrieve links from web page using python and BeautifulSoup import httplib2 from bs4 import BeautifulSoup, SoupStrainer http = httplib2.Http() status, response = http.request('https://www.gofundme.com/mvc.php?route=category&amp;term=sport') for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')): if link.has_attr('href'): print (link['href'])
has comment: http://stackoverflow.com/comment/81842384

http://stackoverflow.com/q/47440442
favorite count: 0
type: Question
has title: Is there a way to write a class decorator for rollback purposes?
has answer: http://stackoverflow.com/a/47440515
type: UnansweredQuestion
tagged with: contextmanager
tagged with: python
has answer: http://stackoverflow.com/a/47440507
score: 0
answer count: 2
has body: I wrote a class with a "revert" decorator. The intention is to change class members in the yield, and if any exception occurs to "revert" all changes. : class A(): def __init__(self): self.kuku = 'old_value' @contextmanager def revertible_transaction(self): old_self = deepcopy(self) try: yield except Exception as e: self = old_self raise e def change_stuff(self): with self.revertible_transaction(): self.kuku = 'new_value' raise Exception I want self.kuku to still be 'old_value' after I run change_stuff(), but it's 'new_value' instead. Any ideas why this is not working and how to do this properly?
upvote count: 1
has comment: http://stackoverflow.com/comment/81835864
downvote count: 1

http://stackoverflow.com/q/47539087
has comment: http://stackoverflow.com/comment/82035347
has comment: http://stackoverflow.com/comment/82035237
linked to: http://stackoverflow.com/q/10778764
has comment: http://stackoverflow.com/comment/82035250
upvote count: 0
accepted answer: http://stackoverflow.com/a/47539170
has comment: http://stackoverflow.com/comment/82035184
has answer: http://stackoverflow.com/a/47539170
has comment: http://stackoverflow.com/comment/82035207
downvote count: 1
has comment: http://stackoverflow.com/comment/82035110
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82035208
has answer: http://stackoverflow.com/a/47539164
has comment: http://stackoverflow.com/comment/82035129
tagged with: python
score: -1
has title: OverflowError: range() result has too many items, although it hasn't
has body: I have this for-loop: for i in range(1000000000, 1000000030): foo(i) When I execute it this error is given: Traceback (most recent call last): File "/CENSORED/Activity.py", line 11, in &lt;module&gt; for i in range(1000000000, 10000000030): OverflowError: range() result has too many items. As far as I know, this range-object should have exactly 30 elements... Where is the problem? Edit: I have removed the extra zero, now I get this: Traceback (most recent call last): File "/CENSORED/Activity.py", line 12, in &lt;module&gt; factorizeInefficient(i) MemoryError Edit 2: def factorizeInefficient(n): teiler = list() for i in range(n): if i != 0: if (n%i)==0: teiler.append(i) print teiler Just found the solution myself: There is a range(n) object in this as well and this causes the memory Error... An extra question: How did you guys know this was python 2? (Btw you were right...)
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/47539164
has comment: http://stackoverflow.com/comment/82035196
answer count: 2
has comment: http://stackoverflow.com/comment/82035189

http://stackoverflow.com/comment/82035830
score: 0
comment on: http://stackoverflow.com/q/47537565
type: Comment
type: QuestionComment
has text: @PauloScardine Can you please elaborate?

http://stackoverflow.com/comment/81826202
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47434585
type: AnswerComment
has text: I was missing the _reference_ part. Thank you :)

http://stackoverflow.com/q/47405336
answer count: 1
accepted answer: http://stackoverflow.com/a/47408184
has answer: http://stackoverflow.com/a/47408184
tagged with: logging
type: AnsweredQuestion
has title: Why does INFO get logged in DEBUG logs
has body: I am using yaml to config logging for my Python application. version: 1 disable_existing_loggers: False formatters: standard: format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" handlers: console: class: logging.StreamHandler level: DEBUG formatter: standard stream: ext://sys.stdout info_file_handler: class: logging.handlers.RotatingFileHandler level: INFO formatter: standard filename: info.log maxBytes: 10485760 # 10MB backupCount: 20 encoding: utf8 error_file_handler: class: logging.handlers.RotatingFileHandler level: ERROR formatter: standard filename: errors.log maxBytes: 10485760 # 10MB backupCount: 20 encoding: utf8 debug_file_handler: class: logging.handlers.RotatingFileHandler level: DEBUG formatter: standard filename: debug.log maxBytes: 10485760 # 10MB backupCount: 20 encoding: utf8 loggers: db_ops: level: DEBUG handlers: [info_file_handler, error_file_handler, debug_file_handler] propagate: true In module db_ops, I use both logger.info and logger.debug for different levels of logging. When I run the app, while INFO did get output to info.log, both INFO and DEBUG messages are output to debug.log. What is the right way to separate the log to different files based on the level?
tagged with: python
type: Question
score: 0
tagged with: yaml

http://stackoverflow.com/a/47419241
upvote count: 2
score: 2
downvote count: 0
type: Answer
has body: 0) import decimal 1) setup appropriate precision of the decimal.getcontext() ( .prec attribute ) 2) declare as decimal.Decimal() instance &gt;&gt;&gt; import decimal &gt;&gt;&gt; decimal.getcontext().prec 28 &gt;&gt;&gt; decimal.getcontext().prec = 300 &gt;&gt;&gt; dec_a = decimal.Decimal( '725692137865927813642341235.0' ) It is a pleasure to use decimal module for extremely extended numerical precision solvers. BONUS: Decimal module has very powerful context-methods, that preserve the decimal-module's strengths .add(), .subtract(), .multiply(), .fma(), .power() so as to indeed build an almost-infinite precision solver methods ... Definitely worth mastering these decimal.getcontext() methods - your solvers spring into another league in precision and un-degraded convergence levels.
has comment: http://stackoverflow.com/comment/81792707
answers question: http://stackoverflow.com/q/47419036

http://stackoverflow.com/comment/81932961
type: QuestionComment
has text: You should use the [`csv` module](https://docs.python.org/3/library/csv.html) in the standard library to read `maths.txt` so the lines are split correctly. That would take care of newlines and correctly handle commas in the text of the answers.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47488859

http://stackoverflow.com/comment/81996838
type: Comment
type: AnswerComment
has text: Thanks a lot, Ratmir! This actually helps a lot. I'll be using this and the answer by Richard as reference for future issues.
comment on: http://stackoverflow.com/a/47494844
score: 0

http://stackoverflow.com/a/47540660
has comment: http://stackoverflow.com/comment/82038635
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47540548
upvote count: 2
answers question: http://stackoverflow.com/q/47540548
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82038676
has comment: http://stackoverflow.com/comment/82038973
score: 2
has body: if you need a standard bar plot: In [8]: import matplotlib ...: matplotlib.style.use('ggplot') ...: In [9]: s.plot.bar(rot=0, grid=True, width=1, alpha=0.7) Out[9]: &lt;matplotlib.axes._subplots.AxesSubplot at 0xaaab7f0&gt;

http://stackoverflow.com/a/47430459
type: Answer
has comment: http://stackoverflow.com/comment/81861800
has body: You can try below approach 1)Give absolute path in environment variable till BeAm.beacon 2) If 1 is not successfull,Create a environment variable PYTHONPATH and provide the absolute path till BeAm.beacon This should solve your issue
score: 1
has comment: http://stackoverflow.com/comment/81862142
upvote count: 1
answers question: http://stackoverflow.com/q/47429196
has comment: http://stackoverflow.com/comment/81903874
has comment: http://stackoverflow.com/comment/81861922
downvote count: 0

http://stackoverflow.com/a/47457049
has comment: http://stackoverflow.com/comment/81924129
type: Answer
has body: If you use anaconda, you might want to turn to turn to the package reticulate, where you can specify the python version to use. # install.packages("reticulate") library(reticulate) use_python("/anaconda/bin/python") However, from my experience this is slower. Otherwise, if you use 'standard' Python, you can start by removing rPython: remove.packages("rPython") And then re-install it specifying the version: install.packages("rPython", configure.vars= "RPYTHON_PYTHON_VERSION=3.5") This should then use Python_3.5 on your machine, see here for more details. You can test, if it was successful by using: library(rPython) python.exec(c("import sys", "\n", "print(sys.version)"))
answers question: http://stackoverflow.com/q/47402765
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47402765
has comment: http://stackoverflow.com/comment/81922181

http://stackoverflow.com/comment/81808671
type: Comment
comment on: http://stackoverflow.com/a/47427036
type: AnswerComment
has text: When I remove this line: super(Avatar, self).save(*args, **kwargs). I cant presave with avatar_id in path. File path come: users/1/avatar/1_None.jpg instead users/1/avatar/1_9.jpg (9 is avatar_id)
score: 0

python-3.x
tags question: http://stackoverflow.com/q/47393991
tags question: http://stackoverflow.com/q/47481373
tags question: http://stackoverflow.com/q/47461781
tags question: http://stackoverflow.com/q/47469576
tags question: http://stackoverflow.com/q/47509074
tags question: http://stackoverflow.com/q/47450881
tags question: http://stackoverflow.com/q/47516428
tags question: http://stackoverflow.com/q/47400814
tags question: http://stackoverflow.com/q/47518403
tags question: http://stackoverflow.com/q/47502985
tags question: http://stackoverflow.com/q/47444179
tags question: http://stackoverflow.com/q/47452824
tags question: http://stackoverflow.com/q/47392579
tags question: http://stackoverflow.com/q/47454716
tags question: http://stackoverflow.com/q/47405018
tags question: http://stackoverflow.com/q/47439189
tags question: http://stackoverflow.com/q/47511048
tags question: http://stackoverflow.com/q/47444178
tags question: http://stackoverflow.com/q/47514567
tags question: http://stackoverflow.com/q/47438202
tags question: http://stackoverflow.com/q/47537849
tags question: http://stackoverflow.com/q/47383584
tags question: http://stackoverflow.com/q/47392364
tags question: http://stackoverflow.com/q/47491602
tags question: http://stackoverflow.com/q/47416854
tags question: http://stackoverflow.com/q/47477724
tags question: http://stackoverflow.com/q/47419831
tags question: http://stackoverflow.com/q/47520850
tags question: http://stackoverflow.com/q/47387351
tags question: http://stackoverflow.com/q/47530075
tags question: http://stackoverflow.com/q/47459078
tags question: http://stackoverflow.com/q/47415824
tags question: http://stackoverflow.com/q/47440467
tags question: http://stackoverflow.com/q/47429525
tags question: http://stackoverflow.com/q/47499876
tags question: http://stackoverflow.com/q/47393362
tags question: http://stackoverflow.com/q/47400806
tags question: http://stackoverflow.com/q/47414022
tags question: http://stackoverflow.com/q/47417332
tags question: http://stackoverflow.com/q/47496309
tags question: http://stackoverflow.com/q/47453537
tags question: http://stackoverflow.com/q/47498403
tags question: http://stackoverflow.com/q/47431648
tags question: http://stackoverflow.com/q/47401517
tags question: http://stackoverflow.com/q/47516838
tags question: http://stackoverflow.com/q/47443445
tags question: http://stackoverflow.com/q/47489905
tags question: http://stackoverflow.com/q/47534067
tags question: http://stackoverflow.com/q/47419769
tags question: http://stackoverflow.com/q/47432401
tags question: http://stackoverflow.com/q/47383380
tags question: http://stackoverflow.com/q/47422080
tags question: http://stackoverflow.com/q/47518068
tags question: http://stackoverflow.com/q/47476608
tags question: http://stackoverflow.com/q/47481271
tags question: http://stackoverflow.com/q/47407720
tags question: http://stackoverflow.com/q/47482115
tags question: http://stackoverflow.com/q/47517925
tags question: http://stackoverflow.com/q/47461480
tags question: http://stackoverflow.com/q/47504523
tags question: http://stackoverflow.com/q/47530535
tags question: http://stackoverflow.com/q/47466390
tags question: http://stackoverflow.com/q/47414426
tags question: http://stackoverflow.com/q/47487324
tags question: http://stackoverflow.com/q/47396382
tags question: http://stackoverflow.com/q/47536038
tags question: http://stackoverflow.com/q/47460744
tags question: http://stackoverflow.com/q/47495732
tags question: http://stackoverflow.com/q/47430496
tags question: http://stackoverflow.com/q/47448401
tags question: http://stackoverflow.com/q/47516916
tags question: http://stackoverflow.com/q/47482705
tags question: http://stackoverflow.com/q/47449557
tags question: http://stackoverflow.com/q/47404153
tags question: http://stackoverflow.com/q/47488664
tags question: http://stackoverflow.com/q/47408891
tags question: http://stackoverflow.com/q/47408435
tags question: http://stackoverflow.com/q/47469332
tags question: http://stackoverflow.com/q/47481370
tags question: http://stackoverflow.com/q/47470697

http://stackoverflow.com/comment/81842724
comment on: http://stackoverflow.com/q/47443685
has text: If this were python 3, then `SimpleNamespace` https://docs.python.org/3.6/library/types.html#types.SimpleNamespace would be enough. Else look up Alex Martelli's Bunch Class http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47520105
answer count: 1
tagged with: websocket
tagged with: django
has answer: http://stackoverflow.com/a/47521829
accepted answer: http://stackoverflow.com/a/47521829
favorite count: 0
type: Question
has body: Short question version: what am I doing wrong in my Daphne config, or my Consumer code, or my client code? channels==1.1.8 daphne==1.3.0 Django==1.11.7 Details below: I am trying to keep a persistent Websocket connection open using Django Channels and the Daphne interface server. I am launching Daphne with mostly default arguments: daphne -b 0.0.0.0 -p 8000 my_app.asgi:channel_layer. I am seeing the connections closing after some idle time in the browser, shortly over 20 seconds. The CloseEvent sent with the disconnect has a code value of 1006 (Abnormal Closure), no reason set, and wasClean set to false. This should be the server closing the connection without sending an explicit close frame. The Daphne CLI has --ping-interval and --ping-timeout flags with default values of 20 and 30 seconds, respectively. This is documented as "The number of seconds a WebSocket must be idle before a keepalive ping is sent," for the former, and "The number of seconds before a WebSocket is closed if no response to a keepalive ping," for the latter. I read this as Daphne will wait until a WebSocket has been idle for 20 seconds to send a ping, and will close the Websocket if no response is received 30 seconds later. What I am seeing instead is connections getting closed after being 20 seconds idle. (Across three attempts with defaults, closed after 20081ms, 20026ms, and 20032ms) If I change the server to launch with daphne -b 0.0.0.0 -p 8000 --ping-interval 10 --ping-timeout 60 my_app.asgi:channel_layer, the connections still close, around 20 seconds idle time. (After three attempts with updated pings, closed after 19892ms, 20011ms, 19956ms) Code below: consumer.py: import logging from channels import Group from channels.generic.websockets import JsonWebsocketConsumer from my_app import utilities logger = logging.getLogger(__name__) class DemoConsumer(JsonWebsocketConsumer): """ Consumer echos the incoming message to all connected Websockets, and attaches the username to the outgoing m…
has title: Websocket timeout in Django Channels / Daphne
score: 7
tagged with: django-channels
tagged with: daphne
tagged with: python
has comment: http://stackoverflow.com/comment/81997870
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81998008
has comment: http://stackoverflow.com/comment/81998846
downvote count: 0
upvote count: 7

http://stackoverflow.com/a/47417967
upvote count: 1
score: 1
has body: Finally, I came up with a better solution of my own program. I have replace os.system('xcopy "%s" "%s" %(x\y\z + k, list2[k])) subprocess.Popen('xcopy /y ' src + ' ' + dst,creationflags = 0x08000000) "creationflags = 0x08000000" can hide the cmd window. with Popen, it will not wait for the copy to finish. so we can copy multiple files together.
type: Answer
accepted answer of: http://stackoverflow.com/q/47392364
answers question: http://stackoverflow.com/q/47392364
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47479248
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81913589
accepted answer: http://stackoverflow.com/a/47480384
answer count: 2
has answer: http://stackoverflow.com/a/47480384
score: 1
has comment: http://stackoverflow.com/comment/81913550
downvote count: 0
upvote count: 1
tagged with: loops
has body: I'm working on class lab and I'm kind of stuck, for example I have a dictionary with key and value which is another dictionary. Dictionary A: dict_a = { 1: { 'Engine': 4, 'Speed': 749, 'max_speed': 1140, 'name': 'Ship1', }, 2: { 'Engine': 2, 'Speed': 600, 'max_speed': 900, 'name': 'B777', }, 3: { 'Engine': 4, 'Speed': 1130, 'max_speed': 1200, 'name': 'Air_max', } } I am trying to write an function which will take two argument (Dictionary A, and a Filter Dictionary) For example: filter = { 'Engine' :4, 'name': 'Air_max', } This function should return a list with dictionaries that has value > or equal to filter: This is just an example. As i just need an Hint idea how to do this. In reality my Dictionary A is very big. So far i have this which does not looking right: filtered = { 'Engine': 2, 'Speed': 300, 'Type': 'Electric' } result = [] for k, v in full_data.items(): for i, s in v.items(): for a, b in filtered.items(): if v[i] &gt;= filtered[a]: result.append(v) filtered_result = [] for each in result: if each not in filtered_result: filtered_result.append(each) filtered_result[:3]
has comment: http://stackoverflow.com/comment/81913645
favorite count: 0
tagged with: iteration
type: Question
has comment: http://stackoverflow.com/comment/81913490
has title: Python dictionaries Filtering stuff out
possible better answer: http://stackoverflow.com/a/47480408
has answer: http://stackoverflow.com/a/47480408
has comment: http://stackoverflow.com/comment/81913358
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81913627

http://stackoverflow.com/q/47446008
score: 0
has body: @app.route('/schedule', methods=['POST']) def schedule(): data = request.get_json() print(data) But error ouccured. TypeError: write() argument must be str, not bytes How to print json data ??
answer count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81848314
type: Question
has title: Flask with python3.5.2 want to print json
has comment: http://stackoverflow.com/comment/81847399
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81847443
has comment: http://stackoverflow.com/comment/81850312
has comment: http://stackoverflow.com/comment/81847844
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/81849614

http://stackoverflow.com/comment/82028239
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47535676
score: 0
has text: The answer's from this thread https://stackoverflow.com/a/40108817/501074 didn't fix the issue.

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

http://stackoverflow.com/a/47432451
has body: Python doesn't consider system path in its arguments, not even PYTHONPATH... You can simulate this using where to find the script in the path where gdal_retile.py &gt; %TEMP%\fullp then use that to set a variable set /P C=&lt;%TEMP%\fullpath then call python with the full path python "%C%" (there's no error checking here on the where command, which could return nothing or more than 1 path, so that solution is perfectible but convenient to launch another interpreter than the one associated with the .py extension on Windows)
answers question: http://stackoverflow.com/q/47432192
type: Answer
score: 0

http://stackoverflow.com/comment/81777668
comment on: http://stackoverflow.com/q/47400968
type: QuestionComment
type: Comment
has text: Please update your question with details on what is going wrong. e.g. what you expect and what you are getting
score: 0

http://stackoverflow.com/q/47536523
has comment: http://stackoverflow.com/comment/82030000
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47536626
has title: Python loop excel sheet printing cell values
answer count: 2
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/82029987
linked to: http://stackoverflow.com/q/22169325
type: Question
favorite count: 0
possible better answer: http://stackoverflow.com/a/47536639
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47536639
accepted answer: http://stackoverflow.com/a/47536626
tagged with: excel
has body: I'm trying to loop through an excel sheet printing the values in each column. Then go down to the next row, print the values of the column, until the end of the file. My data looks like Name email desc date name1 email1 desc1 date1 name2 email2 desc2 date2 name3 email3 desc3 date3 wb = load_workbook('example.xlsx') sheet = wb.get_sheet_by_name('Sheet1') row_count = sheet.max_row -1 column_count = sheet.max_column i = 1 while (i &lt;= row_count): for item in sheet.iter_cols(): #for row in sheet.iter_cols(): first_value = item[i] print (first_value.value) i+=1 I get of error or tuple index out of range, and it also isn't printing the correct data. first_value = item[i] IndexError: tuple index out of range with the code above before the out of range error i get name1, email2, desc3 as output which is clearly wrong because the data isn't in the same row

http://stackoverflow.com/comment/81734997
comment on: http://stackoverflow.com/q/47390035
type: QuestionComment
type: Comment
has text: Done I made the edit
score: 0

http://stackoverflow.com/q/47519776
has comment: http://stackoverflow.com/comment/81996294
upvote count: 1
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81996324
tagged with: pygame
favorite count: 0
type: Question
has body: I have recently tried to upgrade the code for my game I am working on by changing my basic rect and images to the more advanced Class system. However, I seem to be having trouble with my collision detection, where when I tell my sprite hg to stop falling when colliding with floor (or any inputted box) it doesn't detect, but the script is running, so I know that the syntax isn't wrong. What am I doing wrong? Here is what I believe is enough code to help you and the two pictures you will need (tell me if you need more info): ######## basic setup import pygame, sys, time, random, threading, tkinter, ctypes from threading import Timer from pygame.locals import * from tkinter import * pygame.init() WINDOWHEIGHT = 720 WINDOWWIDTH = 1280 windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32) pygame.display.set_caption('Hitman Grandma | vB1.0 (prealpha)') white = (255,255,255) red = (255,0,0) black = (0,0,0) green = (0,255,0) blue = (0,0,255) cyan = (0,255,255) lightgrey = (198,198,198) windowSurface.fill(lightgrey) pygame.display.update() mainClock = pygame.time.Clock() ########## variables level = 0 touching = False global x_speed x_speed = 0 y_speed = 0 leftallowed = True rightallowed = True hgturnright = True hgjumpallowed = True ########### the grandma d'awesome murder sorts hgimage = pygame.image.load('hgfinal.png') hgimage.convert_alpha() class HG(object): def __init__(self,x,y,image): self.image = image self.rect = self.image.get_rect() self.x = x self.y = y def draw(self): windowSurface.blit(self.image,(self.x,self.y)) def move(self): self.x += x_speed self.y += y_speed def topcollide(self,box): if not self.rect.colliderect(box.rect): global y_speed if y_speed &lt; 20: y_speed += 1 elif y_speed == 20: y_speed = 20 print('shhoooo') elif self.rect.colliderect(box.rect): y_speed = 0 print('flop') hg = HG(0,0,hgimage) ########### land and boundary lands = pygame.image.load('hgland1.png') floorland = pygame.transform.scale(lands,(1280,50)) sideedge …
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81996168
has answer: http://stackoverflow.com/a/47519953
tagged with: sprite
accepted answer: http://stackoverflow.com/a/47519953
has comment: http://stackoverflow.com/comment/81996444
has title: Collision Detection Not Working for Sprites in Pygame
has comment: http://stackoverflow.com/comment/82031717
type: AnsweredQuestion

http://stackoverflow.com/a/47433600
answers question: http://stackoverflow.com/q/47432904
upvote count: 2
has body: If you're running a script at build time then it will run the host python as it can't run the target python binary for the obvious reason that its a target binary. The exception your showing is simply that you're trying to run a binary that popen can't find. Remember that inside a build $PATH is sanitised so won't contain what it has outside of bitbake.
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/47503101
type: Answer
answers question: http://stackoverflow.com/q/47503071
score: 3
upvote count: 3
downvote count: 0
has body: Use itertools.groupby from itertools import groupby names = ['Mike','Angela','Bill','\n','Robert','Pam'] [list(g) for k,g in groupby(names, lambda x:x=='\n') if not k] #[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]

http://stackoverflow.com/comment/81939644
comment on: http://stackoverflow.com/q/47491750
type: Comment
score: 0
has text: you know it would help a lot if we had the code to see what you did....
type: QuestionComment

http://stackoverflow.com/q/47477890
tagged with: netbeans-8.2
favorite count: 0
type: Question
upvote count: 9
has body: I just downloaded the most recent version of NetBeans 8.2 with the JDK, specifically the Windows x64 version from here. The issue I'm having is when I open it and go to Available Plugins, there's no option for Python plugins. No Python Plugin Anyone know if there's a python plugin I can find externally to use with this? Looking in the Installed Plugins, there's no indication of a pre-existing Python plugin, btw.
tagged with: python
tagged with: plugins
has comment: http://stackoverflow.com/comment/134219890
accepted answer: http://stackoverflow.com/a/47483810
linked to: http://stackoverflow.com/q/8413242
score: 9
type: AnsweredQuestion
downvote count: 0
has title: Netbeans 8.2 Python Plugin
answer count: 1
has answer: http://stackoverflow.com/a/47483810

http://stackoverflow.com/a/47529424
has body: No, I don't think there is anything faster than dict. The time complexity of its index checking is O(1). ------------------------------------------------------- Operation | Average Case | Amortized Worst Case | ------------------------------------------------------- Copy[2] | O(n) | O(n) | Get Item | O(1) | O(n) | Set Item[1] | O(1) | O(n) | Delete Item | O(1) | O(n) | Iteration[2] | O(n) | O(n) | ------------------------------------------------------- PS https://wiki.python.org/moin/TimeComplexity
score: 4
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47529386
answers question: http://stackoverflow.com/q/47529386
upvote count: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/81991525
score: 0
type: AnswerComment
has text: OK. Let's make algo perfect :) Point (0,0) in ((0,1),(1,0),(0,-1),(-1,0)) gives Sum=8.
comment on: http://stackoverflow.com/a/47508665
type: Comment

http://stackoverflow.com/comment/81813433
type: Comment
has text: @PatrickHaugh I called pop on the stack objects (stk1 and stkall) which i created. Please explain exactly what you mean by it should be called stack.pop() . Can you do a demonstration please ?
type: AnswerComment
comment on: http://stackoverflow.com/a/47423560
score: 0

http://stackoverflow.com/comment/81798620
type: Comment
comment on: http://stackoverflow.com/q/47420889
score: 0
type: QuestionComment
has text: please watch your quote chars in the code sample

http://stackoverflow.com/q/47442348
type: Question
linked to: http://stackoverflow.com/q/12791997
has comment: http://stackoverflow.com/comment/81839967
tagged with: raspberry-pi
answer count: 0
has comment: http://stackoverflow.com/comment/81839892
has title: How can I change the `rwx`-rights of a file in python and how do the rights work?
type: UnansweredQuestion
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/12791997
downvote count: 1
favorite count: 0
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/81840095
has comment: http://stackoverflow.com/comment/81857221
has body: I am currently writing a file managing system in python, now I want to know how can I change the rights for access to a file or folder in a most basic way. I'm programming on a RPi3. I am familiar with linux and python, but I want a "solution closer to the basis of linux". I know well that I could do it by running a shell command with subprocess or so. I want some deep experience with file rights and such stuff. I still have problems with the real basic understanding of the rwx-stuff. Are there a couple of bits that are set to the corresponding values in the actual file or are the right saved somwhere on the drive inbetween the files in a folder? Are the informations stored in the folder containing the file? I really can't imagine how to access this information and/or change it. My final questions are: How does the right system work in the deepest level? Is there some part in the os-libary or some other library to manage this task? I special I'd appreciate a solution for RPi3 but any solutio for linux would be handy as well. Thanks in advance!

http://stackoverflow.com/q/47466354
tagged with: networkx
type: Question
has answer: http://stackoverflow.com/a/47565728
tagged with: matplotlib
has body: I am using python, NetworkX and Matplotlib, I want to connect same node from two graphs For example two graphs:G1 and G2 G1=nx.Graph() G2=nx.Graph() G1.add_nodes_from([0,1,2,3,9,8,10,11,12,13,14]) G2.add_nodes_from([4,5,6,7,8]) G1.add_edges_from([(0,1),(2,3),(2,9),(2,12),(1,9),(10,8),(8,11),(8,13),(8,14)]) G2.add_edges_from([(4,5),(6,7),(4,8)]) pos1=nx.spring_layout(G1,k=0.2,iterations=30) pos2=nx.spring_layout(G2) for k,v in pos2.items(): v[0] = v[0] +3 nx.draw(G1,pos1,with_labels=True,node_color='b') nx.draw(G2,pos2,with_labels=True) The image is like this: My question is how can I connect the same nodes from two graphs? (node "8" is in both of them) I want node"8"(blue) link with node"8"(red). I also used G3= nx.compos(G1,G2), but I don't know how to draw the nodes(color =blue,from G1) at the right side and the other nodes at the left side(color =red, from G2). So I gave up this method.
has answer: http://stackoverflow.com/a/47530865
score: 2
upvote count: 2
has title: networkx: connect the same nodes from two graphs
answer count: 2
downvote count: 0
tagged with: python
type: UnansweredQuestion
favorite count: 0

http://stackoverflow.com/comment/81938358
comment on: http://stackoverflow.com/q/47491371
score: 0
has text: Great, that helps a lot. Note that the offset of `easting` is 16, not 12.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82010173
type: Comment
has text: I have also added one liner ( pythonic way) , @VivekSingh Please check
type: AnswerComment
comment on: http://stackoverflow.com/a/47526895
score: 0

http://stackoverflow.com/comment/81929447
comment on: http://stackoverflow.com/a/47487169
type: Comment
type: AnswerComment
has text: @user8670370 this method doesn't create variable `xx` it only read every line and convert to list which you can assign to different variables. You could use list or dictionary to keep more than last line.
score: 0

http://stackoverflow.com/comment/81792246
comment on: http://stackoverflow.com/a/47418145
has text: This code does what it should except the W_REC list is inserted whole instead of the values in W_REC - I think I can cope with that. The initial loop is extraneous given responses pointing out that a substring needs to be checked against all list elements. And that was part of my attempt to debug.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/51400653
answers question: http://stackoverflow.com/q/47455397
score: 6
has body: I tried with K.clear_session(), and it does boost the loading time each time. However, my models loaded in this way are not able to use model.predict function due to the following error: ValueError: Tensor Tensor("Sigmoid_2:0", shape=(?, 17), dtype=float32) is not an element of this graph. Github #2397 provide a detailed discussion for this. The best solution for now is to predict the data right after loading the model, instead of loading a dozens of models at the same time. After predicting each time you can use K.clear_session() to release the GPU, so that next loading won't take more time.
upvote count: 7
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/97676181

http://stackoverflow.com/q/47406095
has comment: http://stackoverflow.com/comment/81765824
has comment: http://stackoverflow.com/comment/81765696
has comment: http://stackoverflow.com/comment/81765634
tagged with: ubuntu
accepted answer: http://stackoverflow.com/a/52000642
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81765680
has title: How to use python2.7 with python command?
has comment: http://stackoverflow.com/comment/81765761
has comment: http://stackoverflow.com/comment/81765718
has comment: http://stackoverflow.com/comment/81765777
has comment: http://stackoverflow.com/comment/81765711
has comment: http://stackoverflow.com/comment/81765739
score: 1
has comment: http://stackoverflow.com/comment/81765714
tagged with: python
has answer: http://stackoverflow.com/a/52000642
linked to: http://stackoverflow.com/q/10986155
upvote count: 2
has comment: http://stackoverflow.com/comment/81765729
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81765908
tagged with: bash
has comment: http://stackoverflow.com/comment/81765957
has body: I have to install little bit older Python 2.7 : Now to use it every time I need to use python2.7. For example: For Example to Check the latest python version; I need to use below command python2.7 -V and it is giving proper results back like below: Python 2.7.13 But I want to use that with python command. Something like python2.7. How can I do this? How can I do python -V and verify something like Python Python 2.7.13?
answer count: 1
downvote count: 1

http://stackoverflow.com/a/47408626
has body: So I would need to type something like if(health &lt;= 0)" print("Game over") else: print("New health") Shame there isn't something in python for this, wish I could put before my code: cont if(health &lt;= 0): print("Game over") This would mean that whenever the health reached 0 or below, no matter where in the code after this, Game Over would print. Then I wouldn't need to type anything when health is taken away apart from health = health - 1
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47407869

http://stackoverflow.com/a/47497162
accepted answer of: http://stackoverflow.com/q/47496964
type: Answer
answers question: http://stackoverflow.com/q/47496964
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81949707
has body: From the value of df.head() that you have shared in the image above, it is apparent that the CSV file is not getting parsed as desired. Provide the separator argument with the value of semi-colon like so: sep=';' Refer to this post if you need more details about parsing CSV files in Pandas that aren't really comma separated.

http://stackoverflow.com/comment/81835008
comment on: http://stackoverflow.com/q/47440037
type: Comment
has text: `numbers[pos]` is a single value from the list, not itself a list. `[numbers[pos]]` would put it back in a list. Or use `numbers[pos:pos + 1]` to slice one element.
type: QuestionComment
score: 2

http://stackoverflow.com/comment/81873280
score: 0
comment on: http://stackoverflow.com/q/47458024
has text: How could you copy the file *by hand*? Is there a network access to the remote server (`\\server\share\path\to\folder`), or do you use a file copy program (filezilla, scp, sftp, ftp, etc.)? You will have to mimic or use the same from Python.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47507470
tagged with: pandas-groupby
upvote count: 2
tagged with: pandas
score: 2
has title: Pandas groupby with regex capturing unwanted elements in series
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: It's my first time posting, so I hope this is sufficiently documented to explain the issue I'm having. I am working with 25-odd years of NOAA wind direction and speed data, that I have cleaned and loaded into a Pandas data frame. I was able to successfully sort the data by month, using the following to isolate my results to only July of each year: in: july_df = df[df['date'].str.contains('\d{4}\-(7|07)', regex=True)] in: july_df.head(5) Out: date time direction speed 24732 1992-07-01 00:00 128.0 4.1 24733 1992-07-01 00:10 120.0 3.3 24734 1992-07-01 00:20 117.0 3.2 24735 1992-07-01 00:30 108.0 3.1 24736 1992-07-01 00:40 112.0 2.9 However, when I attempt to isolate the data further, grouping it by daily reading from only the month of July, I consistently get a few readings from the first day, and the number of those readings seems to change according to how many entries I want to view at a time. Here, I try to groupby July 14th: in: july_14 = july_df.groupby(df.date.str.contains("\d{4}\-07\-14", regex=True)) in: july_14.head(5) out: date time direction speed 24732 1992-07-01 00:00 128.0 4.1 24733 1992-07-01 00:10 120.0 3.3 24734 1992-07-01 00:20 117.0 3.2 24735 1992-07-01 00:30 108.0 3.1 24736 1992-07-01 00:40 112.0 2.9 26532 1992-07-14 00:00 91.0 4.3 26533 1992-07-14 00:10 82.0 4.2 26534 1992-07-14 00:20 78.0 4.6 26535 1992-07-14 00:30 73.0 4.6 26536 1992-07-14 00:40 71.0 4.2 I expected that grouping as I had previously would output only results related to July 14, which is the date I want to analyze more closely. I think the problem is in the regex I am using. For example, if I change the input to a day not in the dataset (July 32), I still get results for July 1: in: july_14 = july_df.groupby(df.date.str.contains("\d{4}\-07\-32", regex=True)) in: july_14.head() out: date time direction speed 24732 1992-07-01 00:00 128.0 4.1 24733 1992-07-01 00:10 120.0 3.3 24734 1992-07-01 00:20 117.0 3.2 24735 1992-07-01 00:30 108.0 3.1 24736 1992-07-01 00:40 112.0 2.9 I even get …
accepted answer: http://stackoverflow.com/a/47737955
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/47737955
type: AnsweredQuestion

http://stackoverflow.com/comment/94841209
comment on: http://stackoverflow.com/q/47447270
has text: I found a great answer here: https://stackoverflow.com/questions/40993626/list-memory-usage-in-ipython-and-jupyter
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47512483
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48186412
has title: auto execute a web service in falcon
favorite count: 0
type: Question
tagged with: gunicorn
tagged with: falconframework
accepted answer: http://stackoverflow.com/a/48186412
tagged with: netflix-eureka
tagged with: python
has body: I have a function which registers my web-services to spring-eureka discovery server but it automatically de-registers it. to solve this problem, I thought to make a function which will automatically execute in few seconds and register my service again and again. Please suggest what to do and if u have a better approach to encounter this problem that will be great.

http://stackoverflow.com/q/47533787
type: Question
has comment: http://stackoverflow.com/comment/138881416
has comment: http://stackoverflow.com/comment/137333232
answer count: 2
has answer: http://stackoverflow.com/a/67051608
tagged with: python
has comment: http://stackoverflow.com/comment/138369876
upvote count: 177
score: 177
has body: When I want to typehint a tuple in Python like: def func(var: tuple[int, int]): # do something func((1, 2)) # would be fine func((1, 2, 3)) # would throw an error It is required to give the exact number of items in the tuple. That's different from list typehinting: def func(var: list[int]): # do something func([1]) # would be fine func([1, 2]) # would also be fine func([1, 2, 3]) # would also be fine That's consequentially, in a way, because of the type of tuples. Because they are designed not to be changed, you have to hardcode the amount of items in it. So my question is, is there a way to make the number of items in a tuple type hint flexible? I tried something like that but it didn't work: def func(var: tuple[*int]):
has answer: http://stackoverflow.com/a/47534998
accepted answer: http://stackoverflow.com/a/47534998
has title: Type hinting tuples in Python
linked to: http://stackoverflow.com/q/54747253
type: AnsweredQuestion
downvote count: 0
tagged with: python-typing
favorite count: 0
possible better answer: http://stackoverflow.com/a/67051608

http://stackoverflow.com/comment/82000817
type: Comment
comment on: http://stackoverflow.com/q/47522167
type: QuestionComment
score: 0
has text: @PauloScardine Would that help?

http://stackoverflow.com/q/47399349
type: Question
has body: I'm trying to do some hybrid app (Mac, Windos, Linux OS) with Pyinstaller on Ubuntu 17.10, but when I do: pyinstaller XXX.py It generates everything correctly but cannot execute the program (Made with PyQT4 7 Python2.7). The program contains the main.py &amp; file.py &amp; file.ui, What should I do to test the executable? When I run the file inside /dist or /build, it didn't do anything. LOG 82 INFO: PyInstaller: 3.3 82 INFO: Python: 2.7.14 83 INFO: Platform: Linux-4.13.0-16-generic-x86_64-with-Ubuntu-17.10-artful 83 INFO: wrote /home/manel/Documentos/PythonProject/GUI.spec 85 INFO: UPX is not available. 86 INFO: Extending PYTHONPATH with paths ['/home/manel/Documentos/PythonProject', '/home/manel/Documentos/PythonProject'] 86 INFO: checking Analysis 86 INFO: Building Analysis because out00-Analysis.toc is non existent 87 INFO: Initializing module dependency graph... 88 INFO: Initializing module graph hooks... 117 INFO: running Analysis out00-Analysis.toc 129 INFO: Caching module hooks... 131 INFO: Analyzing /home/manel/Documentos/PythonProject/GUI.py 960 INFO: Processing pre-safe import module hook _xmlplus 2511 INFO: Processing pre-find module path hook distutils 2834 INFO: Processing pre-find module path hook PyQt4.uic.port_v3 2835 INFO: Processing pre-find module path hook PyQt4.uic.port_v2 2963 INFO: Loading module hooks... 2963 INFO: Loading module hook "hook-distutils.py"... 2963 INFO: Loading module hook "hook-sysconfig.py"... 2964 INFO: Loading module hook "hook-xml.py"... 3001 INFO: Loading module hook "hook-gtk.py"... 3002 WARNING: Hidden import "gtkglext" not found! 3002 WARNING: Hidden import "gdkgl" not found! 3003 WARNING: Hidden import "gdkglext" not found! 3003 WARNING: Hidden import "gtk.gdk" not found! 3003 WARNING: Hidden import "gtk.gtkgl" not found! 3003 WARNING: Hidden import "gtk.gtkgl._gtkgl" not found! 3004 WARNING: Hidden import "gtkgl" not found! 3046 INFO: Loading module hook "hook-lxml.etree.py"... 3047 INFO: Loading module hook "hook-h…
tagged with: pyinstaller
tagged with: pyqt4
tagged with: python
linked to: http://stackoverflow.com/q/7674790
has answer: http://stackoverflow.com/a/47399411
score: 0
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48507212
has title: How to use PyInstaller with multiple .py?

http://stackoverflow.com/comment/81881334
comment on: http://stackoverflow.com/q/47463177
type: Comment
has text: I have modified the question now,hope it makes sense
type: QuestionComment
score: 0

http://stackoverflow.com/a/47502380
has body: As per the answer by @timgeb I'd use a dictionary, but if you're accessing a lot, care about speed and don't want to define a class you can use caching. from functools import lru_cache def get_ext(file_type): d = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv']} return d[file_type] @lru_cache(maxsize=3, typed=False) def get_ext_cached(file_type): d = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv']} return d[file_type] from timeit import timeit # non cached print(timeit(stmt='get_ext("text")', globals={'get_ext': get_ext})) # 0.48447531609922706 on my machine # cached print(timeit(stmt='get_ext("text")', globals={'get_ext': get_ext_cached})) # 0.11434909792297276 Though for this particular case it's likely overkill and you can just call get on the dictionary directly (cache just builds its own dictionary and does exactly that) you can use this in future for any pure functions which are effectively a computed lookup. d = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv']} # 0.05016115184298542 print(timeit(stmt="d['text']", globals={'d':d,'c':c}))
downvote count: 1
has comment: http://stackoverflow.com/comment/81969214
answers question: http://stackoverflow.com/q/47496415
type: Answer
upvote count: 2
score: 1

http://stackoverflow.com/comment/81874148
score: 0
comment on: http://stackoverflow.com/a/47457647
type: Comment
type: AnswerComment
has text: http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.LatentDirichletAllocation.html and https://github.com/bmabey/pyLDAvis for visualization, perhaps?

http://stackoverflow.com/comment/81762921
comment on: http://stackoverflow.com/q/47404561
type: QuestionComment
has text: What do you mean you want to group them together? Isn't the output in order already?
score: 0
type: Comment

http://stackoverflow.com/q/47425356
score: 1
has answer: http://stackoverflow.com/a/47430899
downvote count: 1
favorite count: 0
type: Question
has body: I have a dataset “Digit” . The dataset includes 1797 small images (8x8 pixels), each one includes a hand-written digit (0-9). Each image is considered as a data sample with pixels as features. Thus, to build the feature table you have to convert each 8x8 image into a row of the feature matrix with 64 feature columns for 64 pixels. How to build a feature matrix and label vector for it ???
tagged with: matplotlib
tagged with: python
possible better answer: http://stackoverflow.com/a/47425473
has answer: http://stackoverflow.com/a/47425473
has title: Build the feature matrix and label vector:
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47430899
answer count: 2
tagged with: scikit-learn

list-comprehension
tags question: http://stackoverflow.com/q/47476737
type: Tag
tags question: http://stackoverflow.com/q/47533351
tags question: http://stackoverflow.com/q/47523123
tags question: http://stackoverflow.com/q/47492077
tags question: http://stackoverflow.com/q/47497321
tags question: http://stackoverflow.com/q/47451284
tags question: http://stackoverflow.com/q/47431752
tags question: http://stackoverflow.com/q/47494385
tags question: http://stackoverflow.com/q/47465658
tags question: http://stackoverflow.com/q/47404659
tags question: http://stackoverflow.com/q/47473084
tag name: list-comprehension
tags question: http://stackoverflow.com/q/47513408
tags question: http://stackoverflow.com/q/47463480

http://stackoverflow.com/comment/81877101
has text: I try to test by using put command but It stuck in 'quit' condition that I've not done it yet "NameError: name 'reqCommand' is not defined' . I passed through the upper code. So, if I go the right way. I just want to know. what should I do next with the 'put' and 'get' the command. @CristiFati
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47460889
type: Comment

http://stackoverflow.com/comment/81845011
has text: In you for loop, you are overwriting your `table_pull` variable so only the last row is being processed. You have to indent the code after the loop so it is executed inside the loop, also making sure you append to dataframe instead of assigning (`df[...] = list(...` lines).
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47444791
type: QuestionComment

http://stackoverflow.com/comment/82045360
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47523018
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160042/discussion-between-roberto-bassett-and-spektre).

http://stackoverflow.com/a/47458161
upvote count: 2
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47458089
has body: a, b = line cannot work because you're trying to unpack a string into 2 elements (unless the string itself is 2 elements long, which isn't the case) you want to convert to float &amp; unpack the splitted line like this: a, b = map(float,line.split()) in that case split() without arguments takes care of multiple spaces, linefeeds, tabs... like awk would do so it's pretty easy.
answers question: http://stackoverflow.com/q/47458089

http://stackoverflow.com/a/47427372
type: Answer
has body: Consider this simplified dataframe df = pd.DataFrame({'id': [2,6,7,8,23], 'props': [['FUT', 2, 'SG'], ['NFIN'], ['PST', 'ACT', 'PL', 'MASC', 'HUM'], ['FUT', 3, 'PL'],['PST', 2, 'SG', 'FEM']]}) You can split the list column using df[[1,2,3,4,5]] = df.props.apply(pd.Series) You get id props 1 2 3 4 5 0 2 [FUT, 2, SG] FUT 2 SG NaN NaN 1 6 [NFIN] NFIN NaN NaN NaN NaN 2 7 [PST, ACT, PL, MASC, HUM] PST ACT PL MASC HUM 3 8 [FUT, 3, PL] FUT 3 PL NaN NaN 4 23 [PST, 2, SG, FEM] PST 2 SG FEM NaN Note: You can specify more relevant column names, I just used 1,2,3,4,5
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47427314

http://stackoverflow.com/comment/81805078
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47424654
has text: Are you running the same version of Python (3.6.0) and Django (1.11.7) on your development environment?

http://stackoverflow.com/q/47433100
tagged with: python
has body: When I go to my "edit profile" page this is what it looks like: So it shows me the algorithm, iterations and hash. And if I want to remove it form my forms.py (remove password): class EditProfileForm(UserChangeForm): template_name='/something/else' class Meta: model = User fields = ( 'email', 'first_name', 'last_name', **'password'** ) It shows me this: Feel free to share your ideas.
accepted answer: http://stackoverflow.com/a/48283107
has comment: http://stackoverflow.com/comment/83549625
type: AnsweredQuestion
tagged with: passwords
score: 0
has comment: http://stackoverflow.com/comment/83543911
answer count: 1
has title: Edit Profile gives me algorithm, iterations and hash in Django
has comment: http://stackoverflow.com/comment/83549787
has answer: http://stackoverflow.com/a/48283107
type: Question
has comment: http://stackoverflow.com/comment/83549558
tagged with: django

http://stackoverflow.com/comment/81875870
has text: i set `window = None` before `funcA()` gets executed. if `funcA()` sets `window` to `self`, shouldnt be `None` after `funcA()` runs
comment on: http://stackoverflow.com/q/47460324
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47413871
has comment: http://stackoverflow.com/comment/81781815
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/81781688
has comment: http://stackoverflow.com/comment/81781244
has title: Mock datetime.datetime.now() while unit testing
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/4481954
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81781650
has body: @pytest.mark.parametrize("test_input,expected_output", data) def test_send_email(test_input, expected_output): emails = SendEmails(email_client=MagicMock()) emails.send_email = MagicMock() emails.send_new_email(*test_input) emails.send_email.assert_called_with(*expected_output) I am looking to mock datetime.datetime.now() which is called in the send_new_email method. I am unsure how to do it however. I tried creating a new datetime object datetime_object = datetime.datetime.strptime('Jun 1 2017 1:33PM', '%b %d %Y %I:%M%p') and then overriding datetime.datetime.now datetime.datetime.now = MagicMock(return_value=datetime_object) However, I get the error TypeError: can't set attributes of built-in/extension type 'datetime.datetime' This question was marked as duplicate of Python: Trying to mock datetime.date.today() but not working Python: Trying to mock datetime.date.today() but not working I had already tried this solution but I could not get it to work. I cannot install freezegun due to the project requirements. I have created a new class in the test file class NewDate(datetime.date): @classmethod def today(cls): return cls(2010, 1, 1) datetime.date = NewDate But I have no idea how to get the SendEmails class to use this.
has answer: http://stackoverflow.com/a/48473381
type: UnansweredQuestion
tagged with: datetime
tagged with: python

http://stackoverflow.com/q/47480570
has comment: http://stackoverflow.com/comment/104199675
type: UnansweredQuestion
tagged with: python
tagged with: bravado
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47480695
has title: Requests / bravado 302 response to POST turns into GET (python)
downvote count: 0
answer count: 1
tagged with: python-requests
linked to: http://stackoverflow.com/q/31887512
has body: As I was writing a handler for a webservice in bravado (through a request.session()) I came across this peculiarity: A POST request turns into a GET request as it's being redirected. Causing my POST to be mangled and I can not get the thing to work. EDIT: The actual requests call is made from bravado as explained in: How do you set a custom http client in Bravado? Which I needed for setting the additional client side certificates. So the requests call/session itself is being obscured by bravado. This issue (the post/get transition by requests) has been discussed in other threads where it is considered according to spec, but a weirdness nonetheless. In the end I just hacked into requests in the following segments in session.py: def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # http://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != 'HEAD': if method == 'POST': #print ( '\n\nDeliberately not changing to GET\n\n' ) else: method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method Where I simply not change to get. And also here: def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs): Where I commented out: ## # https://github.com/requests/requests/issues/1084 ## if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): ## # https://github.com/requests/requests/issues/3490 ## print(prepared_request.headers) ## purged_head…
has comment: http://stackoverflow.com/comment/105432830
favorite count: 0
type: Question

http://stackoverflow.com/comment/81933832
type: Comment
type: QuestionComment
has text: You could hook into the `save` or connect to the `post_save` signal, and call your publish task via `apply_async(eta=instance.publish_date)`. Of course the task itself needs to recheck if the date hasn't changed.
comment on: http://stackoverflow.com/q/47489274
score: 1

http://stackoverflow.com/a/61240860
has body: In general chunk version suggested by @T_cat works great. However, memory exploding might be caused by joining on columns that have Nan values. So you may want to exclude those rows from the join. see: https://github.com/pandas-dev/pandas/issues/24698#issuecomment-614347153
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47386405
type: Answer

http://stackoverflow.com/comment/82073181
type: Comment
has text: So, you are looking for tweets that are 9 years old. You cannot do that with the Twitter API. As I mentioned in my answer, you can only get tweets going back about 1 week (from the present).
type: AnswerComment
comment on: http://stackoverflow.com/a/47541651
score: 0

http://stackoverflow.com/a/60147368
downvote count: 1
answers question: http://stackoverflow.com/q/47392423
has body: It might be due to chromedriver no longer supports chrome version installed on your machine. Update your Chromedriver to more up to date version.
type: Answer
score: 0
upvote count: 1

http://stackoverflow.com/comment/81857588
comment on: http://stackoverflow.com/a/47451313
score: 0
type: Comment
has text: Hi please see edit, using if statements stops the function breaking and creates division errors
type: AnswerComment

http://stackoverflow.com/comment/81927790
type: AnswerComment
comment on: http://stackoverflow.com/a/47464212
score: 0
type: Comment
has text: Saw the example. Can you also provide a screenshot of how you want the final answer to be?

http://stackoverflow.com/q/47514666
has comment: http://stackoverflow.com/comment/81985596
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47514752
type: Question
has answer: http://stackoverflow.com/a/47514724
has body: I have a couple of different functions, that each outputs a json string if successful. I cannot know beforehand whether they will fail or not so I want have to try them all in the order specified below. How can I do this? I have tried things like: import func1 import func2 import func3 def compi(url): try: return func1(url) except: return func2(url) else: return func3(url) I am certain that func3 will not fail.
tagged with: algorithm
tagged with: python
possible better answer: http://stackoverflow.com/a/47514752
has comment: http://stackoverflow.com/comment/81985256
accepted answer: http://stackoverflow.com/a/47514724
type: AnsweredQuestion
answer count: 2
tagged with: function
has title: How to try different function, and return first output that succeds in python?
downvote count: 0

http://stackoverflow.com/a/47446858
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Did you try giving the chrome webdriver path directly inside the parenthesis? Same code works perfectly on my windows machine. I have set environment variables, else i need to provide the path directly.
answers question: http://stackoverflow.com/q/47413099
has comment: http://stackoverflow.com/comment/81849104

sys
tags question: http://stackoverflow.com/q/47525300
tags question: http://stackoverflow.com/q/47403920
type: Tag
tags question: http://stackoverflow.com/q/47493955
tag name: sys
tags question: http://stackoverflow.com/q/47447686

http://stackoverflow.com/comment/81988991
type: QuestionComment
has text: You haven't created any instances of your class.... why would you expect it to work without an instance? If you want it to work without instances, then you probably don't want a class at all.
comment on: http://stackoverflow.com/q/47516511
score: 1
type: Comment

python-imaging-library
tags question: http://stackoverflow.com/q/47415828
tags question: http://stackoverflow.com/q/47442051
tags question: http://stackoverflow.com/q/47417852
type: Tag
tags question: http://stackoverflow.com/q/47385896
tags question: http://stackoverflow.com/q/47433119
tags question: http://stackoverflow.com/q/47495340
tags question: http://stackoverflow.com/q/47418252
tags question: http://stackoverflow.com/q/47478047
tags question: http://stackoverflow.com/q/47492099
tags question: http://stackoverflow.com/q/47418938
tags question: http://stackoverflow.com/q/47530959
tags question: http://stackoverflow.com/q/47387667
tags question: http://stackoverflow.com/q/47420130
tags question: http://stackoverflow.com/q/47436176
tags question: http://stackoverflow.com/q/47519099
tags question: http://stackoverflow.com/q/47494350
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/47398291
tags question: http://stackoverflow.com/q/47481433
tags question: http://stackoverflow.com/q/47431458
tags question: http://stackoverflow.com/q/47485011

http://stackoverflow.com/comment/82001697
has text: I realize it's an odd situation. In a nutshell I'm creating a program for archiving files, and I need to copy the actual font file into the archive. Therefore I need to know what the actual file name is, not the font name
comment on: http://stackoverflow.com/q/47503984
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47533175
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/3768895
tagged with: python
accepted answer: http://stackoverflow.com/a/47533558
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47533558
type: Question
duplicate of: http://stackoverflow.com/q/3768895
has title: Why is this class not JSon serializable?
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/10252010
has body: I have this class in Python 3.5: class DataPoint(object): def __init__(self, time, value): self.time = time self.value = value And when I try to create a JSon from an instance, doing: json.dumps( intance_of_datapoint ) I get the error: TypeError: &lt; DataPoint object at 0x0123 &gt; is not JSon Serializable So I have tried to improve the class overwritting the repr method, like this: class DataPoint(object): def __init__(self, time, value): self.time = time self.value = value def __str__(self): return json.dumps(self.__dict__) __repr__ = __str__ By doing that I get: TypeError: {"value":52.29, "time":1} is not JSon serializable. Can you guys helps me undestand why? I'm pretty lost here.

http://stackoverflow.com/a/47502546
has body: The problem is that you are re-opening the output file on each loop iteration which will cause it to overwrite -- unless you explicitly open it in append mode. The glob logic is also unnecessary when you already know the filename. Try this instead: with open("result.txt", "wb") as outfile: for url in urls: with open(url, "rb") as infile: outfile.write(infile.read())
answers question: http://stackoverflow.com/q/47502360
type: Answer
accepted answer of: http://stackoverflow.com/q/47502360
has comment: http://stackoverflow.com/comment/81962235
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81814046
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47429673
type: QuestionComment
has text: What is the error message you receive?

http://stackoverflow.com/comment/81957729
type: QuestionComment
comment on: http://stackoverflow.com/q/47492363
has text: Does this work ?
score: 0
type: Comment

http://stackoverflow.com/q/47398644
has comment: http://stackoverflow.com/comment/81750725
has comment: http://stackoverflow.com/comment/81750373
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47398886
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81750304
has comment: http://stackoverflow.com/comment/81750354
has answer: http://stackoverflow.com/a/47398886
has comment: http://stackoverflow.com/comment/81750386
has title: How can I label a certain mob, and pull it later
has comment: http://stackoverflow.com/comment/81750341
tagged with: python
upvote count: 0
score: -2
downvote count: 2
answer count: 1
has body: I send this code through a program to decide which mobs the user will be fighting, but every time it gets to this it produces "Headless_Horseman (or whichever mob it picks) is undefined." I cannot figure out how to 'define' the name. def mob_picker_randmob1 (): global Zombie global Zambie global Giant_Worm global Headless_Horseman global Skeleton global Ghost global Ghoul global Baby_Sister global Little_Sister global Big_Sister randmob1=random.randint(1,5) if randmob1 == 1: randmob1 = Zombie mob_picker_randmob2 () elif randmob1 == 2: randmob1 = Skeleton mob_picker_randmob2 () elif randmob1 == 3: randmob1 = Giant_Worm mob_picker_randmob2 () elif randmob1 == 4: randmob1 = Headless_Horseman mob_picker_randmob2 () elif randmob1 == 5: randmob1 = Zambie mob_picker_randmob2 ()

http://stackoverflow.com/comment/81864805
type: Comment
type: QuestionComment
has text: Please provide a minimal, complete example as top-level module code -- not snippets from a method.
comment on: http://stackoverflow.com/q/47453427
score: 0

http://stackoverflow.com/comment/81723052
comment on: http://stackoverflow.com/q/47384746
score: 0
type: Comment
has text: Hmm.. I'm currently using InnoDB. If I were to use a row for each vector point, I would end up with 2,048,000,000 rows for 1 million images.
type: QuestionComment

http://stackoverflow.com/comment/81851829
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47447524
has text: I think I got it. I just put 'Date', 'Pos'. I sanity checked it and it works! Thanks for your help!

http://stackoverflow.com/q/47383360
has answer: http://stackoverflow.com/a/47383609
favorite count: 0
type: Question
tagged with: find
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81726028
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/81727224
tagged with: python
has comment: http://stackoverflow.com/comment/81724384
has title: How to find the first biggest sqaure in image (Without external libraries)
has body: So, I have different images and I have to run on the image and find the first biggest square on the picture by the color that given as variable in the function. (That means if there are for example 2 square with the same amount of pixels so the first square is the chosen) It's a mission that I have to do but I'm stuck and don't know how to get to the result :( We using the function load from the file immagini. filename = the image name c = the RGB code. my code is: from immagini import * def quadrato(filename,c): #Get image from the user (load image) img = load(filename) #print(img[y][x][r,g,b]) #Loop trough the image #Get the width and height of the image counter = [] for y in range(0, len(img[:])): for x in range(0, len(img[y][:])): #Scan for the R #Scan for the G #Scan for the B #If detecs all RGB are the same from the input if img[y][x][0] == c[0] and img[y][x][1] == c[1] and img[y][x][2] == c[2]: counter.append((x,y)) print (((len(counter)), (x ,y),img[y][x])) So my code prints how many pixels with the requested color,the location of the pixel and his color. for example (The number of pixels of the sqaure , (x,y) location) The input ('Img1.png',(255,0,0)) , The output must be (30, (60, 50)) The input ('Img2.png',(0,0,255)) , The output must be (201,(54,240)) Thank you guys, I hope you understand me,it's a little hard for me to explain, If there is a problem in the post,tell me :)
answer count: 1
tagged with: image-processing

http://stackoverflow.com/a/47539231
has comment: http://stackoverflow.com/comment/82046862
score: 1
answers question: http://stackoverflow.com/q/47537024
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82045502
has comment: http://stackoverflow.com/comment/82043645
accepted answer of: http://stackoverflow.com/q/47537024
has comment: http://stackoverflow.com/comment/82043946
has comment: http://stackoverflow.com/comment/82043481
type: Answer
has comment: http://stackoverflow.com/comment/82043658
has body: The easiest way to use Gurobi with Anaconda Python is to use Conda install from the instructions. Activate the Anaconda environment you want use. If your root environment is 3.6.3, then you don't need to do anything. Install Gurobi. Open Gurobi in terminal and copy your key with grbgetkey your_gurobi_key Add the gurobi channel to the list of repositories conda uses conda config --add channels http://conda.anaconda.org/gurobi Install the Gurobi Anaconda Python libraries conda install gurobi check your installation in iPython: m = grb.Model() vars = [m.addVar(name="x." + str(i)) for i in range(n)] m.update() constrs = [m.addConstr(vars[i] &lt;= i) for i in range(n)] m.update() retval = m.optimize() or use this simple script to check if the libraries and license are installed: python abrecheck.py
has comment: http://stackoverflow.com/comment/82043975

http://stackoverflow.com/comment/81791071
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47418294
has text: Do I need to remove pylint in order to work with flake8? Found it as an extension to VSCode

http://stackoverflow.com/q/47459717
has title: Does importing a module in Python execute all the module's imports in local scope?
accepted answer: http://stackoverflow.com/a/47460544
tagged with: python
possible better answer: http://stackoverflow.com/a/47459951
type: AnsweredQuestion
score: 0
tagged with: python-import
answer count: 2
has answer: http://stackoverflow.com/a/47460544
type: Question
has answer: http://stackoverflow.com/a/47459951
has body: $ python -c 'import urllib.parse; print(urllib.error.HTTPError)' Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; AttributeError: module 'urllib' has no attribute 'error' That's expected. I haven't imported urllib.error module. $ python -c 'import urllib.request; print(urllib.request.HTTPError)' &lt;class 'urllib.error.HTTPError'&gt; This one too. urllib.request imports urllib.error: from urllib.error import URLError, HTTPError, ContentTooShortError So the names are available via urllib.request. $ python -c 'import urllib.request; print(urllib.error.HTTPError)' &lt;class 'urllib.error.HTTPError'&gt; But not this one. What makes me able to access HTTPError via urllib.error? I've read the docs, but saw no clues there.

http://stackoverflow.com/comment/81933581
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47489274
has text: I dont need that, I need to schedule tasks using data that stored in database MySQL, and immediately to execute this in time. Also database can be extended by new dates. So Celery should be aware about that immidiatly. You sugest to use static concret date. It is not suitable for me.

http://stackoverflow.com/a/47417479
answers question: http://stackoverflow.com/q/47417436
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47417436
type: Answer
has body: because you have called the start at the end and start returns a none type you have essentailly cleared your kl variable. this should fix it. kl=threading.Thread(target=ftp1.ftptester, args=[self.finallist], daemon=False) k1.start() kl.join()
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47487198
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
tagged with: python
score: -1
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/81929542
has comment: http://stackoverflow.com/comment/81929273
tagged with: list
has body: what would be the correct way to set certain values of a list of lists to 0 then writing these back to a csv file? For example: list = [[a, 1, 0] , [b, 2, 5], [c, 6, 9], ............] Required output: list = [[a, 0, 0] , [b, 0, 0], [c, 0, 0], ............]
has title: Setting specific values in list of list within csv file
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47487210
has comment: http://stackoverflow.com/comment/81929586

http://stackoverflow.com/q/47500318
possible better answer: http://stackoverflow.com/a/47500546
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81956123
has body: Trying to sort a list of tuples that are returned from a mysql cursor in python, by using a secondary list of values. List used to order: [126028, 255872, 252614, 370772, 460757, 2, 412173, 384558, 111669, 232514] The list of tuples to sort: [(111669, '4b2c702d01e33f4bf5a816877d186de9.jpg'), (126028, 'f34d5dcb7311320a81430076604286a5.jpg'), (232514, 'b53ba7b840ce4e9e39c67e1c55af56b1.jpg'), (255872, '06225265afb87e7147a611f3e7ec2c4c.jpg'), (370772, '50502846b5203bd75a17936962ff37ca.jpg'), (384558, '07f3ea5009dbe63bea5211b9c90144cb.jpg'), (412173, 'b1e23c2f41e24459c12f1e5299662534.jpg'), (460757, 'd1b6a265ac26c327684b562be69641f7.jpg')] Ideally if elements aren't found in the returned results, they should be eliminated. Here's the new sorted order where you can see the values [252614, 2] were not found, therefore they would be excluded: [(126028, 'f34d5dcb7311320a81430076604286a5.jpg'), (255872, '06225265afb87e7147a611f3e7ec2c4c.jpg'), (370772, '50502846b5203bd75a17936962ff37ca.jpg'), (460757, 'd1b6a265ac26c327684b562be69641f7.jpg'), (412173, 'b1e23c2f41e24459c12f1e5299662534.jpg'), (384558, '07f3ea5009dbe63bea5211b9c90144cb.jpg'), (111669, '4b2c702d01e33f4bf5a816877d186de9.jpg'), (232514, 'b53ba7b840ce4e9e39c67e1c55af56b1.jpg')] Here is what I've tried: btree_ids = [126028, 255872, 252614, 370772, 460757, 2, 412173, 384558, 111669, 232514] media_id_list = [(111669, '4b2c702d01e33f4bf5a816877d186de9.jpg'), (126028, 'f34d5dcb7311320a81430076604286a5.jpg'), (232514, 'b53ba7b840ce4e9e39c67e1c55af56b1.jpg'), (255872, '06225265afb87e7147a611f3e7ec2c4c.jpg'), (370772, '50502846b5203bd75a17936962ff37ca.jpg'), (384558, '07f3ea5009dbe63bea5211b9c90144cb.jpg'), (412173, 'b1e23c2f41e24459c12f1e5299662534.jpg'), (460757, 'd1b6a265ac26c327684b562be69641f7.jpg')] print(sorted(media_id_list, key=lambda x: btree_ids.index(x[0])))
answer count: 2
has answer: http://stackoverflow.com/a/47500546
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47500368
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47500368
has comment: http://stackoverflow.com/comment/81956118
has comment: http://stackoverflow.com/comment/81956071
has title: Sort list of Tuples by Secondary List, Skip Missing Values in Python
tagged with: python

http://stackoverflow.com/a/47399793
downvote count: 0
answers question: http://stackoverflow.com/q/47399751
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81753008
has body: Slice objects can be assigned a name using the builtin slice: class slice(start, stop[, step]) Return a slice object representing the set of indices specified by range(start, stop, step). &gt;&gt;&gt; my_indices = slice(1, 3) &gt;&gt;&gt; "hello"[my_indices] 'el' Literal slices are actually translated to slice objects behind the scenes. And these are different from range objects in that they are not iterable. They only encapsulate the logic with which a sequence should be sliced: class D(object): def __getitem__(self, x): return x print(D()[1]) # 1 print(D()[1:3]) # slice(1, 3, None)
type: Answer
accepted answer of: http://stackoverflow.com/q/47399751
score: 3
upvote count: 3

http://stackoverflow.com/comment/82421178
type: Comment
has text: @JayBlanchard Thanks a lot for the advice Jay! I will make sure I will follow these in future.
type: AnswerComment
comment on: http://stackoverflow.com/a/47432963
score: 0

http://stackoverflow.com/a/47394732
answers question: http://stackoverflow.com/q/47393609
type: Answer
has comment: http://stackoverflow.com/comment/118241644
upvote count: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47393609
has body: The problem is caused because the QLabels are above the menu, blocking the click event of this. QMainWindow has a particular structure as shown in the following image: If you want to add a widget, you must do it to the Central Widget, when you pass a parent to a widget, it is placed in position `(0, 0) in relation to it. Making the modifications you get the following: class Example(QMainWindow): [...] def initUI(self): [...] #Exit on menubar exitAct = QAction('&amp;Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit applicatiion') exitAct.triggered.connect(qApp.quit) #Open on menubar openAct = QAction('&amp;Open', self) openAct.setShortcut('Ctrl+O') openAct.setStatusTip('Open Directory') openAct.triggered.connect(self.openFile) menubar = self.menuBar() fileMenu = menubar.addMenu('&amp;File') fileMenu.addAction(exitAct) fileMenu.addAction(openAct) centralwidget = QWidget(self) self.setCentralWidget(centralwidget) btn = QPushButton("Test", centralwidget) btn.resize(btn.sizeHint()) btn.move(50, 50) btn.clicked.connect(self.buttonpress) self.label = QLabel(centralwidget) self.image = QLabel(centralwidget) [...]
score: 3

http://stackoverflow.com/q/47538367
has body: My simple python script connects to an FTPS server, but it sets the type to "A". I need to set the Type to "I" but I don't see any helper methods to do this. Here is the code snippet: def connect(): ftp = FTP_TLS() ftp.ssl_version = ssl.PROTOCOL_TLSv1_1 ftp.debugging = 2 ftp.connect('foo.com', 20021) ftp.login('USER', 'PW') ftp.prot_p() return ftp ftp = connect() print ftp.retrlines('LIST')
score: 2
has answer: http://stackoverflow.com/a/76453246
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82046773
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82043783
favorite count: 0
type: Question
has title: Python FTPS - how do I set the Type to binary? (I)
tagged with: ftps
tagged with: python
has comment: http://stackoverflow.com/comment/82034553

http://stackoverflow.com/comment/82036371
score: 0
type: Comment
has text: @gibbz00 if you have a limited number of client ids, assuming you can only make one simultanious request per client ID, one solution would be to put them all into a queue in the beginning. Then you `get()` a client id before making the api call and `put()` it back afterwards. https://docs.python.org/2/library/queue.html
type: AnswerComment
comment on: http://stackoverflow.com/a/47539082

http://stackoverflow.com/a/47494803
downvote count: 0
has comment: http://stackoverflow.com/comment/81944529
has comment: http://stackoverflow.com/comment/81944686
answers question: http://stackoverflow.com/q/47494778
has comment: http://stackoverflow.com/comment/81944615
has body: To check whether elements of 1 list are present in other list or not. You can convert them into sets and use intersection and symmetric difference like this: &gt;&gt;&gt; list1 = ['foo', 'bar', 'baz'] &gt;&gt;&gt; list2 = ['foo', 'bundy', 'baz'] &gt;&gt;&gt; set(list1).intersection(set(list2)) {'foo', 'baz'} &gt;&gt;&gt; set(list1).symmetric_difference(set(list2)) {'bar', 'bundy'} &gt;&gt;&gt; set(list1).difference(set(list2)) {'bar'} &gt;&gt;&gt; set(list2).difference(set(list1)) {'bundy'} &gt;&gt;&gt; Intersection gives you common elements between the 2 sets. Difference gives you elements present in 1 set with respect to another. Symmetric difference gives you uncommon elements from both sets.
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/a/47495342
has comment: http://stackoverflow.com/comment/82010217
has comment: http://stackoverflow.com/comment/82009907
has comment: http://stackoverflow.com/comment/82010448
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Bear in mind that Global variables should be constant in nature. Event though it is possible to update Global variables from a keyword or Test Case, this should be an exceptional action. For regular updating of variables the Suite, Test Case and Keyword scopes should be used. In the below example I use a YAML variable file that holds a nested set of values. YAML imports allows for the definition of Python Lists, Scalars and Dictionaries in a human readable format, which is what makes them so useful for these types of nested imports. data.yaml DATA: Set 1: Lisa: - list item 1 - list item 2 Dica: dict item 1: value 1 dict item 2: value 2 vara: variable value 1 Set 2: Lisa: - list item 3 - list item 4 Dica: dict item 1: value 3 dict item 2: value 4 vara: variable value 2 The above script is loaded through Variables data.yaml statement below. The rest of the script then takes a specific sub-set of that structure and creates Global Variables from the items by looping through them. create_globals.robot *** Setting *** Library Collections Variables data.yaml *** Test Cases *** Test Case Create Globals Set 2 No Operation *** Keywords *** Get Data Set [Arguments] ${name} [Return] ${DATA['${name}']} Create Globals [Arguments] ${name} ${dataset} Get Data Set ${name} @{global_var_names} Get Dictionary Keys ${dataset} :FOR ${global_var_name} IN @{global_var_names} \ Set Global Variable ${${global_var_name}} ${dataset['${global_var_name}']} Because fetching the data set itself is abstracted through a keyword, changing the source of the data to for example a command line import or even a database is relative small change.
answers question: http://stackoverflow.com/q/47490802
has comment: http://stackoverflow.com/comment/82010103
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47490802

http://stackoverflow.com/comment/81901473
has text: Im seeing `radd` for the first time
score: 1
comment on: http://stackoverflow.com/a/47472986
type: AnswerComment
type: Comment

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

http://stackoverflow.com/a/47499864
downvote count: 0
upvote count: 1
has body: Complete solution with regex.findall() function and specific regex pattern: import re price_list = ['Weekly:$3,600.00\n\nMonthly:$15,120.00', 'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00', 'Daily:$1,800.00\n\nWeekend:$2200.00', 'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00'] base_dict = {'Yearly': 'NA', 'Monthly': 'NA', 'Weekly': 'NA', 'Daily': 'NA'} pat = re.compile('(?:(Yearly|Monthly|Weekly|Daily):(\$[\d.,]+))') for p_str in price_list: result_d = dict(base_dict) result_d.update(pat.findall(p_str)) print('Yearly: {Yearly}, Monthly: {Monthly}, Weekly: {Weekly}, Daily: {Daily}'.format(**result_d)) The output: Yearly: NA, Monthly: $15,120.00, Weekly: $3,600.00, Daily: NA Yearly: NA, Monthly: $33,600.00, Weekly: $8,400.00, Daily: $3,000.00 Yearly: NA, Monthly: NA, Weekly: NA, Daily: $1,800.00 Yearly: NA, Monthly: $24,000.00, Weekly: $6,000.00, Daily: NA
type: Answer
answers question: http://stackoverflow.com/q/47499526
score: 1

http://stackoverflow.com/comment/81854195
type: QuestionComment
comment on: http://stackoverflow.com/q/47449452
type: Comment
has text: https://stackoverflow.com/questions/40827356/find-a-value-in-json-using-python
score: 0

http://stackoverflow.com/q/47488873
has body: What am I doing wrong here with a bar chart in python and matplotlib? The first plot is good, the second has a much wider range on the x-axis up to 1500. Notice in the second plot that most of the bars on the low scale disappear, but also the bar at 1500 is not shown. I tried setting the width=0.8 in the bar() method, but that does not help. With a logarithmic x-axis (using plt.xscale('log') ) it seems to work fine import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(12, 6)) plt.bar(np.array([1,2,3,4,11,12]), np.array([10,2,1,1,3,10])) plt.show() #Then I close the figure and run this: plt.bar(np.array([1,2,3,4,11,1500]), np.array([10,2,1,1,3,10])) plt.show()
upvote count: 4
answer count: 1
tagged with: bar-chart
downvote count: 0
favorite count: 0
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/47489008
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47489008
tagged with: matplotlib
tagged with: python
has title: Bar chart in matplotlib shows less bars when having big range on x coordinates
score: 4

http://stackoverflow.com/comment/122756778
comment on: http://stackoverflow.com/a/51808854
type: Comment
type: AnswerComment
score: 1
has text: The author clearly mentioned that "the minimizer is not calling my functions a lot (objective/constraint/gradients)". Your suggestion to speed-up the objective/gradient computations, though interesting, is off-topic. Moreover, your code is tested in dimension `N=20` which is not the same setting as the OP ("1000+ input vector").

http://stackoverflow.com/comment/81950305
type: Comment
comment on: http://stackoverflow.com/a/47474068
type: AnswerComment
has text: after adding verbose=True, I did see the log in the terminal screen instead of notebook browser. On the browser, I can only one line print out as `[LibSVM]` in notebook. Is there any extra congiguration required to view log details?
score: 1

http://stackoverflow.com/a/47467310
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47467189
has comment: http://stackoverflow.com/comment/81889047
has comment: http://stackoverflow.com/comment/81889128
has body: Use zip() &gt;&gt;&gt; list(zip(*matrix)) [(2, 1, 9), (3, 2, 8), (4, 6, 9)] &gt;&gt;&gt;

http://stackoverflow.com/a/57161579
type: Answer
answers question: http://stackoverflow.com/q/47517484
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47517484
score: 0
has body: Generally it is checking for libvlc.dll and other couple of dll files, which were not included in my installed version of VLC (may be due to some issues during installation or any other reason. IDK). So copying the dlls to VLC installation folder or working directory of the project solved the problem.

http://stackoverflow.com/comment/81739385
type: Comment
score: 0
type: AnswerComment
has text: Not sure I understand. I don't want `do_something` to be in `one.py` or `two.py`. At the same time, I want the records in logs to have the names of those files rather than `utils`.
comment on: http://stackoverflow.com/a/47392953

http://stackoverflow.com/comment/81781963
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47408993
has text: You remove any newlines and whitespace so `fold -w` will keep on reading the stream forever. Voting to close as typo/trivial.
score: 0

http://stackoverflow.com/comment/81768212
score: 0
has text: this is vague - It's not possible to convert a document contains an objectId to json
type: QuestionComment
comment on: http://stackoverflow.com/q/47407537
type: Comment

http://stackoverflow.com/comment/108449492
has text: Does this answer your question? [Return multiple columns from apply pandas](https://stackoverflow.com/questions/23586510/return-multiple-columns-from-apply-pandas)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47433679

http://stackoverflow.com/comment/82034362
type: Comment
has text: I need to do a POST request . not GET !
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47530303

http://stackoverflow.com/comment/81759425
type: AnswerComment
has text: This almost *certainly* won't fix the underlying problem. Rather, the error will now be `TypeError: int() argument must be a string or a number, not 'list'`
comment on: http://stackoverflow.com/a/47402839
type: Comment
score: 0

http://stackoverflow.com/comment/81983929
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47513905
has text: I hereby nominate this answer for the Rube Goldberg Award xD
type: Comment

http://stackoverflow.com/a/47393526
type: Answer
has body: Here is a solution based on pandas apply valuecounts i.e import pandas as pd tup= [('2017-11-20', ['US', 'US', 'US', 'US', 'SK', 'SK', 'IE', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'GB', 'ES', 'ES', 'DE', 'CA', 'CA', 'CA', 'CA', 'CA', 'CA', 'CA', 'CA', 'CA', 'CA']), ('2017-11-10', ['US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US', 'US'])] count = pd.DataFrame(tup).set_index(0)[1].apply(pd.Series.value_counts).stack() 2017-11-20 CA 10.0 DE 1.0 ES 2.0 GB 28.0 IE 1.0 SK 2.0 US 4.0 2017-11-10 US 61.0 dtype: float64 count.to_dict() {('2017-11-20', 'ES'): 2.0, ('2017-11-20', 'US'): 4.0, ('2017-11-20', 'CA'): 10.0, ('2017-11-20', 'GB'): 28.0, ('2017-11-20', 'SK'): 2.0, ('2017-11-20', 'IE'): 1.0, ('2017-11-10', 'US'): 61.0, ('2017-11-20', 'DE'): 1.0}
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47393295
score: 1

http://stackoverflow.com/q/47430517
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/47431135
has answer: http://stackoverflow.com/a/47431135
answer count: 1
type: Question
has title: python process creation and process ID
has body: Can some one suggest what could be the best method to spawn a child process in python? I have used one method like below.How can I get the pid of child process in below method ? Or how do I know the process been actually created ? def main(): process = QtCore.QProcess() process.start('python', ['./Hello_World.py']) time.sleep(5) process.kill()
tagged with: python
has comment: http://stackoverflow.com/comment/81816339
has comment: http://stackoverflow.com/comment/81818008
has comment: http://stackoverflow.com/comment/81815473

excel
tags question: http://stackoverflow.com/q/47527630
tags question: http://stackoverflow.com/q/47455562
tags question: http://stackoverflow.com/q/47539523
tags question: http://stackoverflow.com/q/47515300
tags question: http://stackoverflow.com/q/47522167
tags question: http://stackoverflow.com/q/47387857
tags question: http://stackoverflow.com/q/47462108
tag name: excel
tags question: http://stackoverflow.com/q/47537762
tags question: http://stackoverflow.com/q/47489498
tags question: http://stackoverflow.com/q/47492343
tags question: http://stackoverflow.com/q/47442640
type: Tag
tags question: http://stackoverflow.com/q/47483480
tags question: http://stackoverflow.com/q/47517183
tags question: http://stackoverflow.com/q/47452663
tags question: http://stackoverflow.com/q/47474407
tags question: http://stackoverflow.com/q/47523795
tags question: http://stackoverflow.com/q/47432988
tags question: http://stackoverflow.com/q/47446890
tags question: http://stackoverflow.com/q/47389130
tags question: http://stackoverflow.com/q/47514607
tags question: http://stackoverflow.com/q/47446061
tags question: http://stackoverflow.com/q/47465312
tags question: http://stackoverflow.com/q/47430544
tags question: http://stackoverflow.com/q/47536523
tags question: http://stackoverflow.com/q/47504473

http://stackoverflow.com/comment/81838560
has text: You're getting that result because of how `itertools.product()` works. Can you add more detail about what you're trying to accomplish?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47441224
type: Comment

http://stackoverflow.com/q/47465111
has answer: http://stackoverflow.com/a/47465164
has comment: http://stackoverflow.com/comment/81885154
tagged with: classification
upvote count: 0
answer count: 1
downvote count: 3
tagged with: machine-learning
tagged with: text-classification
favorite count: 0
type: Question
has body: I need help on writing a python script foe the following task. Training data format: Record contains: Result: ------------------- --------- (x,f,r,t,w) -&gt; Positive (x,f,d,z,w,m,d) -&gt; Positive (x,f,e,o,p) -&gt; Negative (x,f,r,t,w,d) -&gt; Positive (z,q,4) -&gt; Negative And after that if i give a record like (c,r,s,w,f,h,t,d) then it should return a score based on how negative or positive it's. Note that the result is not positive or negative rather it should be a number between let's say for example 1 - 1000, 0 means most negative and 1000 means most positive.
type: UnansweredQuestion
tagged with: python
score: -3
tagged with: data-science
has title: Python machine learning script for text classification

primes
tags question: http://stackoverflow.com/q/47522991
type: Tag
tag name: primes

http://stackoverflow.com/comment/81871847
score: 0
comment on: http://stackoverflow.com/q/47457546
type: QuestionComment
type: Comment
has text: Checked almost the same logic but with separate worker for each env. passed args queue=ENV_NAME and routing key for each. In Celery config just added unique consumer for each ENV_NAME. And it;s worked. (N.b. group execution still give error "float() >= str()")

http://stackoverflow.com/comment/81950363
score: 2
has text: `s - arr.ravel()`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47497371

http://stackoverflow.com/comment/81963073
score: 0
type: Comment
type: QuestionComment
has text: Since the data set is quite huge, I think solution with np.apply_along_axis() would be better.
comment on: http://stackoverflow.com/q/47503631

http://stackoverflow.com/q/47492955
has body: in udacity self driving https://github.com/udacity/self-driving-car/tree/master/vehicle-detection/u-net the method get_mask_seg(img, bb_boxes_f) gives slice indices must be integers or none or have an index method &lt;ipython-input-58-b0cc385c742b&gt; in &lt;module&gt;() 2 3 training_gen = generate_train_batch(df_vehicles,10) ----&gt; 4 batch_img,batch_mask = next(training_gen) &lt;ipython-input-55-1399e4d6a92a&gt; in generate_train_batch(data, batch_size) 12 scale_range=50 13 ) ---&gt; 14 img_mask = get_mask_seg(img,bb_boxes) 15 batch_images[i_batch] = img 16 batch_masks[i_batch] =img_mask &lt;ipython-input-51-b5ad142378f0&gt; in get_mask_seg(img, bb_boxes_f) 8 bb_box_i = [bb_boxes_f.iloc[i]['xmin'],bb_boxes_f.iloc[i]['ymin'], 9 bb_boxes_f.iloc[i]['xmax'],bb_boxes_f.iloc[i]['ymax']] ---&gt; 10 img_mask[bb_box_i[1]:bb_box_i[3],bb_box_i[0]:bb_box_i[2]]= 1 11 img_mask = np.reshape(img_mask,(np.shape(img_mask)[0],np.shape(img_mask)[1],1)) 12 return img_mask TypeError: slice indices must be integers or None or have an __index__ method
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47493539
possible better answer: http://stackoverflow.com/a/47493539
tagged with: python
has answer: http://stackoverflow.com/a/47492977
accepted answer: http://stackoverflow.com/a/47492977
has title: slice indices must be integers or None or have an __index__ method in udacity self driving
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/a/47495790
downvote count: 0
has comment: http://stackoverflow.com/comment/81946625
has comment: http://stackoverflow.com/comment/81946707
has comment: http://stackoverflow.com/comment/81946660
has body: Use a function to encapsulate asking for information. You can pass in a validation test function: def ask(question, validator, errormessage): while True: result = raw_input(question) if not validator(result): print(errormessage) continue return result name = ask("NAME PLEASE\n", lambda s: s.isalpha(), "Please chars dude") age = ask("Please type your age\n", lambda s: s.isdigit(), "Please digits only") This is far more readable then any number of tests to see if the user already entered a correct name and you only need to ask for the age now.
type: Answer
has comment: http://stackoverflow.com/comment/81946638
has comment: http://stackoverflow.com/comment/81946647
score: 4
accepted answer of: http://stackoverflow.com/q/47495596
upvote count: 4
has comment: http://stackoverflow.com/comment/81946595
has comment: http://stackoverflow.com/comment/81946603
answers question: http://stackoverflow.com/q/47495596
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81946742

http://stackoverflow.com/a/47517764
upvote count: 23
accepted answer of: http://stackoverflow.com/q/47517696
has body: You can use a list comprehension to construct the new list with the cleaned up files names. \d is the regex to match a single character and $ only matches at the end of the string. file_lst_trimmed = [re.sub(r'\d\.fa$', '', file) for file in file_lst] The results: &gt;&gt;&gt; file_lst_trimmed ['cats', 'cats', 'dog', 'dog']
answers question: http://stackoverflow.com/q/47517696
downvote count: 0
type: Answer
score: 23
type: AcceptedAnswer

http://stackoverflow.com/comment/81943739
type: QuestionComment
type: Comment
has text: use `cv2.imread(filename, 3)` `3 for being bgr` and when passing to `countNonZero` make sure you only get one channel like `img[0]`
score: 0
comment on: http://stackoverflow.com/q/47494350

http://stackoverflow.com/a/47481260
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/47476941
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47476941
score: 2
has body: Solved the problem ! my mistake was in views.py in the form_valid function in the render call of the else block I redefined the context rather than passing the current context the context seems to include the information to show the overriden error messages so the corrected code should look like that: def form_valid(self, form, **kwargs): self.object = form.save() context = self.get_context_data(**kwargs) formset = context["formset"] if formset.is_valid(): formset.save() else: return render(self.request, self.template_name, context)

http://stackoverflow.com/comment/81843224
type: Comment
type: AnswerComment
score: 1
has text: Generally an error message tells you a line number where the error occurred. You should look on that line in the code.
comment on: http://stackoverflow.com/a/47422889

http://stackoverflow.com/comment/81781016
type: Comment
type: QuestionComment
has text: what do you want to get - `dfs` or `subtracted`?
score: 0
comment on: http://stackoverflow.com/q/47413535

http://stackoverflow.com/q/47481909
type: AnsweredQuestion
score: 3
has title: Using pydispatch between threads
upvote count: 3
answer count: 1
tagged with: events
accepted answer: http://stackoverflow.com/a/47499085
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47499085
has body: I faced a problem using pydispatch module for communication between threads. I used an example provided here: https://sites.google.com/site/hardwaremonkey/blog/python-howtocommunicatebetweenthreadsusingpydispatch I slightly modified it to provide a bit more detailed information in the log. In particular, I made it display the actual thread name as well: from pydispatch import dispatcher import threading import time import logging log_formatter = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] [%(threadName)s] %(message)s', '%H:%M:%S') logger = logging.getLogger() logger.setLevel(logging.DEBUG) log_handler = logging.StreamHandler() log_handler.setLevel(logging.DEBUG) log_handler.setFormatter(log_formatter) logger.addHandler(log_handler) ALICE_SIGNAL='alice_signal' ALICE_SENDER='alice_sender' BOB_SIGNAL='bob_signal' BOB_SENDER='bob_sender' class Alice(): ''' alice procrastinates and replies to bob''' def __init__(self): logger.debug('Alice instantiated') dispatcher.connect(self.alice_dispatcher_receive, signal=BOB_SIGNAL, sender=BOB_SENDER) self.alice() def alice_dispatcher_receive(self, message): ''' handle dispatcher''' logger.debug('Alice has received message: {}'.format(message)) dispatcher.send(message='thank you from Alice', signal=ALICE_SIGNAL, sender=ALICE_SENDER) def alice(self): ''' loop and wait ''' while True: logger.debug('Alice is procrastinating') time.sleep(1) class Bob(): ''' bob contacts alice periodically ''' def __init__(self): logger.debug('Bob instantiated') dispatcher.connect(self.bob_dispatcher_receive, signal=ALICE_SIGNAL, sender=ALICE_SENDER) self.bob() def bob_dispatcher_receive(self, message): ''' handle dispatcher ''' logger.debug('Bob has received message: {}'.format(message)) def bob(self): ''' loop and send messages using a dispatcher ''' while True: dispatcher.send(message='message from Bob', signal=BOB_SIGNAL, sender=BOB_SENDER) time.sleep(3) if __name__ == '__main__': logger.debug('Starting...') alice_thread = threading.Threa…
tagged with: multithreading
downvote count: 0
tagged with: python

http://stackoverflow.com/q/47500006
has comment: http://stackoverflow.com/comment/81955988
has title: Creating Random Matrix With Equal No of 1's and 0's in python
has comment: http://stackoverflow.com/comment/81956002
has comment: http://stackoverflow.com/comment/81955522
tagged with: python
tagged with: numpy
has body: I wanted to make a random matrix with equal no of 1 and 0 is there any other optimized way of doing that import numpy as np N = 50 X=10 arr = np.array([0] * N + [1] * N) np.random.shuffle(arr) arr=arr.reshape(X,X) print(arr) Is there a more optimized way of doing this?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81956116
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81955685
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81955873
has comment: http://stackoverflow.com/comment/81956176
score: 1

http://stackoverflow.com/q/47405274
has title: How to drop row in Dataframe if column is NaN and there is another row where the column is not NaN
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47405412
has answer: http://stackoverflow.com/a/47405412
type: AnsweredQuestion
tagged with: pandas
has body: I have a pandas dataframe in python where the rows are identified by p1 &amp; p2, but p2 is sometimes NaN: p1 p2 0 a 1 1 a 2 2 a 3 3 b NaN 4 c 4 5 d NaN 6 d 5 The above dataframe was returned from a larger one with many duplicates by using df.drop_duplicates(subset=["p1","p2"], keep='last') which works for the most part, the only issue being that NaN and 5 are technically not duplicates and therefore not dropped. How can I drop the rows (such as: "d", NaN) where there is another row with the same p1 and a p2 value of not.null eg. "d", 5. The important thing here being that "b", NaN is kept because there are no rows with "b", not.null.
score: 1
possible better answer: http://stackoverflow.com/a/47405430
tagged with: dataframe
upvote count: 1
has answer: http://stackoverflow.com/a/47405430
tagged with: nan
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/81852544
comment on: http://stackoverflow.com/a/47425788
type: AnswerComment
has text: Thanks all for the answer. As a side note, is it possible to make a label (eg. news sections) as a scrollable label and nothing else? From what I could find online it looked like you have to inherit it where I have GridLayout, so wasn't sure how to go about doing that.
score: 0
type: Comment

http://stackoverflow.com/comment/81919072
has text: The differences you see are on the order of machine precision; for all intents and purposes the results are the same. What would be interesting to check is the same with `copy=False` and `copy=True`. The suggestion of the documentation you're testing _should_ give the same result, and it does, so there's no question there.
score: 0
comment on: http://stackoverflow.com/q/47481880
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81761487
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47403815
has text: Oh sorry, thought I was in the Spanish community
score: 1

http://stackoverflow.com/comment/81996398
type: QuestionComment
score: 0
has text: You can use os.walk module. Do provide your work.
type: Comment
comment on: http://stackoverflow.com/q/47519913

http://stackoverflow.com/a/47438009
has comment: http://stackoverflow.com/comment/81831145
answers question: http://stackoverflow.com/q/47437326
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81831438
has body: Try: for element in root_elements: print element, type(element) will print: attribute &lt;type 'unicode'&gt; You may expect a dict but it is a string.

http://stackoverflow.com/comment/81797332
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47421316
has text: Good to know, thanks. This is my first time one here so I'l bear that in mind. What I'm trying to do is store those values (the indexes) in another array. This list is dynamic and the number and value of the index shown will change frequently. So I'm trying to find a solution that will automatically retrieve these integers and store them.

http://stackoverflow.com/comment/81752527
type: AnswerComment
score: 0
has text: I don't think that helps much. The script is apparently pointing to a selection of URLs in `all_url='/home/mifi/Desktop/R_project_detecting _malicious_url/original_dataset/data.csv'`. As I can not look into this file I don't think I can help you. Just provide an example of how the URLs sit in this file. If each is in a "cell" than read.csv should be able to seperate them from each other anyway. By the way, the standard option in R is to convert strings to factors when reading in csv files. You can turn that off with read.csv(file, stringsAsFactors = FALSE)...
type: Comment
comment on: http://stackoverflow.com/a/47398221

http://stackoverflow.com/q/47413270
has answer: http://stackoverflow.com/a/47428379
has answer: http://stackoverflow.com/a/47413770
tagged with: jq
upvote count: 0
has answer: http://stackoverflow.com/a/47414016
has comment: http://stackoverflow.com/comment/81780536
has comment: http://stackoverflow.com/comment/81780029
tagged with: python
has body: I have a file services.json which is located on remote machine, [ { "kind": "SpecialService", "type": "attribute", "spec": { "addresses": [ "172.21.3.196:6379" ] }, "apiVersion": "rbac.newDevops.com/v1", "metadata": { "name": "redis", "description": "autogenerated by superagent.py script" } }, ] Now, the task is to append the above file with the following element in json. { "kind": "PilotService", "apiVersion": "rbac.newDevops.com/v1", "type": "attribute-based", "metadata": { "name": "apache", "description": "apache service as a process" }, "spec": { "addresses": [ "172.22.0.7/24:80" ] } } Once we add the content into the json file we need to close the array of the existing json. (The file content starts with an array.) I tried using python to perform ssh to the remote machine but I'm failing in editing json on remote machine using jq or with open of python Any guidance on this like how do we edit json files on remote machine?
has comment: http://stackoverflow.com/comment/81779990
has title: how to add an element in json file which is located on remote machine
has comment: http://stackoverflow.com/comment/81780154
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81780060
possible better answer: http://stackoverflow.com/a/47414390
type: AnsweredQuestion
tagged with: bash
has answer: http://stackoverflow.com/a/47414390
has comment: http://stackoverflow.com/comment/81780186
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81779957
has comment: http://stackoverflow.com/comment/81780409
score: -1
tagged with: shell
linked to: http://stackoverflow.com/q/14711861
answer count: 4
accepted answer: http://stackoverflow.com/a/47413770
has comment: http://stackoverflow.com/comment/81780107
type: Question

http://stackoverflow.com/q/47495484
has answer: http://stackoverflow.com/a/47496643
has body: I am developing a custom GIMP plugin on Mac OS X. For programming reasons, I need to use some python modules that I have installed in system's default python environment (such as OpenCV, MoviePy, and some others), but I am unable to import them on the Python-Fu console because it uses the GIMP's app built-in python environment. My question is. Is there a way to tell GIMP to use another python interpreter? I've searched on GIMP preferences but I haven't found anything such as Python-Fu path or something similar. GIMP's Python interpreter is found here on my system: /Applications/GIMP.app/Contents/MacOS/python The interpreter that I want GIMP to use is found here on my system: /usr/bin/python Thanks!
tagged with: pythonpath
answer count: 1
type: Question
tagged with: gimp
has title: Change Gimp python interpreter path
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/47427386
type: AnsweredQuestion
tagged with: python-2.7
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81809948
has body: I am new in python, trying to make a function for matching the strings. N="TAG" K="L" D="E" g4 = 'NKXD' protein = 'MASEIHMTGPMCLIENTNGRLMANPEALKILSAITQPMVVVAIVGLYRTGKSYLMNKLAGKKKGFSLGSTVQSHTKGIWMWCVPHPKKPGHILVLLDTEGLGDVEKGDNQNDSWIFALAVLLSSTFVYNSIGTINQQAMDQLYYVTELTHRIRSKSSPDENENEVEDSADFVSFFPDFVWTLRDFSLDLEADGQPLTPDEYLTYSLKLKKGTSQKDETFNLPRLCIRKFFPKKKCFVFDRPVHRRKLAQLEKLQDEELDPEFVQQVADFCSYIFSNSKTKTLSGGIQVNGPRLESLVLTYVNAISSGDLPCMENAVLALAQIENSAAVQKAIAHYEQQMGQKVQLPTETLQELLDLHRDSEREAIEVFIRSSFKDVDHLFQKELAAQLEKKRDDFCKQNQEASSDRCSALLQVIFSPLEEEVKAGIYSKPGGYRLFVQKLQDLKKKYYEEPRKGIQAEEILQTYLKSKESMTDAILQTDQTLTEKEKEIEVERVKAESAQASAKMLQEMQRKNEQMMEQKERSYQEHLKQLTEKMENDRVQLLKEQERTLALKLQEQEQLLKEGFQKESRIMKNEIQDLQTKMRRRKACTIS' Functions - I have done so far: def g4_match(g4,protein): N = "NTAG" K = "KLQ" D = "DE" spl_mismatch, mismatch = (0,0) for x,y in zip(g4,protein): if not (x == 'X' or y == x): if(x == 'T' and y in N): spl_mismatch+=1 elif(x == 'L' and y in K): spl_mismatch+=1 elif(x == 'E' and y in D): spl_mismatch+=1 else: mismatch+=1 if mismatch &gt; 0 or spl_mismatch &gt; 2: return False return True print g4_match(g4,protein) X can be anything, we want if N is not then check for T, A, G or if K is not then check for L or if D is not then check for E. our special character is for N == N, T, A, G and for K == K, Q and for D == D, E but if N is there in this case there is no mismatch. I want only two special letter mismatch data or no mismatched like NKXD X can be anything. Example TLKD here T and L is the special mismatch and ALRD here A and L is special mismatch and TKJE - here T and E is special mismatch and NKID this type data here no special mismatch. After Edit getting output ((44, 'GLYRTGK'), (86, 'KKPG'), (126, 'VYNS'), (165, 'EDSAD')) ((44, 'GLYRTGK'), (86, 'KKPG'), (127, 'YNSI'), (165, 'EDSAD')) ((44, 'GLYRTGK'), (86, 'KKPG'), (128, 'NSIG'), (165, 'EDSAD')) ((44, 'GLYRTGK'), (86, 'KKPG'), (129, 'SIGT'), (165, 'EDSAD')) ((44, 'GLYRTGK'), (86, 'KKPG'), (130, 'IGTI'), (165, 'EDSAD…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81809424
has title: How to make a function for matching the string in python
accepted answer: http://stackoverflow.com/a/47427792
has answer: http://stackoverflow.com/a/47427792
tagged with: python

http://stackoverflow.com/comment/82014158
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47528906
has text: Create a task in the OS to run the script
type: Comment

http://stackoverflow.com/comment/82038635
has text: what version of pandas/matplotlib are you using? my default ggplot style has always looked as if `color='r'` argument has been passed. Sidenote, i always add the `edgecolor='k'` argument to my plots to add a black line inbetween bars
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47540660
score: 0

http://stackoverflow.com/a/47431941
type: AcceptedAnswer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/47431752
answers question: http://stackoverflow.com/q/47431752
has body: one-line, using list comprehension: l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))] result = [z for y in (x if isinstance(x[0],tuple) else [x] for x in l) for z in y] print(result) yields: [('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')] this is artificially creating a list if the element is not a tuple of tuples, then flattening all does the job. To avoid creating a single element list [x], (x for _ in range(1)) can also do the job (although it appears clunky) Limitation: doesn't handle more than 1 level of nesting. In which case, a more complex/recursive solution must be coded (check Martijn's answer).
upvote count: 6
type: Answer

http://stackoverflow.com/q/47532293
favorite count: 0
type: Question
score: 3
tagged with: python-cloudant
has body: i've just started using the python-cloudant library for my couchdb related database queries. I implemented a module for database connection. However i'm not sure how to use the python-cloudant errors documentation to help me tell when an operation fails. Forexample i'm updating a document and i really don't know if the operation was successful or not. Below is my database connection module. couchmodule.py class CouchdbAk: def __init__(self): self.client = self.connect() self.db = self.opendb() self.filemodule = FileModule() def __exit__(self, exc_type, exc_val, exc_tb): self.client.disconnect() def connect(self): return CouchDB(constants.USERNAME, constants.PASSWORD, account=constants.ACCOUNT_NAME, url=constants.DBHOST, connect=True, auto_renew=True) def disconnect(self): self.client.disconnect() def opendb(self): return self.client[constants.DBNAME] def updatedoc(self, id, newvalues): doc = self.db[id] for key in newvalues: doc[key] = newvalues[key] doc.save()
tagged with: python
tagged with: python-3.x
answer count: 0
upvote count: 3
type: UnansweredQuestion
has title: python-cloudant document update error handling
has comment: http://stackoverflow.com/comment/82048641
downvote count: 0
tagged with: error-handling
has comment: http://stackoverflow.com/comment/82029841
tagged with: couchdb

http://stackoverflow.com/comment/81883144
type: Comment
type: QuestionComment
has text: And there you have it - your abi is missing the `m` letter (`cp34` instead of `cp34m` which means your python installation was compiled without `pymalloc`. `tensorflow` offers only wheels that require `pymalloc` to be present (all the `manylinux1` wheels have the `m` letter in the soabi string). This is strange as Gentoo compiles python with `pymalloc` and this can't be changed without an explicit ebuild patching. I guess something is wrong with your python installation. Check that your `pip` belongs to python installed by Gentoo and not some custom python build.
score: 1
comment on: http://stackoverflow.com/q/47445519

http://stackoverflow.com/comment/81743678
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47395258
has text: @MadPhysicist yes i am open to any suggestions using python internal modules through which i can connect to unix box without getting this messages and also please note i dont option to use private keys to do passwordless login

http://stackoverflow.com/q/47428708
has title: Why there is no followers list?
type: UnansweredQuestion
has body: Please guide me I call these api to get Instagram followers list but there is no data return.Why? Actually I have 1 follower. This is my code: api_uri = 'https://api.instagram.com/v1/users/self/follows' params = { "access_token" : "6363126973.6c37f35.c7e39150a1d741e29d4ea329889b84b6", "scope": "follower_list" } req = requests.get(api_uri, params = params) print json.loads(req.text) The result is: {u'pagination': {}, u'meta': {u'code': 200}, u'data': []} &lt;Response [200]&gt; My Instagram Account capture:
tagged with: python
has answer: http://stackoverflow.com/a/47445424
tagged with: instagram-api
score: 0
answer count: 1
type: Question

http://stackoverflow.com/comment/81922191
score: 2
comment on: http://stackoverflow.com/a/47483522
type: Comment
type: AnswerComment
has text: Even `if abs(i) < len(lst)` to be super thorough, to also cover negative indices such as `-56`.

http://stackoverflow.com/a/47441130
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47439566
answers question: http://stackoverflow.com/q/47439566
type: Answer
has body: I found the solution, I only had to first read the value, turn it in an integer, add 1 and replace the value turning it again into a string: import xml.etree.ElementTree as ET tree = ET.parse('test.xml') root = tree.getroot() newTimes = int(root[0][7].text) + 1 root[1][6].text = str(newTimes) tree.write('test.xml') That's all.
score: 0

http://stackoverflow.com/a/47411798
has comment: http://stackoverflow.com/comment/81782173
has comment: http://stackoverflow.com/comment/81778448
has body: This is an application for directional statistics, where the angular mean is computed in the complex plane (see this section). The result is a complex number, whose imaginary part represents the mean angle: import numpy as np def angular_mean(angles_deg): N = len(angles_deg) mean_c = 1.0 / N * np.sum(np.exp(1j * angles_deg * np.pi/180.0)) return np.angle(mean_c, deg=True) lons = [ np.array([-175, -170, 170, 175]), # broad distribution np.random.rand(1000) # narrow distribution ] for lon in lons: print angular_mean(lon), np.mean(lon) As you can see, arithmetic mean and angular mean are quite similar for a narrow distribution, whereas they differ significantly for a broad distribution. Using cartesian coordinates is not appropriate, as the center of mass will be located within the earth, but since you are using surface data I assume you want it to be located on the surface.
type: Answer
has comment: http://stackoverflow.com/comment/81781721
score: 0
answers question: http://stackoverflow.com/q/47410023
has comment: http://stackoverflow.com/comment/81780667
has comment: http://stackoverflow.com/comment/81781872
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47410023
has comment: http://stackoverflow.com/comment/81782385

http://stackoverflow.com/comment/81793890
comment on: http://stackoverflow.com/q/47419655
has text: @SuperStew The encoding is utf-8, I'm not sure the error is coming from that
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/103133280
comment on: http://stackoverflow.com/a/56371292
score: 1
has text: That's an entirely different issue, however.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47522302
has body: I have a project I'm trying to put into Python, but am not very strong with coding. I have an array for sunset in local solar time, and want to use that to calculate an hourly load. I am given that the load runs from 2 hours before sunset until 10pm. I'd like to set up an if statement that says if((sunset - 2) &lt; hour &lt; 22): then x calculation occurs. But it doesn't want to let me do that since sunset is an array. days = np.arange (1, 366) #days to 365 day_no = np.repeat(days, 24) declination = pv.declination(day_no) sunrise, sunset = pv.sun_rise_set(latitude, declination, 0) print('Local Solar Time of Sunrise and Sunset (24h): ', sunrise, sunset) for idx, PV_Ah in enumerate(PV_Array_Ah): day_number = np.floor(idx/24) hour = (idx - day_number*24) if ((sunset-2) &lt; hour &lt; 22): load = (4*3 + 20)*.93 answer.append(load) else: load = 0 I'll also end up using my 'load' value in a plot, load on the y-axis vs every hour of the year on the x-axis. How would I go about setting up the if statement for this calculation? And then recording the load in an array to plot?
tagged with: arrays
has comment: http://stackoverflow.com/comment/82003602
has comment: http://stackoverflow.com/comment/82001756
tagged with: if-statement
tagged with: python
type: Question
score: 0
has title: Using Python to Determine time from Sunset minus 2 hours to 10 pm
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82001928

http://stackoverflow.com/comment/81850977
comment on: http://stackoverflow.com/q/47447906
type: QuestionComment
has text: why did you mix python with php?
score: 0
type: Comment

http://stackoverflow.com/comment/81780480
has text: Yup. Thought about it only after I sent my comment that one could also write `for char in wordorg` avoiding any conversion.
comment on: http://stackoverflow.com/q/47413351
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/a/47451550
type: Answer
has body: You can loop over the arrays and check if the first element is 1, then add the second element to a variable: result = 0 for i in range(0, len(my_array)): elem = my_array[i] if elem[0] == 1: result += elem[1]
downvote count: 0
answers question: http://stackoverflow.com/q/47451483
upvote count: 1
score: 1

http://stackoverflow.com/a/47475531
answers question: http://stackoverflow.com/q/47475204
has comment: http://stackoverflow.com/comment/81918868
has comment: http://stackoverflow.com/comment/81905806
type: Answer
score: 0
has body: ConfigParser can read/write ini configure file. I am not sure it can meet your requirement or not. refer to: https://docs.python.org/2/library/configparser.html the first step is read configurations from file, then change the value in config value, at last, write the configure back into file. Hm... sed is more simple.. :) Put a solution based on Alex Martelli's Solution if we have test2.cfg like this: key1=abcd key2=abcd3 Then use code below: import ConfigParser class FakeHeader(object): def __init__(self, fp, section='zconfig'): self.section = '[%s]\n' % section self.fp = fp def readline(self): if self.section: try: return self.section finally: self.section = None else: return self.fp.readline() class ZConfigParser(ConfigParser.ConfigParser, object): def __init__(self, default_section='zconfig'): ConfigParser.ConfigParser.__init__(self) self.default_section = default_section def read(self, fp): new_fp = FakeHeader(open(fp), self.default_section) return super(ZConfigParser, self).readfp(new_fp) def write(self, fp): fp = open(fp, "w") for (key, value) in self.items(self.default_section): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") def get(self, key): return super(ZConfigParser, self).get(self.default_section, key) def set(self, key, value): super(ZConfigParser, self).set(self.default_section, key, value) # here you can use it to read/write a configure file without section in somehow graceful method. zconfig = ZConfigParser() # read file zconfig.read("test2.cfg") print zconfig.get('key1') zconfig.set('key1', 'alfasjdlfabalalla') # then you can check test3.cfg which key1=alfasjdlfabalalla zconfig.write('test3.cfg') Hope it can help you.

http://stackoverflow.com/comment/96610623
type: AnswerComment
has text: Hi - I'm trying to do the same thing, but getting the following error: TypeError: in method 'wrapper_GDALRasterizeDestName', argument 2 of type 'GDALDatasetShadow *'. Could you please clarify what the arguments you're passing to gdal.Rasterize mean, where you got those values, and what exactly your code is doing so that it's easier to troubleshoot? Thank you!
comment on: http://stackoverflow.com/a/47551616
score: 0
type: Comment

http://stackoverflow.com/a/47531972
downvote count: 0
has comment: http://stackoverflow.com/comment/82022677
has comment: http://stackoverflow.com/comment/82022586
has comment: http://stackoverflow.com/comment/82022702
has comment: http://stackoverflow.com/comment/82024617
has comment: http://stackoverflow.com/comment/82024842
has body: Use PeriodIndex, because is not possible create DatetimeIndex without months and days: idx = pd.Int64Index([1992, 1993, 1994, 1995]) print (idx) Int64Index([1992, 1993, 1994, 1995], dtype='int64') per = pd.PeriodIndex(idx, freq='A') print (per) PeriodIndex(['1992', '1993', '1994', '1995'], dtype='period[A-DEC]', freq='A-DEC')
has comment: http://stackoverflow.com/comment/82025654
score: 3
has comment: http://stackoverflow.com/comment/82026478
has comment: http://stackoverflow.com/comment/82022285
answers question: http://stackoverflow.com/q/47531712
has comment: http://stackoverflow.com/comment/82023765
has comment: http://stackoverflow.com/comment/82022360
has comment: http://stackoverflow.com/comment/139577874
has comment: http://stackoverflow.com/comment/82022832
type: Answer
has comment: http://stackoverflow.com/comment/82022736
has comment: http://stackoverflow.com/comment/82025692
upvote count: 3
has comment: http://stackoverflow.com/comment/82024645

http://stackoverflow.com/q/47437158
tagged with: python
has answer: http://stackoverflow.com/a/50649144
has comment: http://stackoverflow.com/comment/81941336
tagged with: pytz
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81857843
tagged with: visual-studio-2017
tagged with: installation
downvote count: 0
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/15185827
has body: I'm taking an online class to learn python, and I skipped a section that was giving me trouble because I had to install something that Visual Studio 2017 doesn't seem to recognize. Now that I've pretty far into the course, if not almost done, I wanted to figure out what's going on. I'm pretty sure Visual Studio 2017 is where the problem is. What I'm trying to install is pytz. As far as my computer is concerned, it is downloaded. However, when I run a program in Visual Studio and import pytz, it says pytz is not a module it recognizes. Is there a way to give Visual Studio a path to what I had downloaded? I looked in the Visual Studio 2017 installer and never saw any mention of pytz in any of the options. Any help is appreciated.
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81987576
has comment: http://stackoverflow.com/comment/81969219
has title: Installing pytz for Python for Visual Studio 2017
has comment: http://stackoverflow.com/comment/81829249

http://stackoverflow.com/comment/82010245
has text: It shows me this error: ` Traceback (most recent call last): File "C:/Dobot Magician/Audio_python/Py3.6/Call_and_check/record_test.py", line 8, in <module> shell=True, preexec_fn=os.setsid) AttributeError: module 'os' has no attribute 'setsid' Process finished with exit code 1`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47526850
score: 0

http://stackoverflow.com/a/47497914
type: Answer
accepted answer of: http://stackoverflow.com/q/47497669
upvote count: 2
answers question: http://stackoverflow.com/q/47497669
score: 2
downvote count: 0
type: AcceptedAnswer
has body: Qt is part of Maya, but if you want to use PyQt5 you need to build it. Be careful, you need to build it against maya’s modified version of Qt. pyQt5 instruction for maya

http://stackoverflow.com/a/47465777
score: 5
has comment: http://stackoverflow.com/comment/81968518
type: Answer
has comment: http://stackoverflow.com/comment/91247284
answers question: http://stackoverflow.com/q/47432006
downvote count: 0
has body: Thanks for @georgexsh advice, I finally end up with this solution. # config.log_filter.py from logging import Filter from django.core.exceptions import ObjectDoesNotExist DEFAULT_EXCLUDE_EXCEPTIONS = [ObjectDoesNotExist, ] class ExceptionFilter(Filter): def __init__(self, exclude_exceptions=DEFAULT_EXCLUDE_EXCEPTIONS, **kwargs): super(ExceptionFilter, self).__init__(**kwargs) self.EXCLUDE_EXCEPTIONS = exclude_exceptions def filter(self, record): if record.exc_info: etype, _, _ = record.exc_info for excluded_exception in self.EXCLUDE_EXCEPTIONS: if issubclass(etype, excluded_exception): return False return True # settings.common.py ... LOGGING = { ... 'filters': { 'exception_filter': { '()': 'config.log_filter.ExceptionFilter' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'filters': ['exception_filter'] } }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', }, ... } } logging.config.dictConfig(LOGGING) Hope it helps someone those encounter the same problem
has comment: http://stackoverflow.com/comment/91254067
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47432006
upvote count: 5

http://stackoverflow.com/q/47464658
tagged with: regex
has body: I have 200k rows with messages in a pandas dataframe. Each message on average contains 230 characters sprinkled with emojis like these . Now i want to filter out everything except lower and upper English and Russian letters and these symbols: #@/:%.,_- What would be the most efficient way of doing that?
type: AnsweredQuestion
tagged with: pandas
score: 1
has title: Python. Efficient way to remove emojis and some punctuation from a large dataset
downvote count: 0
answer count: 1
upvote count: 1
tagged with: string
accepted answer: http://stackoverflow.com/a/47464673
has comment: http://stackoverflow.com/comment/81899066
favorite count: 0
has answer: http://stackoverflow.com/a/47464673
type: Question
tagged with: python

http://stackoverflow.com/comment/81958530
comment on: http://stackoverflow.com/q/47501298
type: Comment
type: QuestionComment
has text: I looked into that in the update to my post and found it is likely a formatting with regards to the socket. Any ideas as to how it is changing during the socket transmission and reception?
score: 0

http://stackoverflow.com/comment/82129502
comment on: http://stackoverflow.com/q/47502946
score: 0
has text: thankyou @ArranCudbard-Bell . so, all I need is modify the 'new client' section right ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81728708
comment on: http://stackoverflow.com/q/47387713
has text: https://stackoverflow.com/search
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81834404
comment on: http://stackoverflow.com/q/47439703
score: 0
type: Comment
has text: Possible duplicate of [How to make a call to an executable from Python script?](https://stackoverflow.com/questions/2473655/how-to-make-a-call-to-an-executable-from-python-script)
type: QuestionComment

http://stackoverflow.com/comment/82042755
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47534937
has text: OP states " It should create all 3 models, but use the same restaurant.". I read this as `Service`, `Resturant` and `DayPeriod` but only one `Restaurant`, the code sample he provides looks like it backs this up

merge
type: Tag
tags question: http://stackoverflow.com/q/47458136
tags question: http://stackoverflow.com/q/47410264
tags question: http://stackoverflow.com/q/47515899
tags question: http://stackoverflow.com/q/47386405
tags question: http://stackoverflow.com/q/47443291
tag name: merge
tags question: http://stackoverflow.com/q/47450259
tags question: http://stackoverflow.com/q/47535889
tags question: http://stackoverflow.com/q/47472207
tags question: http://stackoverflow.com/q/47528555
tags question: http://stackoverflow.com/q/47480147
tags question: http://stackoverflow.com/q/47464060
tags question: http://stackoverflow.com/q/47426796
tags question: http://stackoverflow.com/q/47531615
tags question: http://stackoverflow.com/q/47447033
tags question: http://stackoverflow.com/q/47536497
tags question: http://stackoverflow.com/q/47427837
tags question: http://stackoverflow.com/q/47439234

http://stackoverflow.com/a/47395907
accepted answer of: http://stackoverflow.com/q/47395797
answers question: http://stackoverflow.com/q/47395797
has body: I think need groupby and aggregate mean with unstack for reshape: one = df[df["Period"]==10].groupby(['Electrode','Wave'])['num'].mean().unstack() one.plot.bar(stacked=True) For all subplots: grouped = df.groupby('Period') nrows = int(math.ceil(len(grouped)/2.)) fig, axs = plt.subplots(nrows,2, figsize=(12,30)) for (name, df), ax in zip(grouped, axs.flat): df.groupby(['Electrode','Wave'])['num'].mean().unstack().plot.bar(stacked=True, ax=ax)
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81745087
type: Answer

http://stackoverflow.com/q/47384129
has comment: http://stackoverflow.com/comment/81721406
tagged with: python
favorite count: 0
score: 2
has body: Hi I have been trying to remove non existing twitter users from a list. The reason I want to do this is because overtime I run my code some of the twitter users no longer exist and I get this error kages/tweepy-3.6.0-py3.6.egg/tweepy/binder.py", line 234, in execute tweepy.error.TweepError: [{'code': 34, 'message': 'Sorry, that page does not exist.'}] I can't finish collecting my data because this error keeps stopping the code form running so I have been manually going one by one through my list and finding the twitter accounts that don't exist on twitter which is very inefficient. So I have been trying to use a try except block to override this code, as in remove the usernames that no longer exist and keep running my program but everything I have attempted doesn't work. This is my try except block without tweepy (just regular code) which works. l=["b",23,"c",6,5] print(l) for i in range(0,10): try: for a in l: print("a=",int(a)) except ValueError: l.remove(a) print(l) continue else: print(l) continue Now I tried to implement this into my twitter list pro_trump=['TruthSerum888','karlyherron', 'R41nB14ck', 'RedApplePol', 'MKhaoS_86'] for i in range(0,3): try: for screen_name in pro_trump: user_followers=api.friends_ids(id=screen_name)# this returns the interger value of the user id a sepcifc user is following except tweepy.error.TweepError: print("screen_name that failed=", screen_name) pro_trump.remove(screen_name) print(pro_trump) continue else:# if no error print(pro_trump) continue But it doesn't work. it just goes through the pro_trump list removing each username through the list regardless of if the tweeter account still exists or not. Can someone help me implement what I actually wish my code would do?
has title: removing a no longer existing twitter user from a list (using Tweepy)
tagged with: twitter
linked to: http://stackoverflow.com/q/17431807
tagged with: tweepy
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81721559
has answer: http://stackoverflow.com/a/47384432
upvote count: 2
has comment: http://stackoverflow.com/comment/81721586
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47405573
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47404561
accepted answer of: http://stackoverflow.com/q/47404561
type: Answer
has body: This may not be the most efficient answer to your problem but you could create an empty list (i.e. all_rows) which is going to contain lists which have lengths of 4 items. temp = list() all_rows = list() for item in all.find_all('td'): temp.append(item.text) i += 1 if i % 4 == 0: all_rows.append(temp) temp = [] Which gives the output of: [ ['Hip Primary', '-', '208', '220'], ['Hip Revision', '-', 'Fewer Than 5', '25'], ['Knee Primary', 'Patello-Femoral Replacement', 'Fewer Than 5', '4'], ['Knee Primary', 'Total knee replacement', '211', '230'], ['Knee Primary', 'Unicondylar Knee Replacement', '20', '26'], ['Knee Revision', '-', '5', '16'], ['Shoulder Primary', '-', '15', '16'], ['\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Total', '', '459+', '537'] ] Then you could possibly store all this inside of a dictionary, where your key is index 0, and your values are lists of the remaining 3 items in the lists. Like this: all_rows_dict = dict() for l in all_rows: all_rows_dict[l[0]] = l[1::] This gives output of: { 'Hip Primary': ['-', '208', '220'], 'Hip Revision': ['-', 'Fewer Than 5', '25'], 'Knee Primary': ['Unicondylar Knee Replacement', '20', '26'], 'Knee Revision': ['-', '5', '16'], 'Shoulder Primary': ['-', '15', '16'], '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Total': ['', '459+', '537'] } Then to remove all those non-breaking spaces you could create a clean dictionary like this: clean_dict = {key.replace(u'\xa0', u''): value for key, value in all_rows_dict.items()} With the final output being: { 'Hip Primary': ['-', '208', '220'], 'Hip Revision': ['-', 'Fewer Than 5', '25'], 'Knee Primary': ['Unicondylar Knee Replacement', '20', '26'], 'Knee Revision': ['-', '5', '16'], 'Shoulder Primary': ['-', '15', '16'], 'Total': ['', '459+', '537'] }
has comment: http://stackoverflow.com/comment/81831478
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/81765610
has text: Note that `cryptography`'s `manylinux1` wheel [is not supported on Alpine](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux) because of musl instead of glibc - try building it from source: `$ sudo apk add gcc musl-dev python3-dev libffi-dev openssl-dev`, then `$ pip install cryptography --no-binary cryptography`
type: QuestionComment
comment on: http://stackoverflow.com/q/47405813
score: 0
type: Comment

nearest-neighbor
tags question: http://stackoverflow.com/q/47443874
type: Tag
tag name: nearest-neighbor
tags question: http://stackoverflow.com/q/47464815

scipy
tags question: http://stackoverflow.com/q/47485203
tags question: http://stackoverflow.com/q/47496327
tags question: http://stackoverflow.com/q/47451655
tags question: http://stackoverflow.com/q/47471491
tags question: http://stackoverflow.com/q/47525074
tags question: http://stackoverflow.com/q/47517106
tags question: http://stackoverflow.com/q/47535256
tags question: http://stackoverflow.com/q/47535425
tags question: http://stackoverflow.com/q/47535988
tags question: http://stackoverflow.com/q/47523325
tags question: http://stackoverflow.com/q/47439127
tags question: http://stackoverflow.com/q/47407996
tags question: http://stackoverflow.com/q/47530972
tags question: http://stackoverflow.com/q/47426241
tags question: http://stackoverflow.com/q/47392269
tags question: http://stackoverflow.com/q/47503575
tags question: http://stackoverflow.com/q/47452180
tags question: http://stackoverflow.com/q/47439715
tags question: http://stackoverflow.com/q/47386988
tags question: http://stackoverflow.com/q/47413756
tags question: http://stackoverflow.com/q/47440513
tags question: http://stackoverflow.com/q/47494381
tags question: http://stackoverflow.com/q/47398302
type: Tag
tags question: http://stackoverflow.com/q/47528498
tags question: http://stackoverflow.com/q/47501343
tags question: http://stackoverflow.com/q/47455236
tags question: http://stackoverflow.com/q/47461105
tags question: http://stackoverflow.com/q/47390019
tag name: scipy
tags question: http://stackoverflow.com/q/47405898
tags question: http://stackoverflow.com/q/47519626
tags question: http://stackoverflow.com/q/47429845
tags question: http://stackoverflow.com/q/47419042
tags question: http://stackoverflow.com/q/47491303
tags question: http://stackoverflow.com/q/47443122
tags question: http://stackoverflow.com/q/47417986
tags question: http://stackoverflow.com/q/47412139
tags question: http://stackoverflow.com/q/47449991
tags question: http://stackoverflow.com/q/47420211
tags question: http://stackoverflow.com/q/47470501
tags question: http://stackoverflow.com/q/47425945
tags question: http://stackoverflow.com/q/47538896
tags question: http://stackoverflow.com/q/47492783
tags question: http://stackoverflow.com/q/47459226
tags question: http://stackoverflow.com/q/47478776
tags question: http://stackoverflow.com/q/47514063
tags question: http://stackoverflow.com/q/47473308
tags question: http://stackoverflow.com/q/47457633
tags question: http://stackoverflow.com/q/47434224
tags question: http://stackoverflow.com/q/47390305
tags question: http://stackoverflow.com/q/47498269
tags question: http://stackoverflow.com/q/47514526
tags question: http://stackoverflow.com/q/47498095
tags question: http://stackoverflow.com/q/47536495
tags question: http://stackoverflow.com/q/47443357
tags question: http://stackoverflow.com/q/47437609
tags question: http://stackoverflow.com/q/47386310
tags question: http://stackoverflow.com/q/47449472

http://stackoverflow.com/comment/81949971
has text: @Satendra Of course. You need to use `OrderedDict` to begin with.
type: Comment
comment on: http://stackoverflow.com/q/47497316
type: QuestionComment
score: 1

http://stackoverflow.com/comment/81862780
has text: Oh, I see it now - you probably have two pythons, the system one and brewed one. Can you please execute `$ python -c "import sys; print(sys.path)"` to confirm it or prove me wrong? Also `$ echo $PATH` would be neat.
type: Comment
comment on: http://stackoverflow.com/q/47453268
type: QuestionComment
score: 0

beautifulsoup
tags question: http://stackoverflow.com/q/47502679
tags question: http://stackoverflow.com/q/47497851
tags question: http://stackoverflow.com/q/47457836
tags question: http://stackoverflow.com/q/47458085
tags question: http://stackoverflow.com/q/47468322
tags question: http://stackoverflow.com/q/47517839
tags question: http://stackoverflow.com/q/47397809
tags question: http://stackoverflow.com/q/47506851
tags question: http://stackoverflow.com/q/47461142
tags question: http://stackoverflow.com/q/47404084
tags question: http://stackoverflow.com/q/47389033
type: Tag
tags question: http://stackoverflow.com/q/47482206
tags question: http://stackoverflow.com/q/47403815
tags question: http://stackoverflow.com/q/47446494
tags question: http://stackoverflow.com/q/47533697
tags question: http://stackoverflow.com/q/47385010
tags question: http://stackoverflow.com/q/47468160
tags question: http://stackoverflow.com/q/47433060
tags question: http://stackoverflow.com/q/47445786
tags question: http://stackoverflow.com/q/47447024
tags question: http://stackoverflow.com/q/47522957
tags question: http://stackoverflow.com/q/47502307
tags question: http://stackoverflow.com/q/47482294
tags question: http://stackoverflow.com/q/47402798
tags question: http://stackoverflow.com/q/47444791
tags question: http://stackoverflow.com/q/47441585
tags question: http://stackoverflow.com/q/47523984
tags question: http://stackoverflow.com/q/47429673
tags question: http://stackoverflow.com/q/47526053
tags question: http://stackoverflow.com/q/47442478
tags question: http://stackoverflow.com/q/47471399
tags question: http://stackoverflow.com/q/47444269
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/47489266
tags question: http://stackoverflow.com/q/47383106
tags question: http://stackoverflow.com/q/47488938
tags question: http://stackoverflow.com/q/47404561
tags question: http://stackoverflow.com/q/47411098
tags question: http://stackoverflow.com/q/47481944
tags question: http://stackoverflow.com/q/47434292
tags question: http://stackoverflow.com/q/47514099
tags question: http://stackoverflow.com/q/47527222
tags question: http://stackoverflow.com/q/47520524
tags question: http://stackoverflow.com/q/47499847
tags question: http://stackoverflow.com/q/47500449
tags question: http://stackoverflow.com/q/47433490
tags question: http://stackoverflow.com/q/47458841
tags question: http://stackoverflow.com/q/47426051
tags question: http://stackoverflow.com/q/47418322
tags question: http://stackoverflow.com/q/47482360
tags question: http://stackoverflow.com/q/47495643
tags question: http://stackoverflow.com/q/47477190
tags question: http://stackoverflow.com/q/47528450
tags question: http://stackoverflow.com/q/47476520
tags question: http://stackoverflow.com/q/47468194
tags question: http://stackoverflow.com/q/47435631
tags question: http://stackoverflow.com/q/47399486
tags question: http://stackoverflow.com/q/47475790
tags question: http://stackoverflow.com/q/47498342
tags question: http://stackoverflow.com/q/47441408
tags question: http://stackoverflow.com/q/47473037
tags question: http://stackoverflow.com/q/47477753
tags question: http://stackoverflow.com/q/47480925
tags question: http://stackoverflow.com/q/47442953
tags question: http://stackoverflow.com/q/47396789
tags question: http://stackoverflow.com/q/47395826
tags question: http://stackoverflow.com/q/47473117
tags question: http://stackoverflow.com/q/47533295
tags question: http://stackoverflow.com/q/47457069
tags question: http://stackoverflow.com/q/47422135
tags question: http://stackoverflow.com/q/47503124
tags question: http://stackoverflow.com/q/47449354
tags question: http://stackoverflow.com/q/47487376
tags question: http://stackoverflow.com/q/47444501
tags question: http://stackoverflow.com/q/47521063
tags question: http://stackoverflow.com/q/47460576
tags question: http://stackoverflow.com/q/47438699
tags question: http://stackoverflow.com/q/47532710

http://stackoverflow.com/comment/82032277
has text: Thanks for your answer as well. I went with .get, I'll try yours when I have some extra time on my hand. Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47515022
type: AnswerComment

http://stackoverflow.com/q/47426699
accepted answer: http://stackoverflow.com/a/47643460
tagged with: python
has title: Run crontab job with P4
tagged with: shell
has answer: http://stackoverflow.com/a/47643460
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
tagged with: perforce
type: AnsweredQuestion
tagged with: linux
tagged with: cron
has body: I have a shell script which in turn calls a python script. But before the python script runs I am setting up the environment variables in order to have the right P4 configurations. shell: /home/ag/ump_prod/run.sh python script: /home/ag/ump_prod/cron.py Environment conf: /home/ag/ump_prod/env.conf The python script executes command line P4 commands via the subprocess module. Here is the code for the shell script #!/bin/sh . /home/ag/ump_prod/env.conf python /home/ag/ump_prod/cron.py env.conf export SHELL=/bin/bash export USER=ag export MAIL=/var/mail/ag export HOME=/home/ag export LOGNAME=ag export P4CONFIG=/home/ag/ump_prod/.perforce The perforce config /home/ag/ump_prod/.perforce : P4CLIENT=ag_ump P4EDITOR=/usr/bin/vim P4PORT=rsh:ssh -2 -q -a -x -l p4server p4.****.com /bin/true P4USER=ag Manually running the shell script executes it without any issues. However, when I run it via cronjob it complains that it cannot connect to the server. Error Message: ['TCP receive failed.\n', 'read: socket stdio: Connection reset by peer\n', 'Perforce client error:\n', '\tTCP receive failed.\n', '\tread: socket stdio: Connection reset by peer\n'] Please let me know where I could be going wrong in setting the environment variables for P4 configs. Thanks in advance!
score: 1
answer count: 1

http://stackoverflow.com/a/47490058
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47490033
upvote count: 5
has body: That's your shell prompt. Your output doesn't end with a line terminator, so your shell prints its "next command, please" prompt on the same line as your program's output.
type: Answer
answers question: http://stackoverflow.com/q/47490033
has comment: http://stackoverflow.com/comment/81935485
score: 5
downvote count: 0

http://stackoverflow.com/comment/81910788
score: 0
comment on: http://stackoverflow.com/a/47477954
has text: @Eric That actually makes sense and sounds simpler. So, sure, worth adding that way into the docs I think.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47434852
has comment: http://stackoverflow.com/comment/81841203
type: Question
answer count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/81837063
has comment: http://stackoverflow.com/comment/81824683
has comment: http://stackoverflow.com/comment/81834489
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47446701
score: 0
has comment: http://stackoverflow.com/comment/81835095
has title: why bottle does not show the page I returned?
has body: I am new to bottle. I have searched for the answer but could not get any. Is there anyway to load a page without redirect? The code is like this: from bottle import get, run, template @get('/list/item') def listItems(): r = requests.get('my/url/which/works/') return r.content if __name__ == '__main__': run(host='localhost', port=8080 ) and the webpage is empty. I have also tried return r.text, return template(r.content), return str(r.content), return str(r.content.decode('utf-8')), and nf = urllib.urlopen('my/url/whick/works') return nf.read() none of them returns the page I want. However, if I write this return r.content[0], it works. the page will show the first letter, which is '<'. But if I write return r.content[0:100], it returns a empty page again. If I run the requests in command line, this is what it returns: >>> import requests >>> r = requests.get('my/url/which/works/') >>> >>> r.content '<?xml version="1.0" encoding="utf-8" ?> \n \n \n' Is that possible that anyone can help about this? Thank you very much.
has answer: http://stackoverflow.com/a/47446701
has comment: http://stackoverflow.com/comment/81823912
tagged with: python
tagged with: bottle

http://stackoverflow.com/comment/81976731
has text: Actually, are you sure you have JSP and not Jinja2?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47510544
score: 0

http://stackoverflow.com/a/47682043
has comment: http://stackoverflow.com/comment/82367668
type: Answer
has comment: http://stackoverflow.com/comment/82479625
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47527880
has comment: http://stackoverflow.com/comment/82379735
has body: -Do you really want a button? The main distinction between buttons and labels are those effects (labels don't generate events, but you can make them do so by packing them into a Gtk.EventBox) -Here's how to disable the events that cause the effects in first place: #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # test_inert_button.py # # Copyright 2017 John Coppens &lt;john@jcoppens.com&gt; # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): super(MainWindow, self).__init__() self.connect("destroy", lambda x: Gtk.main_quit()) self.set_size_request(400, 300) btn1 = Gtk.Button("One - inert button") btn2 = Gtk.Button("Two - active button") btn1.connect("enter-notify-event", self.on_leave) btn1.connect("button-press-event", self.on_leave) vbox = Gtk.VBox() vbox.pack_start(btn1, False, False, 0) vbox.pack_start(btn2, False, False, 0) self.add(vbox) self.show_all() def on_leave(self, btn, event): return True def run(self): Gtk.main() def main(args): mainwdw = MainWindow() mainwdw.run() return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv)) The on_leave method's return True tells the default handler that events are handled so it won't do the effects. The top button One doesn't react, the…
answers question: http://stackoverflow.com/q/47527880
has comment: http://stackoverflow.com/comment/82394105

http://stackoverflow.com/comment/81985126
score: 0
type: AnswerComment
has text: Understood! Thanks!
comment on: http://stackoverflow.com/a/47514641
type: Comment

http://stackoverflow.com/comment/81748049
type: AnswerComment
score: 0
has text: Please let me know if this approach worked for you! If the thread pool is confusing, we could perhaps start a thread explicitly but it will take more code.
type: Comment
comment on: http://stackoverflow.com/a/47397477

http://stackoverflow.com/comment/81877058
comment on: http://stackoverflow.com/q/47460959
type: Comment
has text: Consider using: https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xlim.html#matplotlib.axes.Axes.set_xlim
type: QuestionComment
score: 0

http://stackoverflow.com/a/47442354
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47442201
type: AcceptedAnswer
score: 6
downvote count: 0
answers question: http://stackoverflow.com/q/47442201
type: Answer
has body: If you want to get outerHTML of parent element, you can use below html_text = element.find_element_by_xpath('..').get_attribute('outerHTML')

http://stackoverflow.com/q/47472833
has comment: http://stackoverflow.com/comment/81900288
has answer: http://stackoverflow.com/a/47479794
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: neural-network
tagged with: machine-learning
tagged with: python
tagged with: artificial-intelligence
has title: Back propagation for neural network ( Error in shapes )
has comment: http://stackoverflow.com/comment/81900253
answer count: 2
tagged with: conv-neural-network
score: 2
has body: Below I attached 4 pictures with error as a picture. Generally, I'm training my neural network ( having a 2, 3, 1 architecture ) that consists of two input neurons in the input layer, 3 neurons in my hidden layer and 1 output neuron in my output layer. So, I trained my network using back propagation and I am having small error ( which is specified in the picture ). Can someone help me with that please. Error: shapes (200,200) and (1,3) not aligned: 200 (dim 1) != 1 (dim 0) import numpy as np import random # Generating training data set according to the function y=x^2+y^2 input1_train = np.random.uniform(low=-1, high=1, size=(200,)) input2_train = np.random.uniform(low=-1, high=1, size=(200,)) input1_sq_train= input1_train **2 input2_sq_train= input2_train **2 input_merge= np.column_stack((input1_train,input2_train)) # normalized input data input_merge= input_merge / np.amax(input_merge, axis=0) # output of the training data y_output_train= input1_sq_train + input2_sq_train # normalized output data y_output_train= y_output_train / 100 # Generating test data set according to the function y=x^2+y^2 input1_test = np.random.uniform(low=-1, high=1, size=(100,)) input2_test = np.random.uniform(low=-1, high=1, size=(100,)) input1_sq_test= input1_test **2 input2_sq_test= input2_test **2 y_output_test= input1_sq_test + input2_sq_test # Merging two inputs of testing data into an one matrix input_merge1= np.column_stack((input1_test,input2_test)) # normalized input test data input_merge1=input_merge1 / np.amax(input_merge1, axis=0) # normalized output test data y_output_test= y_output_test / 100 # Generating validation data set according to the function y=x^2+y^2 input1_validation = np.random.uniform(low=-1, high=1, size=(50,)) input2_validation = np.random.uniform(low=-1, high=1, size=(50,)) input1_sq_validation= input1_validation **2 input2_sq_validation= input2_validation **2 input_merge2= np.column_stack((input1_validation,input2_validation)) # normalized input validation d…
downvote count: 0
has answer: http://stackoverflow.com/a/47530311

http://stackoverflow.com/comment/81804328
type: QuestionComment
has text: It has shape (1,2). Still, it has 2 different values. Is there any way to retrieve both values separately?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47424682

http://stackoverflow.com/a/47522407
accepted answer of: http://stackoverflow.com/q/47522072
type: Answer
answers question: http://stackoverflow.com/q/47522072
score: 2
has body: I think you should create your variables before assigning the values to them. This might solve your issue, i am not sure. please refer to this link for further details in scope in python. Also, your indentation is incorrect. try this code: location = raw_input("Where are you located? : ") #print (location) recreationList = None businessList = None if location == "London": recreationList = londonRec businessList = londonBus elif location == "California": recreationList = caliRec businessList = caliBus elif location == "Mumbai": recreationList = mumbaiRec businessList = mumbaiBus ....code to be executed based on location
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81920583
type: QuestionComment
score: 0
has text: How did you install Jupyter? With Anaconda? Or did you just install Jupyter itself?
type: Comment
comment on: http://stackoverflow.com/q/47482890

http://stackoverflow.com/comment/81928022
has text: I think I get it now. [:] gives a copy of the array, but using it in this way: b[0,:,1] means choose 0th position in the first dimension, slice of the complete second dimension, and choose 1st position in the third dimension, right?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47486220

http://stackoverflow.com/q/47383830
has title: Find most common object in a list in a for loop
tagged with: python-3.x
tagged with: data-analysis
type: Question
has comment: http://stackoverflow.com/comment/81720641
has body: I am having difficulty in printing out the most popular web link and then counting the amount of times it appears. Instead, all links are printed out and none are counted. I'm not sure if I am misplacing my Counter and .most_common(1) in my code. I have pasted it below. toplinks = [] for i in itb: if "://" in i[1].lower() and '2015-11-16' in i[2].lower(): itb_links = [c for c in i[1].split(" ") if "://" in c.lower()] ##toplinks = collections.Counter(itb_links).most_common(1) toplinks.append(itb_links) for i in toplinks: print ("Top web link: " , i[0] , i[1] ) I commented out my toplinks in the for loop because it seems to do nothing, but duplicate the web link. Any thoughts?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81720538
has answer: http://stackoverflow.com/a/47385816
score: 0
answer count: 1
tagged with: twitter

http://stackoverflow.com/q/47480701
answer count: 1
downvote count: 1
has title: Assigning Values to List items in Several Related Lists
tagged with: arrays
has comment: http://stackoverflow.com/comment/81916452
has comment: http://stackoverflow.com/comment/81916336
has comment: http://stackoverflow.com/comment/81916284
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47480906
has body: I have three lists: "products", "prices" and "item numbers". When user input is added to these lists, how do I, for example, make Python create an association between, let's say "product 6, price 6 and item number 6"? What I want to be able to see is when user chooses an item number from the table, it is stored and the item number actually knows to assign itself the value of the product and the price. Jay's House of Rip-Offs Item Number |Item Name |Price -------------------------------------------------- 1 |Notebook |4.99 2 |Atari |99.99 3 |TrapperKeeper |89.99 4 |Jeans |3.99 5 |Insects |2.99 6 |Harbormaster |299.99 7 |Lobotomy |19.99 8 |PunkRock |3.99 9 |HorseFeathers |4.99 10 |Pants |2.99 11 |Plants |119.99 12 |Salami |1.99 Order products [Y / N]?: Here is the code I have, and I don't really know what to do to make it work. I need the input from user to store in 'orders' and 'quantity'. Also, the input from the name and address inputs needs to be stored in the respective list above. products = ['Notebook', 'Atari', 'TrapperKeeper', 'Jeans', 'Insects', 'Harbormaster', 'Lobotomy', 'PunkRock', 'HorseFeathers', 'Pants', 'Plants', 'Salami'] prices = ['4.99', '99.99', '89.99', '3.99', '2.99', '299.99', '19.99', '3.99', '4.99', '2.99', '119.99', '1.99'] item_nums = [1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12] orders = [] quantity = [] response = '' cust_name = '' street = '' city = '' state = '' zipcode = 0 order_total = 0 order_summary = '' print("Jay's House of Rip-Offs\n\n") titles = ('Item Number', 'Item Name', 'Price') data = [titles] + list(zip(item_nums, products, prices)) for i, d in enumerate(data): line = '|'.join(str(x).ljust(16) for x in d) print(line) if i == 0: print('-' * len(line)) while str(input("Order products [Y / N]?: ")) != 'N': item_nums = input("Enter an item number: ") orders.append(item_nums) quantity = input("How many? ") if len(item_nums) == 0: print("Thank you for browsing.") else: cust_name = input("Enter name: ") street = input("Enter street add…
has comment: http://stackoverflow.com/comment/81916467
upvote count: 0
tagged with: list

http://stackoverflow.com/q/47402063
has comment: http://stackoverflow.com/comment/81758075
has title: VS Code PEP8 error types
linked to: http://stackoverflow.com/q/40831593
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81759006
score: 0
has body: Was successfull to enable VS Code with PEP8 based on https://code.visualstudio.com/docs/python/linting#_pep8 However,now I need to specify a list of PEP8 errors to ignore. How would I do that?
tagged with: visual-studio-code
answer count: 0
type: UnansweredQuestion
tagged with: pep8

http://stackoverflow.com/comment/82033370
has text: Just give it a try
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47538226

http://stackoverflow.com/q/47427053
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/81808871
type: Question
tagged with: attributeerror
type: UnansweredQuestion
has body: import multiprocessing import time def worker(): n=5 #number of process while n&gt;0: print("the time is {0}".format(time.ctime())) time.sleep(2) n-=1 if __name__=="__main__": p=multiprocessing.Process(target=worker) p.start() print("end") 3.5.2 |Continuum Analytics, Inc.| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)] Python Type "help", "copyright", "credits" or "license" for more information. [evaluate multiprocess.py] end Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\Users\xxxxx\Miniconda3\lib\multiprocessing\spawn.py", line 106, in spawn_main exitcode = _main(fd) File "c:\Users\xxxx\Miniconda3\lib\multiprocessing\spawn.py", line 116, in _main self = pickle.load(from_parent) AttributeError: Can't get attribute 'worker' on &lt;module '__mp_main__' from 'C:\\Program Files (x86)\\Wing IDE 101 5.1\\src\\debug\\tserver\\_sandbox.py'&gt; I really have no idea how to fix this Once I use multiprocessing, attribute error would occur error message always shows AttributeError no matter what I do
has comment: http://stackoverflow.com/comment/81808827
has comment: http://stackoverflow.com/comment/81808921
tagged with: python
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/81808847
upvote count: 3
has comment: http://stackoverflow.com/comment/81810163
has title: python multiprocessing AttributeError
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81922188
comment on: http://stackoverflow.com/a/47483671
has text: Awesome Thanks! Does this work for forward looking as well? Like get next n rows as array?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47388334
has answer: http://stackoverflow.com/a/47388391
accepted answer: http://stackoverflow.com/a/47388391
answer count: 1
has title: Pandas Dataframe - Replace column values with reciprocal
type: AnsweredQuestion
has body: My dataframe looks like follows 0 1 2 3 4 0 0.660377 0.75 0.728395 1.000000 0.011364 1 0.452830 0.50 0.629630 0.083333 0.045455 2 0.971698 0.75 0.975309 0.166667 0.079545 3 0.169811 0.25 0.172840 0.291667 0.068182 4 0.216981 0.25 0.222222 0.000000 0.090909 5 0.669811 0.50 0.839506 0.333333 0.045455 I need to replace first column with its reciprocal values. Is there any built-in way to do that in Pandas?
tagged with: pandas
upvote count: 7
score: 7
tagged with: python
favorite count: 0
type: Question
downvote count: 0

http://stackoverflow.com/comment/81961325
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47491751
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thank you! this works great... I have another question for you how can I do this with numeric data; mydf[(mydf["Item Name"]=="Pregabalin") & (mydf["Quantity"]=="2.0")] I am receiving this error TypeError: invalid type comparison when I use the above code
type: Comment

http://stackoverflow.com/q/47510830
score: -1
has comment: http://stackoverflow.com/comment/81977312
has comment: http://stackoverflow.com/comment/81977383
has comment: http://stackoverflow.com/comment/81977444
has comment: http://stackoverflow.com/comment/81977918
type: Question
tagged with: bash
has comment: http://stackoverflow.com/comment/81977757
has comment: http://stackoverflow.com/comment/81977529
upvote count: 0
accepted answer: http://stackoverflow.com/a/47511650
has comment: http://stackoverflow.com/comment/81978028
answer count: 1
has comment: http://stackoverflow.com/comment/81977361
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81977969
has body: I would like to pass the variable "NUMBER_CAMS" and value from my python script to a bash environmental file "env_roadrunner" following is the code that i have written import subprocess import os import sys import ConfigParser os.chdir("/home/vasudev/LTECamOrchestrator_docker/tools/") NUMBER_CAMS=sys.argv[2] cmd = "xterm -hold -e sudo /home/vasudev/LTECamOrchestrator_docker/tools/create_pcap_replay_encoder " \ " /home/vasudev/LTECamOrchestrator_docker/tools/env_roadrunner" p = subprocess.Popen([cmd] , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) Following is my bash script which takes environmental variables #!/bin/bash # the name or ip address of the orchestrator ORCHESTRATOR_IP="192.168.212.131" # the port of the orchestrator ORCHESTRATOR_PORT=9000 # password for the admin user ORCHESTRATOR_PASSWORD='.qoq~^c^%l^U#e~' # number of cameras to create from this pcap file NUMBER_CAMS="$N" # three port numbers that are only used internally but need to be free I wanted to pass the value NUMBER_CAMS through my python script but i am getting following error Traceback (most recent call last): File "/home/vasudev/PycharmProjects/Test_Framework/Stream_provider.py", line 19, in &lt;module&gt; NUMBER_CAMS=sys.argv[2] IndexError: list index out of range any suggestions why i am getting index out of range error
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81977935
has comment: http://stackoverflow.com/comment/81977680
has comment: http://stackoverflow.com/comment/81977335
has title: Pass the variable and value from python to bash
tagged with: python
has comment: http://stackoverflow.com/comment/81977878
has answer: http://stackoverflow.com/a/47511650

http://stackoverflow.com/a/47479461
has comment: http://stackoverflow.com/comment/81915544
has comment: http://stackoverflow.com/comment/81915238
has comment: http://stackoverflow.com/comment/81914334
type: Answer
answers question: http://stackoverflow.com/q/47479275
score: 0
has comment: http://stackoverflow.com/comment/81914465
has comment: http://stackoverflow.com/comment/81952436
accepted answer of: http://stackoverflow.com/q/47479275
type: AcceptedAnswer
has body: Edit: As the usage of eval is considered to be bad practice, I suggest parsing numbers via a regex. Other options with other properties are also possible. import re LIMITS = (1, 100) line = input("Enter integers between %d and %d: " % LIMITS) # parse input for all possible numbers numbers = [int(digits) for digits in re.findall(r'[0-9]+', line)] # filter for valid numbers in given range numbers = [n for n in numbers if LIMITS[0] &lt;= n &lt;= LIMITS[1]] # count occurences; save in dict for easy use later occurences = {} for number in numbers: if number in occurences: occurences[number] += 1 else: occurences[number] = 1 print(occurences) Yes, this could be squeezed into one line. But for readability, you shouldn't. :-)

http://stackoverflow.com/a/47433786
type: AcceptedAnswer
has body: Overwriting __get__ as below does the job, though I am still not sure exactly why my original attempt failed. class Wrapped(): def __init__(self,f): self.f=f def __call__(self,*args,**kwargs): print(self.f,' is being called with ',args,kwargs) return self.f(*args,**kwargs) def __get__(self,obj,type=None): return functools.partial(self,obj)
accepted answer of: http://stackoverflow.com/q/47433768
has comment: http://stackoverflow.com/comment/81823388
answers question: http://stackoverflow.com/q/47433768
type: Answer
has comment: http://stackoverflow.com/comment/81822552
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/81944493
type: Comment
type: QuestionComment
score: 0
has text: I did that because in numba they suggested to decorate with jit any function we are using http://numba.pydata.org/numba-doc/0.35.0/user/jit.html#compilation-options section 1.3.2
comment on: http://stackoverflow.com/q/47494698

http://stackoverflow.com/comment/81919095
has text: This post may help, [link](https://github.com/opencv/opencv/issues/8471)
comment on: http://stackoverflow.com/q/47482055
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81762788
type: Comment
type: AnswerComment
has text: So basically, each generated logs will be a event triggering the code in lambda if I understand correctly? And then what I need to do is to import this event to S3 ( in this way I don't need to care about the timestamps anymore because one event one log). Is this correct?
score: 0
comment on: http://stackoverflow.com/a/47404232

http://stackoverflow.com/comment/81724272
type: Comment
has text: Please post real Python data and show what you have tried yourself.
score: 0
comment on: http://stackoverflow.com/q/47385646
type: QuestionComment

http://stackoverflow.com/comment/81932927
score: 0
type: Comment
type: QuestionComment
has text: my __init__.py is in the same folder as temp.txt
comment on: http://stackoverflow.com/q/47482842

http://stackoverflow.com/q/47412887
has body: I am trying to get and send data to Filenet. I am using cmislib 0.6.0. (Python). The environment I am trying to use has more than one repo. If I use repo = client.defaultRepository I am not get the repo I want (it is not the first of the list). So, for that reason, I am using my_rep = client.getRepository('MY_REPO_ID') But when I tried to get a folder by the path my_folder = my_repo.getObjectByPath('/MY_PATH') *** AttributeError: 'RepositoryService' object has no attribute 'binding' If I check the repo properties: my_repo._cmisClient.__dict__ {'logger': &lt;logging.Logger object at 0x7f0fc73d79d0&gt;, '_uriTemplates': {}} My default repo (which is not the repo I want) has binding attribute: repo_default._cmisClient.__dict__ {'username': 'USER', 'repositoryUrl': 'http://HOST:9080/fncmis/atom11', 'binding': &lt;cmislib.atompub.binding.AtomPubBinding object at 0x7f0fc6afb850&gt;, 'extArgs': {}, 'logger': &lt;logging.Logger object at 0x7f0fc73d7990&gt;, 'password': 'PASSWORD'} What is the configuration I am missing? Many Thanks in advance.
type: Question
tagged with: cmis
has answer: http://stackoverflow.com/a/47430428
tagged with: python
score: 2
tagged with: filenet
upvote count: 2
type: AnsweredQuestion
has title: Filenet and cmislib. AttributeError: 'RepositoryService' object has no attribute 'binding' error when getObjectByPath
tagged with: opencmis
downvote count: 0
accepted answer: http://stackoverflow.com/a/47430428
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/82022329
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47481893
type: Comment
has text: Got this [suggestion](https://medium.com/google-cloud/object-detection-tensorflow-and-google-cloud-platform-72e0a3f3bdd6) on Github. Still didn't have time to test it.

http://stackoverflow.com/q/47511947
has comment: http://stackoverflow.com/comment/86876658
upvote count: 5
downvote count: 0
tagged with: python-extensions
has title: Use Setuptools with C Extension as part of package
has answer: http://stackoverflow.com/a/48155373
tagged with: setuptools
tagged with: python
tagged with: http://stackoverflow.com/tag/c
tagged with: packaging
favorite count: 0
type: Question
has body: I wrote a C Extension to access an error message for a camera from a proprietary library. The structure is setup.py dicamsdk\ |---__init__.py |---control.py |---pcoError.c with setup.py from setuptools import setup, Extension, find_packages from dicamsdk.control import __version__ pcoErrorModule = Extension("dicamsdk.pcoError", sources=["dicamsdk/pcoError.c"], include_dirs=['C:\Program Files (x86)' '\Digital Camera Toolbox' '\Sensicam SDK\include'], define_macros=[("PCO_ERRT_H_CREATE_OBJECT", None)], ) setup( name="pydicamsdk", platforms=["win-amd64", 'win32'], license="GNU GPLv3", ext_modules=[pcoErrorModule], packages=find_packages(), version=__version__ ) and the control.py intends to import the compiled C Extension with from . import pcoError When I try to build (or install) the package I always receive the error ImportError: cannot import name 'pcoError'. The only way it seems to work is to comment out the import in control.py and build the C Extension with setup.py build_ext --inplace. Just with the compiled present I can build/install my library. Is there a solution to be implemented in my setup.py to compile my extension in first place to enable a simple installation?
has answer: http://stackoverflow.com/a/49930332
answer count: 2
score: 5
type: UnansweredQuestion

http://stackoverflow.com/a/74628575
type: Answer
answers question: http://stackoverflow.com/q/47508168
score: 0
has body: Just add this code below to your cell: display(IPython.display.HTML(''' &lt;flexthis&gt;&lt;/flexthis&gt; &lt;style&gt; div.jp-Cell-outputArea:has(flexthis) { display:flex; flex-wrap: wrap; }&lt;/style&gt; ''')) and then, on the same cell, use calls to IPython.display.Image or anything else you want to show. This code above allows you to add custom CSS to that specific output cell. I'm using a flex box (display:flex), but you can change it to your liking.

http://stackoverflow.com/comment/81779438
score: 0
comment on: http://stackoverflow.com/a/47404086
type: Comment
has text: Thanks I thought there might be one easier way to get that but I feel I need to get my hands dirty. Thanks
type: AnswerComment

recursion
type: Tag
tags question: http://stackoverflow.com/q/47418939
tags question: http://stackoverflow.com/q/47535063
tags question: http://stackoverflow.com/q/47477062
tags question: http://stackoverflow.com/q/47482405
tags question: http://stackoverflow.com/q/47383586
tags question: http://stackoverflow.com/q/47489855
tag name: recursion
tags question: http://stackoverflow.com/q/47420635
tags question: http://stackoverflow.com/q/47517099
tags question: http://stackoverflow.com/q/47522587
tags question: http://stackoverflow.com/q/47490033
tags question: http://stackoverflow.com/q/47415441
tags question: http://stackoverflow.com/q/47521620
tags question: http://stackoverflow.com/q/47385933
tags question: http://stackoverflow.com/q/47466773
tags question: http://stackoverflow.com/q/47455239

http://stackoverflow.com/comment/81922090
comment on: http://stackoverflow.com/a/47483615
has text: It says `Tuple of bytes to step in each dimension when traversing an array.` @user2357112 - care to add some explanation?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47401855
score: 1
has body: As suggested by @Maurice Meyer, the problem was in the way I set QWebChannel. I just added &lt;script src="qrc:///qtwebchannel/qwebchannel.js"&gt;&lt;/script&gt; at the top of my HTML code and then: from PyQt5.QtCore import QObject, pyqtSlot from PyQt5.QtWebChannel import QWebChannel from PyQt5.QtWebEngineWidgets import QWebEngineView in my Python code. And the magic happened!
upvote count: 1
answers question: http://stackoverflow.com/q/47401311
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81835224
comment on: http://stackoverflow.com/a/47436483
has text: in my code i load the database query into my variable all_db_item later in my code i create the dict context and create in context the key db, with the value all_db_items this is going to my template and jinga can access it by `{% for item in db %}` ` {{ item.titel }} ` `{% endfor %} please explan me how my dictionary can hold more than just one value. i mean why can i interate over an dictionary value? how is it seperated? and how can i rebuild it in a selfmade dictionary? o.O
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47395819
has comment: http://stackoverflow.com/comment/81744775
answers question: http://stackoverflow.com/q/47395676
has comment: http://stackoverflow.com/comment/81744909
accepted answer of: http://stackoverflow.com/q/47395676
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81744869
upvote count: 8
type: Answer
has body: First, in python 3, you have to force list iteration on map Then, your approach won't work, you'll get all ones or zeroes, because the expression doesn't accumulate the counts. You could use str.count in a lambda, and map the tuples to a dictionary, that works: txt = "hello" d = dict(map(lambda x : (x, txt.count(x)), set(txt))) result: {'e': 1, 'l': 2, 'h': 1, 'o': 1} But once again, collections.Counter is the preferred way to do that.
downvote count: 1
has comment: http://stackoverflow.com/comment/81744929

http://stackoverflow.com/comment/81974915
score: 0
type: AnswerComment
has text: Could you please add screenshots of input dataframes. I mean, with python print statements. "print(df1); print(df2);". I'm doubting input CSVs.
comment on: http://stackoverflow.com/a/47475600
type: Comment

http://stackoverflow.com/a/47448776
has comment: http://stackoverflow.com/comment/81852525
answers question: http://stackoverflow.com/q/47448741
score: 3
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/81852620
has body: today is a class method of the datetime class: &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; type(datetime.today) &lt;class 'builtin_function_or_method'&gt; Therefore, you can't import it on its own. If you really want, you can alias it by assigning it to your own function: from datetime import datetime today = datetime.today but you may not want to do that: it's not clear anymore that today is a datetime class method, and, given the name of the method, today can be read as a variable instead of as a function.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47448741

http://stackoverflow.com/q/47416405
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81786740
score: 2
has body: I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of numbers of each one. I rename each file with the sequence I extracted from .txt path_txt = (r'''C:\Users\user\Desktop\Doc_Classifier\TXT''') for TXT in name_files3: with open(path_txt + '\\' + TXT, "r") as content: search = re.search(r'(([0-9]{4})(/)(([1][9][0-9][0-9])|([2][0-9][0-9][0-9])))', content.read()) if search is not None: name3 = search.group(0) name3 = name3.replace("/", "") os.rename(os.path.join(path_txt, TXT), os.path.join("Processos3", name3 + "_" + str(random.randint(100, 999)) + ".txt")) I need to check if the file already exists, and rename it by adding an increment. Currently to differentiate the files I am adding a random number to the name (random.randint(100, 999))
linked to: http://stackoverflow.com/q/47419831
answer count: 0
has title: rename file that already exists
has comment: http://stackoverflow.com/comment/81787393
duplicate of: http://stackoverflow.com/q/47419831
favorite count: 0

http://stackoverflow.com/a/47439155
has comment: http://stackoverflow.com/comment/101051232
has comment: http://stackoverflow.com/comment/115785259
score: 4
accepted answer of: http://stackoverflow.com/q/47438313
has comment: http://stackoverflow.com/comment/101037286
has comment: http://stackoverflow.com/comment/81920645
type: Answer
answers question: http://stackoverflow.com/q/47438313
has comment: http://stackoverflow.com/comment/81901256
has comment: http://stackoverflow.com/comment/81896950
has comment: http://stackoverflow.com/comment/101049377
has comment: http://stackoverflow.com/comment/81907282
has comment: http://stackoverflow.com/comment/81910453
upvote count: 4
has comment: http://stackoverflow.com/comment/101036290
has comment: http://stackoverflow.com/comment/101038303
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/101031185
has body: You should train the model using the training data (as you did) and then you should predict using new data (the test data). Do the following: nb = MultinomialNB() nb.fit(x_train, y_train) y_predicted = nb.predict(x_test) Now, if you want to evaluate the predictions based on the **accuracy you can do the following:** from sklearn.metrics import accuracy_score accuracy_score(y_test, y_predicted) Similarly, you can calculate other metrics. Finally, we can see all the available metrics here ! EDIT 1 When you type: y_predicted = nb.predict(x_test) y_predicted will contain numerical values that correspond to your categories. To project back these values and get the labels you can do: y_predicted_labels = encoder.inverse_transform(y_predicted)

http://stackoverflow.com/q/47498342
has answer: http://stackoverflow.com/a/47498379
has comment: http://stackoverflow.com/comment/81952065
has body: I'm scraping a website and when I'm running my script, it crashes the API request. I'd like to iterate the loop with a break of 3 seconds between each iteration. def printit(): country_list_id = ['a', 'b', 'c'] product_list_id = ['1', '2', '3'] for c in country_list_id: for p in product_list_id: url = "https://www.example.com/api/country_id=" + c + "&amp;product_id=" + p + "&amp;option=" test(url) def test(url_final): get_url = requests.get(url_final) get_text = get_url.text print(get_text) #I'd like to make a small break here before it iterate again printit()
tagged with: python
duplicate of: http://stackoverflow.com/q/23198720
has title: Run a loop every x seconds in python in order to scrape a website
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/7326950
answer count: 2
possible better answer: http://stackoverflow.com/a/47498374
has answer: http://stackoverflow.com/a/47498374
tagged with: python-requests
duplicate of: http://stackoverflow.com/q/7326950
type: Question
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/47498379
has comment: http://stackoverflow.com/comment/81951908
tagged with: python-multithreading

http://stackoverflow.com/comment/81927438
type: AnswerComment
score: 0
has text: This dll or exe file doesn't help you. You need to install it by using pip or making the whole package which in any way you're going to need python 2.5
type: Comment
comment on: http://stackoverflow.com/a/47485957

http://stackoverflow.com/q/47424306
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: QApplicaiton and QWidget are not recognized in below
tagged with: python
has body: import sys from PyQt5.QtWidgets import QApplication, QWidget app = QApplication(sys.argv) win = QWidget() win.show() app.exec_() QApplication and QWidget are not recognized in the above code written in PyQt5

http://stackoverflow.com/q/47382679
type: AnsweredQuestion
has title: How to instruct jupyter to use python2 not python3
has answer: http://stackoverflow.com/a/47382691
tagged with: python
tagged with: jupyter-notebook
type: Question
has body: Given a PYTHONPATH that seems to point to python : cat $(which jupyter) #!/bin/bash JUPYTER_PATH="/usr/local/etc/jupyter" PYTHONPATH="/usr/local/Cellar/jupyter/1.0.0_1/libexec/lib/python2.7/site-packages: /usr/local/Cellar/jupyter/1.0.0_1/libexec/vendor/lib/python2.7/site-packages: /usr/local/lib/python2.7/site-packages" exec "/usr/local/Cellar/jupyter/1.0.0_1/libexec/bin/jupyter" "$@" Then why does the jupyter notebook report python3? (btw: how to resize that image smaller - but with only scaling not cropping? I tried adding s and it only cropped)
score: 0
accepted answer: http://stackoverflow.com/a/47382691
answer count: 1

http://stackoverflow.com/comment/81828886
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47435631
score: 0
has text: wrong copy paste from the IDLE. Will correct it in a moment. thanks

http://stackoverflow.com/a/47533042
answers question: http://stackoverflow.com/q/47480719
has body: This question is likely a manifestation of the X/Y problem. Instead of asking about your problem X you are asking about the solution Y you came up with. Why are you keeping a counter field in the first place? I mean, why not to remove the count field and query it with: Foo.objects.order_by('fruit', 'stuff', 'color')\ .values('fruit', 'stuff', 'color')\ .annotate(count=Count('*')) Or keep it but use the sum of count instead: Foo.objects.order_by('fruit', 'stuff', 'color')\ .values('fruit', 'stuff', 'color')\ .annotate(total=Sum('count')) If you drop the unique_together constraint all you have to do in order to merge the dataset is to insert your new entries in the database: for fruit, stuff, color in collection: Foo.objects.update_or_create(fruit=fruit, stuff=stuff, color=color) Or assuming collection is a dict of keys and counts: for fruit, stuff, color in collection: Foo.objects.update_or_create( fruit=fruit, stuff=stuff, color=color, count=F('count') + collection[(fruit, stuff, color)], ) Please don't answer "it is for performance reasons" unless you have profiled both approaches - in my not-so-humble opinion it is the database's job to keep the score. If you try it and really find a performance problem then a competent DBA will propose a solution (in rare cases it may involve keeping an auxiliary table with the count through the use of database triggers). My point is, keeping a value that can be calculated by the database is a questionable design. You must have a good reason for it, and you must profile the 'let the database calculate it' approach first - otherwise you risk complicating your design because of imaginary performance reasons. Anyway I can't think any strategy where you can make this better than O(n) - n being the number of entries in the dataset you want to merge. Then I may have guessed your original problem wrong so let us know if it is the case.
type: Answer
has comment: http://stackoverflow.com/comment/82037234
score: 0
has comment: http://stackoverflow.com/comment/82037682

http://stackoverflow.com/comment/81877074
comment on: http://stackoverflow.com/q/47460435
type: QuestionComment
type: Comment
has text: "Failed building wheel for fatiando"
score: 0

http://stackoverflow.com/a/48608490
type: Answer
score: 6
upvote count: 6
has body: In my opinion, the best way to find an optimal curve fitting degree or in general a fitting model is to use the GridSearchCV module from the scikit-learn library. Here is an example how to use this library: Firstly let us define a method to sample random data: def make_data(N, err=1.0, rseed=1): rng = np.random.RandomState(rseed) X = rng.rand(N, 1) ** 2 y = 1. / (X.ravel() + 0.3) if err &gt; 0: y += err * rng.randn(N) return X, y Build a pipeline: def PolynomialRegression(degree=2, **kwargs): return make_pipeline(PolynomialFeatures(degree), LinearRegression(**kwargs)) Create a data and a vector(X_test) for testing and visualisation purposes: X, y = make_data(200) X_test = np.linspace(-0.1, 1.1, 200)[:, None] Define the GridSearchCV parameters: param_grid = {'polynomialfeatures__degree': np.arange(20), 'linearregression__fit_intercept': [True, False], 'linearregression__normalize': [True, False]} grid = GridSearchCV(PolynomialRegression(), param_grid, cv=7) grid.fit(X, y) Get the best parameters from our model: model = grid.best_estimator_ model Pipeline(memory=None, steps=[('polynomialfeatures', PolynomialFeatures(degree=4, include_bias=True, interaction_only=False)), ('linearregression', LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False))]) Fit the model with the X and y data and use the vector to predict the values: y_test = model.fit(X, y).predict(X_test) Visualize the result: plt.scatter(X, y) plt.plot(X_test.ravel(), y_test, 'r') The best fit result The full code snippet: from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.pipeline import make_pipeline import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import GridSearchCV def make_data(N, err=1.0, rseed=1): rng = np.random.RandomState(rseed) X = rng.rand(N, 1) ** 2 y = 1. / (X.ravel() + 0.3) if err &gt; 0: y += err * rng.randn(N) return X, y def PolynomialRegression(degree=2, **kwargs): return …
answers question: http://stackoverflow.com/q/47442102
downvote count: 0

http://stackoverflow.com/q/47538896
tagged with: scipy
answer count: 1
has body: I am trying to optimize the first function given the latter two constraining function, using Scipy. def entropy(x): entropy = 0 for i in range(6): entropy = entropy + x[i]*np.log(x[i]) return entropy def constraint_1(x): validpmf = 0 for i in range(6): validpmf = validpmf + x[i] return validpmf - 1 def constraint_2(x): mean = 0 for i in range(7): mean = mean + (i*x[i-1]) return mean - 4.5 Here is the Scipy code. ans = sp.optimize.minimize(entropy, [.04,.08,.1,.15,.25,.35], \ constraints = cons, jac = False, method = 'SLSQP') I am receiving the actual correct answer back, but I am getting a runtime warning: [ 0.05447023 0.07863089 0.1140969 0.16556351 0.23970755 0.34753092] RuntimeWarning: invalid value encountered in log entropy = entropy + x[i]*np.log(x[i]) I had this issue before with a simpler optimization problem where it was returning an incorrect answer which I fixed by changing my initial guesses. I don't understand why that had worked. In this case however, the initial guesses are quite good approximations so I want to keep them, and also changing them around hasn't managed to mitigate the runtime warning. To summarize, solution is correct but I don't understand the runtime warning.
tagged with: numpy
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47539226
tagged with: entropy
has answer: http://stackoverflow.com/a/47539226
tagged with: mathematical-optimization
type: AnsweredQuestion
score: 0
has title: Python Scipy Optimization: Runtime Warning Invalid Value Encountered in Log

http://stackoverflow.com/a/47398424
has comment: http://stackoverflow.com/comment/81749985
type: Answer
answers question: http://stackoverflow.com/q/47398242
has comment: http://stackoverflow.com/comment/81749916
has body: You can try this one: loweralphas=["a", "b","c","d","e","f"] upperalphas=["a", "b","c","d","e","f"] for index, lower in enumerate(loweralphas[:2]): print(lower) for upper in upperalphas[index*3:(index*3)+3]: print(upper.title()) print() Output: a A B C b D E F
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81750121
score: 0
accepted answer of: http://stackoverflow.com/q/47398242

http://stackoverflow.com/comment/81933346
has text: In the 2nd, `temp=b[0]` is evaluated. Then `temp1=temp[:]`, then `temp1[1]`. That is, separate indexing operations. `b[0,:,1]` is one indexing operation, evaluate as a whole by `numpy`. Trying match the two operations isn't always useful.
score: 0
comment on: http://stackoverflow.com/q/47486188
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82006916
comment on: http://stackoverflow.com/q/47525379
score: 0
has text: what does the meaning of the `product` in here?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81886019
comment on: http://stackoverflow.com/q/47465658
type: QuestionComment
has text: When speed is important, why not keeping the whole structure as numpy-array instead of list of arrays?
type: Comment
score: 2

http://stackoverflow.com/a/47502575
downvote count: 0
has comment: http://stackoverflow.com/comment/81961090
upvote count: 1
has body: IMO, the correct way to do this would be a Python 2D list. It's pretty simple: solutions = [ ["ans1", "ans2", "ans3", 2], ["ans4", "ans5", 3] # etc. ] # If you want "ans1", you can use solutions[0][0]. For "ans3": solutions[0][2] for question in solutions: answers = input("answers here:").split(",") if(answers == question): # This checks to see if the lists are the same, e.g. ["foo", 3, "bar"] == ["foo", 3, "bar"] returns True. print("right") else: print("wrong")
type: Answer
accepted answer of: http://stackoverflow.com/q/47502527
score: 1
has comment: http://stackoverflow.com/comment/81961080
answers question: http://stackoverflow.com/q/47502527
type: AcceptedAnswer

http://stackoverflow.com/a/47628914
downvote count: 0
upvote count: 1
has body: Your points are in a different format than OpenCV wants. Your pt1 and pt2 probably look something like np.array(x, y), but look what the tuple looks like when you cast it: &gt;&gt;&gt; pt1 = np.array([[50, 50]]) &gt;&gt;&gt; tuple(pt1) (array([50, 50]),) This is a tuple with a single element, instead of two items like you expect. Obviously for drawing, it wants a tuple with length 2 (namely, the x and y coordinates). Hence the error; the inner function expects two arguments but only one value was inside your tuple. To demonstrate: &gt;&gt;&gt; pt1 = np.array([[50, 50]]) &gt;&gt;&gt; cv2.circle(img, tuple(pt1), 5, 255, -1) Traceback (most recent call last): File "...", line 10, in &lt;module&gt; cv2.circle(img, tuple(pt1), 5, 255, -1) TypeError: function takes exactly 2 arguments (1 given) Instead, this is what you want the tuple to look like: &gt;&gt;&gt; tuple(pt1[0]) (50, 50) Supposing you want to be able to handle points passed in either format, just reshape the point first. Either way you only have two values in the pt1 or pt2 arrays, so reshaping won't affect it. For e.g. you could use flatten() from numpy: &gt;&gt;&gt; tuple(pt1.flatten()) (50, 50) And this should fix your issue. &gt;&gt;&gt; pt1 = np.array([[50, 50]]) &gt;&gt;&gt; cv2.circle(img, tuple(pt1.flatten()), 5, 255, -1) &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/47429580
accepted answer of: http://stackoverflow.com/q/47429580
type: Answer
score: 1
type: AcceptedAnswer

equality
tags question: http://stackoverflow.com/q/47479955
tag name: equality
type: Tag

http://stackoverflow.com/q/47497708
has comment: http://stackoverflow.com/comment/82005343
has comment: http://stackoverflow.com/comment/81967473
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/82011295
score: 0
has comment: http://stackoverflow.com/comment/81954665
answer count: 0
tagged with: selenium-iedriver
type: Question
tagged with: robotframework
has comment: http://stackoverflow.com/comment/81964717
type: UnansweredQuestion
tagged with: selenium2library
has body: I am trying to run my script in ie i am getting below error. But same works fine with firefox, chrome. Selenium :: 3.7.1 IE Version :: 11 (32 bit) IEDriverServer :: tried with 3.6 and 3.7 (all 32 bit) Robotframework :: 3.0.2 OS :: windows 7 Enterprise edition (64 bit) The error message is: WebDriverException: Message: Unexpected error launching Internet Explorer. IELaunchURL() returned HRESULT 80070012 ('There are no more files.') for URL 'http://localhost:64094/' below settings are applicable for IE. Internet security options for all the zones, the checkbox is unchecked for Enable protected mode. zoom level is set to 100%
has comment: http://stackoverflow.com/comment/81966169
tagged with: python
has title: RoboFrameWork:: WebDriverException: Message: Unexpected error launching Internet Explorer

http://stackoverflow.com/comment/81769097
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47407845
has text: Mock just only the function what I want. I think this answer is what I'm looking for. But if I write another `test_function` iside the `TestLibrary` is not actually calling the `query_fun` mock method instead it's just call the normal method.

http://stackoverflow.com/q/47459317
tagged with: amazon-elastic-beanstalk
favorite count: 0
type: Question
tagged with: maven
tagged with: python
tagged with: amazon-web-services
tagged with: bitbucket-pipelines
type: AnsweredQuestion
has title: How to deploy Java Maven based application on AWS ElasticBeanstalk using Bitbucket pipelines?
downvote count: 0
upvote count: 1
score: 1
has body: How to deploy Java Maven based application on AWS ElasticBeanstalk using Bitbucket pipelines? I found there example how to do it using python script. I modify yml and py script for my needs. All steps are going ok, bot on last one(execute python script it throws error. What is going wrong? Thanks. YML File image: openkbs/jre-mvn-py3 pipelines: branches: master: - step: caches: - maven - node script: - mvn clean install - apt-get update - apt-get -y install python-pip - pip install boto3 - export AWS_SECRET_ACCESS_KEY=KEY - export AWS_ACCESS_KEY_ID=KEY - export AWS_DEFAULT_REGION=REGION - python beanstalk_deploy.py Python Script Source Traceback (most recent call last): File "beanstalk_deploy.py", line 107, in main() File "beanstalk_deploy.py", line 99, in main if not create_new_version(): File "beanstalk_deploy.py", line 56, in create_new_version Process=True File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 586, in _make_api_call api_params, operation_model, context=request_context) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 641, in _convert_to_request_dict api_params, operation_model) File "/usr/local/lib/python2.7/dist-packages/botocore/validate.py", line 291, in serialize_to_request raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed: Invalid type for parameter SourceBundle.S3Bucket, value: None, type: , valid types:
answer count: 1
has answer: http://stackoverflow.com/a/47470098
accepted answer: http://stackoverflow.com/a/47470098

http://stackoverflow.com/comment/81887952
type: Comment
score: 0
type: AnswerComment
has text: yes, you are right, I used htop and it shows that Mem is used with a high percentage.
comment on: http://stackoverflow.com/a/47408840

http://stackoverflow.com/comment/81991600
score: 0
type: Comment
type: QuestionComment
has text: So, `dfmi.A` and `dfmi.B` would have the same shapes, right?
comment on: http://stackoverflow.com/q/47516935

http://stackoverflow.com/comment/81952755
type: AnswerComment
has text: Thank you, @Mark_M!! Much appreciated!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47498716

http://stackoverflow.com/comment/81737038
comment on: http://stackoverflow.com/a/47392070
type: Comment
score: 0
type: AnswerComment
has text: I'm still getting 0 after commenting this line.

http://stackoverflow.com/a/61539349
answers question: http://stackoverflow.com/q/47454788
has comment: http://stackoverflow.com/comment/108861860
score: 0
type: Answer
has body: c = [] for items in a: for numbers in b: if items == numbers: if items in c: None else: c.append(items) print(c)

http://stackoverflow.com/a/47476389
has body: 2 things: You need to modify your function to accept the argument that bind passes. (You don't need to use it, but you need to accept it). def enter(event=None): And you need to pass the function, not the result, to the bind method. So drop the (). bt.bind('&lt;Return&gt;',enter) Note this binds Return to the Button, so if something else has focus then this won't work. You probably want to bind this to the Frame. fr.bind('&lt;Return&gt;',enter) If you want a way to push an in focus Button the space bar already does that.
answers question: http://stackoverflow.com/q/47475783
has comment: http://stackoverflow.com/comment/81910463
score: 16
upvote count: 16
has comment: http://stackoverflow.com/comment/81910753
has comment: http://stackoverflow.com/comment/81910424
has comment: http://stackoverflow.com/comment/81908418
type: Answer
has comment: http://stackoverflow.com/comment/81909427
has comment: http://stackoverflow.com/comment/81909378
has comment: http://stackoverflow.com/comment/81910589
accepted answer of: http://stackoverflow.com/q/47475783
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81748307
type: QuestionComment
comment on: http://stackoverflow.com/q/47396893
score: 0
has text: Try: Lambda x: str(x)[1]
type: Comment

http://stackoverflow.com/a/58081815
has body: When the business day convention is Following: Add n solar months, as in your example Add 0 business days. This will adjust the date to match the first following business day, only in case the result of the first calculation doesn't fall on a business day. The code above modified accordingly: from datetime import datetime from pandas.tseries.offsets import DateOffset, BDay datetime(2017, 11, 23) + DateOffset(months=1) + BDay(0) This seems to work for me. I am using pandas 0.25.1 on python 3.7.4.
answers question: http://stackoverflow.com/q/47454111
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47476329
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/81907469
has comment: http://stackoverflow.com/comment/81908086
favorite count: 0
type: Question
has body: import scipy as sp atomos=open("Átomo.txt", 'r') deltaX=[] deltaY=[] deltaZ=[] d=0 def dist(xf, xi, yf, yi,zf, zi): d=sp.sqrt((xf-xi)*(xf-xi)+(yf-yi)*(yf-yi)+(zf-zi)*(zf-zi)) return d for colunas in atomos: coluna_limpa=colunas.strip().split("\t") deltaX.append(coluna_limpa[1]) deltaY.append(coluna_limpa[2]) deltaZ.append(coluna_limpa[3]) print(deltaX, deltaY, deltaZ) d= dist(deltaX[0], deltaX[9],deltaY[0], deltaY[9], deltaZ[0], deltaZ[9] ) print("A distância do segmento formado pelos atomos é de ", d) File "&lt;ipython-input-5-e2b6e08387d0&gt;", line 11, in dist d=sp.sqrt((xf-xi)*(xf-xi)+(yf-yi)*(yf-yi)+(zf-zi)*(zf-zi)) TypeError: unsupported operand type(s) for -: 'str' and 'str'
has comment: http://stackoverflow.com/comment/81907291
tagged with: typeerror
has answer: http://stackoverflow.com/a/47476382
has title: Don't know what to do? python
tagged with: python
has answer: http://stackoverflow.com/a/47476378
downvote count: 4
has comment: http://stackoverflow.com/comment/81907271
upvote count: 0
answer count: 2

http://stackoverflow.com/q/47460196
score: 2
answer count: 0
upvote count: 2
downvote count: 0
has body: I have 2 different xml files with the following name spaces f1 has the namespace {'ns1': 'http://www.internaltext.com/document/informationtable'} f2 has the namespace {'abc': 'http://www.externaltest.org/2016/XMLSchema-instance', None: 'http://www.internaltext.com/document/informationtable'} As can be seen, the namesapce have different keys for the same values. I am able to parse both the files using the same python script if I create a namespace dictionary and use it: from lxml import etree d1 = etree.parse(f1) r1 = d1.getroot() ns = {'abc': 'http://www.externaltest.org/2016/XMLSchema-instance', 'miss': 'http://www.sec.gov/edgar/document/thirteenf/informationtable'} for i in r1.findall('miss:infoTable',ns): name = i.find('miss:name',ns) But is there a way to do this, without defining the namespace dictionary and using the nsmap function to extract the namespace dictionary and use that? Like ns = r1.nsmap
has title: Getting namespace dictionary using nsmap to parse different files with same python script
favorite count: 0
type: Question
tagged with: lxml
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: http://stackoverflow.com/tag/xml

python-twitter
tag name: python-twitter
type: Tag
tags question: http://stackoverflow.com/q/47415824

http://stackoverflow.com/comment/81796871
comment on: http://stackoverflow.com/q/47410054
type: Comment
type: QuestionComment
score: 0
has text: We probably all guessed that `min, max` relates to the triangle coordinates. But looking at her other question, I am afraid, we won't get any feedback.

http://stackoverflow.com/q/47418760
answer count: 6
possible better answer: http://stackoverflow.com/a/61976069
accepted answer: http://stackoverflow.com/a/47418941
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55839939
downvote count: 0
has answer: http://stackoverflow.com/a/70648620
has answer: http://stackoverflow.com/a/61972021
favorite count: 0
has answer: http://stackoverflow.com/a/55840082
score: 8
upvote count: 8
has answer: http://stackoverflow.com/a/61976069
type: Question
has body: I have opened a python Jupyter notebook but did not notice that it was in read-only, Not Trusted mode. How to save my changes now? Things that I have tried and did not help: File -> Make a Copy File -> Save and Checkpoint File -> Download as File -> Trust Notebook
has answer: http://stackoverflow.com/a/47418941
has title: How to save changes in read-only Jupyter Notebook
tagged with: python
tagged with: jupyter-notebook

http://stackoverflow.com/q/47461245
answer count: 7
tagged with: python
score: -1
has title: A replacement between lists
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47461325
has answer: http://stackoverflow.com/a/47461315
has answer: http://stackoverflow.com/a/47461321
type: UnansweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47461347
downvote count: 1
has comment: http://stackoverflow.com/comment/81877250
has answer: http://stackoverflow.com/a/47461351
has answer: http://stackoverflow.com/a/47461537
has body: a = ["I like apple","I love you so much"] I want to change "apple" and "love" words with followings : "orange","like" but I don't want to change the elements ( sentences) in a so output must be a= ["I like orange","I like you so much"] No changes should happen in anything except words orange and like. Not even a space added or dropped.
has answer: http://stackoverflow.com/a/47461377

http://stackoverflow.com/q/47490284
has comment: http://stackoverflow.com/comment/81935876
tagged with: graph
type: AnsweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81935826
tagged with: python
accepted answer: http://stackoverflow.com/a/47490368
has answer: http://stackoverflow.com/a/47490368
type: Question
has comment: http://stackoverflow.com/comment/81935907
score: 0
tagged with: linked-list
has title: How can I write a The Breadth First Search algorithm on a linked data structure?
answer count: 1
has body: We can use a queue and mark all the nodes to do BFS. This is easy if the graph is stored in adjacency matrix, where we can easily get how many nodes are there and create an marker array. What should I do if I have such TreeNode definition? (Giving such definition, I do not know how many nodes are in the tree.) # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81983764
type: QuestionComment
comment on: http://stackoverflow.com/q/47513720
score: 0
type: Comment
has text: Yes; that's what the `wraps` argument to `Mock` is for.

http://stackoverflow.com/a/47432369
type: Answer
has body: After running some speed tests with the proposals, I have realized that a weak point about the solutions proposed, if I am not mistaken, is that the complete loop will always be done for the mapping. By skipping the loop earlier in case the result is already known, speed could be improved. In addition, if one list is much larger than all the others, there is some potential to speed things up. I think the following could be faster, in case one of the lists is much larger than the others. The assumption is that list3 is much larger than the others. list1 = ['London', 'Manchester', 'Liverpool', 'Edimburgh'] list2 = ['Dublin', 'Cork', 'Galway'] list3 = ['Berlin', 'Munich', 'Frankfurt', 'Paris', 'Milan', 'Rome', 'Madrid', 'Barcelona', 'Lisbon', ...] #assuming list3 is much larger than all others list4 = ['Washington', 'New York', 'San Francisco', 'LA', 'Boston', ...] A possibility would be: def in_same_group(city1, city2): for group in [list1, list2, list4]: #note that list3, the largest, is skipped if city1 in group and city2 not in group: return False return True #if this point is reached, both cities belong to the biggest group
answers question: http://stackoverflow.com/q/47416917
score: 0

http://stackoverflow.com/comment/81797608
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47417474
has text: Thanks! Also, would it be safe to assume that the strings would always of the same number of characters, like here they are two character strings?
score: 0

http://stackoverflow.com/q/47491875
tagged with: pygame
score: -4
has comment: http://stackoverflow.com/comment/81939098
has title: Python web communication between files
downvote count: 4
has answer: http://stackoverflow.com/a/47558155
has comment: http://stackoverflow.com/comment/81939125
upvote count: 0
has comment: http://stackoverflow.com/comment/81939150
tagged with: web
answer count: 1
favorite count: 0
has body: I have my game created in pygame and now i want to create some sort of multiplayer, where one player will be hosting and the other will join the room. At the moment i have no idea about internet connection between two programs on different PCs and haven't found anything on google either. Thanks for any clues
type: Question
has comment: http://stackoverflow.com/comment/81939064
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47527153
tagged with: gps
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82011015
tagged with: raspberry-pi
downvote count: 0
answer count: 1
upvote count: 1
has title: GPS reading not changing corresponding to moving device
accepted answer: http://stackoverflow.com/a/47587748
favorite count: 0
type: Question
tagged with: raspbian
has answer: http://stackoverflow.com/a/47587748
score: 1
has comment: http://stackoverflow.com/comment/82010602
tagged with: python
has body: I am developing an application in raspberry pi to use it as a location tracker. I am using neo-6m GPS via USB interface to get the position data in raspberry pi. For this I am setting up GPSD to point to the USB-Serial device. (See instructions) The following python script polls the GPSD daemon and sends the location data to the parent process via a Unix Domain Socket: #!/usr/bin/python import os from gps import * from time import * import time import threading import socket import math t1, t2 = socket.socketpair() gpsd = None #seting the global variable host = "localhost" port = 8888 class GpsPoller(threading.Thread): def __init__(self): threading.Thread.__init__(self) global gpsd #bring it in scope gpsd = gps(mode=WATCH_ENABLE,host=host,port=port) #starting the stream of info self.current_value = None self.running = True #setting the thread running to true def run(self): print("%%%%%%%GPS RUN") global gpsd while self.running: gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer time.sleep(3) def poll_gps(socket): print('GPS POLL') gpsp = GpsPoller() # create the thread gpsp.start() try: while True: #It may take a second or two to get good data #print gpsd.fix.latitude,', ',gpsd.fix.longitude,' Time: ',gpsd.utc #print 'latitude ' , gpsd.fix.latitude #print 'longitude ' , gpsd.fix.longitude if gpsd.fix.latitude is not None and gpsd.fix.longitude is not None and not math.isnan(gpsd.fix.longitude ) and not math.isnan(gpsd.fix.latitude ) and gpsd.fix.latitude != 0.0 and gpsd.fix.longitude != 0.0 : gps_str='{0:.8f},{1:.8f}'.format(gpsd.fix.latitude, gpsd.fix.longitude) dict_str="{'type' : 'gps', 'value' : '"+gps_str+"'}" dict_str_new="{'type' : 'gps', 'value' : '"+str(gpsd.fix.latitude)+","+str(gpsd.fix.longitude)+"'}" print("GPS123_OLD" +dict_str) print("GPS123_NEW" +dict_str_new) if socket == None: print("GOT GPS VALUE") sys.exit(0) socket.sendall(dict_str+'\n') else: print('%%%%%%%%%%%%%%%%%%GPS reading returnd None!') time.sleep…
tagged with: gpsd

http://stackoverflow.com/q/47398489
type: Question
has comment: http://stackoverflow.com/comment/81752870
tagged with: linux
has body: On a Red Hat 7 machine with Python 2.7.5, I'm noticing some weird behavior. If I run the app directly (ie, $ myApp.py?), it'll hang when performing a certain operation. If I run it via $ python myApp.py, the operation succeeds. I have #!/usr/bin/env python at the top of my script (and each of its included modules as well). I've attempted to use pdb to diagnose it, but since that's invoked via $ python ... myApp.py, it works! $ /usr/bin/env python --version and $ python --version return the same value, so I suspect they're pointing at the same executable. Is there something sneaky happening with my program loader?
has title: Different behavior calling python vs directly
tagged with: python
has comment: http://stackoverflow.com/comment/81754028
has comment: http://stackoverflow.com/comment/81751205
has comment: http://stackoverflow.com/comment/81753132
has comment: http://stackoverflow.com/comment/81750221
tagged with: python-2.7
score: 0
tagged with: bash
answer count: 0
type: UnansweredQuestion
tagged with: rhel7
has comment: http://stackoverflow.com/comment/81753636
has comment: http://stackoverflow.com/comment/81753302

http://stackoverflow.com/comment/81920990
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47482942
has text: Where is the `print`?
score: 1

http://stackoverflow.com/q/47401563
tagged with: function
has body: I am new to Python, and am confused by the literature as to how to design a function to display error messages when the input is either not a string of length 21. This is the latest permutation that is not working. For a string of length 19 for example, it does not return the right error message. My background is not in comp sci, so any help on this and an explanation as to how this works would be helpful. Thanks test = "test_string_for_slice" test2 = "test_string_for_" def stringSlice(x): if type(x) != str: raise Exception("The input is not a string.") elif len(x) != 21: raise ValueError("The input is not exactly 21 characters.") else: slice1 = x[0:6] slice2 = x[6:12] slice3 = x[13:] return slice1, slice2, slice3 stringSlice(test) stringSlice(test2) #this should return an error but does not
tagged with: error-handling
has comment: http://stackoverflow.com/comment/81757168
answer count: 1
has comment: http://stackoverflow.com/comment/81757346
has comment: http://stackoverflow.com/comment/81756886
has comment: http://stackoverflow.com/comment/81756759
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47401622
tagged with: python
has title: Python Function Error When Input Is Not String Or Not Certain Length
has answer: http://stackoverflow.com/a/47401622
has comment: http://stackoverflow.com/comment/81757033
has comment: http://stackoverflow.com/comment/81756818
has comment: http://stackoverflow.com/comment/81757436
type: Question
score: 0

http://stackoverflow.com/q/47445310
tagged with: debugging
has title: Python : (Titanic) debugging error in imputing fare
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
score: 0
has body: I will thank very much for your help.I have a problem with the classic Kaggle Titanic Tutorial for machine learning. My problem is when using a pivotal table to imput means in a dataframe (or tupple): fare_means = df.pivot_table("Fare", index= "Pclass", aggfunc="mean") ​fare_means.info() fare_class 'pandas.core.frame.DataFrame'&gt; Int64 Index: 3 entries, 1 to 3 Data columns (total 1 columns): Fare 3 non-null float64 dtypes: float64(1) memory usage: 48.0 bytes fare_means Out[46]: Fare ---Pclass 1 ------- 84.154687 2 -------20.662183 3 -------13.675550 df_test['Fare'] = df_test'Fare', 'Pclass'.apply(lambda x: fare_means[x['Pclass']] if pd.isnull(x['Fare']) else x['Fare'], axis=1) KeyError: (3, u'occurred at index 152') df_test.iloc[150:155, 0: ] Index-- Pclass ---- Fare 150 ------ 1 --------83.1583 151 ------ 3 --------7.8958 152 ------ 3 --------NaN 153 ------ 3 --------12.1833 154 ------ 3 --------31.3875
has answer: http://stackoverflow.com/a/47519338
answer count: 1
type: Question

http://stackoverflow.com/a/47415350
has comment: http://stackoverflow.com/comment/81785080
score: 1
answers question: http://stackoverflow.com/q/47406152
has comment: http://stackoverflow.com/comment/81785003
type: Answer
downvote count: 0
has body: If you go to API Explorer and simulate your request you will see that this library returns you exactly the same output in python data structures. In there ID looks the most like gs:// link: "id": "test-bucket/text.txt/0000000000000000" or in python it looks like: u'id': u'test-bucket/text.txt/00000000000000000' Simple use this to transform it into a gs:// link: import os u'gs://' + os.path.dirname(svc_response['id']) which would return: u'gs://test-bucket/text.txt' If you want to use the google-cloud-python you will be facing the same issue.
upvote count: 1

http://stackoverflow.com/q/47493806
tagged with: anaconda
downvote count: 0
linked to: http://stackoverflow.com/q/33175827
has comment: http://stackoverflow.com/comment/81942833
answer count: 4
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/47498538
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
has comment: http://stackoverflow.com/comment/81942807
has comment: http://stackoverflow.com/comment/81942878
has title: How to clean iPython environment so I can start over with Jupyter and Python 3.x?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52123490
upvote count: 5
has answer: http://stackoverflow.com/a/64539615
tagged with: python
has comment: http://stackoverflow.com/comment/81942800
has answer: http://stackoverflow.com/a/47498448
linked to: http://stackoverflow.com/q/45271344
has comment: http://stackoverflow.com/comment/81942684
has body: Over the past couple years I've pip installed lots of things without knowing what I was doing. All of a sudden, I am getting this error when I run a snippet in a Python 2.7 Jupyter Notebook: ImportError: No module named matplotlib When I run this in Terminal: which -a python python 3... I get: Sams-MacBook-Pro-2:~ sambrand$ which -a python python3 //anaconda/bin/python /usr/local/bin/python /usr/bin/python /usr/local/bin/python I think this is showing that I have Python in a few places, which might explain why my standard libraries (eg. matplotlib) aren't being found in the Python environment that I want to use. My ideal result: Ultimately, I just want to clean up my environment and start from scratch so that I can use Keras, Tensorflow, and all Anaconda packages with Python 3 as my default when I open a Jupyter Notebook. Additionally, I'd like any subsequent pip install from the terminal to update what I'm using in Jupyter. From what I gather, this kind of bewilderment about Python environment is a fairly common issue, so I hope this post proves helpful.

http://stackoverflow.com/comment/86944154
type: Comment
score: 0
type: AnswerComment
has text: Kumail, setup.py is part of tf models project. In github it is under models/research. clone or fork it and modify.
comment on: http://stackoverflow.com/a/48008919

http://stackoverflow.com/q/47410131
has answer: http://stackoverflow.com/a/47410594
has comment: http://stackoverflow.com/comment/81774296
score: -5
answer count: 2
has comment: http://stackoverflow.com/comment/81773798
upvote count: 0
has body: myfile = open(Class".csv","a+") I am trying to set whats in Class as the name of the csv file but it comes up with a syntax error. Can someone advise me on how to fix this issue.
has answer: http://stackoverflow.com/a/47410983
has title: How do I use a variable name as the name of a csv file?
has comment: http://stackoverflow.com/comment/81773662
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81774140
has comment: http://stackoverflow.com/comment/81773612
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81773674
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/81773931
has comment: http://stackoverflow.com/comment/81774072

http://stackoverflow.com/comment/81792375
has text: This doesn't add 1, it adds 100000
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47419095
type: AnswerComment

http://stackoverflow.com/q/47384763
score: -4
has comment: http://stackoverflow.com/comment/81722383
tagged with: python
possible better answer: http://stackoverflow.com/a/47385097
tagged with: indexing
has comment: http://stackoverflow.com/comment/81722359
type: AnsweredQuestion
has title: String out of index
has answer: http://stackoverflow.com/a/47385097
downvote count: 4
accepted answer: http://stackoverflow.com/a/47385052
tagged with: string
has comment: http://stackoverflow.com/comment/81722551
has answer: http://stackoverflow.com/a/47385052
favorite count: 0
type: Question
answer count: 2
has body: My requirements Use Python to create a function cleanstring(S) to "clean up" the spaces in a sentence S. The sentence may have extra spaces at the front and/or at the end and/or between words. The subroutine returns a new version of the sentence without the extra spaces. That is, in the new string, the words should be the same but there should be no spaces at the start, only one space between each word and no spaces at the end. This program is about you writing code to search through a string to find words and so you are not allowed to use the split function in Python. You can solve this problem with the basic capabilities of the if and while statements and string operations of len and concatentation. For example: if the input is: " Hello to the world !" then the output should be: "Hello to the world!" Question My program creates an error. How do I fix the error in my program? def cleanupstring (S): newstring = ["", 0] j = 1 for i in range(len(S)): if S[i] != " " and S[i+1] != " ": newstring[0] = newstring[0] + S[i] else: newstring[1] = newstring [1] + 1 return newstring # main program sentence = input("Enter a string: ") outputList = cleanupstring(sentence) print("A total of", outputList[1], "characters have been removed from your string.") print("The new string is:", outputList[0])
upvote count: 0
has comment: http://stackoverflow.com/comment/81722384

http://stackoverflow.com/q/47465579
has answer: http://stackoverflow.com/a/47465589
tagged with: text
score: 0
tagged with: python
has title: Python - Text to List but not as strings
tagged with: readline
tagged with: class
type: Question
tagged with: list
type: UnansweredQuestion
answer count: 1
has body: I Have a text file containing class statements like so: Person('John Smith','1st Street','1987') Patient('Steve White','2nd Street','1976','456 132 768 128','11/14/17','St. Johns','Warren','309C') Employee('Roger Marks','3rd Street','1991','192837465','2011') Doctor('Paul Warren','4th Street','1967','918213665','2007','250000','Cardiology','17') Staff('Mike Clark','5th Street','1983','285018539','2009','Custodian','Sanatation','18', 'Full') When I enter them into a list using: infile = open('ClassData.txt', 'r') line = infile.readline() for line in infile: pObjects.append(line) I get them in quotes, for example: pObjects = ["Person('John Smith','1st Street','1987')","Employee('Roger Marks','3rd Street','1991','192837465','2011')"] What could I change to get them in there without the quotes so they can be pulled from the list and ran, like, pObjects = [Person('John Smith','1st Street','1987'),Employee('Roger Marks','3rd Street','1991','192837465','2011')]

http://stackoverflow.com/a/49800817
type: Answer
upvote count: 4
has body: The OP is correct here. There is a serious bug when you try to load multiple weight files in the same script. The above answer doesn't solve this. If you actually interrogate the weights when loading weights for multiple models in the same script you will notice that the weights are different than when you just load weights for one model on its own. This is where the randomness is the OP observes coming from. EDIT: To solve this problem you have to encapsulate the model.load_weight command within a function and the randomness that you are experiencing should go away. The problem is that something weird screws up when you have multiple load_weight commands in the same script like you have above. If you load those model weights with a function you issues should go away.
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47394104

http://stackoverflow.com/q/47442975
type: AnsweredQuestion
score: 0
has title: Python Pandas - increment matching rows by 1
tagged with: pandas
has answer: http://stackoverflow.com/a/47443042
downvote count: 1
accepted answer: http://stackoverflow.com/a/47443042
has comment: http://stackoverflow.com/comment/81840985
tagged with: python
has body: I have the following code where a dataframe d has two columns with col1 of strings values and col2 with int values. I want to find all the rows matching to a pattern (using contains) and then increase the col2 values by 1 for the corresponding row. In the last line of my code where I am trying to increment by one I am getting following error: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self[name] = value import pandas as pd d = {'col1': ['abc', 'ave','abd', 'ave','abe', 'ave'], 'col2': [0,1,0,1,0,1]} df = pd.DataFrame(data=d) #print(df[df.col1.str.contains("ab")]) df[df.col1.str.contains("ab")].col2 +=1 How can I increment the value using vector operation. I am trying to avoid for loop.
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/47443208
has answer: http://stackoverflow.com/a/47443208
favorite count: 0
type: Question

http://stackoverflow.com/comment/81898826
has text: why the "div binding" line ?
comment on: http://stackoverflow.com/a/47460867
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82035638
has text: And now you have a list of ranges and static values. Go!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47539335
type: Comment

http://stackoverflow.com/a/47480170
accepted answer of: http://stackoverflow.com/q/47474571
type: Answer
has comment: http://stackoverflow.com/comment/81970175
has comment: http://stackoverflow.com/comment/81972285
has body: 1) Pass request obj to your function to use it in it's body to retrieve POST params. In your code (when you do not pass request obj to your write function) you cannot get desired params because request is not a flask request object in write func body, just an undefined var. To use flask request obj in your function body - you need to pass it as a second argument: view.py: @app.route('/add', methods=['GET','POST']) def add_entry(): if request.method == 'POST': filename = request.form['file_name'] read_file(filename) #returns a dictionnary list write_file(filename, request) return redirect(url_for('index')) else : return render_template("file_add.html",title='Add a file', items=items) function.py: def write_file(filename, request): with open("app/static/DATA/{}".format(filename), "w") as f: global items items2 = [{ 'fixed_address': request.form['mac_address'], 'hardware': request.form['ip_address'], 'host': request.form['host_name'], 'comment': request.form['comment']}] items.append(items2) f.write(items) 2) Always use full path here with open("app/static/DATA/{}".format(filename), "w") as f: 3) Use json.dump() to write your data to a file: import json obj = [{"123": "123"}] with open("&lt;full_path&gt;", "w") as f: json.dump(obj, f, indent=4) 4) Do not use filename = request.form['file_name'] - use filename = request.form.get('file_name') instead.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47474571

stacked-chart
tags question: http://stackoverflow.com/q/47512793
tag name: stacked-chart
tags question: http://stackoverflow.com/q/47395797
type: Tag

http://stackoverflow.com/q/47536982
has answer: http://stackoverflow.com/a/47537240
type: UnansweredQuestion
score: 0
has body: Given a Pandas Dataframe like this: A B C ------------------------- A. b. b. d. a c. c. d a. k. b. b a. b. a, B Code: df = pd.DataFrame({ 'A': ['A. b.', 'c.', 'a. k.', 'a.'], 'B': ['b. d.', 'c.', 'b.', 'b.'], 'C': ['a', 'd', 'b', 'a, B'] }) I want to select all rows where A or B contain any value from C. Here, the result would be: A B C ------------------------- A. b. b. d. a a. k. b. b a. b. a, B All cells contain values in a simple delimited format (can use split). I've tried: df[df['A'].str.contains(df['C'].split(','))] But no success so far.
tagged with: pandas
has title: Find rows where one of 2 cols contains any value from a third split column in Pandas
tagged with: python
has answer: http://stackoverflow.com/a/47537505
type: Question
answer count: 2

http://stackoverflow.com/q/47407887
has comment: http://stackoverflow.com/comment/81796252
has comment: http://stackoverflow.com/comment/81772562
downvote count: 0
has comment: http://stackoverflow.com/comment/81770458
upvote count: 1
has body: I have run across a few examples of Python code that looks something like this: class GiveNext : list = '' def __init__(self, list) : GiveNext.list = list def giveNext(self, i) : retval = GiveNext.list[i] return retval class GiveABCs(GiveNext): i = -1 def _init__(self, list) : GiveNext.__init__(self, list) def giveNext(self): GiveABCs.i += 1 return GiveNext.giveNext(self, GiveABCs.i) class Give123s(GiveNext): i = -1 def _init__(self, list) : GiveNext.__init__(self, list) def giveNext(self): Give123s.i += 1 return GiveNext.giveNext(self, Give123s.i) for i in range(3): print(GiveABCs('ABCDEFG').giveNext()) print(Give123s('12345').giveNext()) the output is: A 1 B 2 C 3 If I were more clever, I could figure out how to put the string literals inside the constructor...but that is not crucial right now. My question is on the use of classes this way. Yes, an instance of the class gets created each time that that the call within the print() gets made. Yet the i's are 'permanent' in each class. This strikes me as less of an object-oriented approach, and more of a way of using classes to accomplish encapsulation and/or a functional programming paradigm, since the instances are entirely transitory. In other words, an instance of the class is never instantiated for its own purposes; it is there only to allow access to the class-wide methods and variables within to do their thing, and then it is tossed away. In many cases, it seems like the class mechanism is used in a back-handed way, in order to leverage inheritance and name resolution/spacing: an instance of the class is never really required to be built or used, conceptually. Is this standard Python form? Bonus question: how would I put the string literals inside each class declaration? Right now, even if I change the _init__ for GiveABCs to GiveNext.__init__(self, 'wxyz') it completely ignores the 'wxyz' literal, and uses the 'ABCDEF' one - even though it is never mentioned...
favorite count: 0
has answer: http://stackoverflow.com/a/47408389
type: Question
has answer: http://stackoverflow.com/a/47408377
has comment: http://stackoverflow.com/comment/81795511
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81769152
has comment: http://stackoverflow.com/comment/81769416
tagged with: python
tagged with: inheritance
has comment: http://stackoverflow.com/comment/81792455
tagged with: class
has title: Using Python classes for encapsulation, not instantiation
answer count: 2
score: 1

http://stackoverflow.com/q/47540270
type: Question
has answer: http://stackoverflow.com/a/47540820
tagged with: python
has comment: http://stackoverflow.com/comment/82037663
has answer: http://stackoverflow.com/a/47540691
score: 1
has comment: http://stackoverflow.com/comment/82037932
has comment: http://stackoverflow.com/comment/82037956
has comment: http://stackoverflow.com/comment/82038209
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/47541343
answer count: 4
accepted answer: http://stackoverflow.com/a/47541672
possible better answer: http://stackoverflow.com/a/47540820
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82038348
has answer: http://stackoverflow.com/a/47541672
tagged with: intersect
has comment: http://stackoverflow.com/comment/82038026
has comment: http://stackoverflow.com/comment/82037970
has comment: http://stackoverflow.com/comment/82038065
downvote count: 1
has title: intersect 4 lists in python with list comprehension
tagged with: list
has comment: http://stackoverflow.com/comment/82037669
has body: Is there a way to do with list comprehension the following: I have 4 lists: t1, x1(t1), t2, x2(t2). t1 and t2 have different length, and so do x1 and x2. I want to add up the values of x1 and x2 in which t1 and t2 intersect and for those values where t2 and t1 don't intersect just append their values in two new lists x and t. t1 = [0.0, 20.0, 40.0, 50.0, 60.0, 80.0] x1 = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] t2 = [40.0, 50.0, 80.0] x2 = [7.0, 8.0, 9.0] so that my new t and x are: t = [0.0, 20.0, 40.0, 50.0, 60.0, 80.0] x = [1.0, 2.0, 10.0, 12.0, 5.0, 15.0] This is the code with a double loop. Although so far it only does the add up. Still need to append those values for both t1, t2, x1 and x2 that do not intersect: x = [] t = [] for y in range(len(t1)): for z in range(len(t2)): if t1[y] == t2[z]: t.append(t1[y]) x.append(x1[y] + x2[z])

http://stackoverflow.com/comment/81764541
type: Comment
has text: This will miss cases like `3.3..4` and `3.3.`.
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47405538

http://stackoverflow.com/q/47407044
answer count: 0
score: 1
downvote count: 0
linked to: http://stackoverflow.com/q/45097302
tagged with: selenium
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/81770484
has comment: http://stackoverflow.com/comment/81774255
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/81767348
linked to: http://stackoverflow.com/q/44838538
has comment: http://stackoverflow.com/comment/81770541
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/45097302
has title: Need to download mutilple PDF link in one go from web table
type: UnansweredQuestion
has body: **from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions chrome_path = r"C:/chromedriver.exe" chrome_profile = webdriver.ChromeOptions() profile = {"download.default_directory": "C:\\Users\\adarshb061\\Desktop", "download.prompt_for_download": False, "download.directory_upgrade": True, "plugins.plugins_list": [{"enabled":False,"name":"Chrome PDF Viewer"}]} chrome_profile.add_experimental_option("prefs", profile) chrome_profile.add_argument("--disable-extensions") browser = webdriver.Chrome(chrome_options=chrome_profile, executable_path=chrome_path) browser.get("https://rbi.org.in/") browser.maximize_window() browser.find_element_by_xpath("""//*[@id="FEMA"]/a""").click() browser.find_element_by_xpath("""//*[@id="FEMANotifications"]""").click() def download_lnk(url): browser.get(url) browser.execute_script("window.history.go(-1)") rows = browser.find_elements_by_xpath("//table[@class='tablebg']//tr//td/a[contains(@href,'http://')]") for row in rows: pdf_link = row.get_attribute('href') print(pdf_link) download_lnk(pdf_link)** It is downloading only one PDF file from the web table. After that is giving me below exception: selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document Please suggest? Thanks in advance!
tagged with: python

http://stackoverflow.com/a/47480250
accepted answer of: http://stackoverflow.com/q/47478800
has body: Just like ax.patches, you can use ax.lines. Of course, I assume that error bars are the only lines you have in your plot otherwise you may have to do something extra to uniquely identify the error bars. The following works: for p in ax.lines: width = p.get_linewidth() xy = p.get_xydata() print(xy) print(width) print(p)
upvote count: 5
type: Answer
type: AcceptedAnswer
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47478800

http://stackoverflow.com/q/47384307
answer count: 1
has answer: http://stackoverflow.com/a/47401991
tagged with: import
type: Question
has title: Python fails to import packages within same folder structure
tagged with: python
has comment: http://stackoverflow.com/comment/81721475
has comment: http://stackoverflow.com/comment/81721607
type: AnsweredQuestion
score: 0
has body: I'm creating a personal application with flask_restful, and I was doing everything with a single models.py and app.py, but the application is going to grow so I decided to make some folder restructuring. I currently have the following structure: /project_folder application_name __init__.py controllers.py models.py config.py manage.py run.py tests __init__.py test_controller.py Everything works so far, but I want the structure to be the following: /project_folder application_name __init__.py controllers __init__.py brewery_controller.py ...others models __init__.py base_model.py brewery.py ...others config.py manage.py run.py tests __init__.py test_controller.py But I can't seem to make it work. Here is the application __init__.py #/project_folder/application_name/__init__.py import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_restful import Api from controllers import BreweryList, BreweryResource from models import db def initApp(config): app = Flask(__name__) app.config.from_object(config) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) api = Api(app) api.add_resource(BreweryList, '/breweries') api.add_resource(BreweryResource, '/breweries/&lt;brewery_id&gt;') return app I tried with from brewery_controller import BreweryList, BreweryResource from base_model import db with no luck. I keep getting ImportError: cannot import BreweryList and the same goes for db if I uncomment the Brewery classes import line. The controllers/__init__.py and models/__init__.py are both empty. Here is also the run.py import os from beerinv import initApp if __name__ == '__main__': app = initApp(os.environ['APP_SETTINGS']) app.run()
accepted answer: http://stackoverflow.com/a/47401991

http://stackoverflow.com/a/48387243
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86569216
has body: This may not be the asker's scenario, but I was receiving this error anytime I ran the reproduction script in Hyper 1.4.8 (with powershell.exe as my shell). Using Command Prompt or PowerShell outside of Hyper avoided the error.
answers question: http://stackoverflow.com/q/47476304

numpy
tags question: http://stackoverflow.com/q/47519841
tags question: http://stackoverflow.com/q/47469924
tags question: http://stackoverflow.com/q/47411957
tags question: http://stackoverflow.com/q/47479587
tags question: http://stackoverflow.com/q/47464227
tags question: http://stackoverflow.com/q/47509417
tags question: http://stackoverflow.com/q/47520820
tags question: http://stackoverflow.com/q/47428707
tags question: http://stackoverflow.com/q/47441952
tags question: http://stackoverflow.com/q/47492955
tags question: http://stackoverflow.com/q/47499959
tags question: http://stackoverflow.com/q/47486164
tags question: http://stackoverflow.com/q/47461938
tags question: http://stackoverflow.com/q/47510238
tags question: http://stackoverflow.com/q/47427238
tags question: http://stackoverflow.com/q/47499098
tags question: http://stackoverflow.com/q/47510098
tags question: http://stackoverflow.com/q/47459226
tags question: http://stackoverflow.com/q/47500905
tags question: http://stackoverflow.com/q/47531532
tags question: http://stackoverflow.com/q/47521088
tags question: http://stackoverflow.com/q/47462798
tags question: http://stackoverflow.com/q/47525011
tags question: http://stackoverflow.com/q/47492528
tags question: http://stackoverflow.com/q/47524685
tags question: http://stackoverflow.com/q/47481544
tags question: http://stackoverflow.com/q/47389447
tags question: http://stackoverflow.com/q/47443874
tags question: http://stackoverflow.com/q/47394572
tags question: http://stackoverflow.com/q/47397247
tags question: http://stackoverflow.com/q/47428193
tags question: http://stackoverflow.com/q/47388013
tags question: http://stackoverflow.com/q/47521116
tags question: http://stackoverflow.com/q/47487763
tags question: http://stackoverflow.com/q/47456806
tags question: http://stackoverflow.com/q/47495048
tags question: http://stackoverflow.com/q/47517485
tags question: http://stackoverflow.com/q/47486188
tags question: http://stackoverflow.com/q/47401706
tags question: http://stackoverflow.com/q/47457633
tags question: http://stackoverflow.com/q/47434224
tags question: http://stackoverflow.com/q/47492974
tags question: http://stackoverflow.com/q/47502640
tags question: http://stackoverflow.com/q/47486898
tags question: http://stackoverflow.com/q/47534715
tags question: http://stackoverflow.com/q/47391487
tags question: http://stackoverflow.com/q/47426595
tags question: http://stackoverflow.com/q/47386409
tags question: http://stackoverflow.com/q/47484899
tags question: http://stackoverflow.com/q/47509393
tags question: http://stackoverflow.com/q/47397469
tags question: http://stackoverflow.com/q/47539760
tags question: http://stackoverflow.com/q/47515454
tags question: http://stackoverflow.com/q/47413540
tags question: http://stackoverflow.com/q/47511048
tags question: http://stackoverflow.com/q/47498920
tags question: http://stackoverflow.com/q/47491371
tags question: http://stackoverflow.com/q/47510617
tags question: http://stackoverflow.com/q/47520367
tags question: http://stackoverflow.com/q/47514987
tags question: http://stackoverflow.com/q/47469947
tags question: http://stackoverflow.com/q/47393362
tags question: http://stackoverflow.com/q/47413756
tags question: http://stackoverflow.com/q/47535940
tags question: http://stackoverflow.com/q/47463515
tags question: http://stackoverflow.com/q/47493034
tags question: http://stackoverflow.com/q/47475611
tags question: http://stackoverflow.com/q/47514923
tags question: http://stackoverflow.com/q/47460835
tags question: http://stackoverflow.com/q/47447955
tags question: http://stackoverflow.com/q/47461317
tags question: http://stackoverflow.com/q/47421443
tags question: http://stackoverflow.com/q/47440539
tags question: http://stackoverflow.com/q/47475331
tags question: http://stackoverflow.com/q/47509438
tags question: http://stackoverflow.com/q/47443992
tags question: http://stackoverflow.com/q/47387555
tags question: http://stackoverflow.com/q/47489580
tags question: http://stackoverflow.com/q/47442115
tags question: http://stackoverflow.com/q/47398302

http://stackoverflow.com/q/47425891
has title: Using .write function with multiple arguments for writing to a txt file - Python
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47426033
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47426033
has body: I am trying to write the following loop to a .txt file (in addition to printing the output to terminal). On doing so I get an error that says: &gt; TypeError:function takes exactly 1 argument (2 given) I understand what the error is trying to convey, but is there a way to work around this. I do need the labels and the results output to the .txt file just like they are printed on the terminal Here is the code I am using: out_write = open(write_to, 'wb') for arr in top_k: print(labels[arr], results[arr]) out_write.write(labels[arr], results[arr]) print ("\n\n\n") out_write("\n\n\n") out_write.close() I am working in python 2.7
tagged with: python
has comment: http://stackoverflow.com/comment/81806755
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81806716
score: 1

http://stackoverflow.com/comment/81754953
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47399733
type: Comment
has text: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/159423/discussion-on-answer-by-maxu-saving-pandas-styler-object-in-anyway).

http://stackoverflow.com/q/47475299
score: 0
answer count: 1
has body: I'm trying to figure out why essentially the same line of code works in one function, but not in another. I have three files as shown below. My issue is that it runs default_login() fine and has no issue with the find_element_by_xpath line, but then fails to run log_out() and bombs out at the find_element_by_xpath line with the following error: - AttributeError: 'NoneType' object has no attribute 'find_element_by_xpath' I can run this same line independently in a file with no functions defined and it finds the element without issue. I also get the same (similar) error when it runs the tearDown() line self.driver.quit(): - AttributeError: 'NoneType' object has no attribute 'quit' If anybody could tell me why it is failing like this I would appreciate it greatly. I'm having all sorts of issues like this and am starting to wonder whether I have something configured wrong somewhere... Project files: - initialisation.py from selenium import webdriver def start_webdriver(): driver = webdriver.Chrome('C:\TEMP\chromedriver.exe') driver.maximize_window() return driver def start_browser(driver): driver.get("https://myURL") return driver login.py from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec def default_login(driver): wait = WebDriverWait(driver, 5) login_link = driver.find_element_by_xpath("//a[contains(@href, 'login')]") login_link.click() username_text_field = wait.until(ec.element_to_be_clickable((By.NAME, "email"))) password_text_field = driver.find_element_by_name("password") username_text_field.send_keys("username") password_text_field.send_keys("password") login_button = driver.find_element_by_xpath("//*[@class='btn save btn-primary']") login_button.click() def log_out(driver): new_project = driver.find_element_by_xpath("//table[@id='my-projects-table']/tbody/tr/td[3]") new_project.click() logout_user = driver.find_element_by_class_name("dropdown-toggl…
has title: find_element_by_xpath works fine in one function, but not in the next one - nonetype error
tagged with: google-chrome
type: AnsweredQuestion
tagged with: attributeerror
tagged with: nonetype
accepted answer: http://stackoverflow.com/a/47476258
tagged with: python
has answer: http://stackoverflow.com/a/47476258
tagged with: selenium-webdriver
type: Question

http://stackoverflow.com/a/47428259
answers question: http://stackoverflow.com/q/47428190
has body: You can use itertools.takewhile for this pattern: from itertools import takewhile def nothree(nt): return sum(takewhile(lambda x: x != 3, nt)) &gt;&gt;&gt; nothree([1, 2, 5, 2, 3, 1]) 10 While Fejs has you covered with an instructive loop-based solution, I might add this one-line hack that works without any libraries: return sum(x if x != 3 else next(iter([])) for x in nt) where the StopIteration raised by next(iter([])) will stop the generator on the first 3.
type: Answer
score: 0

http://stackoverflow.com/comment/81848130
comment on: http://stackoverflow.com/q/47425595
has text: @Miguel by "email reader", do you mean e.g. the macOS mail client?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47538986
has title: Play Again Button Tkinter Python 3
answer count: 3
has body: I made the game hangman inside tkinter with a friend of mine, and we are nearly finished but we'd like to add a button that says play again and replays the game, but we can't figure out the correct way of doing it. My original idea was to create a play again button to close out the current window, open up a new one with the same basis, and play the game again, but whenever it comes to the "Easy" "Medium" and "Hard" buttons, they don't do anything. I'd prefer solutions that don't include using other modules. Thanks! EDIT: I forgot to include the code!!! I'm dumb, sorry! from tkinter import * import random as r import time as tm #Hang Man class menu: def __init__(self): self.game = Tk() self.game.geometry('600x600+50+50') self.game.title("Hang Man") self.canvas = Canvas(self.game,height=400,width=800,bg='light goldenrod yellow') self.canvas.delete(ALL) self.canvas.create_line(100,50,100,500,tags="Line") #Vertical self.canvas.create_line(20,500,80,500,tags="Line") #Lower Horizontal self.canvas.create_line(100,50,150,50,tags="Line") #Horizontal Line self.canvas.pack() self.play = Button(self.game,text="Play",command=self.playbt) self.play.pack(side=BOTTOM) self.game.mainloop() # Create an event loop def playagain(self): self.game.destroy() self.__init__() def playbt(self): self.difs() def difs(self): self.play.destroy() self.easy = Button(self.game,text="Easy",command=self.easy) self.medium = Button(self.game,text="Medium",command=self.medium) self.hard = Button(self.game,text="Hard",command=self.hard) self.easy.pack(side=BOTTOM) self.medium.pack(side=BOTTOM) self.hard.pack(side=BOTTOM) def easy(self): ewords = r.choice(["TABLE","CHAIR","DESK","PHONE","LIGHT","MAN"]) self.playP(ewords.lower()) def medium(self): mwords = r.choice(["PYTHON","LAPTOP","JACKET","VIDEO","MODULE","LIBRARY"]) self.playP(mwords.lower()) def hard(self): hwords = r.choice(["PROGRAM","TOLEDO","UNIVERSITY","ENGINEER","FOOTBALL","LANGUAGE"]) self.playP(hwords.lower()) def playP(self,words): self.lwor…
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47539268
possible better answer: http://stackoverflow.com/a/47539268
has answer: http://stackoverflow.com/a/62927468
has comment: http://stackoverflow.com/comment/82070752
has answer: http://stackoverflow.com/a/47539274
favorite count: 0
type: Question
tagged with: tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/82036337
accepted answer: http://stackoverflow.com/a/47539274
type: AnsweredQuestion

http://stackoverflow.com/a/47439003
accepted answer of: http://stackoverflow.com/q/47438914
type: Answer
answers question: http://stackoverflow.com/q/47438914
has body: It would work by putting players into a dict: class Character(object): def __init__(self): self.NAME = '' self.life = 50 players = ["red","green","blue","yellow"] dict_players = {} for player in players: dict_players[player] = Character() However, printing would only work if you create a __str__ method for your class.
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47394390
score: 1
has comment: http://stackoverflow.com/comment/81742074
has comment: http://stackoverflow.com/comment/81742261
has body: Actually, this is well done. I'm not sure why the code feels convoluted to you. The key is that each function is doing one thing only is a plus. Obviously the function names should reflect the kinds of transformations that are being made. Code like this is very testable and maintainable. When you need to make a change to the pipeline six months from now, you might be surprised how easy it is to find the part than needs adjusting an make the change. I would suggest modifying your read_data generator as follows: def read_data(file_location): with open(file_location) as f: for line in f: yield line
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47394184
downvote count: 0

http://stackoverflow.com/comment/82038128
score: 0
comment on: http://stackoverflow.com/q/47539035
has text: Try with my answer
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81917190
type: Comment
comment on: http://stackoverflow.com/q/47479446
score: 0
has text: Never mind, I provided the solution up.
type: QuestionComment

http://stackoverflow.com/a/47538637
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47538226
has body: Take the code and run this on the file, assuming it is called 'my_code.py' 2to3 -w my_code.py The code will now be Python 3 code! This process will save the old Python 2 code as my_code.py.bak should you want to restore it.
answers question: http://stackoverflow.com/q/47538226

http://stackoverflow.com/comment/81996929
type: Comment
type: QuestionComment
has text: If two transactions happen in the same month, how do you sort them?
comment on: http://stackoverflow.com/q/47519701
score: 1

http://stackoverflow.com/q/47517930
has answer: http://stackoverflow.com/a/49160990
tagged with: api
upvote count: 3
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: firebase
score: 3
tagged with: react-native
has title: How to connect react native app to python?
has body: I would like to use python as part of a react-native project which handles heavy algorithms. However, as many have suggested, it is not recommended to do that, but simply create an API for the python. Now firstly, I'm confused by the term "create an API", what does that mean? Is it to use something like firebase that deals with backend, and then simply use firebase api?
tagged with: python
has answer: http://stackoverflow.com/a/49161803
answer count: 2

http://stackoverflow.com/comment/81973893
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47504747
has text: Anyhow, you will not get row indices with the answer I've given here. You may get the row indices with pandas version of the code.
type: Comment

http://stackoverflow.com/q/47409365
answer count: 1
has body: I wanted to make a util function that returns the absolute path for the file, where the function has been called, however I did not found a way to do so. For a better picture, this is what I'm trying to achieve. Suppose I have the following directory structure: core/ utils/ __init__.py files.py __init__.py service.py where files.py contains import os def get_current_dir(): return os.path.abspath(os.path.dirname(__file__)) and service.py contains from utils.files import get_current_dir print(get_current_dir()) The expected results are not the desired ones. What I wanted to achieve: /usr/src/app/core The actual output: /usr/src/app/core/utils I've been looking for on many answers here, but none of them has an example where a function is used to determine the path. Are there any ways or is it at least possible to achieve what I'm looking for? Thanks!
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47409595
has answer: http://stackoverflow.com/a/47409595
tagged with: path
tagged with: python
has comment: http://stackoverflow.com/comment/81772672
type: AnsweredQuestion
has title: Get absolute path for the file where the function has been called
score: 2
has comment: http://stackoverflow.com/comment/81772867
upvote count: 3

http://stackoverflow.com/comment/95687615
comment on: http://stackoverflow.com/q/47513024
score: 0
type: Comment
has text: @CharlesDuffy This _is_ the appropriate place for this question. See https://stackoverflow.com/help/on-topic the guidelines say SO is for questions relating to "software tools commonly used by programmers" and installing Python in a local development environment definitely is a programming task.
type: QuestionComment

http://stackoverflow.com/a/47780201
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47443332
score: 1
type: Answer
has body: Pythonic way y = [11, 13, 15] z = [12, 14] ypos = [1, 3, 5] x = z[:] for c, n in enumerate(ypos): x.insert(n - 1, y[c]) print(x) output [11, 12, 13, 14, 15] In a function def func(y, ypos, z): x = z[:] for c,n in enumerate(ypos): x.insert(n-1,y[c]) return x print(func([11,13,15],[1,2,3],[12,14])) outoput [11, 12, 13, 14, 15] Using zip y, z, ypos = [11, 13, 15], [12, 14], [1, 3, 5] for i, c in zip(ypos, y): z.insert(i - 1, c) print(z) [out:] &gt; [11, 12, 13, 14, 15]

http://stackoverflow.com/a/47404997
upvote count: 1
has body: A simple way to get the shape with the last value halved: half_shape = tf.shape(output[..., 1::2]) What it does is simply iterate output in its last dimension with step 2, starting from the second element (index 1). The ... doesn't touch other dimensions. As a result, you will have output[..., 1::2] with the same dimensions as output, except for the last one, which will be sampled like the following example, resulting in half the original value. &gt;&gt;&gt; a = np.random.rand(5,5) &gt;&gt;&gt; a array([[ 0.21553665, 0.62008421, 0.67069869, 0.74136913, 0.97809012], [ 0.70765302, 0.14858418, 0.47908281, 0.75706245, 0.70175868], [ 0.13786186, 0.23760233, 0.31895335, 0.69977537, 0.40196103], [ 0.7601455 , 0.09566717, 0.02146819, 0.80189659, 0.41992885], [ 0.88053697, 0.33472285, 0.84303012, 0.10148065, 0.46584882]]) &gt;&gt;&gt; a[..., 1::2] array([[ 0.62008421, 0.74136913], [ 0.14858418, 0.75706245], [ 0.23760233, 0.69977537], [ 0.09566717, 0.80189659], [ 0.33472285, 0.10148065]]) This half_shape prints the following Tensor: Tensor("Shape:0", shape=(3,), dtype=int32) Alternatively you could get the shape of output and create the shape you want manually: s = output.get_shape().as_list() half_shape = tf.TensorShape(s[:-1] + [s[-1] // 2]) This half_shape prints a TensorShape showing the shape halved in the last dimension.
has comment: http://stackoverflow.com/comment/81825074
has comment: http://stackoverflow.com/comment/81808629
score: 1
has comment: http://stackoverflow.com/comment/81834295
type: Answer
answers question: http://stackoverflow.com/q/47403217
has comment: http://stackoverflow.com/comment/81809138
downvote count: 0
has comment: http://stackoverflow.com/comment/81824797

http://stackoverflow.com/comment/81779975
has text: If you have already attempted something, edit your question and include it.
comment on: http://stackoverflow.com/q/47413325
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47386753
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81727292
answers question: http://stackoverflow.com/q/47386523
has body: First add new column message and then groupby with custom function for dict by to_dict, reset_index and last convert to json by to_json: print (df) school_id city id name batch roll_no age 0 xx ax 1 abc a1 100 13 1 xx ax 1 dsf a2 200 45 2 xy ay 2 fas a1 400 23 3 xy ay 3 fas1 a11 500 33 j = (df.assign(message='The school Table.') .groupby(['message','school_id','city'])['id','name','batch','roll_no','age'] .apply(lambda x: x.to_dict('r')) .reset_index(name='ids') .to_json(orient='records') ) print (j) [{"message":"The school Table.", "school_id":"xx", "city":"ax", "ids":[{"roll_no":100,"batch":"a1","age":13,"name":"abc","id":1}, {"roll_no":200,"batch":"a2","age":45,"name":"dsf","id":1}]}, {"message":"The school Table.", "school_id":"xy", "city":"ay", "ids":[{"roll_no":400,"batch":"a1","age":23,"name":"fas","id":2}, {"roll_no":500,"batch":"a11","age":33,"name":"fas1","id":3}]}]
has comment: http://stackoverflow.com/comment/81727154
has comment: http://stackoverflow.com/comment/81727312
has comment: http://stackoverflow.com/comment/81726766
has comment: http://stackoverflow.com/comment/81727112
type: Answer
accepted answer of: http://stackoverflow.com/q/47386523
has comment: http://stackoverflow.com/comment/81726580
downvote count: 0

http://stackoverflow.com/q/47417420
has comment: http://stackoverflow.com/comment/81789085
accepted answer: http://stackoverflow.com/a/47418507
tagged with: python
has answer: http://stackoverflow.com/a/47418507
favorite count: 0
type: Question
tagged with: numpy
has title: padding numpy rolling window operations using strides
upvote count: 2
has body: I have a function f that I would like to efficiently compute in a sliding window. def efficient_f(x): # do stuff wSize=50 return another_f(rolling_window_using_strides(x, wSize), -1) I have seen on SO that is particularly efficient to do that using strides: from numpy.lib.stride_tricks import as_strided def rolling_window_using_strides(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) print np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides).shape return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) Then I try to apply it on a df: df=pd.DataFrame(data=np.random.rand(180000,1),columns=['foo']) df['bar']=df'foo'.apply(efficient_f,raw=True) # note the double [[, otherwise pd.Series.apply # (not accepting raw, and axis kwargs) will be called instead of pd.DataFrame. It is working very nicely, and it indeed led to significant performance gains. However, I still get the following error: ValueError: Shape of passed values is (1, 179951), indices imply (1, 180000). This is because I am using wSize=50, which yields rolling_window_using_strides(df['foo'].values,50).shape (1L, 179951L, 50L) Is there a way by zero/np.nan padding at the borders to get (1L, 180000, 50L) hence same size as the original vector
tagged with: sliding-window
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81790264
type: AnsweredQuestion
score: 2
tagged with: pandas

http://stackoverflow.com/a/47488466
answers question: http://stackoverflow.com/q/47488410
downvote count: 1
has body: The array is build with indices: 0,1,2,...,n You can enter each index by selecting its position e.g. array[2] gets you the third value of the array. Your code, like @script8man explained, selects the 4-ith index. in a range(2) (0,1), it will return the 4th and 3rd index, this index is overwritten with the i-th index (0,1).
upvote count: 0
type: Answer
score: -1

http://stackoverflow.com/comment/81780425
has text: Redirect it to a new file with `jq ... file.json > new.json`. There is no inplace option for `jq`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47413264
type: Comment

http://stackoverflow.com/a/47568869
answers question: http://stackoverflow.com/q/47511746
type: Answer
has body: Problem (Post Mortem): Let's start with defining the problem: Status 302: The requested resource resides temporarily under a different URI. -source So that leads us to assume that you are getting redirected thus the test fails. Where this happens: In your get() method we find this code: if user is None: return redirect(reverse('dashboard-login')) So if the user is Anonymous (Unauthenticated) the view redirects him to the login page. From the above, we can state that the problem occurs when you make an unauthenticated request to PasswordResetConfirmView.get(). Solution: You need to authenticate (login) your user before you make the request. You can do this by utilizing the force_login() method: If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important. def my_test_case(): ... Do stuff ... # Login self.client.force_login(self.user) # Make the request response = self.client.get(...)
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47531300
type: Question
has answer: http://stackoverflow.com/a/47531435
tagged with: time-series
score: 5
possible better answer: http://stackoverflow.com/a/74282651
upvote count: 5
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/74282651
downvote count: 0
accepted answer: http://stackoverflow.com/a/47531435
has body: I'm looking for a way how to get a value from the previous year for the same day. F.e. we have a value for 2014-01-01 and I want to create a new column with the value for this day but from one year ago. a sample of the table, and I want to get the Previos_Year column. Date Ticks Previos_Year 2013-01-01 0 NaN 2013-01-02 1 NaN 2013-01-03 2 NaN .... 2014-01-01 3 0 2014-01-02 4 1 What have I tried so far: I created a new column day of the year, df['Day_in_Year'] = df.Date.dt.dayofyear but I could not figure out how to use it for my task. Also, I tried the shift fucntion: df['Ticks'].shift(365) and it works, until a leap year...
has title: Pandas: get a value from previous year for the same day of the year
favorite count: 0

http://stackoverflow.com/comment/81837410
type: QuestionComment
has text: Also, but I may be opinionated here, there is no good reason for using the `matrix` class which can behave quite counterintuitively at times. Use plain 2-d `arrays` instead, they are much more consistent. If you need matrix multiplication: python/numpy has now for some time supported the `@` infix operator for that, so matlab * <-> numpy @ - matlab .* <-> numpy *
type: Comment
comment on: http://stackoverflow.com/q/47439222
score: 0

http://stackoverflow.com/q/47516778
has answer: http://stackoverflow.com/a/47517866
favorite count: 0
type: Question
score: 1
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/81990017
tagged with: matplotlib-basemap
has answer: http://stackoverflow.com/a/70691033
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/47517912
has comment: http://stackoverflow.com/comment/81990432
downvote count: 0
has answer: http://stackoverflow.com/a/47517912
has title: Pyplot contourf don't fill in "0" level
upvote count: 1
possible better answer: http://stackoverflow.com/a/70691033
has body: I'm plotting precipitation data from weather model output. I'm contouring the data I have, using contourf. However, I don't want it to fill in the "0" level with color (only the values >0). Is there a good way to do this? I've tried messing around with the levels. Here's the code I'm using to plot: m = Basemap(projection='stere', lon_0=centlon, lat_0=centlat, lat_ts=centlat, width=width, height=height) m.drawcoastlines() m.drawstates() m.drawcountries() parallels = np.arange(0., 90, 10.) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) meridians = np.arange(180., 360, 10.) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) lons, lats = m.makegrid(nx, ny) x, y = m(lons, lats) cs = m.contourf(x, y, snowfall) cbar = plt.colorbar(cs) cbar.ax.set_ylabel("Accumulated Snow (km/m^2)") plt.show() And here's the image I'm getting. An example snowfall dataset would look something like: 0 0 0 0 0 0 0 0 1 1 1 0 0 1 2 2 1 0 0 2 3 2 1 0 0 1 0 1 2 0 0 0 0 0 0 0

http://stackoverflow.com/comment/81781460
score: 0
type: Comment
has text: `FeeDict = [{u'100': u'Booking Fee'}, {u'101': u'Penalty Fee'}]` reference point. Return `FeeDict[0].keys()` for test, you will be see `What I meant`
type: QuestionComment
comment on: http://stackoverflow.com/q/47413341

http://stackoverflow.com/q/47452119
has comment: http://stackoverflow.com/comment/81868364
upvote count: 4
type: AnsweredQuestion
answer count: 2
downvote count: 0
has body: I am using python Kmean clustering algorithm for cluster document. I have created a term-document matrix from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans vectorizer = TfidfVectorizer(tokenizer=tokenize, encoding='latin-1', stop_words='english') X = vectorizer.fit_transform(token_dict.values()) Then I applied Kmean clustering using following code km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1) y=km.fit(X) My next task is to see the top terms in every cluster, searching on googole suggested that many of the people has used the km.cluster_centers_.argsort()[:, ::-1] for finding the top term in the clusters using the following code: print("Top terms per cluster:") order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = vectorizer.get_feature_names() for i in range(true_k): print("Cluster %d:" % i, end='') for ind in order_centroids[i, :10]: print(' %s' % terms[ind], end='') print() Now my question is that to my understanding km.cluster_centers_ returns the coordinated of the center of the clusters so for example if there are 100 features and three clusters it would return us a matrix of 3 rows and 100 column representing a centroid for each cluster. What I wish to understand how it is used in the above code to determine the top terms in the cluster. Thanks Any comments are appreciated Nadeem
has comment: http://stackoverflow.com/comment/81860132
tagged with: scikit-learn
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47457647
tagged with: k-means
tagged with: cluster-analysis
possible better answer: http://stackoverflow.com/a/65327741
has title: Kmean clustering top terms in cluster
tagged with: python
accepted answer: http://stackoverflow.com/a/47457647
score: 4
has answer: http://stackoverflow.com/a/65327741

http://stackoverflow.com/a/47426974
has comment: http://stackoverflow.com/comment/81808565
has comment: http://stackoverflow.com/comment/81808677
accepted answer of: http://stackoverflow.com/q/47426909
has body: It seems that the error is happening due to "Number of labels=44 does not match number of samples=45" Which means you X and Y length is different. Can you confirm the X and Y length?
type: Answer
answers question: http://stackoverflow.com/q/47426909
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47421419
type: UnansweredQuestion
has body: I'm working on my first web crawler, and I'm trying to get some data of telephone numbers in Mexico, and the website that provides the data is: site, it works with xhr requests. I have this code so far: from requests import Request, Session import xml.etree.ElementTree as ET import requests import lxml.etree as etree url = 'https://sns.ift.org.mx:8081/sns-frontend/consulta-numeracion/numeracion-geografica.xhtml' s = Session() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36', 'Content-Type': 'text/html; charset=UTF-8', } str1 = s.post(url, headers=headers) #Loading the page xhtml=str1.text.encode('utf-8') #Savig the first response, to get the ViewState text_file = open("loaded.txt", "w") text_file.write(xhtml) text_file.close() x = ET.fromstring(xhtml) namespace = "{http://www.w3.org/1999/xhtml}" path = './/*[@id="javax.faces.ViewState"]' e = x.findall(path.format(namespace)) for i in e: VS = i.attrib['value'] #ViewState print VS #ViewState At this point I get the ViewState of the page, now I send a new POST with the data and the number I want to consult plus the ViewState. data = { "javax.faces.partial.ajax": "true", "javax.faces.source": "FORM_myform:BTN_publicSearch", "javax.faces.partial.execute": "@all", "javax.faces.partial.render": "FORM_myform:P_containerConsulta+FORM_myform:P_containerpoblaciones+FORM_myform:P_containernumeracion+FORM_myform:P_containerinfo+FORM_myform:P_containerLocal+FORM_myform:P_containerDesplegable", "FORM_myform:BTN_publicSearch": "FORM_myform:BTN_publicSearch", "FORM_myform": "FORM_myform", "FORM_myform:TXT_NationalNumber": "6564384757", "javax.faces.ViewState=": VS #ViewState } req = s.post(url, data=data, headers=headers) #Saving the new response, this is supposed to bring the results text_file = open("Output.txt", "w") text_file.write(req.text.encode('utf-8')) text_file.close() The thing is that the response I get is the full code of the page wi…
has comment: http://stackoverflow.com/comment/81912681
linked to: http://stackoverflow.com/q/12175763
has comment: http://stackoverflow.com/comment/81832936
has title: Web crawler - Python Requests POST not returning data
tagged with: python
tagged with: xmlhttprequest
duplicate of: http://stackoverflow.com/q/12175763
linked to: http://stackoverflow.com/q/8623870
score: 0
has comment: http://stackoverflow.com/comment/81878641
answer count: 2
tagged with: jsf
has answer: http://stackoverflow.com/a/47422195
has comment: http://stackoverflow.com/comment/81879325
has answer: http://stackoverflow.com/a/47439396
tagged with: web-scraping
tagged with: python-requests
has comment: http://stackoverflow.com/comment/81834291
type: Question
has comment: http://stackoverflow.com/comment/81833872
has comment: http://stackoverflow.com/comment/81816771

http://stackoverflow.com/a/47869465
score: 2
upvote count: 2
has body: There is no way to configure HoundCI to check code written on python 2.x at this moment. Hound support only python3.x in a proper way. If you trying to check the code you probably got "wrong" hound's messages for python2 like: print "hello" # should be flagged as a Syntax Error or in other cases like a missed builtins namespace in Python 3 which you may use for version 2.x like for _ in xrange(n)] # should be flagged as undefined name 'xrange' So, in this cases, you can hack HundCI. To configure Hound to ignore this errors put configuration file for flake8 .flake8.ini in your project root: [flake8] ignore = # E999 SyntaxError E999, # undefined name F821 # But in 'undefined name' case would be better to specify builtins builtins = 'xrange' Here is a list of Errors / Violations Then, tell Hound to use linter config with specified ignores. Add path to flake8 config to your .hound.yml: python: enabled: true config_file: .flake8.ini
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47427916
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47427916
type: Answer
has comment: http://stackoverflow.com/comment/82722435

http://stackoverflow.com/q/47451233
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/81857321
tagged with: error-handling
tagged with: loops
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47451258
has title: Condensing if statements to give more accurate output
tagged with: if-statement
has answer: http://stackoverflow.com/a/47451258
tagged with: python
has body: I'm trying to write a simple if-statement that depends on a set of conditions (the occurences in a list being 0) however I have encountered bugs when two of my conditions are both 0, only one of the statements is displayed. if let1 == 0: print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n") elif let2 == 0: print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n") elif let3 == 0: print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n") I've tried using or statements but am unable to produce the desired output informing the user that one, two or three of their inputs may not be in the body of text used in the rest of my program. Apologies for the lack of succint terminology as I'm very new to programming. Thanks EDIT: Thank you for the replies but I should have given the full function... def segment_sequence(mycorpus, letter1, letter2, letter3): corpus_string = "".join(mycorpus) a = letter1 b = letter2 c = letter3 d = a + b e = b + c let1 = corpus_string.count(a) let2 = corpus_string.count(b) let3 = corpus_string.count(c) let1let2 = corpus_string.count(d) let2let3 = corpus_string.count(e) print(let1,let2,let3) if let1 == 0: print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n") if let2 == 0: print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n") if let3 == 0: print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n") break else: trans_prob1 = let1let2/let1 trans_prob2 = let2let3/let2 if trans_prob1 &gt; trans_prob2: print('Here is the proposed boundary given the training corpus:\n') print('Proposed end of one word:' ,d,'\n') print('Proposed beginning of new word:' ,c,'\n') elif trans_prob2 &gt; trans_prob1: print('Here is the proposed boundary given the training corpus:\n') print('Proposed end of one word: ',e,'\n') print('Proposed beginning of new word: ',a,'\n')…
has answer: http://stackoverflow.com/a/47451255
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47451313
answer count: 3
has answer: http://stackoverflow.com/a/47451313

windows
tags question: http://stackoverflow.com/q/47445224
tags question: http://stackoverflow.com/q/47413755
tags question: http://stackoverflow.com/q/47429232
tags question: http://stackoverflow.com/q/47495885
tags question: http://stackoverflow.com/q/47519350
tags question: http://stackoverflow.com/q/47420369
tags question: http://stackoverflow.com/q/47502241
tags question: http://stackoverflow.com/q/47444272
tags question: http://stackoverflow.com/q/47508349
tags question: http://stackoverflow.com/q/47460138
tags question: http://stackoverflow.com/q/47536272
tags question: http://stackoverflow.com/q/47511298
tags question: http://stackoverflow.com/q/47400957
tags question: http://stackoverflow.com/q/47491750
tags question: http://stackoverflow.com/q/47437988
type: Tag
tags question: http://stackoverflow.com/q/47527948
tags question: http://stackoverflow.com/q/47417346
tags question: http://stackoverflow.com/q/47388431
tags question: http://stackoverflow.com/q/47407179
tags question: http://stackoverflow.com/q/47498038
tags question: http://stackoverflow.com/q/47425171
tags question: http://stackoverflow.com/q/47477122
tags question: http://stackoverflow.com/q/47469836
tags question: http://stackoverflow.com/q/47432192
tag name: windows
tags question: http://stackoverflow.com/q/47520053
tags question: http://stackoverflow.com/q/47539201
tags question: http://stackoverflow.com/q/47391242
tags question: http://stackoverflow.com/q/47401160
tags question: http://stackoverflow.com/q/47453427
tags question: http://stackoverflow.com/q/47453133
tags question: http://stackoverflow.com/q/47488586
tags question: http://stackoverflow.com/q/47433307
tags question: http://stackoverflow.com/q/47446517
tags question: http://stackoverflow.com/q/47403302
tags question: http://stackoverflow.com/q/47391498
tags question: http://stackoverflow.com/q/47458024

http://stackoverflow.com/a/47514869
upvote count: 1
downvote count: 1
has body: Have an Event to break out of the loop. It is the same thing as a Boolean flag, but it can be used across processes and threads. import multiprocessing from threading import Timer class TTT(multiprocessing.Process): def __init__(self, name): # must call this before anything else multiprocessing.Process.__init__(self) self.daemon = True self.alive = multiprocessing.Event() self.alive.set() def run(self): while self.alive.is_set(): t = Timer(5, self.doSomething) t.start() t.join() def doSomething(self): try: raise Exception('a','b') except Exception as e: print(e) # I want to terminate process here~ self.alive.clear() if __name__ == '__main__' : t = TTT('aaa') t.start() t.join()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47514593

http://stackoverflow.com/q/47463827
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
has title: solving 1D Schrödinger equation with Numerov method (python)
downvote count: 0
tagged with: differential-equations
tagged with: numerical-methods
tagged with: math
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47466493
accepted answer: http://stackoverflow.com/a/47466493
tagged with: physics
has body: I'm currently trying to solve the 1D Schrödinger eq. (time independent) with the Numerov method. The derivation of the method is clear to me but I have some problems with the implementation. I tried to look for solutions on google, and there are some (like this one or this one), but I don't really understand what they are doing in their codes... The Problem: With some math you can get the equation to this form: where . For the beginning I'd like to look at the potential V(x)=1 if -a&lt;x&lt;a. Since I don't have values for the energy or the first values of Psi (which are needed to start the algorithm) I just guessed some... The code looks like this: import numpy as np import matplotlib.pyplot as plt from scipy.constants import hbar m= 1e-27 E= 0.5 def numerov_step(psi_1,psi_2,k1,k2,k3,h): #k1=k_(n-1), k2=k_n, k3=k_(n+1) #psi_1 = psi_(n-1) and psi_2=psi_n m = 2*(1-5/12. * h**2 * k2**2)*psi_2 n = (1+1/12.*h**2*k1**2)*psi_1 o = 1 + 1/12. *h**2 *k3**2 return (m-n)/o def numerov(N,x0,xE,a): x,dx = np.linspace(x0,xE,N+1,retstep=True) def V(x,a): if (np.abs(x)&lt;a): return 1 else: return 0 k = np.zeros(N+1) for i in range(len(k)): k[i] = 2*m*(E-V(x[i],a))/hbar**2 psi= np.zeros(N+1) psi[0]=0 psi[1]=0.1 for j in np.arange(2,N): psi[j+1]= numerov_step(psi[j],psi[j+1],k[j-1],k[j],k[j+1],dx) return psi x0 =-10 xE = 10 N =1000 psi=numerov(N,x0,xE,3) x = np.linspace(x0,xE,N+1) plt.figure() plt.plot(x,psi) plt.show() Since the plot doesn't look like a wavefunction at all something has to be wrong, but I'm having trobule to find out what it is.. Would be nice if someone could help a little.

http://stackoverflow.com/q/47504144
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python nested function
has comment: http://stackoverflow.com/comment/81964211
has comment: http://stackoverflow.com/comment/81964253
possible better answer: http://stackoverflow.com/a/47504187
tagged with: python
linked to: http://stackoverflow.com/q/36636
answer count: 4
has answer: http://stackoverflow.com/a/47504187
has answer: http://stackoverflow.com/a/47504202
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/47504198
accepted answer: http://stackoverflow.com/a/47504202
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47504223
has body: I came across this interesting code # Define echo def echo(n): """Return the inner_echo function.""" # Define inner_echo def inner_echo(word1): """Concatenate n copies of word1.""" echo_word = word1 * n return echo_word # Return inner_echo return inner_echo # Call echo: twice twice = echo(2) # Call echo: thrice thrice = echo(3) # Call twice() and thrice() then print print(twice('hello'), thrice('hello')) output : hellohello hellohellohello But I'm not able to understand how it is working since twice and thrice functions is calling the function echo and providing the value n, how is the value of word1 is passed?
tagged with: nested-function

http://stackoverflow.com/comment/81851024
type: Comment
has text: This worked :) I wish I could upvote this, being a new member it says votes with less than 15 reputations are not shown! Thanks!!!
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47446822

http://stackoverflow.com/q/47503575
tagged with: python
has title: What do the values that `graphviz` renders inside each node of a decision tree mean?
has answer: http://stackoverflow.com/a/47506058
score: 8
type: Question
accepted answer: http://stackoverflow.com/a/47506058
has body: For the image above using the AdaBoostClassifier library from scipy and graphviz I was able to create this subtree visual and I need help interpreting the values that are in each node? Like for example, what does "gini" mean? What is the significance of the "samples" and "value" fields? What does it mean that attribute F5 &lt;= 0.5? Here is my code (I did this all in jupyter notebook): import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns %matplotlib inline f = open('dtree-data.txt') d = dict() for i in range(1,9): key = 'F' + str(i) d[key] = [] d['RES'] = [] for line in f: values = [(True if x == 'True' else False) for x in line.split()[:8]] result = line.split()[8] d['RES'].append(result) for i in range(1, 9): key = 'F' + str(i) d[key].append(values[i-1]) df = pd.DataFrame(data=d, columns=['F1','F2','F3','F4','F5','F6','F7','F8','RES']) from sklearn.model_selection import train_test_split X = df.drop('RES', axis=1) y = df['RES'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) from sklearn.ensemble import AdaBoostClassifier ada = AdaBoostClassifier() ada.fit(X_train, y_train) from IPython.display import Image from sklearn.externals.six import StringIO from sklearn.tree import export_graphviz import pydot # https://stackoverflow.com/questions/46192063/not-fitted-error-when-using-sklearns-graphviz sub_tree = ada.estimators_[0] dot_data = StringIO() features = list(df.columns[1:]) export_graphviz(sub_tree, out_file=dot_data,feature_names=features,filled=True,rounded=True) graph = pydot.graph_from_dot_data(dot_data.getvalue()) Image(graph[0].create_png()) NOTE: External packages may need to be installed in order to view the data locally (obviously) Here is a link to the data file: https://cs.rit.edu/~jro/courses/intelSys/dtree-data
answer count: 1
downvote count: 0
tagged with: scikit-learn
tagged with: scipy
favorite count: 0
type: AnsweredQuestion
upvote count: 8
tagged with: pygraphviz
linked to: http://stackoverflow.com/q/46192063

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

http://stackoverflow.com/comment/81806896
type: Comment
type: QuestionComment
has text: One: Never use `codecs.open`; it's buggy in numerous subtle ways, and you want `io.open` (equivalent to Python 3's built-in `open`) on Python 2.6 and higher. Two: You need to use the `csv` module (or on Python 2, the third party `unicodecsv` module) to parse CSV. If you do otherwise, you'll get things wrong, either by failing to split at all in this case, or by getting the complex rules for quoting wrong when you figure out splitting the naive way.
comment on: http://stackoverflow.com/q/47425858
score: 1

http://stackoverflow.com/comment/81861395
comment on: http://stackoverflow.com/a/47408288
score: 0
type: AnswerComment
has text: Then there is no file "Home" in the directory you specified when calling `web.template.render(directory)`.
type: Comment

http://stackoverflow.com/comment/81966770
score: 0
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ that would be a better dupe target I suppose, which has been duped again to the target you initially proposed... can't argue with that. (*Although I still think there's a difference between creating a dynamic number of variables and variable lookup by string*)
comment on: http://stackoverflow.com/q/47496415

http://stackoverflow.com/a/47424553
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81806903
has comment: http://stackoverflow.com/comment/81805863
accepted answer of: http://stackoverflow.com/q/47424075
score: 0
has comment: http://stackoverflow.com/comment/81826166
answers question: http://stackoverflow.com/q/47424075
has comment: http://stackoverflow.com/comment/81842253
type: Answer
has comment: http://stackoverflow.com/comment/82031620
has comment: http://stackoverflow.com/comment/81805077
has body: Please try the question in python first before asking it. Your column is missing a quote. Let's fix it and name your column: col = ["{'type':", "'text/html',", "'language':", 'None,', "'base':", "'https://www.google.com/alerts/feeds/04514242672909724721/7712142301995898267'",", }"] So now you are saying that this is actually a column in a DataFrame. Let's put this into a DataFrame to make the question reproducible: df = DataFrame({'x':col}) You are saying that you have a number of these columns, and the 5th item is the URL that you are looking for. Then you can iterate over the columns and query the 5th element, and collect it in a list named URLs as follows: URLs = [] for column in df: URLs.append(df[column][5]) After your comments, I think the structure is a bit different. So you have only 1 column, and inside that column you have multiple rows. And the 5th element of each row is a URL you want to collect. Let's see if this mimics what you have (I made up 3 URL's): row1 = ["{'type':", "'text/html',", "'language':", 'None,', "'base':", "'https://www.google.com/1'",", }"] row2 = ["{'type':", "'text/html',", "'language':", 'None,', "'base':", "'https://www.google.com/2'",", }"] row3 = ["{'type':", "'text/html',", "'language':", 'None,', "'base':", "'https://www.google.com/3'",", }"] df = pd.DataFrame({'col': [row1, row2, row3]}) which gives us: In [352]: df Out[352]: col 0 [{'type':, 'text/html',, 'language':, None,, '... 1 [{'type':, 'text/html',, 'language':, None,, '... 2 [{'type':, 'text/html',, 'language':, None,, '... If that is the case, the solution is as simple as In [353]: [e[5] for e in df['col']] Out[353]: ["'https://www.google.com/1'", "'https://www.google.com/2'", "'https://www.google.com/3'"] Please comment if this does or doesn't answer your question.
has comment: http://stackoverflow.com/comment/82003315

http://stackoverflow.com/a/47455322
score: 1
accepted answer of: http://stackoverflow.com/q/47454479
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Your input file is a docx file, which is a pkzip compressed archive. You can't open it as though it is a text file. Instead you could look at an external package such as python-docx. Something like this might work for you: import docx doc = docx.Document('path.docx') content = [p.text for p in doc.paragraphs]
type: Answer
has comment: http://stackoverflow.com/comment/81866016
answers question: http://stackoverflow.com/q/47454479
has comment: http://stackoverflow.com/comment/81865781

http://stackoverflow.com/comment/81740331
score: 0
has text: yes, there is no difference, because if you run this code using for example `python main.py` - you get binded to 8080 TCP port every time you run this code. there is nothing that can force flask to bind to another port (in allowed range obviously)
comment on: http://stackoverflow.com/a/47393654
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82036415
type: Comment
comment on: http://stackoverflow.com/q/47539628
type: QuestionComment
has text: I would guess that [○this question](https://stackoverflow.com/questions/42994338/creating-figure-with-exact-size-and-no-padding-and-legend-outside-the-axes)'s answer does what you want (it's just putting the legend above instead of below the plot).
score: 0

http://stackoverflow.com/comment/81806242
type: Comment
has text: The function works for odd numbers however, if enter a string with no odd numbers such as 2*4*6*8, the function should simply return 0.0 but in this case I get an error.
type: AnswerComment
comment on: http://stackoverflow.com/a/47425640
score: 0

http://stackoverflow.com/a/47492713
has comment: http://stackoverflow.com/comment/81940724
has body: Your issue is on the scope of horas. You're defining horas as a local variable in the method calculo_salario. This means that the variable will only be available inside the method definition and not outside. I'd suggest starting out your program without any methods and then figure out how it would work by encapsulating logic within these methods. horas = float(input("input salario: ")) tarifa = float(input("input tarifa: ")) ganancias = (horas * tarifa) preOt = (40 * tarifa) if horas &gt; 40 : overtimeHr = horas - 40 overtimeAm = (overtimeHr * tarifa) * 1.5 gananciasOt = overtimeAm + preOt print(gananciasOt) else : print(ganancias) The code above should run without any issues notice that now all the variables are in the global scope of the script.
type: Answer
answers question: http://stackoverflow.com/q/47492657
has comment: http://stackoverflow.com/comment/81940697
score: 0

http://stackoverflow.com/comment/81919244
type: Comment
comment on: http://stackoverflow.com/a/47398609
score: 0
type: AnswerComment
has text: @vasia Oh I thought that they were just trying to be jackasses. Thanks for telling me though. I didn't realize that this was the mentality. Also, I'll take a look at those articles.

http://stackoverflow.com/q/47404429
has body: I'm totally a rookie to python and tensorflow, hope my description won't be too confusing. I run the tensorflow code (https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10.py) following the tutorial (https://www.tensorflow.org/tutorials/deep_cnn), on a cloud system, which uses a hdfs file system (this may be useful), and there are some errors as shown below. It's totally OK when I run the code on my computer. I'd appreciate it if you guys can give me some advice. Log Type: stdout Log Upload Time: Tue Nov 21 10:16:29 +0800 2017 Log Length: 1692 Job name: default Task index: 0 CUDA_VISIBLE_DEVICES: [ 0 ] usage: cifar10.py [-h] [--batch_size BATCH_SIZE] [--data_dir DATA_DIR] [--use_fp16 USE_FP16] [--model_dir MODEL_DIR] [--max_steps MAX_STEPS] [--log_device_placement LOG_DEVICE_PLACEMENT] [--log_frequency LOG_FREQUENCY] cifar10.py: error: unrecognized arguments: --tf_fs hdfs://default -- tf_prefix /user/mt_tenant_120282045 --default_fs hdfs://gh-mos- sigmoid01.gh.sankuai.com:8020 --worker_num 0 --num_gpus 1 --num_ps 0 -- num_worker 1 run failed: Traceback (most recent call last): File "tensorflow_main.py", line 282, in map_fun File "/usr/local/gpu/python/lib/python2.7/runpy.py", line 252, in run_path return _run_module_code(code, init_globals, run_name, path_name) File "/usr/local/gpu/python/lib/python2.7/runpy.py", line 82, in _run_module_code mod_name, mod_fname, mod_loader, pkg_name) File "/usr/local/gpu/python/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "cifar10.py", line 68, in &lt;module&gt; FLAGS = parser.parse_args() File "/usr/local/gpu/python/lib/python2.7/argparse.py", line 1704, in parse_args self.error(msg % ' '.join(argv)) File "/usr/local/gpu/python/lib/python2.7/argparse.py", line 2374, in error self.exit(2, _('%s: error: %s\n') % (self.prog, message)) File "/usr/local/gpu/python/lib/python2.7/argparse.py", line 2362, in exit _sys.exit(status) SystemExit: 2 exit code is 2,failed. tensorflow is …
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81763262
tagged with: tensorflow
has title: Running tensorflow code on a
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81767940
type: Question

http://stackoverflow.com/q/47485373
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81927029
tagged with: python
tagged with: large-data
tagged with: memory
tagged with: numpy
type: AnsweredQuestion
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/47485449
has title: I want to read a large amount of images for deep learning, but what is the solution for when there is insufficient memory?
score: 1
has answer: http://stackoverflow.com/a/47485449
answer count: 1
downvote count: 0
has body: In deep learning program written in python, I wanted to store a large amount of image data in numpy array at once, and to extract batch data randomly from that array, but the image data is too large and memory is run out. How should we deal with such cases? I have no choice but to do IO processing and read image data from storage every time you retrieve batch data?
upvote count: 1

http://stackoverflow.com/q/47385336
type: AnsweredQuestion
answer count: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81723828
has comment: http://stackoverflow.com/comment/81723973
upvote count: 0
has body: I am trying to make a brick breaker-like game in python using the Tkinter library. I have a previous version of the code that runs well, but due to an error in indentation, all of the functions are in the __init__. When I corrected this error and then added the features to make it a playable game, my main animation loop stopped working. I read other posts that showed this was a spacing error, and verified this was not using python -tt. Update: self.moveBall() was moved into __init__ but moveBall() still does not run. from tkinter import * class Application(Frame): def __init__(self): # Constructing the Screen root = Tk() Frame.__init__(self) self.canvas = Canvas(root, width=800, height=400) # Label self.v = StringVar() self.l = 5 self.label = Label(root, textvariable=self.v, font=('Courier', 20), bg='white', width=50) self.v.set('Lives: ' + str(self.l)) self.label.grid() self.canvas.grid() # Ball self.canvas.create_oval( 2, 2, 22, 22, fill='red', tags='ball', ) # Paddle self.canvas.create_rectangle( 360, 380, 440, 400, fill='black', tag='paddle', ) # Keybindings self.canvas.focus_set() self.canvas.bind('&lt;Left&gt;', self.paddleLeft) self.canvas.bind('a', self.paddleLeft) self.canvas.bind('&lt;Button-1&gt;', self.paddleLeft) self.canvas.bind('&lt;Right&gt;', self.paddleRight) self.canvas.bind('d', self.paddleRight) self.canvas.bind('&lt;Button-3&gt;', self.paddleRight) # Logic self.horizontal_direction = 'east' self.vertical_direcction = 'south' self.moveBall() def collide(self): (x1, y1, x2, y2) = self.canvas.coords('ball') (px1, py1, px2, py2) = self.canvas.coords('paddle') if x2 &gt;= 800: self.horizontal_direction = 'west' if x1 &lt;= 0: self.horizontal_direction = 'east' if y1 &lt;= 0: self.vertical_direcction = 'south' if y2 &gt;= 400: self.l -= 1 self.v.set('Lives: ' + str(self.l)) self.vertical_direcction = 'north' if y2 &gt;= py1: if x1 in range(int(px1), int(px2)) or x2 in range(int(px1), int(px2)): self.vertical_direcction = 'north' def moveBall(self): w…
accepted answer: http://stackoverflow.com/a/47385782
possible better answer: http://stackoverflow.com/a/47385882
has comment: http://stackoverflow.com/comment/81724336
downvote count: 1
has comment: http://stackoverflow.com/comment/81723626
has answer: http://stackoverflow.com/a/47385882
has title: NameError: name 'self' is not defined Python when calling method from within a class
favorite count: 0
has comment: http://stackoverflow.com/comment/81724168
type: Question
has comment: http://stackoverflow.com/comment/81723872
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81723919
has comment: http://stackoverflow.com/comment/81723986
has comment: http://stackoverflow.com/comment/81724090
has comment: http://stackoverflow.com/comment/81724056
has comment: http://stackoverflow.com/comment/81724205
has comment: http://stackoverflow.com/comment/81723940
has comment: http://stackoverflow.com/comment/81723902
has comment: http://stackoverflow.com/comment/81723818
tagged with: python
has comment: http://stackoverflow.com/comment/81723661
has answer: http://stackoverflow.com/a/47385782
score: -1
has comment: http://stackoverflow.com/comment/81723707
has comment: http://stackoverflow.com/comment/81724028
has comment: http://stackoverflow.com/comment/81723933

http://stackoverflow.com/comment/81949174
type: Comment
has text: @MadPhysicist: not sure we need to go into that much detail.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47496749

http://stackoverflow.com/q/47458888
has answer: http://stackoverflow.com/a/47459489
has answer: http://stackoverflow.com/a/47459025
score: 2
tagged with: list
has comment: http://stackoverflow.com/comment/81872595
has answer: http://stackoverflow.com/a/47459247
has body: I'm a Python newbie, taking a class. I have to find out how many times each letter appears in a string. I've seen all the responses about .count and counter, but this has not been covered yet. I took my string and created a list of the characters so they only appeared once. Then I tried to count how many times the character from the list appears in the string, and I just can't get it to work. I know how to check for a specific letter, but I can't make it check for each letter in my list. Program is below (there are some extra codes, but I'm using them to make sure it's counting properly). # CONSTANTS and Blank Lists letter_list = [] count = 0 letter_count = [] index = 0 # Begin programming my_string = 'SUKI IS SWEET' for ch in my_string: if ch not in letter_list: letter_list.append(ch) print(letter_list) print() for ch in my_string: if letter_list[index] == ch: count = count + 1 letter_count.append(count) # Double-checks to make sure running properly print(letter_list[0],'appears',letter_count[0], 'times') print() print(letter_count) print() When I run this, I get the proper answer: ['S', 'U', 'K', 'I', ' ', 'W', 'E', 'T'] (my letter_list) S appears 3 times (S does appear 3 times) [3] (my letter_count) However, I KNOW that my letter_count.append is in the wrong place. But if I move it in, it gets jacked up. And the moment I try to move it along by increasing the index, it blows up (see below): # CONSTANTS and Blank Lists letter_list = [] count = 0 letter_count = [] index = 0 # Begin programming my_string = 'SUKI IS SWEET' for ch in my_string: if ch not in letter_list: letter_list.append(ch) print(letter_list) print() for ch in my_string: if letter_list[index] == ch: count = count + 1 letter_count.append(count) index = index + 1 # Double-checks to make sure running properly print(letter_list[0],'appears',letter_count[0], 'times') print() print(letter_count) print() RESULTS: Traceback (most recent call last): File "C:\Users\Rogue\Desktop\TEST_2.py", line 30, in main()…
upvote count: 2
downvote count: 0
tagged with: string
accepted answer: http://stackoverflow.com/a/47459025
has title: Count how many times a list of characters appear in a string - Python (no count or counter)
possible better answer: http://stackoverflow.com/a/47458951
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81872368
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47458951
answer count: 5
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/71330420

http://stackoverflow.com/comment/81877300
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47461325
has text: it wont work.. >>> [i.replace('apple','orange') or replace('love','like') for i in a] ['I like orange', 'I love you so much'] priority matters

http://stackoverflow.com/q/47423898
tagged with: dataframe
tagged with: python
type: Question
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81802624
has title: How to select rows based on unlabelled first column of a multidimentional dataframe in pandas in python?
favorite count: 0
accepted answer: http://stackoverflow.com/a/47424012
type: AnsweredQuestion
has body: I have the following dataframe: 1 2 3 4 5 6 7 8 9 10 cat cat 1 1 1 1 1 1 0 0 1 1 dog 1 0 1 1 1 1 0 0 1 1 fox 0 0 0 0 0 0 0 0 0 0 jumps 1 0 1 1 1 0 0 1 1 1 over 1 0 1 1 1 1 0 0 1 1 the 1 0 1 1 1 1 0 0 1 1 dog cat 1 1 0 1 1 1 0 0 1 0 dog 1 1 1 1 1 1 0 0 1 1 fox 1 1 1 1 1 1 0 0 1 1 jumps 1 1 1 1 1 1 0 1 1 1 over 1 1 1 1 1 1 0 0 1 1 the 1 1 1 1 1 1 1 0 1 1 fox cat 0 0 0 0 0 0 0 0 0 0 dog 1 1 1 1 1 1 0 0 1 1 fox 1 1 1 1 1 1 0 0 1 1 jumps 1 1 1 1 1 1 0 1 1 1 over 1 1 1 1 1 1 0 0 1 1 the 1 1 1 1 1 1 1 0 1 1 jumps cat 1 1 0 1 0 1 1 0 1 0 dog 1 1 1 1 1 1 1 0 1 0 fox 1 1 1 1 1 1 1 0 1 0 jumps 1 1 1 1 1 1 0 0 1 0 over 1 0 1 1 1 0 0 1 1 0 the 1 0 1 1 1 1 0 0 1 0 over cat 1 1 0 1 1 1 0 0 1 0 dog 1 1 1 1 1 1 0 0 1 0 fox 1 1 1 1 1 1 0 0 1 0 jumps 1 1 0 1 0 1 1 0 1 0 over 1 1 1 1 1 1 0 0 1 0 the 1 0 1 1 1 0 0 1 1 0 the cat 1 1 0 1 1 1 0 0 1 0 dog 1 1 1 1 1 1 0 1 1 0 fox 1 1 1 1 1 1 0 1 1 0 jumps 1 1 0 1 1 1 0 0 1 0 over 1 1 0 1 0 1 1 0 1 0 the 1 1 1 1 1 1 0 0 1 0 As you can see the first two columns are unlabelled. I want to select all rows where column1 == 'dog' So that I end up with this: dog cat 1 1 0 1 1 1 0 0 1 0 dog dog 1 1 1 1 1 1 0 0 1 1 dog fox 1 1 1 1 1 1 0 0 1 1 dog jumps 1 1 1 1 1 1 0 1 1 1 dog over 1 1 1 1 1 1 0 0 1 1 dog the 1 1 1 1 1 1 1 0 1 1 If it had a label, the solution would have been: print(df.loc[df['label'] == 'dog']) But because it doesn't have a label, how do I achieve that? Any suggestions will be highly appreciated. Thank you.
has answer: http://stackoverflow.com/a/47424012
linked to: http://stackoverflow.com/q/45740537
tagged with: pandas
score: 1

http://stackoverflow.com/comment/81830447
type: AnswerComment
has text: Continue without saving the data. What I try is to update my Boleto object in those 2 fields of Estatus and Client_id, since Client_id is a Foreign Key
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47425608

http://stackoverflow.com/a/47445963
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82056595
has comment: http://stackoverflow.com/comment/82070848
score: 3
has comment: http://stackoverflow.com/comment/81866843
type: Answer
accepted answer of: http://stackoverflow.com/q/47437893
has comment: http://stackoverflow.com/comment/81867215
answers question: http://stackoverflow.com/q/47437893
has comment: http://stackoverflow.com/comment/81874184
has body: I'm not sure how you arrived at a value of 0.0001 for alpha, but I think it's too low. Using your code with the cancer data shows that cost is decreasing with each iteration -- it's just going glacially. When I raise this to 0.5, I still get a decreasing costs, but at a more reasonable level. After 1000 iterations it reports: cost: 0.23668000993020666 And after fixing the Accuracy function I'm getting 92% on the test segment of the data. You have Numpy installed, as shown by X = np.array(X). You should really consider using it for your operations. It will be orders of magnitude faster for jobs like this. Here is a vectorized version that gives results instantly rather than waiting: import math import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split df = pd.read_csv("cancerdata.csv") X = df.values[:,2:-1].astype('float64') X = (X - np.mean(X, axis =0)) / np.std(X, axis = 0) ## Add a bias column to the data X = np.hstack([np.ones((X.shape[0], 1)),X]) X = MinMaxScaler().fit_transform(X) Y = df["diagnosis"].map({'M':1,'B':0}) Y = np.array(Y) X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.25) def Sigmoid(z): return 1/(1 + np.exp(-z)) def Hypothesis(theta, x): return Sigmoid(x @ theta) def Cost_Function(X,Y,theta,m): hi = Hypothesis(theta, X) _y = Y.reshape(-1, 1) J = 1/float(m) * np.sum(-_y * np.log(hi) - (1-_y) * np.log(1-hi)) return J def Cost_Function_Derivative(X,Y,theta,m,alpha): hi = Hypothesis(theta,X) _y = Y.reshape(-1, 1) J = alpha/float(m) * X.T @ (hi - _y) return J def Gradient_Descent(X,Y,theta,m,alpha): new_theta = theta - Cost_Function_Derivative(X,Y,theta,m,alpha) return new_theta def Accuracy(theta): correct = 0 length = len(X_test) prediction = (Hypothesis(theta, X_test) &gt; 0.5) _y = Y_test.reshape(-1, 1) correct = prediction == _y my_accuracy = (np.sum(correct) / length)*100 print ('LR Accuracy %: ', my_accuracy) def Log…

http://stackoverflow.com/q/47481748
tagged with: bazel
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has body: I am just trying to use my gpu with tensorflow on a Ubuntu 16.04 64bit system. I noticed while running some tensorflow commands that neither my cpu nor my gpu were using all of the configurations available. Thus, I updated the driver for my Nvidia GTX-970 card to x86_64-384.98, updated the toolkit to 9.0, and the cuDNN to 7.0. I have verified the installation and can write some simple code using python to wrap Cuda language to access the GPU for simple pings of info and short calculations. Yet, I cannot access the GPU from tensorflow code. This should not be the focus, but simply the impetus for trying to update everything. I proceeded to install tensorflow from source following the instructions at https://www.tensorflow.org/install/install_sources#ConfigureInstallation My configuration options have been everything and in between. I do choose to use python3, I am choosing cuda. The tensorflow configure settings are as follows Please specify the location of python. [Default is /usr/bin/python]: /usr/bin/python3 Please input the desired Python library path to use. /usr/local/lib/python3.5/dist-packages jemalloc as malloc support will be enabled for TensorFlow. No Google Cloud Platform support will be enabled for TensorFlow. No Hadoop File System support will be enabled for TensorFlow. No Amazon S3 File System support will be enabled for TensorFlow. No XLA JIT support will be enabled for TensorFlow. No GDR support will be enabled for TensorFlow. No VERBS support will be enabled for TensorFlow. No OpenCL SYCL support will be enabled for TensorFlow. CUDA support will be enabled for TensorFlow. Please specify the CUDA SDK version you want to use: 9.0 Please specify the location where CUDA 9.0 toolkit is installed.: /usr/local/cuda Please specify the cuDNN version you want to use.: 7.0 Please specify the location where cuDNN 7.0 library is installed.: /usr/local/cuda/lib64 Please specify a list of comma-separated Cuda compute capabilities you want to build with.: 5.2 Do yo…
answer count: 1
accepted answer: http://stackoverflow.com/a/47482582
tagged with: tensorflow
favorite count: 0
type: Question
has title: Building tensor flow from source using bazel on Ubuntu 16.04. Error is ---> Linking of rule '//tensorflow/contrib/lite/toco:toco' failed (Exit 1)
linked to: http://stackoverflow.com/q/47080760
tagged with: ubuntu-16.04
has answer: http://stackoverflow.com/a/47482582
tagged with: python

http://stackoverflow.com/comment/81920585
has text: it giving me an average for each file rather than average for each latitude and longitude horizontally
score: 0
comment on: http://stackoverflow.com/q/47482412
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47533961
downvote count: 0
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47533818
has body: There's a handy function in Python called all() which returns true if all arguments are true. Feel free to find a nice way of using it, but in general: &gt;&gt;&gt; DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z'] &gt;&gt;&gt; &gt;&gt;&gt; s="udl" &gt;&gt;&gt; print(all(c in DIRECTION_LETTERS for c in s)) True &gt;&gt;&gt; s="udlxa" &gt;&gt;&gt; print(all(c in DIRECTION_LETTERS for c in s)) False
has comment: http://stackoverflow.com/comment/82024869
upvote count: 2

http://stackoverflow.com/q/47486843
score: 1
possible better answer: http://stackoverflow.com/a/47488205
tagged with: python
tagged with: import
type: Question
tagged with: robotframework
answer count: 2
has answer: http://stackoverflow.com/a/47493441
tagged with: class-method
downvote count: 0
upvote count: 1
favorite count: 0
has body: I have written a test case in Robot Framework which creates an instance of a class in the middle of Test Suite using Builtin.Import_Library keyword, then calls its methods using Builtin.Call_Method: *** Settings *** Resource MyKeywords.robot Test Suite Initiate My Test *** Keywords *** Initiate My Test ${ip} = SET VARIABLE localhost ${port} = SET VARIABLE 2020 IMPORT LIBRARY src/Interface/Utility/WebServiceUtil.py ... ws_ip=${ip} ws_port=${port} WITH NAME webserviceutil *** Test Cases *** Test Report A ${result} = CALL METHOD webserviceutil get_report_a LOG Result: ${result} console=${TRUE} File src/Interface/Utility/WebServiceUtil.py contains: # -*- encoding: utf-8 -*- import requests import json from robot.api import logger class WebServiceUtil(object): ROBOT_LIBRARY_SCOPE = 'TEST SUITE' def __init__(self, ws_ip, ws_port): self.reporter_a = ReportA(ip=ws_ip, port=ws_port) self.reporter_b = ReportB(ip=ws_ip, port=ws_port) self.reporter_c = ReportC(ip=ws_ip, port=ws_port) logger.console('&gt;&gt; ZiZi &gt;&gt; webserviceutil has been initialized successfully!') logger.console('&gt;&gt; ZiZi &gt;&gt; self.__dict__: ' + str(self.__dict__)) logger.console('&gt;&gt; ZiZi &gt;&gt; dir(self): ' + str(dir(self))) def get_report_a(self): return self.reporter_a.get_report() def get_report_b(self): return self.reporter_b.get_report() def get_report_c(self): return self.reporter_c.get_report() class Report(object): def get_report(): return 'This is abstract class!' class ReportA(Report): def get_report(): return 'This is class A!' class ReportB(Report): def get_report(): return 'This is class B!' class ReportC(Report): def get_report(): return 'This is class C!' I get this error in test execution: Object 'webserviceutil' does not have method 'get_sponsor_report'. The console prints which I have put in the __init__ of class WebServiceUtil returns: &gt;&gt; ZiZi &gt;&gt; webserviceutil has been initialized successfully! &gt;&gt; ZiZi &gt;&gt; self.__dict__: {'reporter_a': &lt;We…
has title: Robot Framework import library instance does not contain defined methods
tagged with: object
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47493441
has answer: http://stackoverflow.com/a/47488205

http://stackoverflow.com/q/47521187
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47521390
has answer: http://stackoverflow.com/a/47521390
downvote count: 1
favorite count: 0
type: Question
tagged with: graph
has body: I have generally wondering if it is possible to access data displayed on graphs such as these: https://coinmarketcap.com/currencies/bitcoin/ I have looked at the .htm file and other links within this, yet none seem to be containing this. Would anyone know how to retrieve and print information from the graph using python?
tagged with: python
tagged with: urlretrieve
score: -1
has title: Accessing Data from a graph on a website using python
type: AnsweredQuestion

http://stackoverflow.com/a/47524455
has body: To be able to perform a "batch" replacement (and assuming you need to keep the count of elements replaced) I would do the following: lookup = {"Alpha": "CharlieChoo", "Bravo": "DeltaAir", "Charlie": "Alpha bet", "Delta": "ChooChoo", "Echo": "Airline"} lookup_count = {"Alpha": 2, "Bravo": 2, "Charlie": 2, "Delta": 2, "Echo": 2} def replace_using_lookups(match): word = match.group(1) if word in lookup and lookup_count[word] &gt; 0: lookup_count[word] -= 1 return '"{}"'.format(lookup[word]) return '"{}"'.format(word) re.sub('"(\w+)"', replace_using_lookups, body) If the lookup_count dict isn't necessary you could perform the replacement using a simpler lambda.
score: 0
answers question: http://stackoverflow.com/q/47523386
type: Answer

http://stackoverflow.com/comment/81896325
type: Comment
comment on: http://stackoverflow.com/q/47470825
has text: I agree that. But in the above example, what is the problem if i remove yield statement with a variable to store the generated value and process that value such that next iteration I overwrite that variable ?
score: 0
type: QuestionComment

list
tags question: http://stackoverflow.com/q/47478587
type: Tag
tags question: http://stackoverflow.com/q/47491836
tags question: http://stackoverflow.com/q/47446626
tags question: http://stackoverflow.com/q/47521140
tags question: http://stackoverflow.com/q/47485633
tags question: http://stackoverflow.com/q/47417825
tags question: http://stackoverflow.com/q/47422148
tags question: http://stackoverflow.com/q/47499544
tags question: http://stackoverflow.com/q/47419342
tags question: http://stackoverflow.com/q/47468129
tags question: http://stackoverflow.com/q/47535063
tags question: http://stackoverflow.com/q/47487744
tags question: http://stackoverflow.com/q/47450773
tags question: http://stackoverflow.com/q/47415878
tags question: http://stackoverflow.com/q/47426736
tags question: http://stackoverflow.com/q/47514258
tags question: http://stackoverflow.com/q/47400711
tags question: http://stackoverflow.com/q/47415317
tags question: http://stackoverflow.com/q/47441934
tags question: http://stackoverflow.com/q/47465579
tags question: http://stackoverflow.com/q/47469155
tags question: http://stackoverflow.com/q/47398383
tags question: http://stackoverflow.com/q/47445582
tags question: http://stackoverflow.com/q/47528886
tags question: http://stackoverflow.com/q/47421787
tags question: http://stackoverflow.com/q/47501207
tags question: http://stackoverflow.com/q/47438715
tags question: http://stackoverflow.com/q/47454788
tags question: http://stackoverflow.com/q/47441224
tags question: http://stackoverflow.com/q/47487198
tags question: http://stackoverflow.com/q/47392585
tags question: http://stackoverflow.com/q/47518293
tags question: http://stackoverflow.com/q/47498189
tags question: http://stackoverflow.com/q/47440951
tags question: http://stackoverflow.com/q/47415746
tags question: http://stackoverflow.com/q/47523123
tags question: http://stackoverflow.com/q/47531879
tags question: http://stackoverflow.com/q/47386454
tags question: http://stackoverflow.com/q/47398452
tags question: http://stackoverflow.com/q/47538996
tags question: http://stackoverflow.com/q/47396893
tags question: http://stackoverflow.com/q/47503071
tags question: http://stackoverflow.com/q/47431413
tags question: http://stackoverflow.com/q/47465825
tags question: http://stackoverflow.com/q/47510820
tags question: http://stackoverflow.com/q/47464535
tags question: http://stackoverflow.com/q/47396680
tags question: http://stackoverflow.com/q/47538904
tags question: http://stackoverflow.com/q/47401701
tags question: http://stackoverflow.com/q/47442708
tags question: http://stackoverflow.com/q/47403176
tags question: http://stackoverflow.com/q/47460971
tags question: http://stackoverflow.com/q/47411319
tags question: http://stackoverflow.com/q/47514913
tags question: http://stackoverflow.com/q/47534817
tags question: http://stackoverflow.com/q/47461504
tags question: http://stackoverflow.com/q/47504943
tags question: http://stackoverflow.com/q/47492077
tags question: http://stackoverflow.com/q/47393295
tags question: http://stackoverflow.com/q/47493446
tags question: http://stackoverflow.com/q/47454479
tags question: http://stackoverflow.com/q/47497735
tags question: http://stackoverflow.com/q/47526902
tags question: http://stackoverflow.com/q/47480701
tags question: http://stackoverflow.com/q/47539880
tags question: http://stackoverflow.com/q/47469433
tags question: http://stackoverflow.com/q/47451284
tags question: http://stackoverflow.com/q/47499262
tags question: http://stackoverflow.com/q/47441025
tags question: http://stackoverflow.com/q/47405022
tags question: http://stackoverflow.com/q/47385721
tags question: http://stackoverflow.com/q/47420298
tags question: http://stackoverflow.com/q/47466078
tags question: http://stackoverflow.com/q/47473676
tags question: http://stackoverflow.com/q/47523102
tags question: http://stackoverflow.com/q/47436956
tags question: http://stackoverflow.com/q/47479035
tags question: http://stackoverflow.com/q/47525029
tags question: http://stackoverflow.com/q/47464509

http://stackoverflow.com/q/47499847
tagged with: web-scraping
tagged with: beautifulsoup
type: Question
answer count: 0
has title: Passing Links from CSV to Beautiful Soup Returns Attribute Error: No Attribute .read()
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81955628
has comment: http://stackoverflow.com/comment/81955376
has body: I have a list of scraped links in the first column of a .csv file. I'm trying to iterate through each link so I can scrape additional data, however BeautifulSoup can't read the link. I've been searching for an hour but can't find the problem: AttributeError: 'list' object has no attribute 'read' import csv from bs4 import BeautifulSoup def scrape_data(csv_file): writer = csv.writer(csv_file, delimiter=',') reader = csv.reader(csv_file, delimiter=',') for row in reader: soup = BeautifulSoup(urllib.request.urlopen(row.read(), 'lxml')) # THINGS I'M SCRAPING ARE HERE # for data in zip(scrape1, scrape2, scrape3): writer.writerow(data) with open(r"C:\etc.csv", 'r+') as file: scrape_data(file) file.close()
has comment: http://stackoverflow.com/comment/81955741
has comment: http://stackoverflow.com/comment/81955218
has comment: http://stackoverflow.com/comment/81955502
has comment: http://stackoverflow.com/comment/81955465
tagged with: http://stackoverflow.com/tag/csv
score: 0
has comment: http://stackoverflow.com/comment/81955802

http://stackoverflow.com/q/47413756
has answer: http://stackoverflow.com/a/47415023
tagged with: scipy
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47415023
tagged with: arrays
has answer: http://stackoverflow.com/a/47414036
has title: Python: check if every element in a list exists a specific time
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81780964
possible better answer: http://stackoverflow.com/a/47414036
has body: I have the following question. I have a list of ranges like this: parameterRanges2 = [(1,5),(1,5),(1,7),(1,7),(0,10),(1,20),(1,3),(0,1)] And I have a numpy array like this : arr = np.array([[2.0,4.0,3.0,5.0,1.0,3.0,2.0,4.0,2.0,4.0,3.0,5.0,1.0,3.0,2.0,4.0,2.0,4.0,3.0,5.0], [4.0,2.0,3.0,4.0,2.0,4.0,5.0,1.0,2.0,4.0,1.0,3.0,4.0,2.0,3.0,5.0,1.0,3.0,4.0,2.0], [2.0,3.0,4.0,6.0,7.0,1.0,2.0,3.0,5.0,6.0,1.0,2.0,4.0,5.0,6.0,2.0,3.0,4.0,5.0,6.0], [6.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,2.0,2.0,3.0,4.0,5.0], [8.0,9.0,0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,7.0,8.0,9.0,0.0,1.0,2.0,3.0,4.0,5.0,6.0], [11.0,13.0,14.0,16.0,17.0,19.0,1.0,3.0,4.0,6.0,7.0,9.0,10.0,11.0,13.0,14.0,16.0,17.0,19.0,1.0], [1.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,3.0,3.0,3.0,3.0,1.0,1.0,1.0,1.0,1.0,2.0], [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0]]) Every parameterRange tuple in the list corresponds with the subarray in the numpy array. Is there a way to check if all elements in the corresponding range exists at least one time? so for example that in the first sublist in the numpy array all numbers 1,2,3,4,5 exists at least one time, in the second sublists exists one time and in the third list for example the numbers 1,2,3,4,5,6,7 exists one time and so on.

http://stackoverflow.com/comment/81914195
score: 2
comment on: http://stackoverflow.com/q/47479664
has text: You've misspelled `__init__` as `_init_` (with one set of underscores rather than two) in your class.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81834273
has text: piR is a legend, he might already have used all possible awesome approaches
type: AnswerComment
comment on: http://stackoverflow.com/a/47439322
score: 0
type: Comment

http://stackoverflow.com/comment/81843697
score: 0
comment on: http://stackoverflow.com/q/47441191
has text: @MartijnPieters: for example this one: https://stackoverflow.com/questions/40553285/determining-a-variables-type-is-nonetype-in-python However, the accepted answer mentioned `is` as prefered way
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81888151
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47466806
has text: What is the desired output?

http://stackoverflow.com/comment/81930417
type: QuestionComment
score: 0
has text: first I thought that requests (after first `auth`) can be redirected to new page (but it lost data for second `auth`) so you may have to use `allow_redirection=False` in first request and get destination URL from response, and use this new URL in second request (with second `auth`). But maybe you have to use Session() to keep informatione between requests.
comment on: http://stackoverflow.com/q/47486952
type: Comment

http://stackoverflow.com/q/47444042
type: Question
score: 2
upvote count: 3
has body: I get the following error message below. When I try to run a python file with the command python3 training.py I found a potential solution here but when I went to make the suggested change it appeared that my machine had what was considered the correct setup. To clarify, I have did significant research and none of the following fixes work GitHub 286 1192890 1480388 Any suggestions to what it could be and how to fix it? Failed to import the site module Traceback (most recent call last): File "/usr/lib/python3.5/site.py", line 580, in &lt;module&gt; main() File "/usr/lib/python3.5/site.py", line 566, in main known_paths = addusersitepackages(known_paths) File "/usr/lib/python3.5/site.py", line 287, in addusersitepackages user_site = getusersitepackages() File "/usr/lib/python3.5/site.py", line 263, in getusersitepackages user_base = getuserbase() # this will also set USER_BASE File "/usr/lib/python3.5/site.py", line 253, in getuserbase USER_BASE = get_config_var('userbase') File "/usr/lib/python3.5/sysconfig.py", line 595, in get_config_var return get_config_vars().get(name) File "/usr/lib/python3.5/sysconfig.py", line 538, in get_config_vars _init_posix(_CONFIG_VARS) File "/usr/lib/python3.5/sysconfig.py", line 410, in _init_posix from _sysconfigdata import build_time_vars File "/usr/lib/python3.5/_sysconfigdata.py", line 6, in &lt;module&gt; from _sysconfigdata_m import * ImportError: No module named '_sysconfigdata_m'
tagged with: ubuntu
downvote count: 1
has answer: http://stackoverflow.com/a/48054297
favorite count: 0
has answer: http://stackoverflow.com/a/65206495
type: AnsweredQuestion
tagged with: linux
answer count: 3
has comment: http://stackoverflow.com/comment/81843359
has comment: http://stackoverflow.com/comment/81843889
has title: Ubuntu 'Failed to import the site module' error message
accepted answer: http://stackoverflow.com/a/47487857
tagged with: ubuntu-16.04
possible better answer: http://stackoverflow.com/a/48054297
tagged with: python
linked to: http://stackoverflow.com/q/21446220
has answer: http://stackoverflow.com/a/47487857

http://stackoverflow.com/q/47535889
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82028709
type: UnansweredQuestion
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82313173
has comment: http://stackoverflow.com/comment/82029663
score: 0
tagged with: list
has body: I'm struggling with a quite difficult problem. I want to calculate some kind of difference measure between two lists. One is verified correct data, the other has been generated by a program. I want to test how accurate this program is, but in order to achieve this I need these two lists merged in some way. Example data can be found below. Expected output: A list of dictionaries, with each entry specifying if there were two matching entries. If they don't match, there should be an error type, specifying what is wrong. The output list must be the length of the largest of the two lists, and each entry in this list should be one of: {"matching": True} {"matching": False, "error_type": "deleted"} {"matching": False, "error_type": "inserted"} {"matching": False, "error_type": "updated"} I am working in Python 3, so if someone can provide Python code that would be amazing, but some pseudo-code that accurately describes this kind of algorithm is plenty of help! If you find an easier way of representing the output data, that is also fine. What I have so far isn't much, I really can't wrap my head around how to start this, but here's the small amount of code I have so far: compare_data = [{} for i in range(max(len(correct_data), len(program_data)))] for i in range(len(compare_data)): if len(program_data) &lt;= i: compare_data[i]['matching'] = False compare_data[i]['error_type'] = 'deleted' elif len(correct_data) &lt;= i: compare_data[i]['matching'] = False compare_data[i]['error_type'] = 'inserted' elif correct_data[i]['type'] != program_data[i]['type']: compare_data[i]['matching'] = False compare_data[i]['matching'] = 'updated' else: compare_data[i]['matching'] = True # I really don't have a clue what to do... I was originally looking for some general kind of "Merge two unequal lists with similar structure" algorithm that could be applied to this, but I couldn't find an algorithm that achieves this. Correct data: [ {"type": "a", "data": ["some", "random"]}, {"type": "b", "da…
has title: Merging two possibly unequal lists with low amounts of structure
tagged with: algorithm
has comment: http://stackoverflow.com/comment/82029231
has answer: http://stackoverflow.com/a/47540787
has comment: http://stackoverflow.com/comment/82314179
tagged with: merge

http://stackoverflow.com/a/47409351
type: Answer
accepted answer of: http://stackoverflow.com/q/47409308
score: 2
has body: No need for a while loop, you can use the for-else Python construct for this: for url in list_urls: # do stuff if day == tomorrow: # do and print stuff break else: # break never encountered print("no data found")
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47409308
downvote count: 0

http://stackoverflow.com/q/47450751
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47459166
has answer: http://stackoverflow.com/a/49241777
has body: I am trying to use the python library pyrad ( https://github.com/wichert/pyrad ) to build a simple Radius server. But I had some problems on it. This is the code I am using to create a Radius server: from pyrad import dictionary, packet, server class FakeServer(server.Server): def _HandleAuthPacket(self, pkt): server.Server._HandleAuthPacket(self, pkt) print('Received an authentication request') print("Attributes: ") for attr in pkt.keys(): print("%s: %s" % (attr, pkt[attr])) # print username = pkt['User-Name'][0] password = pkt['User-Password'][0] password = pkt.PwDecrypt(password) device_ip = pkt['NAS-IP-Address'][0] reply = self.CreateReplyPacket(pkt) # Default to refuse reply.code = packet.AccessReject reply['Reply-Message'] = 'You are unable to login' return self.SendReplyPacket(pkt.fd, reply) def _HandleAcctPacket(self, pkt): server.Server._HandleAcctPacket(self, pkt) print("Received an accounting request") print("Attributes: ") for attr in pkt.keys(): print("%s: %s" % (attr, pkt[attr])) # print reply = self.CreateReplyPacket(pkt) self.SendReplyPacket(pkt.fd, reply) if __name__ == '__main': srv = FakeServer(dict=dictionary.Dictionary("dictionary/dictionary")) srv.hosts["192.168.3.183"] = server.RemoteHost("192.168.3.183", b"Kah3choteereethiejeimaeziecumi", "192.168.3.183") srv.BindToAddress("") print('Radius server is ready to start!') srv.Run() This is the code I am using to connect the server: from __future__ import print_function from pyrad.client import Client from pyrad.dictionary import Dictionary import pyrad.packet srv = Client(server="192.168.3.183", secret=b"Kah3choteereethiejeimaeziecumi", dict=Dictionary("dictionary/dictionary")) # create request req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name="test", NAS_IP_Address="192.168.2.101") req["User-Password"] = req.PwCrypt("password") # send request reply = srv.SendPacket(req) if reply.code == pyrad.packet.AccessAccept: print("access accepted") else: print("access denied") print("At…
tagged with: radius
type: Question
tagged with: python-3.x
has title: Some questions on Pyrad
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47524688
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/82005667
downvote count: 1
has comment: http://stackoverflow.com/comment/82005589
answers question: http://stackoverflow.com/q/47524648
has comment: http://stackoverflow.com/comment/82005947
has body: You can do something like this dict_keys=yourdict.keys() expected_keys=['a','b','c'] result= list(set(dict_keys).intersection(set(expected_keys))) if result: for i in expected_keys: if i in result: yourdict.get(i)
type: Answer
has comment: http://stackoverflow.com/comment/82005527
has comment: http://stackoverflow.com/comment/82005495

http://stackoverflow.com/a/47491928
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47491379
has body: Use regex to check if the whole word ag or ag &amp; co. is there in the string: check_str="dimension data germany ag &amp; co." if re.search(r'\bag\b|\bag &amp; co.\b', check_str): print('True') else: print('False') True
downvote count: 0
score: 1

http://stackoverflow.com/comment/82031999
type: Comment
score: 0
type: QuestionComment
has text: @Katie these are terminal commands.
comment on: http://stackoverflow.com/q/47536735

http://stackoverflow.com/q/47537675
has answer: http://stackoverflow.com/a/47573372
tagged with: django
tagged with: python
has title: SyntaxError at django with Apache and wsgi
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82032521
linked to: http://stackoverflow.com/q/44914961
tagged with: mod-wsgi
score: 0
has comment: http://stackoverflow.com/comment/82034305
tagged with: apache
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/82032502
has body: This is error_log file of httpd when running the django app File "/var/www/html/mailqenv/lib/python3.4/site-packages/celery/utils/functional.py", line 11, in <module> [Tue Nov 28 21:26:18.349280 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from kombu.utils.functional import ( [Tue Nov 28 21:26:18.349296 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/kombu/utils/__init__.py", line 5, in <module> [Tue Nov 28 21:26:18.349322 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from .compat import fileno, maybe_fileno, nested, register_after_fork [Tue Nov 28 21:26:18.349333 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/kombu/utils/compat.py", line 29, in <module> [Tue Nov 28 21:26:18.349350 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from typing import NamedTuple [Tue Nov 28 21:26:18.349400 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/typing.py", line 133 [Tue Nov 28 21:26:18.349408 2017] [:error] [pid 3665] [remote 41.187.94.200:84] def __new__(cls, name, bases, namespace, *, _root=False): [Tue Nov 28 21:26:18.349412 2017] [:error] [pid 3665] [remote 41.187.94.200:84] ^ [Tue Nov 28 21:26:18.349416 2017] [:error] [pid 3665] [remote 41.187.94.200:84] SyntaxError: invalid syntax The conf file of httpd: Alias /static /var/www/html/mailqueue/static Require all granted Require all granted Order deny,allow Allow from all WSGIDaemonProcess mailqueue python-path=/var/www/html/mailqueue:/var/www/html/mailqenv/lib/python3.4/site-packages WSGIProcessGroup mailqueue WSGIScriptAlias / /var/www/html/mailqueue/mailqueue/wsgi.py` OS > PRETTY_NAME="Red Hat Enterprise Linux Server 7.2 (Maipo)" But if I activated my virtual environment and run with python manage.py runserver 0.0.0.0:8000 it works well and all is good so what is the problem here, is it python version compatibility Update --…
has comment: http://stackoverflow.com/comment/82032292
accepted answer: http://stackoverflow.com/a/47573372
linked to: http://stackoverflow.com/q/34269772

http://stackoverflow.com/comment/81764439
has text: All the HTML files that I have been given have a mix of /login and /login.html. I could just do a find and replace to get them all the same I suppose.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47405339
type: QuestionComment

http://stackoverflow.com/q/47489456
has answer: http://stackoverflow.com/a/47489479
has answer: http://stackoverflow.com/a/47489528
tagged with: python
score: 2
type: AnsweredQuestion
has title: Downloading list of urls/files using loop - python
answer count: 2
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
has body: I need to download approximately 1000 file/url and it will be hard to download them manually. I tried to put the urls in a list and loop through the list but it I think my code overwrite the previous files and keep only the last item in the list Here is my code #!/usr/bin/env python import urllib3 http = urllib3.PoolManager() urls = ["http://url1.nt.gz" , "http://url2.nt.gz" , "http://url3.nt.gz"] N =1; // counter helps me to rename the downloaded files print "downloading with urllib" for url in urls r = http.request('GET',url) Name =str(N+1) // each time increment the counter by one with open("file"+Name+".nt.gz", "wb") as fcont: fcont.write(r.data) Any suggestions?
possible better answer: http://stackoverflow.com/a/47489479
tagged with: urllib3
accepted answer: http://stackoverflow.com/a/47489528

http://stackoverflow.com/comment/81960340
score: 0
type: QuestionComment
type: Comment
has text: did you register program on AWS ? Did you get ACCESS_KEY, SECRET_KEY, SESSION_TOKEN from AWS ?
comment on: http://stackoverflow.com/q/47501831

http://stackoverflow.com/comment/81736332
comment on: http://stackoverflow.com/q/47391673
type: Comment
type: QuestionComment
score: 0
has text: can you please explain more. Because I try to use map function but does not work with me :(

http://stackoverflow.com/comment/81926662
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47485908
has text: Thanks Panna! The tutorial I was following didn't have that so I thought it was a bit strange.
score: 2

http://stackoverflow.com/comment/82340527
score: 0
has text: then write it as a detailed answer and accept it, so that future visitors can find a solution easier. Thanks!
type: QuestionComment
comment on: http://stackoverflow.com/q/47409170
type: Comment

http://stackoverflow.com/a/47398124
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/81749606
answers question: http://stackoverflow.com/q/47397983
has body: Running the in check (an O(n) operation for lists) for each j-5 within the nested loop (an O(nxm) operation) slows down the performance of your code - because lookup is slow and vanilla for loops in Python are not cheap. You can simply take set differences and add 5, then extend the inner list with the result: st = set(range(5)) for l in X1: l.extend(sorted([x+5 for x in st.difference(l)])) print(X1) You'll go much faster if you don't actually need to sort the new items you're appending, since the inner lists are not sorted anyway, as sorting throws in an extra O(nlogn) complexity. Also the for loop in the list comprehension runs faster than a vanilla for loop, so I can argue the wall time performance of the nesting here is much better than the original. The set difference out performs repeatedlist.__contains__ while the single list.extend also out performs repeated list.append. [[0, 1, 2, 8, 9], [3, 1, 5, 7, 9], [2, 0, 1, 8, 9], [4, 3, 5, 6, 7], [1, 3, 4, 5, 7]]
has comment: http://stackoverflow.com/comment/81749428
has comment: http://stackoverflow.com/comment/81749691
has comment: http://stackoverflow.com/comment/81749395
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/81749705
has comment: http://stackoverflow.com/comment/81749804
accepted answer of: http://stackoverflow.com/q/47397983
has comment: http://stackoverflow.com/comment/81749633
type: AcceptedAnswer

http://stackoverflow.com/comment/81841400
type: Comment
comment on: http://stackoverflow.com/a/47434315
type: AnswerComment
has text: See the edit. It didn't require for this script, though.
score: 0

http://stackoverflow.com/comment/81899992
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47465305
has text: @Enroy Yes. The string creation syntax using quotes is just "sugar" that the language provides to make string creation easy.
score: 0

http://stackoverflow.com/comment/81845442
score: 0
type: Comment
has text: what happens currently?
type: QuestionComment
comment on: http://stackoverflow.com/q/47445043

http://stackoverflow.com/comment/81960523
type: AnswerComment
comment on: http://stackoverflow.com/a/47502313
score: 0
type: Comment
has text: no it means that wherever you installed the `mysql` connector isn't in the same place where python is being read from. are you on a nix machine?

http://stackoverflow.com/q/47528222
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/82015183
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82013348
has title: How to get only the cropped portion of an image in python
favorite count: 0
type: Question
tagged with: numpy
has body: I need to crop a polygon from an image. I have used PIL. I can get the cropped image, but while I read the cropped polygon for further calculation, it reads the hole image not the cropped portion. I need to get only the cropped portion. here is my code import numpy as np from PIL import Image,ImageDraw im = Image.open("input.jpg").convert("RGBA") imArray = np.asarray(im) polygon=[cropping points] #print(polygon) print(imArray.shape) maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0) ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1) mask = np.array(maskIm) newImArray = np.empty(imArray.shape, dtype='uint8') newImArray[:, :, :3] = imArray[:, :, :3] #print(newImArray) newImArray[:, :, 3] = mask * 255 newIm = Image.fromarray(newImArray, "RGBA") newIm.save("out.png","PNG")
has answer: http://stackoverflow.com/a/47528808
accepted answer: http://stackoverflow.com/a/47528808
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82013461
tagged with: image

http://stackoverflow.com/a/47486923
answers question: http://stackoverflow.com/q/47486802
type: Answer
score: 0
has body: The return value of the print function is None. None is assigned to the variable put. You probably want to change this line: put = print("var"+str(xx))

http://stackoverflow.com/a/47493763
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47383106
has body: You are placing the loop wrong! Place it below the mechanize browser and then put a try catch at the end. It will work. Comment once u tried and it works.
type: Answer
accepted answer of: http://stackoverflow.com/q/47383106
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47425881
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47425676
has body: Here is a class that calculates the overlaps using efficient binary search, and code showing its use to solve your problem. Run with python3. import bisect import sys class Overlap(): def __init__(self): self._intervals = [] def intervals(self): return self._intervals def put(self, interval): istart, iend = interval # Ignoring intervals that start after the window. i = bisect.bisect_right(self._intervals, (iend, sys.maxsize)) # Look at remaining intervals to find overlap. for start, end in self._intervals[:i]: if end &gt; istart: return False bisect.insort(self._intervals, interval) return True yz_list = [(0, 6), (1, 7), (2, 8), (3, 9), (4, 10), (5, 11), (6, 12), (18, 24)] ov = Overlap() for i in yz_list: ov.put(i) print('Original:', yz_list) print('Result:', ov.intervals()) OUTPUT: Original: [(0, 6), (1, 7), (2, 8), (3, 9), (4, 10), (5, 11), (6, 12), (18, 24)] Result: [(0, 6), (6, 12), (18, 24)]
downvote count: 0

http://stackoverflow.com/comment/81949461
type: AnswerComment
comment on: http://stackoverflow.com/a/47496643
score: 0
type: Comment
has text: I'm pretty sure PIP installs things for the python runtime that is used to run it, so it would be a mere matter of changing the path temporarily (but you would have to first install PIP for Gimp's python runtime)

http://stackoverflow.com/comment/81835151
type: QuestionComment
has text: That's the nature of "Not A Number". Because of that we have `pd.isnull()`, `pd.notnull()`, `IS (NOT) NULL` in SQL, etc
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47440077

http://stackoverflow.com/comment/81866315
has text: Thank you, your answer led me to a solution :)
comment on: http://stackoverflow.com/a/47455413
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47399116
linked to: http://stackoverflow.com/q/4700614
upvote count: 1
has answer: http://stackoverflow.com/a/47399311
type: AnsweredQuestion
score: 1
has body: I get a jointplot as following using sns.jointplot with kind="kde". and I want to move the text to the left corner, what should I do here? Thanks
tagged with: matplotlib
has title: How to change the position of text in seaborn jointplot
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47399311
favorite count: 0
type: Question
tagged with: seaborn
downvote count: 0

http://stackoverflow.com/a/47428946
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47428874
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81812561
has body: This is how you do it. Please let know in comments if there is something that you don't understand, or if I am doing anything wrong. class A(object): a = "Hello" b = "World" class B(A): pass class C(B): pass c = C() print(c.a,c.b) Prints Hello World
accepted answer of: http://stackoverflow.com/q/47428874
type: Answer
has comment: http://stackoverflow.com/comment/81814587
has comment: http://stackoverflow.com/comment/81813126
has comment: http://stackoverflow.com/comment/81812496

http://stackoverflow.com/comment/81951700
score: 0
type: Comment
type: QuestionComment
has text: I have saw it done by just leaving the message in, I can change it though if that seems like a better way of doing it
comment on: http://stackoverflow.com/q/47498230

http://stackoverflow.com/comment/82030467
has text: just check if the service is a valid one before printing it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47536336
score: 0

http://stackoverflow.com/comment/81796163
score: 0
has text: Why not just use it.
type: QuestionComment
comment on: http://stackoverflow.com/q/47420510
type: Comment

http://stackoverflow.com/comment/81963584
has text: This is a complete example with some renaming. Not sure how to supply verifiable example as the issue is not reproducible on my local setup. Would really appreciate any pointers. All I can do is gather required information from the production environment and share.
score: 0
comment on: http://stackoverflow.com/q/47503731
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81818879
score: 0
type: AnswerComment
has text: Ok now, it prints "None" but at least it prints the values on that black command prompt rather than in VS. I wasn't expecting this.
type: Comment
comment on: http://stackoverflow.com/a/47432190

http://stackoverflow.com/comment/81935547
comment on: http://stackoverflow.com/a/47490027
score: 0
type: Comment
type: AnswerComment
has text: @Code_Control_jxie0755 I doubt this is the first function you've seen used for it's side effect. `print` is a function that is used for it's side-effect, and of course, many list-methods do just that, e.g. `.append`. Note, both `.append` and `print` return `None`

http://stackoverflow.com/q/47441463
has answer: http://stackoverflow.com/a/47441841
type: AnsweredQuestion
score: 0
tagged with: python
has title: Get tracks for each returned album is not working in some cases where there are spaces between names
type: Question
accepted answer: http://stackoverflow.com/a/47441841
has body: I'm getting the top artists from a specific country, albums of that artists and tracks of that albums from lastfm api. I'm getting the artists and albums without errors, but in the tracks it appears: for album in album_response['album']['tracks']['track']: KeyError: 'album' The issue seems that is because some artists have spaces in the name, so I replace it with "+" also with "%2b" but none solution is working it always appears the error above. chosen = artists[i]['name'].replace(" ", "+") chosen = '+'.join(artists[i]['name'].lower().split()) chosen = artists[i]['name'].replace(" ", "%2B") The track part where is the error : tracks = {} for i,v in albums.items(): artist = albums[i]['artist'].replace(" ","+") name = albums[i]['name'].replace(" ", "+") album_response_data = requests.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&amp;format=json&amp;api_key='+api_key+'&amp;artist='+artist+'&amp;album='+name) album_response = album_response_data.json() print(album_response) for album in album_response['album']['tracks']['track']: title = album['name'] number = album['@attr']['rank'] duration = album['duration'] tracks[ID] = {} tracks[ID]['title'] = title tracks[ID]['number'] = number tracks[ID]['artist'] = albums[i]['artist'] tracks[ID]['album'] = albums[i]['name'] tracks[ID]['albumID'] = albums[i]['ID'] tracks[ID]['duration'] = duration ID += 1 Full working example: import requests api_key = "b088cbedecd40b35dd89e90f55227ac2" #generated for the example ID= 0 #Get artists from specific country artists = {} for i in range(2, 3): artists_response = requests.get( 'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&amp;country=spain&amp;format=json&amp;page=' + str(i) + '&amp;api_key=' + api_key) artists_data = artists_response.json() for artist in artists_data["topartists"]["artist"]: name = artist["name"] url = artist["url"] #if ID &gt; 3 continue artists[ID] = {} artists[ID]['ID'] = ID artists[ID]['name'] = name ID += 1 #Get TopAlbums info from abov…
answer count: 1

http://stackoverflow.com/q/47440140
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81854258
has comment: http://stackoverflow.com/comment/81836020
favorite count: 0
has comment: http://stackoverflow.com/comment/81835870
has comment: http://stackoverflow.com/comment/81835723
type: Question
has comment: http://stackoverflow.com/comment/81835227
tagged with: ubuntu-14.04
has comment: http://stackoverflow.com/comment/81835399
score: 1
has comment: http://stackoverflow.com/comment/81835604
has comment: http://stackoverflow.com/comment/81836372
has body: I'm trying to make communication via Internet between client and server, both written in Python. I have the next code for server: def handle_client(clnt): while True: data = clnt.recv(1024) if data: print data, del data sock = socket.socket() sock.bind(('0.0.0.0', 12345)) sock.listen(5) while True: client,addr = sock.accept() print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1]) # spin up our client thread to handle incoming data client_handler = threading.Thread(target=handle_client,args=(client,)) client_handler.start() client.close() and for client: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('my public IP-address', 12345)) sock.send('Some plain text') When working with localhost, it works properly. After i have loaded it to my Ubuntu-14.04 server, which is not in the same local network, client doesn't want to connect. The output is: socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond I have already created rule for server firewall, run server and client as administrator, disabled client antivirus, checked the Internet connection, pinged each other but it still doesn't seem to work throwing me the same error over and over again (the same error is shown if the server wasn't started). Any ideas what`s wrong or how to fix this issue?
has comment: http://stackoverflow.com/comment/81835540
tagged with: sockets
has comment: http://stackoverflow.com/comment/81838083
downvote count: 0
has title: Can`t connect to another PC via Python sockets
answer count: 0
upvote count: 1

multidimensional-array
tags question: http://stackoverflow.com/q/47398452
tags question: http://stackoverflow.com/q/47443293
tags question: http://stackoverflow.com/q/47424061
tags question: http://stackoverflow.com/q/47426375
tags question: http://stackoverflow.com/q/47443874
tags question: http://stackoverflow.com/q/47461504
tags question: http://stackoverflow.com/q/47456806
type: Tag
tags question: http://stackoverflow.com/q/47538605
tags question: http://stackoverflow.com/q/47510441
tags question: http://stackoverflow.com/q/47446909
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/47432263
tags question: http://stackoverflow.com/q/47424458
tags question: http://stackoverflow.com/q/47432632

http://stackoverflow.com/comment/82076628
comment on: http://stackoverflow.com/q/47521328
type: QuestionComment
type: Comment
has text: Yup - @alecxe's answer below helped. Moving away from `','.join([str(row) for row in values_list])` & using placeholders instead worked.
score: 0

http://stackoverflow.com/comment/81965630
has text: @timgeb - thanks for the tip. Yup, a dictionary would have probably been a better shout; in addition to the suggestions on why I'm down voted (thanks for this), I should have mentioned I'm a rookie and dictionaries isn't something I've covered yet (I'm teaching myself), but I need to.
score: 0
comment on: http://stackoverflow.com/q/47504706
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47514258
has comment: http://stackoverflow.com/comment/81984434
favorite count: 0
has comment: http://stackoverflow.com/comment/81984213
type: Question
has answer: http://stackoverflow.com/a/47514429
possible better answer: http://stackoverflow.com/a/47514400
upvote count: 2
has title: How do I perform an operation on only the int part of lists?
has answer: http://stackoverflow.com/a/47514400
has answer: http://stackoverflow.com/a/47515090
downvote count: 0
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/47514480
has answer: http://stackoverflow.com/a/47516662
tagged with: int
score: 2
has answer: http://stackoverflow.com/a/47514937
has body: I'm trying to complete this assignment for a class. The instructions say to: L is a list of lists. The first item in each sublist is a student name and the rest of the items in the sublist are grade values (float or int). Return a new list of lists where each sublist has length 2 of the form [student_name (str), average grade (float)] &gt;&gt;&gt; average_grade([['Bob', 56, 80, 72, 90], ['Alice', 60, 88, 44, 70], ['Joe', 44, 100, 80, 60, 50]]) [['Bob', 74.5], ['Alice', 65.5], ['Joe', 66.8]] The problem that I'm having with my code is that I'm trying to be able to enter in the lists, but only find the average of the integers. So far I have this: for int in ['Bob', 'Alice', 'Joe']: return (map(L[sum(int)/len(int)]), map(L[sum(int)/len(int)]), map(L[sum(int)/len(int)])) But when I enter in even only one list, I get this: builtins.TypeError: unsupported operand type(s) for +: 'int' and 'str' I'm not sure what to do here. Any help?
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/81984620
has comment: http://stackoverflow.com/comment/81984214
tagged with: string
accepted answer: http://stackoverflow.com/a/47514429

http://stackoverflow.com/comment/81729431
has text: The default value for the second argument to `.get()` is already `None`. `elif not request.POST.get('foo'):` suffices.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47388058
type: AnswerComment

http://stackoverflow.com/a/54618199
downvote count: 0
has body: You get this error, because the python.exe path has not been added to the System environment variable. To do that, simply: go to the path C:\Users\%Username%\AppData\Local\Programs\Python\Python37-32 which contains python.exe copy the path and open System environment variables and in the variable section look for variable called Path. If not, create a new variable with Variable Name as Path and value as the copied path Once you do that, close the window and simply open cmd. Type python and you should get something like this:
score: 3
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/47539201

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

http://stackoverflow.com/q/47415824
has title: How can I retrieve the full text of a tweet?
tagged with: python
tagged with: python-twitter
tagged with: tweepy
downvote count: 0
score: 1
upvote count: 1
has body: I run the code below and even I set as parameter tweet_mode='extended' i do not get the full text of the retrieved tweets. Can anybody help me to fix it? import tweepy consumer_key ='xxxx' consumer_secret = 'xxxx' access_token = 'xxxx' access_token_secret = 'xxxx' # create our authentication variable auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token,access_token_secret) api = tweepy.API(auth) cursor= tweepy.Cursor(api.search,q="obama",tweet_mode='extended', lang="en", date='2017-11-13', days_ago=9).items(5) for tweet in cursor: print (tweet.created_at,tweet.full_text) Here are the corresponded results. 2017-11-21 13:55:20 Another one of Obama's poor little underprivileged Black ladies, oppressed by Whites? 2017-11-21 13:55:20 RT @PoliticalShort: Remember when it was considered immoral to question whether Obama’s 20-year patronage at Wright’s radical church could… 2017-11-21 13:55:20 RT @IosrscIub: i had a dream that i was trying to find a fruit scale in walmart to weigh my pomegranates and then obama stopped me, took th… 2017-11-21 13:55:19 @WhereIs_Billy @FoxNews No Ure wrong! He saved them from possible yrs in jail there Dumb Ass! Look Wht happened to Otto cause Racist OBAMA did NOTHING! Mayb all u liberals shld go to N K good bye! No F...... Respect! MAGA MAGA 2017-11-21 13:55:19 RT @oldhippiebroad: This is no judge. He’s politician all the way. He’s a disgrace. #UraniumOneScandal #LockThemAllUp
answer count: 1
tagged with: twitter
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47611087
type: UnansweredQuestion

http://stackoverflow.com/a/47442093
type: Answer
has comment: http://stackoverflow.com/comment/81839378
score: 2
has body: df[df.L.apply(lambda i: ','.join(i)).str.contains('yourstring')]
upvote count: 2
answers question: http://stackoverflow.com/q/47441980
downvote count: 0

http://stackoverflow.com/comment/139409337
has text: You are the man!
score: 0
comment on: http://stackoverflow.com/a/62664850
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47507626
answers question: http://stackoverflow.com/q/47507426
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Use pd.to_datetime with errors='coerce' to identify bad data and fix it. pd.to_datetime(df.dispatch_due, errors='coerce')\ .fillna('please add dispatch_due') 0 2017-11-27 00:00:00 1 2017-11-28 00:00:00 2 please add dispatch_due 3 please add dispatch_due Name: dispatch_due, dtype: object If you don't want the trailing timestamp, you could convert the date to strftime before filling NaNs. pd.to_datetime(df.dispatch_due, errors='coerce')\ .dt.strftime('%y-%m-%d').replace('NaT', 'please add dispatch_due') 0 17-11-27 1 17-11-28 2 please add dispatch_due 3 please add dispatch_due Name: dispatch_due, dtype: object
type: Answer
accepted answer of: http://stackoverflow.com/q/47507426

http://stackoverflow.com/comment/81984976
has text: @JonathanPorter There's explicit, and then there's unnecessary code. If the reader doesn't already know that `sublist[0]` is a list, then `new_list = []` isn't going to be any more enlightening; their just going to see that the line is unnecessary because it is immediately changed. There are better ways to provide type hints in Python.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47514480
type: Comment

http://stackoverflow.com/comment/82013552
score: 0
has text: What does "be ready for duplicates" mean? To you need to preserve all duplicates, or ignore them? A list of tuples sounds like it would do the job in the first case, and could easily be adapted to prevent duplicates at insert time.
type: QuestionComment
comment on: http://stackoverflow.com/q/47528415
type: Comment

http://stackoverflow.com/q/47396350
tagged with: toolz
linked to: http://stackoverflow.com/q/42404728
tagged with: python
tagged with: dictionary
answer count: 4
has body: Consider the following piece of code: from collections import Counter from cytoolz import merge_with my_list = ["a", "b", "a", "a", "c", "d", "b"] my_dict = {"a" : "blue", "b" : "green", "c" : "yellow", "d" : "red", "e" : "black"} pair_dict = merge_with(tuple, my_dict, Counter(my_list)) I obtain the following pair_dict: {'a': ('blue', 3), 'b': ('green', 2), 'c': ('yellow', 1), 'd': ('red', 1), 'e': ('black',)} In my real case application I need the values in my pair_dict to be pairs, so pair_dict["e"] should be ('black', 0). It would be very convenient if I could have a class that extends Counter with the nice behaviour of a defaultdict(int). Is this easily done? I naïvely tried the following: class DefaultCounter(defaultdict, Counter): pass pair_dict = merge_with(tuple, my_dict, DefaultCounter(my_list)) But I get TypeError: first argument must be callable or None. I guess this is due to the fact that defaultdict expects a factory function. So I tried the following: pair_dict = merge_with(tuple, my_dict, DefaultCounter(int, my_list)) This results in ValueError: dictionary update sequence element #0 has length 1; 2 is required. I also tried class DefaultCounter(Counter, defaultdict) but this does not have the desired effect: pair_dict["e"] is still ('black',). Probably something else should be done in the definition of the class. So I tried to adapt this answer: class DefaultCounter(Counter): def __missing__(self, key): self[key] = 0 return 0 But this also doesn't have the desired effect (pair_dict["e"] still misses a second element). Edit: Counter already behaves as defaultdict(int), but merge_with does not trigger this behaviour. As suggested in the comments, a Counter already has the desired behaviour: my_counts = Counter(my_list) assert my_counts["e"] == 0 The issue may actually lie in the way merge_with works: It doesn't trigger the desired defaultdict behaviour. This is verified by the following test using a defaultdict instead of a Counter: from collections im…
type: AnsweredQuestion
has title: Python Counter with defaultdict(int) behaviour
upvote count: 3
has answer: http://stackoverflow.com/a/47396616
downvote count: 0
has comment: http://stackoverflow.com/comment/81747421
tagged with: multiple-inheritance
tagged with: collections
possible better answer: http://stackoverflow.com/a/47396625
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81746578
accepted answer: http://stackoverflow.com/a/47398590
score: 3
has answer: http://stackoverflow.com/a/47396625
has answer: http://stackoverflow.com/a/47512336
has answer: http://stackoverflow.com/a/47398590

http://stackoverflow.com/q/47465070
tagged with: django
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/81884954
has comment: http://stackoverflow.com/comment/81929189
favorite count: 0
type: Question
tagged with: python-2.7
tagged with: django-views
score: 1
tagged with: python
has title: In Django, how to re-package a Request.response as a Django response?
has comment: http://stackoverflow.com/comment/81885512
has body: I have a Django App that accepts messages from a remote device as a POST message. This fits well with Django's framework! I used the generic View class (from django.views import View) and defined my own POST function. But the remote device requires a special reply that I cannot generate in Django (yet). So, I use the Requests library to re-create the POST message and send it up to the manufacturer's cloud server. That server processes the data, and responds with the special message in the body. Idealy, the entire HTML response message should go back to the remote device. If it does not get a valid reply, it will re-send the message. Which would be annoying! I've been googling, but am having trouble getting a clear picture on how to either: (a): Reply back in Django with the Requests.response object without any edits. (b): Build a Django response and send it back. Actually, I think I do know how to do (b), but its work. I would rather do (a) if its possible. Thanks in Advance! Rich.
has comment: http://stackoverflow.com/comment/81929226
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47487167

http://stackoverflow.com/comment/81940218
has text: look, you have `_do_damage(self.database_scientific)`. dictionary or not, **this is a function call.** If you want to store the function as a value in a dictionary, just do `d = {'scientific database':_do_damage}` and then to call it, `d['scientific database'](self.database_scientific)`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47492398

http://stackoverflow.com/q/47491348
has answer: http://stackoverflow.com/a/48536440
linked to: http://stackoverflow.com/q/29514077
has comment: http://stackoverflow.com/comment/81960731
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47502419
tagged with: django-rest-framework
has title: Django DRF JWT authentication get token - JSON parse error - Expecting value
tagged with: jwt
has comment: http://stackoverflow.com/comment/81962925
has comment: http://stackoverflow.com/comment/81961112
score: 0
has body: I have simple Django DRF application setup which I have implemented JWT authentication. I used the Django REST framework JWT documentation I am using curl to test the implementation. I can successfully get a token using the following notation used in the documentation: $ curl -X POST -d "username=admin&amp;password=password123" http://localhost:8000/api-token-auth/ The token is returned in following format: {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNpdHJ1Y3AiLCJleHAiOjE1MTE2NTEyMTQsInVzZXJfaWQiOjEsImVtYWlsIjoiY3VydGlzLnBva3JhbnRAZ21haWwuY29tIn0.F1TSkxe5tQVpddetUdOJDdAPP1XB9Bimb5U3c75oWd0"} However, when I try using this other variation, I get an error: $ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/ The error I get is: {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} I also had the same error when trying to refresh or verify the token: Refresh: $ curl -X POST -H "Content-Type: application/json" -d '{"token":"&lt;EXISTING_TOKEN&gt;"}' http://localhost:8000/api-token-refresh/ Verify: $ curl -X POST -H "Content-Type: application/json" -d '{"token":"&lt;EXISTING_TOKEN&gt;"}' http://localhost:8000/api-token-verify/ I was adding the token as follows: curl -X POST -H "Content-Type: application/json" -d '{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNpdHJ1Y3AiLCJleHAiOjE1MTE2NDg5MjIsInVzZXJfaWQiOjEsImVtYWlsIjoiY3VydGlzLnBva3JhbnRAZ21haWwuY29tIn0.T5h_PSvzvKOZCPTS60x5IUm3DgAsRCRmbMJeGWZk3Tw"}' http://localhost:8800/api-token-refresh/ Am I perhaps adding the token incorrectly? Does it need some other formatting with quotes?

http://stackoverflow.com/comment/81744332
type: AnswerComment
comment on: http://stackoverflow.com/a/47395586
score: 0
has text: Ah, I thought mistakenly that my series had no duplicates in it. Thanks for the correction.
type: Comment

http://stackoverflow.com/q/47477664
has comment: http://stackoverflow.com/comment/81913211
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81915859
has body: Even though my issue might be a common one, I couldn't find a clear answer for it. I'm a beginner with AngularJS and there is a very simple code that is not working, and actually all my directives doesn't work. Here is my small project /templates -index.html -header.html -script.js mainapp.py In index.html there is in header.html I'm supposed to see this And mainapp.py from flask import Flask, render_template app = Flask(__name__) @app.route("/") def mainpage(): return render_template("index.html") if __name__ == "__main__": app.run(debug=True) Nothing in script.js When I'm running mainapp.py I'm expecting to see "I'm supposed to see this" but I don't because the directives doesn't seem to be working. However if I'm trying the html code alone (on Plunker for example) it's working fine. I assume there is configuration that I need to do but I have no idea what, any ideas? (and if someone could provide an explanation for why it's not working that would be great) Note that using data- before my directives doesn't change the issue. Thanks
downvote count: 0
answer count: 1
tagged with: directive
has answer: http://stackoverflow.com/a/47481577
accepted answer: http://stackoverflow.com/a/47481577
favorite count: 0
has title: AngularJS directives don't seem to work with Python Flask
type: Question
tagged with: python

http://stackoverflow.com/q/47480031
upvote count: 1
has answer: http://stackoverflow.com/a/47480043
has answer: http://stackoverflow.com/a/47480418
accepted answer: http://stackoverflow.com/a/47480043
possible better answer: http://stackoverflow.com/a/47480418
favorite count: 0
type: Question
has title: Create a list of years from dataframe
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pandas
has body: I have a dataframe df which the head looks like : total_cost date 2006-03-04 -1465.052092 2006-04-04 -1213.508277 2006-05-04 -1459.290503 2006-06-04 -1460.119361 2006-07-04 -772.482609 Is there a way to create a list that just has the distinct years that are included in the timeseries. So, for example, if the above timeseries had entries from 2006 to 20012 the list would look like: [2006,2007,2008,2009,2010,2011,2012] I thought about using a pivot table, but couldn't get the date by year.
score: 1

amazon-lex
tags question: http://stackoverflow.com/q/47505488
type: Tag
tag name: amazon-lex

http://stackoverflow.com/comment/81760998
type: Comment
type: QuestionComment
has text: this can be solved with a google search and is out of place on stack overflow please read the [mcve guidelines](https://stackoverflow.com/help/mcve)
score: 0
comment on: http://stackoverflow.com/q/47403608

http://stackoverflow.com/q/47452180
has comment: http://stackoverflow.com/comment/81859293
accepted answer: http://stackoverflow.com/a/47452422
downvote count: 1
answer count: 1
tagged with: scipy
favorite count: 0
type: Question
tagged with: equation-solving
has comment: http://stackoverflow.com/comment/81859303
has answer: http://stackoverflow.com/a/47452422
tagged with: python
score: -1
has body: I am trying to solve a system of simultaneous equations as follows: "145.0x/21025 = -0.334" "(-48.402x-96.650y+96.650z)/21025 = -0.334" "(-48.402x+132.070y+35.214z)/21025 = -0.334" "sqrt(x^2+y^2+z^2) = 145.0" I am using the following Python script: from scipy.optimize import root from numpy import sqrt from sys import argv, stdout initGuesses = eval(argv[1]) equations = argv[2:] def f(variables): x,y,z = variables results = [] for eqn in equations: results.append(eval(eqn)) return results solution = root(f, initGuesses, method="lm") stdout.write(str(solution["x"][0]) + "," + str(solution["x"][1]) + "," + str(solution["x"][2])) stdout.flush() The program is called as follows: python3 SolvePosition3D.py "(1,1,1)" "(145.0*x+0.0*y+0.0*z)/21025.0+0.334" "(-48.402*x-96.650*y+96.650*z)/21025+0.334" "(-48.402*x+132.070*y+35.214*z)/21025+0.334" "sqrt(x**2+y**2+z**2)-145.0" And I am receiving the following output: 48.2699997956,35.4758788666,132.042180583 This solution is wrong; the correct solution is roughly -48,-35,-132 which is the same numbers but * -1. The answer returned by the program satisfies the final equation, but violates all others. Does anyone know why this is happening? Getting the correct solutions to these equations (and many others like them) is vitally important to my current project.
has title: scipy.optimize.root returning incorrect solution
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/47539815
tagged with: insertion
has body: I have the following code that performs an insertion sort for 4 items in a list. It works, but it uses IF statements. I am interested in the various solutions that show a)conversion (based on my code and variables) to a simpler more efficient algorithm using loops where there is repetition and b) a clear explanation as to where/why what has been implemented. The code for the insertion sort using IF statements: def main(): list=[4,1,2,6] print("original list:",list) cv=list[1] if cv&lt;list[0]: list[1]=list[0] list[0]=cv print("Compare element 1 with 0:",list) cv=list[2] if cv&lt;list[1]: list[2]=list[1] list[1]=cv print("Compare element 2 with 1 &amp; shift 1 upto 2:",list) if cv&lt;list[0]: list[1]=list[0] list[0]=cv print("Compare element 2 with 0 and shift 0 and 1 up:",list) cv=list[3] if cv&lt;list[2]: list[3]=list[2] list[2]=cv print("Compare element 3 with 2 &amp; shift 2 upto 3:",list) if cv&lt;list[1]: list[2]=list[1] list[1]=cv print("Compare element 3 with 1 and shift 1 and 2 up:",list) if cv&lt;list[0]: list[1]=list[0] list[0]=cv print("Compare element 3 with 0 and shift 0 up:",list) main() How does this code above translate into a for loop/loop based solution + I'd also be interested in a recursive solution, but again derived directly from this one for teaching/learning purposes. One could start, for example, by reocgnising that each iteration is done for lengthoflist-1 times. So: for i in range((len(list))-1): cv=list[i+1] etc I get that there will be an outer loop and an inner loop. How are these best constructed, and again, a clear explanation as to how the solution is derived from this original if-based code, is what I'm after.
tagged with: sorting
has answer: http://stackoverflow.com/a/47540005
accepted answer: http://stackoverflow.com/a/47540005
favorite count: 0
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/82038090
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82038170
linked to: http://stackoverflow.com/q/2493920
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/82037051
has title: conversion from if statements to efficient for loop based solution for INSERTION SORT in Python
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/81893101
score: 0
type: Comment
type: AnswerComment
has text: how to fix it? I don't know much about linux. Can you tell me which part of linux need to set correctly, I'll google it
comment on: http://stackoverflow.com/a/47468428

http://stackoverflow.com/comment/82008294
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47525812
type: Comment
has text: Note that the timing difference is both in using the libraries you used and also just reading the images; OpenCV is [twice as fast as PIL](https://stackoverflow.com/a/45892102/5087436) at reading images.

http://stackoverflow.com/comment/81755293
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47400827
has text: Alternatively, for /r %v in (*.pyc) do uncompyle6 -o . "%v" "%vx" :). You can run this in Python through os.popen if needed too.
type: Comment

http://stackoverflow.com/q/47534197
downvote count: 0
tagged with: caffe
upvote count: 1
favorite count: 0
tagged with: deep-learning
tagged with: python
score: 1
type: Question
has body: I want to plot train and test accuracy for my caffe model. The settings are as follows: I have 1200 training samples, and 300 development set samples. (small numbers for question simplicity). I divided the Train into 100 mini-batches each has 12 samples, and the Dev into 100 mini-batches each has 3 samples. My goal is to loop on the training and test every 1 epoch = 100 iterations. Solver file: test_iter: 3 test_interval: 100 # The base learning rate, momentum and the weight decay of the network. base_lr: 0.001 #momentum: 0.9 weight_decay: 0.0005 # The learning rate policy lr_policy: "inv" gamma: 0.0001 power: 0.75 # Display every 100 iterations display: 10000 # The maximum number of iterations max_iter: 200 Now i want to iterate on the test set and every 1 epoch i want to save and test: base_weights = "VGG_CNN_F.caffemodel" solver = caffe.SGDSolver('solver.prototxt') solver.net.copy_from(base_weights) niter = 200+1 test_interval = 100 test_iter = 3 save_interval = 100 #losses will also be stored in the log train_loss = np.zeros(niter) train_acc = np.zeros(niter) test_acc = np.zeros(int(np.ceil(niter / test_interval))) test_counter = 0 #the main solver loop for it in range(niter): solver.step(1) #(forward, backward, update) on 1 mini-batch #store the train loss train_loss[it] = solver.net.blobs['loss'].data train_acc[it] = solver.net.blobs['accuracy'].data if it%save_interval== 0: solver.net.save('classifier.caffemodel') print('Train loss at itr', it,' = ' ,train_loss[it]) print('Train accuracy at itr ', it,' = ' ,train_acc[it]) if (it%test_interval == 0) and (it!=0): temp = np.zeros(test_iter) for t_it in range(test_iter): # test on all Dev mini-batches solver.test_nets[0].forward() temp[t_it] = solver.test_nets[0].blobs['accuracy'].data test_acc[test_counter] = temp.mean() print ("Mean TEST acc at iteration = " + str(it) + " is " + str(test_acc[test_counter])) test_counter = test_counter + 1 solver.net.save('classifier.caffemodel') The output: I1128 15:24:50.67723…
answer count: 0
has title: Store Train and Test Accuracy in Caffe
type: UnansweredQuestion

user-input
tags question: http://stackoverflow.com/q/47383380
tags question: http://stackoverflow.com/q/47488664
type: Tag
tag name: user-input
tags question: http://stackoverflow.com/q/47382799
tags question: http://stackoverflow.com/q/47500101
tags question: http://stackoverflow.com/q/47400055
tags question: http://stackoverflow.com/q/47465292
tags question: http://stackoverflow.com/q/47389632
tags question: http://stackoverflow.com/q/47532462

http://stackoverflow.com/comment/81984232
score: 0
has text: Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the links it contains. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.
type: Comment
comment on: http://stackoverflow.com/q/47514099
type: QuestionComment

http://stackoverflow.com/q/47525580
upvote count: 2
answer count: 1
has title: Decrypting in pgpy fails with "ValueError: Expected: ASCII-armored PGP data"
downvote count: 0
tagged with: gpgpu
favorite count: 0
type: Question
tagged with: pgp
tagged with: openpgp
type: UnansweredQuestion
tagged with: encryption
tagged with: python
has comment: http://stackoverflow.com/comment/82024744
has answer: http://stackoverflow.com/a/47538780
score: 2
has body: I have an OpenPGP encrypted file and its private key in a text file and know its passphrase. I tried this below code: import pgpy emsg = pgpy.PGPMessage.from_file('PGPEcrypted.txt') key,_ = pgpy.PGPKey.from_file('PrivateKey.txt') with key.unlock('passcode!'): print (key.decrypt(emsg).message) But while trying to execute I am getting following error: Traceback (most recent call last): File "D:\Project\PGP\pgp_test.py", line 4, in &lt;module&gt; key,_ = pgpy.PGPKey.from_file('SyngentaPrivateKey.txt') File "D:\Anaconda\lib\site-packages\pgpy\types.py", line 191, in from_file po = obj.parse(data) File "D:\Anaconda\lib\site-packages\pgpy\pgp.py", line 2252, in parse unarmored = self.ascii_unarmor(data) File "D:\Anaconda\lib\site-packages\pgpy\types.py", line 131, in ascii_unarmor raise ValueError("Expected: ASCII-armored PGP data") ValueError: Expected: ASCII-armored PGP data How can I decrypt the file in python?

python-unicode
tags question: http://stackoverflow.com/q/47409514
type: Tag
tag name: python-unicode
tags question: http://stackoverflow.com/q/47436649
tags question: http://stackoverflow.com/q/47394521

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

http://stackoverflow.com/comment/81884441
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47464783
has text: Where is your data and expected output?
type: Comment

http://stackoverflow.com/q/47532632
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/82021916
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47532839
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47532839
answer count: 2
has comment: http://stackoverflow.com/comment/82021744
has body: I have this HTML: 13 days ago 13 days ago 8 days ago 3 days ago 6 hours ago My code detect if the comment was written within the last 24 hours and from me, unfortunatly always the first comment in the HTML. I want to check if the last comment is 24 hours ago and written from me. I can´t use driver.find_element_by_class_name("comment-1197000") because I have to use the code for other pages with the same HTML structure and comments can be added. (so next comment would be comment-1197001) This is my code so far: from pyvirtualdisplay import Display from selenium import webdriver display = Display() display.start() driver = webdriver.Chrome() driver.maximize_window() commentar = driver.find_element_by_class_name("issuePanelContainer") if commentar.is_displayed(): comment_author = driver.find_element_by_xpath("//*[@id='issue_actions_container']").find_element_by_tag_name("a") author = comment_author.get_attribute("rel") written = driver.find_element_by_class_name("livestamp") last_comment = parse_date(written.get_attribute("datetime")) dt = datetime.datetime.now() if comment_author.get_attribute("rel") in author_list and last_comment < dt.replace(tzinfo=timezone.utc) - datetime.timedelta(seconds=86400): # 86400 Seconds for 24 h print "Last comment is from you and was written on", written.get_attribute("datetime") else: print "Last comment is not from you or older than 24 hours" For a solution I thought about a for loop, but I'm new to python and I don't really know how to solve this problem. Hope someone can help. Thanks :)
upvote count: 0
has comment: http://stackoverflow.com/comment/82022066
has title: python find last in HTML
possible better answer: http://stackoverflow.com/a/47532875
downvote count: 1
tagged with: webdriver
has answer: http://stackoverflow.com/a/47532875
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82021945

http://stackoverflow.com/a/47401243
has body: If symbols is just a list of allowed characters such as: symbols = [";", ",", ".", "-"] then even if user_password contains only letters and these symbols, the print will still happen as normal characters (letters a-z) won't be in symbols.
score: 0
answers question: http://stackoverflow.com/q/47400209
type: Answer

http://stackoverflow.com/a/47424982
has comment: http://stackoverflow.com/comment/81805126
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81805398
answers question: http://stackoverflow.com/q/47424885
has comment: http://stackoverflow.com/comment/81805497
has comment: http://stackoverflow.com/comment/81805168
has comment: http://stackoverflow.com/comment/81805175
accepted answer of: http://stackoverflow.com/q/47424885
score: 1
has comment: http://stackoverflow.com/comment/81804842
type: Answer
has body: This seems like an ideal use case for crontab. I'd write 2 bash scripts that run every 3 hours via cron. So something like the following: #ScriptA.sh ifProcessRunning KillProcess #ScriptB.sh ifProcessNotRunning StartProcess #CronTab 0,6,12,18 * * * * ScriptA.sh 3,9,15,21 * * * * ScriptB.sh For killing the process you can use any normal unix command, so piping a ps aux and running kill within the shell script could work. Hopefully this helps -- comment if you want me to flesh things out more!
has comment: http://stackoverflow.com/comment/81808309

http://stackoverflow.com/a/47418454
has body: Python 3 search_value = '02-TAC-MWKKK' ind = (ind for ind, val in enumerate(list) if val[0]['bu'] == search_value).__next__() Python 2 search_value = '02-TAC-MWKKK' ind = (ind for ind, val in enumerate(list) if val[0]['bu'] == search_value).next() Also, as mentioned by @mrCarnivore, please don't name your variable list.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47417364

http://stackoverflow.com/comment/138960810
comment on: http://stackoverflow.com/a/47504662
has text: Adding more complexity is usually the wrong solution. See also [Actual meaning of `shell=True` in `subprocess`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47499998
has body: I've discovered this wierd glitch in python. I was playing around with evolution simulations, so I made loads of creatures that each has it's own genes. As you can imagine, it's important to be able to mutate the genes and create new creatures with it. I saved each creatures genes in a dictionary, and each gene was a list within the dictionary (which might have had more lists in it). The problem arose when trying to apply mutations to the genes. If I didn't make a copy of the gene dictionary any change to the dictionary would result in a similar change in all other creatures. (Not really a big problem, but I would be interested in hearing a reason for this. Do dictionaries and classes not play well together?) So whats the problem? Just copy the genes, right? Well, the thing I discovered was that this problem also applied to the lists inside the dictionary. If I didn't want the changes to translate across all instances, I would have to copy the list (copyList = List[:]). This would happen even though I was making the changes to a COPY of the original f*cking gene dictionary. What's more, any list within a list would have to get the same treatment. What's even more, I still get this problem if I make the changes in a function outside the class which I call within the class. This is quite annoying, but I think there may be other problems I am not aware of: other ways in which the genes of other instances may be corrupted. I've been having problems with my simulation because of this. Making copy after copy after copy results in messy code. Does anybody know why this is happening? Is there a simple way to fix it? Below is some simplified code to illustrate the problem. I can't imagine what is going on. tl;dr: Run the code below to see some wierd voodoo shit: #DEMONSTRATION OF A F*CKING STUPID PHENOMENON WITH PYTHON CLASSES class creature(object): def __init__(self,genes): self.genes = genes def changeGenes(self,details): genes = self.genes.copy() n,i,s = details try: gen…
answer count: 2
has title: Modifying dictionary in one instance of a class makes same change to all other instances
upvote count: 1
type: UnansweredQuestion
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47500077
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/47500067
type: Question

http://stackoverflow.com/q/47503883
tagged with: python-2.7
favorite count: 0
type: Question
has body: Let's say I have two lists: list_one = ["Alex", "Alex", "John", "Alex", "John", "John"] list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"] And I want to merge alike items next to each other in list one (call this list three) list_one = ["Alex", "Alex", "John", "Alex", "John", "John"] list_three = ["Alex", "John", "Alex", "John"] And list two turns into list four, which follows the "pattern" of merging items in list one: list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"] list_four = ["Hi Are you there?", "Hello Alex!", "How are you John?", "I am good Alex How about yourself?"] How would I do so? I found this: Remove adjacent duplicate elements from a list, but it doesn't handle multiple lists, and I don't want to remove items from the second list. Edit: I found a thread where I can get all instances of an item in a list, the code they use is: def all_indices(value, qlist): indices = [] idx = -1 while True: try: idx = qlist.index(value, idx+1) indices.append(idx) except ValueError: break return indices Now if I do this for my code, I get two lists: Alex = [0,1,3] John = [2,4,5] However, how can I write a function that would combine list_two[0] and list_two[1]? Or what if Alex = [0,1,2,3,4,5], how could I combine all of those into one item in a list?
accepted answer: http://stackoverflow.com/a/47504139
linked to: http://stackoverflow.com/q/3460161
answer count: 1
upvote count: 1
downvote count: 1
type: AnsweredQuestion
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/47504139
has title: Merge items in list if they're alike and next to each other
tagged with: python

http://stackoverflow.com/comment/82003420
score: 0
type: Comment
type: AnswerComment
has text: Thank you! is there a way where I can make the simulations start at 1000 and maybe stay at 1000?
comment on: http://stackoverflow.com/a/47523583

http://stackoverflow.com/comment/81815239
has text: Updated the screenshot in question update - RecievedValue is populated from the socket as string.
comment on: http://stackoverflow.com/a/47406138
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81751043
comment on: http://stackoverflow.com/a/47398974
score: 0
type: AnswerComment
type: Comment
has text: he wnats to keep the ( ) - yours discards it

http://stackoverflow.com/comment/81787599
comment on: http://stackoverflow.com/a/47406904
has text: @TomaszPrzemski always :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47438533
has comment: http://stackoverflow.com/comment/81903036
accepted answer of: http://stackoverflow.com/q/47437326
has body: The problem here is, that in your example you just got one product. So as Elis said, in the loop element is just the string attribute. Actually you already tried to cover the possibility of just one product but you made a mistake there. You have to put it in a list, if it IS an OrderedDict: root_elements = obj['product'] if type(obj) != OrderedDict else [obj['product']] The code works well if there are several products except a couple of small mistakes. You have to put the PSdata initialization inside the loop where you iterate over your products, because otherwise, with every product, 4 new columns get attached and the values of the former product written in the same line. So you might want to check if there is only one product in your root_elements and handle this case separately. Furthermore don't name your variables uppercase. Another point: lists are zero indexed in Python, so to get the 4 value you should go with: for element in root_elements: psdata = [] something1 = element['attribute'][0]['value'] psdata.append(something1) something2 = element['attribute'][1]['value'] psdata.append(something2) something3 = element['attribute'][2]['value'] psdata.append(something3) something4 = element['attribute'][3]['value'] csvwriter.writerow(psdata) Or shorter with a list comprehension: for element in root_elements: csvwriter.writerow([element['attribute'][i]['value'] for i in range(4)]) So here is an updated version of your script, which follows most of pep8: #!/usr/bin/python # -*- coding: utf-8 -*- import csv import xmltodict from collections import OrderedDict class Test: def psxml(self): with open('test.csv', 'w') as file_ps: csvwriter = csv.writer(file_ps) header = ['Something1', 'Something2', 'Something3', 'Something4'] csvwriter.writerow(header) with open('test.xml') as fd: obj = xmltodict.parse(fd.read()) obj = obj['import']['products'] root_elements = obj['product'] if type(obj) != OrderedDict else [obj['product']] for element in root_elements: csvwriter.writer…
type: Answer
answers question: http://stackoverflow.com/q/47437326
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81856451

bayesian-networks
tag name: bayesian-networks
type: Tag
tags question: http://stackoverflow.com/q/47430891

http://stackoverflow.com/q/47481588
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47481700
type: Question
has answer: http://stackoverflow.com/a/47481700
has body: I am parsing Java source code using Python. I need to extract the comment text from the source. I have tried the following. Take 1: cmts = re.findall(r'/\*\*(.|[\r\n])*?\*/', lines) Returns: blanks [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] Take 2: (added a grouping bracket around the regex) cmts = re.findall(r'(/\*\*(.|[\r\n])*?\*/)', lines) Returns Single line comment (example only): ('/**\n\n * initialise the tag with the colors and the tag name\n\n */', ' ') Multi line comment (example only): ('/**\n\n * Get the color related to a specified tag\n\n * @param tag the tag that we want to get the colour for\n\n * @return color of the tag in String\n\n */', ' ') I am interested only in initialise the tag with the colors and the tag name or Get the color related to a specified tag, @param tag the tag that we want to get the colour for, @return color of the tag in String and am not able to get my head around it. Please give me some pointers!
tagged with: python
tagged with: comments
tagged with: regex
has title: python regex for extracting java comment
score: 2
type: AnsweredQuestion
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/81805986
score: 0
comment on: http://stackoverflow.com/q/47425528
has text: @wpercy Sure can, give me a sec
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47410106
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81774092
has comment: http://stackoverflow.com/comment/81774030
tagged with: python
has comment: http://stackoverflow.com/comment/81773801
score: 0
answer count: 0
has title: How can I loop over all inner values of an arbitrary deep nested list?
has body: I have a deep_list which might be something like deep_list = [{'foo': 1, 'bar': 2} for _ in range(2)] or deep_list = [[{'foo': 1, 'bar': 2} for _ in range(42)] for _ in range(10)] or deep_list = [[[{'foo': 1, 'bar': 2} for _ in range(2)] for _ in range(42)] for _ in range(10)] So a list of (lists of)* dicts. I would like to iterate over them in a way for index_tuple, element in elements_of(deep_list): print((index_tuple, element)) For the first example, it would print ((0, ), {'foo': 1, 'bar': 2}) ((1, ), {'foo': 1, 'bar': 2}) For the second example, it would print something like (I don't care about the order) ((0, 0), {'foo': 1, 'bar': 2}) ((0, 1), {'foo': 1, 'bar': 2}) ... For the third list it would be something like ((0, 0, 0), {'foo': 1, 'bar': 2}) ((0, 0, 1), {'foo': 1, 'bar': 2}) ... My approach would be to write a recursive traversing function ... but is there something nicer / directly built-in into Python?
has comment: http://stackoverflow.com/comment/81773901
type: Question
has comment: http://stackoverflow.com/comment/81774404
tagged with: nested-lists

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

http://stackoverflow.com/q/47516659
type: Question
has comment: http://stackoverflow.com/comment/82020297
has title: Using map and lambda to emulate a dict comprehension
accepted answer: http://stackoverflow.com/a/47516688
has answer: http://stackoverflow.com/a/47516688
tagged with: python
tagged with: dictionary
tagged with: lambda
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81989256
downvote count: 0
answer count: 1
has body: I have a list of tuples that are coordinates: xy = [(x_1, y_1), (x_2, y_2), ...] and an specific point xy_sp = [x_sp, y_sp]. I want to calculate the distance from each point to the so called "specific point" and to create a dictionary in the form: {coordinates_of_1st_point: distance_1, coordinates_of_2nd_point: distance_2, ...} and then perhaps I just can order my dictionary by values. I want to do this with a functional pythonic approach. So I did: import numpy as np distances = list(map(lambda k: np.linalg.norm(np.asarray(k) - np.asarray(xy)), xy)) And then I just created a dictionary comprehension: dict_distances = {k : v for k, v in zip(xy, distances)} It is this last point that I want to do with a maps and lambdas in a functional approach but I don't know how to do it. If it can be all done in a line of code it would be interesting, although I suppose it will be not readable at all and therefore not very recommendable. Any suggestions are welcomed.
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/47516281
downvote count: 0
upvote count: 1
score: 1
has body: The solution is to only change your kv File and no changes required to your Python Script. The changes are as follow: kv File 1. TextInput: Add on_text Event The textinput’s text is stored in its TextInput.text property. To run a callback when the text changes, do the following. on_text: root.running_total = self.text 2. Label: Reference StringProperty, root.running_total Replace: text: starting_number.text with: text: root.running_total testbutton.kv #:kivy 1.10.0 &lt;TestingWidget&gt;: BoxLayout: orientation: 'horizontal' TextInput: id: starting_number hint_text: root.starting_number on_text: root.running_total = self.text Button: id: add_one_button text: 'Add 1 to Starting Number' on_press: root.button_pressed() Label: id: running_total text: root.running_total Output
type: Answer
answers question: http://stackoverflow.com/q/47513847

http://stackoverflow.com/comment/81980418
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47512347
type: QuestionComment
has text: Can the key contain a semicolon?

http://stackoverflow.com/q/47516877
has comment: http://stackoverflow.com/comment/81990172
accepted answer: http://stackoverflow.com/a/47517552
upvote count: 1
answer count: 1
has title: Sum of two binary numbers represented by reversed lists in Python
has comment: http://stackoverflow.com/comment/81989824
has comment: http://stackoverflow.com/comment/81989923
favorite count: 0
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/81989857
has comment: http://stackoverflow.com/comment/81989881
tagged with: algorithm
has answer: http://stackoverflow.com/a/47517552
has body: Can you help me to get this right? I have a binary representation of the number in a reversed list. Accompanied function bn can be used to create the encoded number. I want to add two binary numbers by carry method, but I can't get it right plus the code is getting messy. The restriction is that one can use only boolean operators and list splicing on the algorithm. # encode binary form of the number, not part of the algo def bn (n): return list(reversed(list(map(lambda x: 1 if x == "1" else 0, "{0:b}".format(n))))) # main algo to sum two binary numbers def s(m, n): def _ (a, b, c): if a and b: return [0 if (0 if a[0] == b[0] else 1) == c else 1] + \ _(a[1:], b[1:], 1 if (c and (a[0] or b[0])) or (a[0] and b[0]) else 0) if a: return [0 if a[0] == c else 1] + ([1]+a[2:] if c else a[1:]) if b: return [0 if b[0] == c else 1] + ([1]+b[2:] if c else b[1:]) return [1] if c else [] return _(m, n, 0) print(bn(2017), bn(3), s(bn(2017), bn(3)), bn(2017+3)) Here the s(bn(2017), bn(3)) [0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1] doesn't match with the bn(2017+3)) [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1] as it should. So I ask help to correct the code plus any optimizations you could make would be appreciated. Addition To test elementary cases one can use something like: for i in range(0, 12, 2): for j in range(0, 12, 3): x, y = bn(i+j), s(bn(i), bn(j)) print(x == y, bn(i), bn(j), "%s + %s = %s %s -&gt; %s" % (i, j, i+j, x, y)) But beware, this doesn't catch the problematic addition 2017+3 I gave above...
has comment: http://stackoverflow.com/comment/81989819
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81990175
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81989885

http://stackoverflow.com/comment/82023477
comment on: http://stackoverflow.com/a/47532497
score: 0
type: AnswerComment
type: Comment
has text: Yes, you are right. Although, using `"utf-8"` would have given a different result.

http://stackoverflow.com/q/47514753
score: 0
accepted answer: http://stackoverflow.com/a/47514777
answer count: 1
has answer: http://stackoverflow.com/a/47514777
has body: In [4]: import re In [5]: print(re.escape('\n')) \ In [6]: print(re.escape(r'\n')) \\n In [7]: print(r'\n') \n In [8]: print('\n') In [9]: print('\\n') \n The third example print(r'\n') gives the output I want (also the last example). BUT the string I want to print is a variable that was not defined as a raw string. Needless to say I cannot manually add backslashes to the string.
type: Question
type: AnsweredQuestion
has title: How do a print a backslash-escaped string to output '\n' in Python?
has comment: http://stackoverflow.com/comment/81985409
tagged with: python
linked to: http://stackoverflow.com/q/7262828

dataframe
tags question: http://stackoverflow.com/q/47533178
tags question: http://stackoverflow.com/q/47520367
tags question: http://stackoverflow.com/q/47486763
tags question: http://stackoverflow.com/q/47488744
tags question: http://stackoverflow.com/q/47406062
tags question: http://stackoverflow.com/q/47424345
tags question: http://stackoverflow.com/q/47449545
tags question: http://stackoverflow.com/q/47526059
tags question: http://stackoverflow.com/q/47418295
tags question: http://stackoverflow.com/q/47525175
tags question: http://stackoverflow.com/q/47449651
tags question: http://stackoverflow.com/q/47450259
tags question: http://stackoverflow.com/q/47499032
tags question: http://stackoverflow.com/q/47439234
tags question: http://stackoverflow.com/q/47519729
tags question: http://stackoverflow.com/q/47395797
tags question: http://stackoverflow.com/q/47395944
tags question: http://stackoverflow.com/q/47473550
tags question: http://stackoverflow.com/q/47513619
tags question: http://stackoverflow.com/q/47469579
tags question: http://stackoverflow.com/q/47445635
tags question: http://stackoverflow.com/q/47416164
tags question: http://stackoverflow.com/q/47528555
tags question: http://stackoverflow.com/q/47514858
tags question: http://stackoverflow.com/q/47423930
tags question: http://stackoverflow.com/q/47508365
tags question: http://stackoverflow.com/q/47437381
tags question: http://stackoverflow.com/q/47401961
tags question: http://stackoverflow.com/q/47392290
tags question: http://stackoverflow.com/q/47519029
tags question: http://stackoverflow.com/q/47405274
tags question: http://stackoverflow.com/q/47519294
tags question: http://stackoverflow.com/q/47400561
tags question: http://stackoverflow.com/q/47464362
tags question: http://stackoverflow.com/q/47531712
tags question: http://stackoverflow.com/q/47501177
tags question: http://stackoverflow.com/q/47493299
tags question: http://stackoverflow.com/q/47500522
tags question: http://stackoverflow.com/q/47444631
tags question: http://stackoverflow.com/q/47485768
tags question: http://stackoverflow.com/q/47464060
tags question: http://stackoverflow.com/q/47384535
tags question: http://stackoverflow.com/q/47413535
tags question: http://stackoverflow.com/q/47540369
tags question: http://stackoverflow.com/q/47466164
tags question: http://stackoverflow.com/q/47516326
tags question: http://stackoverflow.com/q/47512234
tags question: http://stackoverflow.com/q/47515586
tags question: http://stackoverflow.com/q/47442733
tags question: http://stackoverflow.com/q/47424128
tags question: http://stackoverflow.com/q/47506182
tags question: http://stackoverflow.com/q/47483901
tags question: http://stackoverflow.com/q/47424458
tags question: http://stackoverflow.com/q/47480456
tags question: http://stackoverflow.com/q/47512749
tags question: http://stackoverflow.com/q/47412314
tags question: http://stackoverflow.com/q/47387203
tags question: http://stackoverflow.com/q/47444269
tags question: http://stackoverflow.com/q/47444999
tags question: http://stackoverflow.com/q/47447358
tags question: http://stackoverflow.com/q/47427238
tags question: http://stackoverflow.com/q/47463413
tags question: http://stackoverflow.com/q/47451517
tags question: http://stackoverflow.com/q/47531369
tags question: http://stackoverflow.com/q/47522231
tags question: http://stackoverflow.com/q/47461149
tags question: http://stackoverflow.com/q/47416113
tags question: http://stackoverflow.com/q/47501684
tags question: http://stackoverflow.com/q/47515357
tags question: http://stackoverflow.com/q/47445364
tags question: http://stackoverflow.com/q/47496261
tags question: http://stackoverflow.com/q/47463481
tags question: http://stackoverflow.com/q/47511511
tags question: http://stackoverflow.com/q/47510766
tags question: http://stackoverflow.com/q/47480262
tags question: http://stackoverflow.com/q/47505790
tags question: http://stackoverflow.com/q/47426595
tags question: http://stackoverflow.com/q/47495896
tags question: http://stackoverflow.com/q/47517983
tags question: http://stackoverflow.com/q/47506763

http://stackoverflow.com/q/47451429
answer count: 1
tagged with: unit-testing
has title: Mock a method of a mocked object in Python?
favorite count: 0
accepted answer: http://stackoverflow.com/a/47451903
type: Question
score: 31
tagged with: python
has answer: http://stackoverflow.com/a/47451903
has body: I am writing unit tests for a project written in Python 3.4, using the unittest.mock library. The function I am testing contains a call to a function versions = get_all_versions(some_argument) which I have patched with a MagicMock object that returns a list, so that version becomes a list of version numbers, which all works fine. Now, the code I am testing has changed a bit, and looks like versions = get_all_versions(some_argument).order_by(another_argument) Now I need the order_by method to return the same list of version numbers, while get_all_versions should remain mocked, and I have some problems achieving this. I have tried patching it with get_all_versions = MagicMock() get_all_versions.order_by = version_list but that does not work, and I guess it is because order_by is a method and not a property. I have also tried get_all_versions = MagicMock() get_all_versions.order_by = MagicMock(return_value=version_list) and (more desperately) get_all_versions = MagicMock(return_value=MagicMock(return_value=version_list)) but neither of those two work. How do I mock a function that returns an object, and then mock a method of that object so that it returns a list?
type: AnsweredQuestion
tagged with: python-3.x
tagged with: mocking
upvote count: 31
downvote count: 0

http://stackoverflow.com/comment/81916236
type: AnswerComment
has text: In that case, that is if both `df_a` and `df_c` contain only zeros and ones, then `df_a | df_c.loc[df_a.index, df_a.columns]` solves the multiindex case as well. (As I suppose you can verify on your own data as well?)
score: 0
comment on: http://stackoverflow.com/a/47480454
type: Comment

http://stackoverflow.com/comment/81840329
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47415918
has text: If you need to wait for the tread to come back then may be it should not be daemon. Hope this helps.
score: 1

http://stackoverflow.com/a/47531538
answers question: http://stackoverflow.com/q/47528401
downvote count: 0
type: AcceptedAnswer
has body: Though GPhilo's answer addresses the issue why running the code is getting slower and slower, but in reality, that solution will result in creation of computation graph again and again which is not good. The following two lines of code, (GPhilo has also mentioned) are continuously adding operations to your graph for each iteration. loss=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits( \ labels=y_, logits=logits_2)*[rate[0],rate[1]]) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) As I can see, you are having two values rate[0], rate[1] which needs to be supplied to your graph. Why are you not supplying these two values through placeholder and define your graph only once. Once you start running Session you shouldn't add more operations in your graph. Also, you shouldn't be considering initializing your Session for iteration. Check this modified code (only important parts) # To clear previously created graph (if any) present in memory. tf.reset_default_graph() x=tf.placeholder(tf.float32, shape=[1,n_input]) y_=tf.placeholder(tf.float32,shape=[n_output]) y_r=tf.placeholder(tf.float32,shape=[n_output]) # Add these two placeholders (Assuming they are single float value) rate0 = tf.placeholder(tf.float32, shape = []) rate1 = tf.placeholder(tf.float32, shape = []) W1=tf.Variable(tf.random_uniform([n_input, n_hidden])) .... accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Bring this code outside from loop (Note replacement of rate[0] with placeholder) loss=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels=y_, \ logits=logits_2) * [rate0, rate1]) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) # Instantiate session only once. with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # Move the subsequent looping code inside. rate=[0,0] for i in range(-100,200,10): rate[0]=i; After this modification, whenever your Session runs train_step, you need to supply these two extra placeholders i…
has comment: http://stackoverflow.com/comment/82033857
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47528401
score: 4

http://stackoverflow.com/q/47445582
tagged with: function
has answer: http://stackoverflow.com/a/63565264
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81862900
has comment: http://stackoverflow.com/comment/81846695
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81847212
has comment: http://stackoverflow.com/comment/81854427
has comment: http://stackoverflow.com/comment/81854331
score: 1
has body: I'm having a button save what's in an entry, and, for some reason, it isn't saving it properly to the list outside of the function, as in inside the function Submit(), it remembers the entry value just fine. Here is the part of the function for setting up the entry: Q8answer = Entry(r) Q8answer.config(fg = "blue",bg = "white",font = ("Arial",20),) Q8answer.place(relx = 0.5,rely = 0.5,anchor = "center") submit = Button(r, text = "Submit THIS Answer",command = Submit) submit.place(relx = 0.5, rely = 0.8, anchor = "center") And this is the function called Submit(): def Submit(): answers[7] = str(Q8answer.get()) print(answers) And BTW, I do globalise all the variables needed, as the other answers which are multiple choice with button questions ( answers[0] to answers[6] ), all worked and saved to the list properly. EDIT:Heres some more context: Q8answer.place_forget() submit.place_forget() Q8answer = Entry(r) Q8answer.config(fg = "blue",font = ("Arial",20),) submit = Button(r, text = "Submit THIS Answer", command = Submit() ) Amode = 0 Bmode = 0 Cmode = 0 Dmode = 0 Abutton.config(image = unselected) Bbutton.config(image = unselected) Cbutton.config(image = unselected) Dbutton.config(image = unselected) if mode == 1: if questionNumber &lt; len(questions): questionNumber += 1 if questionNumber == 8: Correct() elif questionNumber == 7: Abutton.place_forget() Bbutton.place_forget() Cbutton.place_forget() Dbutton.place_forget() Alabel.place_forget() Blabel.place_forget() Clabel.place_forget() Dlabel.place_forget() Number = Label(r,text = "Question " + str(questionNumber + 1)) Number.config(fg = "blue",bg = "grey", font = ("Arial",15)) Number.place(relx = 0.02, rely = 0.02 ) question = questions[questionNumber] Question.place_forget() Question = Label(r,text = question) Question.config(fg = "blue",bg = "grey") Question.config(font = ("Arial",20)) Question.place(relx = 0.5, rely = 0.15, anchor = "center") Q8answer = Entry(r) Q8answer.config(fg = "blue",bg = "white",font = ("Ar…
has comment: http://stackoverflow.com/comment/81847032
tagged with: python
has comment: http://stackoverflow.com/comment/85612764
has comment: http://stackoverflow.com/comment/81863015
has comment: http://stackoverflow.com/comment/81847244
has title: Lists Not Saving Entry Data Tkinter
tagged with: list
tagged with: tkinter

http://stackoverflow.com/comment/81771664
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47397692
has text: So, when you call pd.read_html(...)[0].groupby(...) you get exactly the same exception?
type: Comment

http://stackoverflow.com/a/47484785
type: Answer
has body: You can "right align" a row by padding it with spaces. Here, the Ith rows should have N-I spaces and I hashes: for i in range(1, n + 1): print(' ' * (n - i) + '#' * i)
has comment: http://stackoverflow.com/comment/81924656
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81924520
accepted answer of: http://stackoverflow.com/q/47484753
answers question: http://stackoverflow.com/q/47484753

http://stackoverflow.com/comment/82030164
comment on: http://stackoverflow.com/q/47536336
score: 0
type: QuestionComment
type: Comment
has text: I'm fairly sure we could, but as SteveJ said, you're not quite giving the right information. While we appreciate the effort put into crafting a good question (many people don't), we need more information about the logic and less about the overall architecture. Tell us what those 4 examples should look like in your example and how you arrived at that solution, and we'll see if we can help. Also it may be that it requires the same number of if statements, but I actually quite doubt it.

http://stackoverflow.com/a/47392471
accepted answer of: http://stackoverflow.com/q/47392269
answers question: http://stackoverflow.com/q/47392269
type: Answer
type: AcceptedAnswer
downvote count: 0
has body: raw_input is now called input in Python3. You also had a variable called input, which may have caused confusion. from scipy import * from scipy.integrate import odeint from operator import itemgetter import matplotlib matplotlib.use('Agg') from matplotlib.ticker import FormatStrFormatter from pylab import * from itertools import product, islice from numpy import zeros_like from string import ascii_lowercase import operator import sys t_range = arange(0.0, 20.0, 0.1) # initial_condi = [] # VarList = [] # ParamsList = [] ops = "+-" opsdict = { "+": operator.add, "-": operator.sub } # if len(initial_condi)!=len(VarList): # sys.exit('error: the number of initional conditions do not equal to the number of variables') def odeFunc(Y, t, model, K): return GenModel(Y, model, K) def GenModel(Y, model, K): # New array of floating-point zeros the size of Y dydt = zeros_like(Y) for i, derivative in enumerate(model): for j, operator in enumerate(derivative): # Sequentially compute dy/dt for each variable in Y dydt[i] = opsdict[operator](dydt[i],K[j]*Y[j]) return dydt # Returns a nicer-looking string for a derivative expression given the encoding def derivString(vars, deriv): result = "" for i, v in enumerate(vars): if i == 0 and deriv[i] == '+': result += v else: result += deriv[i]+v return result # main numvars = int(input("Enter number of variables\n&gt; ")) VarList = ascii_lowercase[:numvars] nummodels = (2**numvars)**numvars # begin looping input_ = "" while input_ != "quit": print("\n%d possible models" % nummodels) input_ = input("Enter model ID (zero-indexed) or 'quit'\n&gt; ") # Basic input filtering if input_ == "quit": continue elif not input_.isdigit(): print("Input must be a non-negative integer") continue ID = int(input_) if ID &gt;= nummodels or ID &lt; 0: print("Invalid ID") continue # itertools.product creates a generator for all possible combinations of +- derivatives = product(ops, repeat=numvars) # We take the product again to generate all models models = produ…
upvote count: 1
score: 1

http://stackoverflow.com/q/47395931
answer count: 0
has comment: http://stackoverflow.com/comment/81745010
has comment: http://stackoverflow.com/comment/81748724
has comment: http://stackoverflow.com/comment/81745147
type: Question
has body: i am using this statement in my python 36 version: from bs4 import BeautifulSoup, then i get a syntax error like this: You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work. You need to convert the code, either by installing it (python setup.py install) or by running 2to3 (2to3 -w bs4).' how do i fix this? Any help will be much appreciated
has title: how do i run BeautifulSoup in my python 3 version?
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/47526053
has title: Python - parsing comments from Steam
type: Question
score: 0
has body: I want to practice how to parse values from website. However, when I parse the comments from Steam, I only can parse the first page of comment. How do I crawl all the comments? Here is my code: from bs4 import BeautifulSoup import urllib.request url = 'http://steamcommunity.com/games/dota2/announcements/detail/1449457773770927103' html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html, 'lxml') for t in soup.body.find_all('div', attrs = {'class':'commentthread_comment_text'}): print(t.text)
answer count: 1
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82008139
linked to: http://stackoverflow.com/q/24435774
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/47526231
has answer: http://stackoverflow.com/a/47526231

http://stackoverflow.com/a/47414742
score: 0
has body: as it was advised in the comments, i used endpoints = modelout.create_base(images_placeholder, labels_one_hot=None) and it worked
accepted answer of: http://stackoverflow.com/q/47395799
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47395799

http://stackoverflow.com/comment/81920017
type: AnswerComment
has text: Is there any way I can do the same thing using find_element_by_xpath? In addition, why is there a hashtag before "snsPrice"?
score: 0
comment on: http://stackoverflow.com/a/47482593
type: Comment

http://stackoverflow.com/a/47398777
answers question: http://stackoverflow.com/q/47398318
downvote count: 0
type: Answer
upvote count: 1
has body: To make a pivot to stay always twice of the height whenever you change the height value, try to code like this: import maya.cmds as cmds hght=4 cmds.polyCone(r=1,h=hght,sx=6) cmds.move(0,2,0) cmds.xform("pCone1",ws=True,piv=(0,hght*2,0)) # cmds.xform("pCone1",ws=True,rp=(0,2,0),sp=(0,0,0))
score: 1

http://stackoverflow.com/a/47475849
has body: I was able to get this working correctly. This script creates a VideoWriter object for every frame with a temporary file. If motion is no detected within that frame, the writer is released and the file that was created with VideoWriter gets deleted. If motion is detected, the file is kept and written to. Once motion is no longer detected, a countdown timer is started so it continues recording as long as you set. If motion is detected before the timer hits 0, then it continues to record and resets the timer and so on. This is still being tuned, but works pretty well. #!/usr/local/bin/python3 import argparse import warnings import datetime import imutils import json import numpy as np import os import time import cv2 print("[INFO] Kicking off script - " + datetime.datetime.now().strftime("%Y-%m-%d_%H_%M_%S")) # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-c", "--conf", required=True, help="path to the JSON configuration file") args = vars(ap.parse_args()) # filter warnings, load the configuration warnings.filterwarnings("ignore") conf = json.load(open(args["conf"])) # initialize the camera and grab a reference to the raw camera capture # if the video argument is None, then we are reading from webcam if not conf["use_ip_cam"]: camera = cv2.VideoCapture(0) time.sleep(0.25) # otherwise, we are reading from a video input else: camera = cv2.VideoCapture(conf["ip_cam_addr"]) # allow the camera to warmup, then initialize the average frame, last # uploaded timestamp, and frame motion counter print("[INFO] warming up...") time.sleep(conf["camera_warmup_time"]) avg = None lastUploaded = datetime.datetime.now() motion_counter = 0 non_motion_timer = conf["nonMotionTimer"] fourcc = 0x00000020 # a little hacky, but works for now writer = None (h, w) = (None, None) zeros = None output = None made_recording = False # capture frames from the camera while True: # grab the raw NumPy array representing the image and initialize # t…
accepted answer of: http://stackoverflow.com/q/47384294
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47384294
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/comment/81728526
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47387351
has text: I still need help
type: Comment

http://stackoverflow.com/q/47440077
downvote count: 0
has title: How to check if particular value (in cell) is NaN in pandas DataFrame?
has comment: http://stackoverflow.com/comment/81835301
has comment: http://stackoverflow.com/comment/81835078
has body: Let's say I have the following pandas DataFrame: import pandas as pd import numpy as np df = pd.DataFrame({"A": [1, np.nan, 2], "B": [5, 6, 0]}) Which would look like: >>> df A B 0 1.0 5 1 NaN 6 2 2.0 0 First option I know one way to check if a particular value is NaN: >>> df.isnull().iloc[1,0] True But this checks the whole dataframe just to get one value, so I imagine it's wasteful. Second option (not working) I thought below option, using iloc, would work as well, but it doesn't: >>> df.iloc[1,0] == np.nan False However if I check that value I get: >>> df.iloc[1,0] nan So, why is the second option not working? Is it possible to check for NaN values using iloc? Editor's note: This question previously used pd.np instead of np and .ix in addition to .iloc, but since these no longer exist, they have been edited out to keep it short and clear.
has answer: http://stackoverflow.com/a/71524750
tagged with: nan
has comment: http://stackoverflow.com/comment/81835272
has comment: http://stackoverflow.com/comment/81835373
has comment: http://stackoverflow.com/comment/81835454
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/53694839
answer count: 5
has answer: http://stackoverflow.com/a/75381422
accepted answer: http://stackoverflow.com/a/47440315
has comment: http://stackoverflow.com/comment/81846319
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81835203
has comment: http://stackoverflow.com/comment/81835230
linked to: http://stackoverflow.com/q/20320022
has comment: http://stackoverflow.com/comment/81835150
has answer: http://stackoverflow.com/a/47440315
has comment: http://stackoverflow.com/comment/81835109
has comment: http://stackoverflow.com/comment/81835151
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81835251
has comment: http://stackoverflow.com/comment/81835305
score: 109
upvote count: 109
has comment: http://stackoverflow.com/comment/81846120
tagged with: pandas
has answer: http://stackoverflow.com/a/56384875
linked to: http://stackoverflow.com/q/52086574
has comment: http://stackoverflow.com/comment/81835370
has answer: http://stackoverflow.com/a/53694839

http://stackoverflow.com/a/47418375
answers question: http://stackoverflow.com/q/47415317
upvote count: 6
type: Answer
score: 6
has body: Networkx recently moved to version 2.0 from 1.11. You should read the migration guide. In this case the guide provides an example: &gt;&gt;&gt; D = nx.DiGraph() &gt;&gt;&gt; D.add_edges_from([(1, 2), (2, 3), (1, 3), (2, 4)]) &gt;&gt;&gt; D.nodes NodeView((1, 2, 3, 4)) &gt;&gt;&gt; list(D.nodes) [1, 2, 3, 4] &gt;&gt;&gt; D.edges OutEdgeView([(1, 2), (1, 3), (2, 3), (2, 4)]) &gt;&gt;&gt; list(D.edges) [(1, 2), (1, 3), (2, 3), (2, 4)] In general if you need to convert X to a list, you use list(X). This works for your case where you've used data=True as well.
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47415317

http://stackoverflow.com/comment/129215812
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47530508
has text: **voting to close due to a typo**. you're missing a C: `TM_CCOEFF`
score: 0

http://stackoverflow.com/comment/81838721
comment on: http://stackoverflow.com/a/47415654
type: Comment
has text: QtWidgets is a sub-package within PyQt5, QWidget is the basic widget of all pyqt.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81797454
type: QuestionComment
has text: The credentials you are supplying to put_object are not correct. I can't see the code that calls put_object but I would guess that either you are accidentally overriding the credentials that the Lambda function would intrinsically have, or perhaps you are attempting to write to a bucket that is not actually owned by the account for which the credentials have been presented.
type: Comment
comment on: http://stackoverflow.com/q/47418067
score: 0

http://stackoverflow.com/a/47422997
has comment: http://stackoverflow.com/comment/95539257
has comment: http://stackoverflow.com/comment/95640339
type: Answer
answers question: http://stackoverflow.com/q/47419943
has body: You need utf8mb4, not utf8, when connecting to MySQL and in the columns involved. More python tips: http://mysql.rjweb.org/doc.php/charcoll#python (Except use utf8mb4 in place of utf8. UTF-8 should not be changed.) A more detailed explanation to this can be found here.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47419943
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/81822028
has comment: http://stackoverflow.com/comment/95640554
upvote count: 13
has comment: http://stackoverflow.com/comment/95640514
has comment: http://stackoverflow.com/comment/95551761

http://stackoverflow.com/comment/81731816
comment on: http://stackoverflow.com/q/47389207
has text: Well it's now saved on disk as a pdf - what do you want to do with it?
type: Comment
score: 0
type: QuestionComment

scikit-learn
tags question: http://stackoverflow.com/q/47521872
tags question: http://stackoverflow.com/q/47480836
tags question: http://stackoverflow.com/q/47407996
tags question: http://stackoverflow.com/q/47403696
tags question: http://stackoverflow.com/q/47477043
tags question: http://stackoverflow.com/q/47434224
tags question: http://stackoverflow.com/q/47468627
tags question: http://stackoverflow.com/q/47509303
tag name: scikit-learn
tags question: http://stackoverflow.com/q/47393845
tags question: http://stackoverflow.com/q/47503575
tags question: http://stackoverflow.com/q/47387727
tags question: http://stackoverflow.com/q/47484481
tags question: http://stackoverflow.com/q/47529887
tags question: http://stackoverflow.com/q/47416721
tags question: http://stackoverflow.com/q/47394462
tags question: http://stackoverflow.com/q/47476209
tags question: http://stackoverflow.com/q/47463262
tags question: http://stackoverflow.com/q/47425356
tags question: http://stackoverflow.com/q/47510135
tags question: http://stackoverflow.com/q/47483215
tags question: http://stackoverflow.com/q/47477942
tags question: http://stackoverflow.com/q/47393060
type: Tag
tags question: http://stackoverflow.com/q/47455454
tags question: http://stackoverflow.com/q/47514568
tags question: http://stackoverflow.com/q/47464939
tags question: http://stackoverflow.com/q/47431117
tags question: http://stackoverflow.com/q/47431306
tags question: http://stackoverflow.com/q/47425872
tags question: http://stackoverflow.com/q/47385781
tags question: http://stackoverflow.com/q/47383696
tags question: http://stackoverflow.com/q/47423854
tags question: http://stackoverflow.com/q/47536157
tags question: http://stackoverflow.com/q/47464067
tags question: http://stackoverflow.com/q/47424458
tags question: http://stackoverflow.com/q/47522045
tags question: http://stackoverflow.com/q/47527330
tags question: http://stackoverflow.com/q/47499142
tags question: http://stackoverflow.com/q/47488774
tags question: http://stackoverflow.com/q/47416982
tags question: http://stackoverflow.com/q/47438750
tags question: http://stackoverflow.com/q/47414819
tags question: http://stackoverflow.com/q/47452119
tags question: http://stackoverflow.com/q/47460201
tags question: http://stackoverflow.com/q/47441896
tags question: http://stackoverflow.com/q/47433031
tags question: http://stackoverflow.com/q/47525609
tags question: http://stackoverflow.com/q/47421731
tags question: http://stackoverflow.com/q/47397337
tags question: http://stackoverflow.com/q/47489705
tags question: http://stackoverflow.com/q/47418063
tags question: http://stackoverflow.com/q/47426909
tags question: http://stackoverflow.com/q/47450804
tags question: http://stackoverflow.com/q/47390313
tags question: http://stackoverflow.com/q/47431661
tags question: http://stackoverflow.com/q/47389499
tags question: http://stackoverflow.com/q/47477728
tags question: http://stackoverflow.com/q/47403693
tags question: http://stackoverflow.com/q/47390514
tags question: http://stackoverflow.com/q/47490494
tags question: http://stackoverflow.com/q/47437398
tags question: http://stackoverflow.com/q/47438313
tags question: http://stackoverflow.com/q/47481880
tags question: http://stackoverflow.com/q/47455156
tags question: http://stackoverflow.com/q/47444608
tags question: http://stackoverflow.com/q/47463987
tags question: http://stackoverflow.com/q/47399350
tags question: http://stackoverflow.com/q/47452166

http://stackoverflow.com/comment/81866871
type: Comment
comment on: http://stackoverflow.com/q/47454282
score: 0
type: QuestionComment
has text: Your code looks fine. I think you'll need to add more information about how to reproduce the problem.

http://stackoverflow.com/comment/81805892
has text: And do something like `re.sub('( ).*?( )',r"\1" + new_text + r"\2", text_msg, flags=re.DOTALL)` so the div tags don't get cut off from the final string.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47425374
type: QuestionComment

http://stackoverflow.com/comment/81870980
type: Comment
comment on: http://stackoverflow.com/a/47447191
score: 0
type: AnswerComment
has text: @user8817477 `username, password1, email` thess three should not in the `fields` because they not in `NewUser`, you can add them in `RegisterForm ` fields.

http://stackoverflow.com/q/47475976
tagged with: opencv
has comment: http://stackoverflow.com/comment/81907020
has comment: http://stackoverflow.com/comment/81907435
has comment: http://stackoverflow.com/comment/81906525
tagged with: python
tagged with: alignment
has comment: http://stackoverflow.com/comment/81907398
type: AnsweredQuestion
has body: I want to perform face aligment in a sequence of frames from video. I am using itraface face detector tracker which tracks points of interest in the face. Those points ca be found here: What I want to is to rotate (using Python code). My question is if there is a way to calculate the rotate angle using the points from the eyes or the mouth (extreme right and left points of the eye or the mouth). How can I calculate that angle?
score: 0
has answer: http://stackoverflow.com/a/47476546
has title: Face alignment in video using python
answer count: 1
linked to: http://stackoverflow.com/q/36590516
accepted answer: http://stackoverflow.com/a/47476546
type: Question

http://stackoverflow.com/a/47467429
answers question: http://stackoverflow.com/q/47467249
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47467249
upvote count: 1
score: 1
type: Answer
has body: Use: cols = ['w1v1','w1v2','w2v1','w2v2'] test1 = (test'w1', 'w2', 'w1', 'w2' * test'v1', 'v1', 'v2', 'v2'.values) test1.columns = cols print (test1) w1v1 w1v2 w2v1 w2v2 0 1.0 8.0 0.3 2.4 1 6.0 2.0 1.2 0.4 2 3.0 3.0 0.2 0.2 3 3.5 10.5 0.6 1.8 4 2.0 0.5 0.0 0.0 5 3.0 1.0 0.6 0.2 6 6.0 0.0 0.0 0.0 df = test.join(test1).groupby('id').sum() df1 = df[cols] / df'w1', 'w2', 'w1', 'w2'.values print (df1) w1v1 w1v2 w2v1 w2v2 id 1 22.5 16.818182 4.5 3.818182 2 11.0 11.666667 1.8 2.000000 3 22.5 15.000000 0.5 1.000000 Another more dynamic solution with MultiIndex DataFrames: a = ['v1', 'v2'] b = ['w1', 'w2'] mux = pd.MultiIndex.from_product([a,b]) df1 = test.set_index('id').drop('d', axis=1) v = df1.reindex(columns=mux, level=0) w = df1.reindex(columns=mux, level=1) print (v) v1 v2 w1 w2 w1 w2 id 1 10 10 3 3 2 20 20 4 4 3 15 15 1 1 1 35 35 6 6 2 5 5 0 0 2 10 10 2 2 3 30 30 0 0 print (w) v1 v2 w1 w2 w1 w2 id 1 0.1 0.8 0.1 0.8 2 0.3 0.1 0.3 0.1 3 0.2 0.2 0.2 0.2 1 0.1 0.3 0.1 0.3 2 0.4 0.1 0.4 0.1 2 0.3 0.1 0.3 0.1 3 0.2 0.0 0.2 0.0 df = w * v print (df) v1 v2 w1 w2 w1 w2 id 1 1.0 8.0 0.3 2.4 2 6.0 2.0 1.2 0.4 3 3.0 3.0 0.2 0.2 1 3.5 10.5 0.6 1.8 2 2.0 0.5 0.0 0.0 2 3.0 1.0 0.6 0.2 3 6.0 0.0 0.0 0.0 df1 = df.groupby('id').sum() / w.groupby('id').sum() #flatten MultiIndex columns df1.columns = ['{0[1]}{0[0]}'.format(x) for x in df1.columns] print (df1) w1v1 w2v1 w1v2 w2v2 id 1 22.5 16.818182 4.5 3.818182 2 11.0 11.666667 1.8 2.000000 3 22.5 15.000000 0.5 1.000000

http://stackoverflow.com/q/47431178
has body: I'm actually writing an application for a BioTech laboratory. The idea is to prepare environments with preset list of products. There is also a need to handle the stock of products. I tried the following structure but I have no idea how to handle the presets... #models.py class Products(models.Model): nutrients = models.CharField(max_length=10) globalQuantity = models.FloatField() rcvdate = models.DateTimeField() user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) lot = models.CharField(max_length=50) class Environments(models.Model): lot = models.CharField(max_length=25, unique=True) date = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.SET_NULL) initvolume = models.FloatField() preparation = ? class Presets(models.Model): name = models.CharField(max_length=25) product = models.ForeignKey('products', on_delete=models.SET_NULL) quantity = models.FloatField() The idea is then to populate preset like following : 1. name = preset1 | product = NH4 | quantity = 50 2. name = preset1 | product = SO4 | quantity = 25 3. name = preset2 | product = NaCl | quantity = 40 4. name = preset2 | product = Mn | quantity = 30 Where a "recipe" (like preset1 and preset2) contains different products. It must be dynamic because users needs to be able to add "recipes" if they want. The problem is : " How to add a preparation to an environment using one preset defined in the class presets ? " The fields of a table are defined at beginning so how handle preparations which can be different following preset structure ?
type: AnsweredQuestion
has title: Django model datas as preset for creating other model
score: 0
has comment: http://stackoverflow.com/comment/81817827
has answer: http://stackoverflow.com/a/47431878
has comment: http://stackoverflow.com/comment/81816987
has comment: http://stackoverflow.com/comment/81818107
answer count: 1
type: Question
tagged with: foreign-keys
tagged with: database
tagged with: django
tagged with: django-models
tagged with: python
accepted answer: http://stackoverflow.com/a/47431878

http://stackoverflow.com/a/47514673
accepted answer of: http://stackoverflow.com/q/47514593
type: Answer
has comment: http://stackoverflow.com/comment/81985424
answers question: http://stackoverflow.com/q/47514593
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has body: A clean solution is to put a flag in your TTT object: class TTT(multiprocessing.Process): ... def run(self): self.running = True while self.running: t = Timer(5, self.doSomething) t.start() t.join() def doSomething(self): try: raise Exception('a','b') except Exception as e: print(e) self.running = False Non-clean solution is to simply sys.exit(1) in your exception handler. It is not clean because now your doSomething function becomes the master of the process. What if something else needs cleaning up? Don't do that. I'm putting it here just for academic purposes.
has comment: http://stackoverflow.com/comment/81985584
has comment: http://stackoverflow.com/comment/81985091

http://stackoverflow.com/q/47527122
tagged with: loops
tagged with: string
has answer: http://stackoverflow.com/a/47527265
type: Question
has answer: http://stackoverflow.com/a/47527486
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82010258
has body: I have a large py script and at the beginning of it I have to enter a variable. For example: year = "2015" # yellow red orange pink color= "yellow" in_folder = r"E:/test/" + year + "/03_lines/" + color ... Instead of running the script manually for each of the color, I would like to have a loop doing it automatically for me. But since I am new with python, I really don´t know how to deal with it. If I create a string color= ['yellow', 'red', 'orange', 'pink'] and I loop for i in color:, should it be ok? Thanks!
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82010320
has title: looping script over factors

http://stackoverflow.com/comment/81978137
has text: ya tried that too but getting 1 for all the NaN fields
comment on: http://stackoverflow.com/a/47511103
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47495775
downvote count: 0
has title: Flask render_template with function return
has comment: http://stackoverflow.com/comment/81946708
answer count: 1
has body: I recently working on Flask. And i have a problem with it. My script looks like this: @app.route('/') def index(): // execute return render_template('index.html', body=body, block=block) @app.route('/api/') def api(): // execute return 'api' function api and index do exactly same thing. What I think is to create a function that both page can call, and represent same thing. Is there a possible way to achive that?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47495864
accepted answer: http://stackoverflow.com/a/47495864
tagged with: python
tagged with: flask
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/comment/81821009
comment on: http://stackoverflow.com/a/47431426
score: 1
type: Comment
has text: The phrase "remove one by one" indicates a STATIC CONTENT . STATIC CONTENT = FILE
type: AnswerComment

http://stackoverflow.com/q/47439829
has comment: http://stackoverflow.com/comment/81834472
upvote count: 0
has title: How to print a work in string containing specific characters
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47440218
downvote count: 5
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/47440218
has body: For this string: string ='fieldnameRelated_actions/fieldnamedatatypeRESOURCE_LIST&lt;/datatype&gt;&lt;values&gt;&lt;value&gt;![CDATA[nprod00123456]/value&gt;value&gt;![CDATA[nprod00765432]]/valuevaluesfield' I want to print nprod00123456 and nprod00765432 or word like: nprodxxxxxxxx How can this be done in Python?
type: AnsweredQuestion
tagged with: python-2.7
score: -5

http://stackoverflow.com/q/47449818
tagged with: language-agnostic
tagged with: sorting
has comment: http://stackoverflow.com/comment/81854453
has answer: http://stackoverflow.com/a/47450796
has answer: http://stackoverflow.com/a/47450077
answer count: 4
has body: I have to create algorithm for merging sorted arrays. Here is what I did: import sys lists = [[1,2,3], [-100, 70], [23, 50]] pivot = [0] * len(lists) # [0, 0, 0] finalSorted = [] for _ in range(sum(len(x) for x in lists)): # quantity of items in 2D array smallest = sys.maxint index_of_smallest = -1 for indx, list in enumerate(lists): if pivot[indx] &lt; len(list): current = list[pivot[indx]] if current &lt;= smallest: smallest = current index_of_smallest = indx finalSorted.append(smallest) pivot[index_of_smallest] = pivot[index_of_smallest]+1 print(finalSorted) #[-100, 1, 2, 3, 23, 50, 70] Questions: Is this the best way of doing this? Is algorithmic complexity kn^2? Where 'k' is average array length and n is quantity of arrays. Is it good only for cases where k is much bigger then n? Where is the point of such k and n having which quicksort here become better solution?
type: AnsweredQuestion
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47451086
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47450094
has answer: http://stackoverflow.com/a/47450094
tagged with: algorithm
tagged with: arrays
has title: Merge sorted arrays algorithm
has comment: http://stackoverflow.com/comment/81854645
accepted answer: http://stackoverflow.com/a/47450077
tagged with: python

http://stackoverflow.com/q/47488774
tagged with: scikit-learn
type: Question
score: 0
tagged with: out-of-memory
has comment: http://stackoverflow.com/comment/81953102
has comment: http://stackoverflow.com/comment/81949925
tagged with: python
tagged with: svm
has comment: http://stackoverflow.com/comment/81936010
has body: I am training a SVM with a big data set containing 93 features and 61878 training examples. As I don't want to plot such a big data set, I'm extracting 40 random samples to train another SVM to visualize it. But I am getting a MEMORY ERROR in the clf.predict() function in the contour plot function. My code: import numpy as np from numpy import random from matplotlib import cm from sklearn.svm import SVC import matplotlib.pyplot as plt import matplotlib.axes as ax import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score #Making the meshgrid def make_meshgrid(x, y, h=.02): x_min, x_max = x.min() - 1, x.max() + 1 y_min, y_max = y.min() - 1, y.max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h),copy=False) return xx, yy #plotting the decision contour def plot_contours(ax, clf, xx, yy, **params): Z = clf.predict(np.c_[xx.ravel(),yy.ravel()]) Z = Z.reshape(xx.shape) out = ax.contourf(xx, yy, Z, **params) return out #extracting data from csv file f1 = open('train.csv', 'r') train_data = pd.read_csv(f1) train_arr = np.array(train_data) X = np.array(train_arr[:, :-1]) y = np.array(train_arr[:, 94]) X_train, X_cv, y_train, y_cv = train_test_split(X, y, test_size=0.3); print('Printing cross validation data.....') print(X_cv) print(y_cv) clf = SVC(C=1, kernel='poly', gamma='auto') clf.fit(X_train, y_train) print('Cross validation score:', clf.score(X_cv, y_cv)) print('Cross validation prediction:') res = clf.predict(X_cv) print(res) print('Cross validation accuracy score:', accuracy_score(y_cv, res, normalize=True)) f2 = open('test.csv', 'r') test_data = pd.read_csv(f2) test_arr = np.array(test_data) print('Test data prediction:') y_res = clf.predict(test_arr) print(y_res) #plotting part of the data by taking random 40 rows to reduce the data set plot_arr=[] for i in range(0,39): j = random.randint(0,61878) plot_arr.append(train_arr[j,:]) parr = np.asarray(plot_arr) X_plot = parr[:,:-1]…
has title: memory error using predict function in sklearn svm
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81949679
tagged with: machine-learning

http://stackoverflow.com/a/47504202
downvote count: 0
upvote count: 1
has body: echo is a function that takes a parameter n and returns another function that closes over the supplied value of n and also takes an argument word1. In other words, calling echo(n) for some n returns a function which is then called with twice(word1) The flow is essentially. echo = function (n) -&gt; function (word1) with closure (n) -&gt; word1 repeated n times twice = echo (2) -&gt; function (word1) with closure (n = 2) -&gt; word1 repeated 2 times twice('hello') -&gt; 'hello' repeated 2 times I have described it in the above manner because, AFAICT Python does not have a syntax for expressing the types of functions.
type: Answer
accepted answer of: http://stackoverflow.com/q/47504144
answers question: http://stackoverflow.com/q/47504144
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81771762
type: Comment
has text: @Ev.Kounis *Applicability to other programmers* is a big criterion for SO questions. Will this question ever be applicable to anyone else? Will anyone else ever *find* this problem given the title and terse description? … Probably not. → Downvote. → Lower visibility in searches. → Better discoverability of good content.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47408984

http://stackoverflow.com/comment/81877465
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47460947
has text: I've also added a recommendation on the scene management. Actually I'd use classes as in [this example](https://www.reddit.com/r/pygame/comments/3kghhj/simple_state_machine_example/).

http://stackoverflow.com/comment/81823717
comment on: http://stackoverflow.com/q/47434658
score: 0
type: QuestionComment
has text: I haven't actually gone all the way through the loopy solution - working on it now. But yes seems like there would be a nice solution?
type: Comment

http://stackoverflow.com/comment/81737496
score: 0
type: AnswerComment
has text: @alkopop79 You should have changed either of them, *not* both. Please update your question to include your most recent code and the most recent error you are getting. **Also** make sure the name of your script is not daemon.py by any chance.
comment on: http://stackoverflow.com/a/47391552
type: Comment

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

http://stackoverflow.com/comment/81884269
has text: see my edit, problems arise when there are values of 10 or greater.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47464563
type: Comment

http://stackoverflow.com/q/47400357
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81754470
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81754917
tagged with: prediction
has comment: http://stackoverflow.com/comment/81755171
has comment: http://stackoverflow.com/comment/81754552
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/47465909
tagged with: python
has answer: http://stackoverflow.com/a/47465909
has title: Which model can I apply, confused between applying models
type: AnsweredQuestion
score: 0
has body: Below are the 3 columns I have in my data-set can anyone guide me on applying any models for the below. So I would probably want to predict region based on country and variety column. I am completely new towards this and would appreciate if someone could suggest me or guide me on applying model's col1(country) col2(variety) col3(region) Argentina Chasselas r1 Israel Gamay r2 Mexico Grenache r3 Chile Kalecik Karasi r4 China Kallmet r5 I am trying something known as DecisionTreeClassifier, but would be happy if someone gives me other ideas over this
answer count: 1

http://stackoverflow.com/comment/81976919
has text: Post your code as text, not as picture!
comment on: http://stackoverflow.com/q/47510614
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81854381
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47446535
type: Comment
has text: contract_instance.setLog('tlatk', '12', 'product',transact={'from': w3.eth.coinbase,'gas':3000000})) this code is not work so return value is ''

http://stackoverflow.com/comment/81845298
type: QuestionComment
has text: You could create an equivalent example with far less code and data. See how to create a [mcve]. Creating the example might help you understand the problem.
comment on: http://stackoverflow.com/q/47414418
score: 0
type: Comment

http://stackoverflow.com/comment/81779042
has text: Because there are different columns names. If change `df2=pd.DataFrame(np.random.randn(6,1),index=list("ABCDEF"), columns=['X'])` and then `print(df1 * df2)` it only match column `X` with `X`. But if need multiple all columns need `Series` from column.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47412567
type: Comment

http://stackoverflow.com/q/47390661
score: 1
answer count: 1
downvote count: 0
has title: How to deal with the product between matrix [None, 32, 32] and matrix [32, 32] with `tf.matmul`?
upvote count: 1
has comment: http://stackoverflow.com/comment/81763684
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81752305
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
tagged with: python-2.7
has body: Before building a DNN model, I need to have the product of two matrixes: [None, 32, 32] and [32, 32] Since I know that this method works (from the example of MNIST) x = tf.placeholder("float", shape=[None, 784]) W = tf.Variable(tf.zeros([784,10])) l = tf.matmul(x, W) I try this one on my question x = tf.placeholder(tf.float32, shape = [None, 64, 64]) w = t.Variable(tf.random_normal([64, 64], 0, 0.3)) l = tf.matmul(x, w) But it is wrong. -- I know that if w = t.Variable(tf.random_normal([constant, 64, 64], 0, 0.3)), this product could work. But I need the w to be the two-dimension matrix [64, 64]. Could I have one method that makes this product between [None, 32, 32] and [32, 32] successful?
has answer: http://stackoverflow.com/a/47410031
tagged with: matrix

http://stackoverflow.com/comment/81986346
type: Comment
type: QuestionComment
has text: When you get to a resolution, please remember to up-vote useful things and accept your favourite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.
comment on: http://stackoverflow.com/q/47444914
score: 0

http://stackoverflow.com/comment/81960759
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47501953
has text: The problem is reconnecting. I've tried creating a function that calls `cv2.VideoCapture()`. That function would be called when there's nothing returned from `cap.read()` in `if not ret:`

http://stackoverflow.com/comment/81956051
score: 0
type: Comment
type: QuestionComment
has text: stop using IDLE, find other python shell, editor or IDE ;)
comment on: http://stackoverflow.com/q/47500289

http://stackoverflow.com/comment/82010845
type: Comment
comment on: http://stackoverflow.com/a/47512364
has text: Now it's working perfect. Do you know how can I get the data before when I click edit and not blank forms?
score: 0
type: AnswerComment

http://stackoverflow.com/a/47527663
type: Answer
has body: I have found the answer! I need to use 'firstfield__secondfield__thirdfield' for creating multiply samples in python. For my example inside of the problem description i should write: queryset_for_table.values('group__name') Maybe it will help someone there
answers question: http://stackoverflow.com/q/47416747
score: 0

http://stackoverflow.com/a/47490190
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47474155
answers question: http://stackoverflow.com/q/47474155
has body: Reasons for running out of memory: Image file size and the size of corresponding array in memory are different. Images, e.g., PNG and JPEG formats, are compressed. The size of a corresponding uncompressed BMP image is more relevant here. Also, ndarray holds some meta-information that makes it a bit larger. Converting to float32 from uint8 multiplies the size by 4. Try to avoid this if possible (I recognize uint8 imposes some limitations, like being unable to normalize and center the data). Possible remedies: Use numpy.memmap to create an array stored on disk Reduce the quality of images, by converting to grayscale and/or reducing the resolution. Train the model on a smaller number of images.

http://stackoverflow.com/comment/81917420
comment on: http://stackoverflow.com/a/47480733
score: 0
has text: thanks, getting SyntaxError: invalid character in identifier on line: df.groupby(['Year','Month'])['total_co‌​st'].agg([sum,np.mea‌​n,np.std])
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82036562
score: 1
type: Comment
type: QuestionComment
has text: then, for a simple start, just return what was sent: `conn.sendall(data)`.
comment on: http://stackoverflow.com/q/47539645

http://stackoverflow.com/comment/81814966
score: 0
comment on: http://stackoverflow.com/q/47429232
type: Comment
type: QuestionComment
has text: How do I use find_overlapping in this case? I don't quite understand how to use it.

http://stackoverflow.com/q/47484336
tagged with: python
linked to: http://stackoverflow.com/q/40433717
tagged with: python-2.7
answer count: 2
has title: How to find count of records per week of given month in django 1.11?
score: 0
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/47484408
type: Question
has answer: http://stackoverflow.com/a/47485328
has body: I need to count the number of records per week of given month. I got count per month of given year using query as below c = Cars.objects.filter(sold__year='2017').extra(select={'month':'extract(month from sold)'}).values('month').annotate(perMnth=Count('sold')) How to find count per week of given month, that is like week wise count of month 'November' , like week1=10, week2=12,week3=5,etc
tagged with: postgresql
tagged with: django-1.11

pyqt5
tags question: http://stackoverflow.com/q/47517925
tags question: http://stackoverflow.com/q/47481370
tags question: http://stackoverflow.com/q/47529509
tags question: http://stackoverflow.com/q/47438663
type: Tag
tags question: http://stackoverflow.com/q/47481929
tags question: http://stackoverflow.com/q/47438832
tags question: http://stackoverflow.com/q/47392881
tags question: http://stackoverflow.com/q/47532133
tags question: http://stackoverflow.com/q/47452303
tags question: http://stackoverflow.com/q/47532153
tags question: http://stackoverflow.com/q/47502885
tags question: http://stackoverflow.com/q/47393597
tags question: http://stackoverflow.com/q/47455452
tags question: http://stackoverflow.com/q/47448063
tags question: http://stackoverflow.com/q/47401311
tags question: http://stackoverflow.com/q/47513816
tags question: http://stackoverflow.com/q/47462352
tags question: http://stackoverflow.com/q/47395529
tags question: http://stackoverflow.com/q/47482998
tags question: http://stackoverflow.com/q/47513314
tags question: http://stackoverflow.com/q/47475224
tags question: http://stackoverflow.com/q/47393609
tags question: http://stackoverflow.com/q/47405395
tag name: pyqt5
tags question: http://stackoverflow.com/q/47494200
tags question: http://stackoverflow.com/q/47486151
tags question: http://stackoverflow.com/q/47520966
tags question: http://stackoverflow.com/q/47384116
tags question: http://stackoverflow.com/q/47417913
tags question: http://stackoverflow.com/q/47417354
tags question: http://stackoverflow.com/q/47535867
tags question: http://stackoverflow.com/q/47454317

arrays
tags question: http://stackoverflow.com/q/47522302
tags question: http://stackoverflow.com/q/47514987
tag name: arrays
tags question: http://stackoverflow.com/q/47413756
tags question: http://stackoverflow.com/q/47525815
tags question: http://stackoverflow.com/q/47526519
tags question: http://stackoverflow.com/q/47460835
tags question: http://stackoverflow.com/q/47447955
tags question: http://stackoverflow.com/q/47475331
tags question: http://stackoverflow.com/q/47513326
tags question: http://stackoverflow.com/q/47531797
tags question: http://stackoverflow.com/q/47433987
tags question: http://stackoverflow.com/q/47413640
tags question: http://stackoverflow.com/q/47538283
tags question: http://stackoverflow.com/q/47442115
tags question: http://stackoverflow.com/q/47409940
tags question: http://stackoverflow.com/q/47538605
tags question: http://stackoverflow.com/q/47419345
tags question: http://stackoverflow.com/q/47483215
tags question: http://stackoverflow.com/q/47449818
tags question: http://stackoverflow.com/q/47446284
tags question: http://stackoverflow.com/q/47496949
tags question: http://stackoverflow.com/q/47424407
type: Tag
tags question: http://stackoverflow.com/q/47393115
tags question: http://stackoverflow.com/q/47460105
tags question: http://stackoverflow.com/q/47430784
tags question: http://stackoverflow.com/q/47484539
tags question: http://stackoverflow.com/q/47488506
tags question: http://stackoverflow.com/q/47502527
tags question: http://stackoverflow.com/q/47523386
tags question: http://stackoverflow.com/q/47437481
tags question: http://stackoverflow.com/q/47442741
tags question: http://stackoverflow.com/q/47464747
tags question: http://stackoverflow.com/q/47426375
tags question: http://stackoverflow.com/q/47423529
tags question: http://stackoverflow.com/q/47456055
tags question: http://stackoverflow.com/q/47538996
tags question: http://stackoverflow.com/q/47402505
tags question: http://stackoverflow.com/q/47531584
tags question: http://stackoverflow.com/q/47480221
tags question: http://stackoverflow.com/q/47396893
tags question: http://stackoverflow.com/q/47462798
tags question: http://stackoverflow.com/q/47388013
tags question: http://stackoverflow.com/q/47510820
tags question: http://stackoverflow.com/q/47399561
tags question: http://stackoverflow.com/q/47385950
tags question: http://stackoverflow.com/q/47476926
tags question: http://stackoverflow.com/q/47404516
tags question: http://stackoverflow.com/q/47393056
tags question: http://stackoverflow.com/q/47398441
tags question: http://stackoverflow.com/q/47515454
tags question: http://stackoverflow.com/q/47497846
tags question: http://stackoverflow.com/q/47480701
tags question: http://stackoverflow.com/q/47405541
tags question: http://stackoverflow.com/q/47393362
tags question: http://stackoverflow.com/q/47493409
tags question: http://stackoverflow.com/q/47464676
tags question: http://stackoverflow.com/q/47474140
tags question: http://stackoverflow.com/q/47420298
tags question: http://stackoverflow.com/q/47443293
tags question: http://stackoverflow.com/q/47384440
tags question: http://stackoverflow.com/q/47520590
tags question: http://stackoverflow.com/q/47498619
tags question: http://stackoverflow.com/q/47483579
tags question: http://stackoverflow.com/q/47506716
tags question: http://stackoverflow.com/q/47516286
tags question: http://stackoverflow.com/q/47478047
tags question: http://stackoverflow.com/q/47408448
tags question: http://stackoverflow.com/q/47485692
tags question: http://stackoverflow.com/q/47421930
tags question: http://stackoverflow.com/q/47504706
tags question: http://stackoverflow.com/q/47445588
tags question: http://stackoverflow.com/q/47466040
tags question: http://stackoverflow.com/q/47522329
tags question: http://stackoverflow.com/q/47523488
tags question: http://stackoverflow.com/q/47538247
tags question: http://stackoverflow.com/q/47389601
tags question: http://stackoverflow.com/q/47496868
tags question: http://stackoverflow.com/q/47462664

http://stackoverflow.com/q/47437488
has answer: http://stackoverflow.com/a/55179682
accepted answer: http://stackoverflow.com/a/47438771
has comment: http://stackoverflow.com/comment/81829579
tagged with: python
has title: Extracting Old Tweets using Twitter streaming API using Geo-Location Filter
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47438771
answer count: 2
has body: My aim is to extract old tweets for the entire month of Jan 2017 for New York City ('locations':'-74,40,-73,41') using python. I am able to get the live streaming tweets using the following code: import json import pandas as pd import numpy as np from TwitterAPI import TwitterAPI #Set up the variables for the 'application' consumerkey = 'cfKguErYawo2WB7cfNtAT2lKl' consumersecret = 'my_consumer_secret' access_token_key = '2195434704-Wov69oF2iIBRgUjWJhD0KThqcLApYCJXqtbYI4K' access_token_secret = 'my_access_token_secret' #Setup the API key api = TwitterAPI(consumerkey,consumersecret,access_token_key,access_token_secret) # Breaking after extracting 10 live tweets from New York City r = api.request('statuses/filter', {'locations':'-74,40,-73,41'}) for row,item in enumerate(r): print(row, item['text']) if row &gt;= 10: break But this is not what I am looking for. Can someone suggest how to extract the old tweets for this location filter using Twitter streaming API or any other package in python? Thanks!
possible better answer: http://stackoverflow.com/a/55179682
tagged with: python-requests
tagged with: twitter-streaming-api
tagged with: twitter-rest-api
type: Question

http://stackoverflow.com/comment/81871252
comment on: http://stackoverflow.com/a/47458192
score: 0
type: Comment
has text: @Wen: To get the format button back, you may need to remove your browser cache. On firefox, go to `History > Clear Recent History`. Then when you reload the SO page, the correct auxiliary files will be reloaded.
type: AnswerComment

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

http://stackoverflow.com/q/47393978
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/47394144
possible better answer: http://stackoverflow.com/a/47394144
has answer: http://stackoverflow.com/a/47395174
favorite count: 0
type: Question
has body: I am looking for a smarter solution to do what my code does. I have to explore a text file. There are many Materials inside this text, and I want to change some material properties by replacing these values with new ones. This is the Material structure: Material, PLASTERBOARD-1, !- Name MediumSmooth, !- Roughness 0.01200, !- Thickness {m} 0.16000, !- Conductivity {W/m-K} 950.000, !- Density {kg/m3} 840.00, !- Specific Heat {J/kg-K} 0.900000, !- Thermal Absorptance 0.600000, !- Solar Absorptance 0.600000; !- Visible Absorptance This is my actual code: from tempfile import mkstemp from shutil import move from os import fdopen, remove def update_capacity(idf_file_path, material, capacity): check = False #Create temp file fh, abs_path = mkstemp() with fdopen(fh,'w') as new_file: with open(idf_file_path) as old_file: for line in old_file: if material in line: check = True if check: if '!- Conductivity {W/m-K}' in line: line = ' '+str(capacity)+ ',' i = 26 - len(str(capacity)) while(i&gt;0): line +=' ' i-=1 line += '!- Conductivity {W/m-K}\n' line.strip('(') check= False new_file.write(line) #Remove original file old_file.close() new_file.close() remove(idf_file_path) #Move new file move(abs_path, idf_file_path) return idf_file_path mat = 'FIBERGLASS QUILT-1' cap = 2,0 idf_file = 'D:\\users\\f35943c\\Downloads\\Exercise1A.idf' update_capacity(idf_file, mat, cap) From if material in line to new_file.write(line) is where I want to optimize my code. Furthermore, strip does not work as I wanted, because I can't remove the parenthesis inside the line. This is my benchmark string " 0.16000, !- Conductivity {W/m-K}" and I have to respect the numbers of characters before the !- Conductivity {W/m-K} Can someone bring me to a smarter solution?
tagged with: python
tagged with: formatting
has title: Python: change something inside a string respecting length constrains
accepted answer: http://stackoverflow.com/a/47395174
tagged with: replace
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81741059
answer count: 2
has comment: http://stackoverflow.com/comment/81741144

http://stackoverflow.com/q/47437893
has comment: http://stackoverflow.com/comment/81831822
upvote count: 5
has comment: http://stackoverflow.com/comment/81830798
tagged with: logistic-regression
accepted answer: http://stackoverflow.com/a/47445963
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47445963
has answer: http://stackoverflow.com/a/47448337
score: 5
has comment: http://stackoverflow.com/comment/81843778
downvote count: 0
has answer: http://stackoverflow.com/a/68669926
has answer: http://stackoverflow.com/a/56892752
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/81835906
favorite count: 0
has body: I am a complete beginner in machine learning and coding in python, and I have been tasked with coding logistic regression from scratch to understand what happens under the hood. So far I have coded for the hypothesis function, cost function and gradient descent, and then coded for the logistic regression. However on coding for printing the accuracy I get a low output (0.69) which doesnt change with increasing iterations or changing the learning rate. My question is, is there a problem with my accuracy code below? Any help pointing to the right direction would be appreciated X = data[['radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean', 'compactness_mean', 'concavity_mean', 'concave points_mean', 'symmetry_mean', 'fractal_dimension_mean', 'radius_se', 'texture_se', 'perimeter_se', 'area_se', 'smoothness_se', 'compactness_se', 'concavity_se', 'concave points_se', 'symmetry_se', 'fractal_dimension_se', 'radius_worst', 'texture_worst', 'perimeter_worst', 'area_worst', 'smoothness_worst', 'compactness_worst', 'concavity_worst', 'concave points_worst', 'symmetry_worst', 'fractal_dimension_worst']] X = np.array(X) X = min_max_scaler.fit_transform(X) Y = data["diagnosis"].map({'M':1,'B':0}) Y = np.array(Y) X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.25) X = data["diagnosis"].map(lambda x: float(x)) def Sigmoid(z): if z &lt; 0: return 1 - 1/(1 + math.exp(z)) else: return 1/(1 + math.exp(-z)) def Hypothesis(theta, x): z = 0 for i in range(len(theta)): z += x[i]*theta[i] return Sigmoid(z) def Cost_Function(X,Y,theta,m): sumOfErrors = 0 for i in range(m): xi = X[i] hi = Hypothesis(theta,xi) error = Y[i] * math.log(hi if hi &gt;0 else 1) if Y[i] == 1: error = Y[i] * math.log(hi if hi &gt;0 else 1) elif Y[i] == 0: error = (1-Y[i]) * math.log(1-hi if 1-hi &gt;0 else 1) sumOfErrors += error constant = -1/m J = constant * sumOfErrors #print ('cost is: ', J ) return J def Cost_Function_Derivative(X,Y,theta,j,m,alpha): sumErrors = 0 for…
type: Question
possible better answer: http://stackoverflow.com/a/56892752
has title: How to calculate logistic regression accuracy

http://stackoverflow.com/comment/81971621
type: Comment
type: QuestionComment
has text: Please fix your indentation. In python it is very relevant how much each line of code is indented!
score: 0
comment on: http://stackoverflow.com/q/47507832

http://stackoverflow.com/comment/81824323
comment on: http://stackoverflow.com/q/47434428
score: 0
has text: It's impossible to debug without having your xml file, but you maight have a BOM at the beginning of your file. Microsoft is notably (in)famous for insisting on putting useless BOM on all utf-8 files. You can check the first three characters of your file for the `codecs.BOM_UTF8` sequence (`'\xef\xbb\xbf'`) and strip it out if it's there.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47384107
tagged with: python
has answer: http://stackoverflow.com/a/47384491
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81721505
has answer: http://stackoverflow.com/a/66513637
has comment: http://stackoverflow.com/comment/81735620
type: Question
answer count: 2
has title: Matplotlib FuncAnimation not plotting x-axis in order
type: UnansweredQuestion
has body: I'm trying to grab data from a text file and plot it using the animation.FuncAnimation module from matplotlib. Here is my code that I'm trying to make run correctly import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style style.use('ggplot') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) def animate(i): graph_data = open('example.txt', 'r').read() lines = graph_data.split('\n') xs = [] ys = [] for line in lines: x,y = line.split(',') xs.append(x) ys.append(y) ax1.clear() ax1.plot(xs, ys) animation.FuncAnimation(fig, animate, interval=1000) plt.show() example.txt is an 18-line text file (omitted for space reasons) which contain (x,y) pairs of data which I'd like to plot. However, matplotlib is not plotting the x values in order: once they reach 10, they 'wrap around' back to the beginning, sandwiching themselves between 1 and 2. Makes for a pretty bad graph. I'm having some trouble figuring out what's wrong with my implementation. I've even tried sorting the values before plotting them, but the plot still comes out like this. All help is appreciated! I've been scouring doc pages and StackOverflow for a while now, and I can't seem to find anyone whose had this same problem.

http://stackoverflow.com/a/47441756
answers question: http://stackoverflow.com/q/47441717
type: Answer
has body: Convert the column to a list of dicts using tolist, create a new dataframe by calling the constructor. v = pd.DataFrame(df.assigned_to.tolist()) v display_value link 0 Michael http://www.testlink.com 1 Vinod http://www.testlink.com 2 Vinod http://www.testlink.com 3 Carrie http://www.testlink.com 4 Carrie http://www.testlink.com You can now concatenate the new columns to the original using pd.concat: pd.concat([v, df], 1) display_value link \ 0 Michael http://www.testlink.com 1 Vinod http://www.testlink.com 2 Vinod http://www.testlink.com 3 Carrie http://www.testlink.com 4 Carrie http://www.testlink.com assigned_to 0 {'link': 'http://www.testlink.com', 'display_v... 1 {'link': 'http://www.testlink.com', 'display_v... 2 {'link': 'http://www.testlink.com', 'display_v... 3 {'link': 'http://www.testlink.com', 'display_v... 4 {'link': 'http://www.testlink.com', 'display_v... Timings df = pd.concat([df] * 10000) df = df.reset_index(drop=1) %%timeit v = pd.DataFrame(df.assigned_to.tolist()) pd.concat([v, df], 1) 10 loops, best of 3: 58.7 ms per loop %timeit df.assigned_to.apply(pd.Series) 1 loop, best of 3: 17.5 s per loop
has comment: http://stackoverflow.com/comment/81839103
has comment: http://stackoverflow.com/comment/81839137
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/47499434
answers question: http://stackoverflow.com/q/47499284
score: 0
has comment: http://stackoverflow.com/comment/82012272
has body: w = tf.Variable(tf.truncated_normal(forme, stddev=(2/n)**.5)) # poid forme appears to be a complex number, on the lines above and below that you're referencing forme[0], which I presume is the real part of the complex number. Whereas on the line shown above forme is referenced without the index to the real part of the number. Did you want: w = tf.Variable(tf.truncated_normal(forme[0], stddev=(2/n)**.5)) # poid If not, print out the value of forme and verify that it is what you expect it to be. If you didn't mean for it to be a complex number, track down that issue.
type: Answer
has comment: http://stackoverflow.com/comment/82031738
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47499284

http://stackoverflow.com/comment/81963100
comment on: http://stackoverflow.com/q/47503396
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ, in this case, it is setting a value to a new column. I am determining if it is higher, lower or equal to the previous value and labeling it accordingly.
score: 0

http://stackoverflow.com/a/47510424
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47510207
has comment: http://stackoverflow.com/comment/81977209
has comment: http://stackoverflow.com/comment/81977104
has comment: http://stackoverflow.com/comment/81977532
downvote count: 0
has comment: http://stackoverflow.com/comment/81976714
has body: Approach #1 : Here's a NumPy solution using justify - pd.DataFrame(justify(df.values, invalid_val=np.nan, axis=1, side='left')[:,:4]) Sample run - In [211]: df Out[211]: Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Index 1991-12-31 100.0 100.000 100.000 89.123 NaN NaN NaN NaN 1992-01-31 98.3 101.530 100.000 NaN 92.342 NaN NaN NaN 1992-02-29 NaN 100.230 98.713 97.602 NaN NaN NaN NaN 1992-03-31 NaN NaN 102.060 93.473 98.123 NaN NaN NaN 1992-04-30 NaN 102.205 107.755 94.529 94.529 NaN NaN NaN In [212]: pd.DataFrame(justify(df.values, invalid_val=np.nan, axis=1, side='left')[:,:4]) Out[212]: 0 1 2 3 0 100.000 100.000 100.000 89.123 1 98.300 101.530 100.000 92.342 2 100.230 98.713 97.602 NaN 3 102.060 93.473 98.123 NaN 4 102.205 107.755 94.529 94.529 Approach #2 : Using tailor-made function for masks - def app2(df, N=4): a = df.values out = np.empty_like(a) mask = df.isnull().values mask_sorted = np.sort(mask,1) out[~mask_sorted] = a[~mask] return pd.DataFrame(out[:,:N]) Runtime test for working solutions that keep order - # Using df from posted question to recreate a bigger one : df = df.set_index('Index') df = pd.concat([df] * 10000, ignore_index=1) In [298]: %timeit app2(df) 100 loops, best of 3: 4.06 ms per loop In [299]: %timeit pd.DataFrame(justify(df.values, invalid_val=np.nan, axis=1, side='left')[:,:4]) 100 loops, best of 3: 4.78 ms per loop In [300]: %timeit df.apply(sorted, key=np.isnan, axis=1).iloc[:, :4] 1 loop, best of 3: 4.05 s per loop
has comment: http://stackoverflow.com/comment/81976394
score: 5
has comment: http://stackoverflow.com/comment/81977086

http://stackoverflow.com/q/47414418
favorite count: 0
score: 2
has body: How can I get the 7th record by using the below code? from pprint import pprint def date_op(total_input_list): total_pages=36 list=[] for xy in total_input_list: for i in range(1,len(xy)): Start_page=xy[i]["start_page"] End_page=xy[i+1]["start_page"]-1 Date = xy[i]["date"] list.append(Date) date=set(list) d1 = [{i: {"start_page": Start_page, "end_page": End_page,"date":date}}] print(d1) total_input_list=[{1:{"start_page":1,"end_page":None,"date":"10/12/2015"}, 2:{"start_page":4,"end_page":None,"date":"12/12/2015"}, 3:{"start_page":8,"end_page":None,"date":"22/1/2016"}, 4:{"start_page":15,"end_page":None,"date":"22/1/2016"}, 5:{"start_page":22,"end_page":None,"date":"22/1/2016"}, 6:{"start_page":24,"end_page":None,"date":"20/12/2016"}, 7:{"start_page":28,"end_page":None,"date":"26/2/2017"}}] date_op(total_input_list) I'm seeing this output [{1: {'date': {'10/12/2015'}, 'end_page': 3, 'start_page': 1}}] [{2: {'date': {'10/12/2015', '12/12/2015'}, 'end_page': 7, 'start_page': 4}}] [{3: {'date': {'22/1/2016', '10/12/2015', '12/12/2015'}, 'end_page': 14, 'start_page': 8}}] [{4: {'date': {'22/1/2016', '10/12/2015', '12/12/2015'}, 'end_page': 21, 'start_page': 15}}] [{5: {'date': {'22/1/2016', '10/12/2015', '12/12/2015'}, 'end_page': 23, 'start_page': 22}}] [{6: {'date': {'22/1/2016', '10/12/2015', '12/12/2015', '20/12/2016'}, 'end_page': 27, 'start_page': 24}}]
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81782413
has answer: http://stackoverflow.com/a/47414910
tagged with: python
has comment: http://stackoverflow.com/comment/81782326
has comment: http://stackoverflow.com/comment/81782420
has comment: http://stackoverflow.com/comment/81782450
has title: why its printing only 6 fields and not 7 python
has answer: http://stackoverflow.com/a/47414571
type: Question
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/47414566
has comment: http://stackoverflow.com/comment/81845298
possible better answer: http://stackoverflow.com/a/47414566
downvote count: 0
has comment: http://stackoverflow.com/comment/81782304
accepted answer: http://stackoverflow.com/a/47414571

http://stackoverflow.com/q/47517696
accepted answer: http://stackoverflow.com/a/47517764
downvote count: 0
has answer: http://stackoverflow.com/a/47517787
answer count: 5
has answer: http://stackoverflow.com/a/47517797
has comment: http://stackoverflow.com/comment/81991555
possible better answer: http://stackoverflow.com/a/47517833
has comment: http://stackoverflow.com/comment/81991588
favorite count: 0
upvote count: 9
type: AnsweredQuestion
tagged with: python
has title: Replace strings in a list (using re.sub)
has answer: http://stackoverflow.com/a/47517738
has answer: http://stackoverflow.com/a/47517833
score: 9
type: Question
has answer: http://stackoverflow.com/a/47517764
has body: I am trying to replace parts of file extensions in a list of files. I would like to be able to loop through items (files), and remove the extensions. I don't know how to appropriately loop through items in the list when re.sub as the third parameter requires a string. eg. re.sub(pattern, repl, string, count=0, flags=0) import re file_lst = ['cats1.fa', 'cats2.fa', 'dog1.fa', 'dog2.fa'] file_lst_trimmed =[] for file in file_lst: file_lst_trimmed = re.sub(r'1.fa', '', file) The issue arising here is that re.sub expects a string and I want it to loop through a list of strings. Thanks for any advice!

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/47486898
tags question: http://stackoverflow.com/q/47488253
tags question: http://stackoverflow.com/q/47414502
type: Tag
tags question: http://stackoverflow.com/q/47506764
tags question: http://stackoverflow.com/q/47441025
tags question: http://stackoverflow.com/q/47408181
tags question: http://stackoverflow.com/q/47420012
tags question: http://stackoverflow.com/q/47492347
tags question: http://stackoverflow.com/q/47504616
tags question: http://stackoverflow.com/q/47540135
tags question: http://stackoverflow.com/q/47404793
tags question: http://stackoverflow.com/q/47402207
tags question: http://stackoverflow.com/q/47535654
tags question: http://stackoverflow.com/q/47531292
tags question: http://stackoverflow.com/q/47538605
tags question: http://stackoverflow.com/q/47396204
tags question: http://stackoverflow.com/q/47413325
tags question: http://stackoverflow.com/q/47538420
tags question: http://stackoverflow.com/q/47519294
tags question: http://stackoverflow.com/q/47419823
tags question: http://stackoverflow.com/q/47501644
tags question: http://stackoverflow.com/q/47423040
tags question: http://stackoverflow.com/q/47413030
tags question: http://stackoverflow.com/q/47476974
tags question: http://stackoverflow.com/q/47534879
tags question: http://stackoverflow.com/q/47537234
tag name: csv
tags question: http://stackoverflow.com/q/47463269
tags question: http://stackoverflow.com/q/47525204
tags question: http://stackoverflow.com/q/47446613
tags question: http://stackoverflow.com/q/47515644
tags question: http://stackoverflow.com/q/47416343
tags question: http://stackoverflow.com/q/47445586
tags question: http://stackoverflow.com/q/47520668
tags question: http://stackoverflow.com/q/47526522
tags question: http://stackoverflow.com/q/47388570
tags question: http://stackoverflow.com/q/47509402
tags question: http://stackoverflow.com/q/47400696
tags question: http://stackoverflow.com/q/47509163
tags question: http://stackoverflow.com/q/47522231
tags question: http://stackoverflow.com/q/47459441
tags question: http://stackoverflow.com/q/47386655
tags question: http://stackoverflow.com/q/47459474
tags question: http://stackoverflow.com/q/47409514
tags question: http://stackoverflow.com/q/47521340
tags question: http://stackoverflow.com/q/47508048
tags question: http://stackoverflow.com/q/47535168
tags question: http://stackoverflow.com/q/47410643
tags question: http://stackoverflow.com/q/47488938
tags question: http://stackoverflow.com/q/47491586
tags question: http://stackoverflow.com/q/47530014
tags question: http://stackoverflow.com/q/47512664
tags question: http://stackoverflow.com/q/47451256
tags question: http://stackoverflow.com/q/47481373
tags question: http://stackoverflow.com/q/47412324
tags question: http://stackoverflow.com/q/47435824
tags question: http://stackoverflow.com/q/47383584
tags question: http://stackoverflow.com/q/47510614
tags question: http://stackoverflow.com/q/47514099
tags question: http://stackoverflow.com/q/47520872
tags question: http://stackoverflow.com/q/47506128
tags question: http://stackoverflow.com/q/47418718
tags question: http://stackoverflow.com/q/47474986
tags question: http://stackoverflow.com/q/47518041
tags question: http://stackoverflow.com/q/47499847
tags question: http://stackoverflow.com/q/47516434
tags question: http://stackoverflow.com/q/47483258
tags question: http://stackoverflow.com/q/47536038
tags question: http://stackoverflow.com/q/47425858
tags question: http://stackoverflow.com/q/47462524
tags question: http://stackoverflow.com/q/47457362
tags question: http://stackoverflow.com/q/47453611
tags question: http://stackoverflow.com/q/47537014
tags question: http://stackoverflow.com/q/47466393
tags question: http://stackoverflow.com/q/47405905
tags question: http://stackoverflow.com/q/47512037
tags question: http://stackoverflow.com/q/47495847
tags question: http://stackoverflow.com/q/47492742
tags question: http://stackoverflow.com/q/47394035

http://stackoverflow.com/q/47485606
type: AnsweredQuestion
has title: How np.array (or vstack) column slice work?
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/47486002
has comment: http://stackoverflow.com/comment/81927687
has answer: http://stackoverflow.com/a/47486002
type: Question
has comment: http://stackoverflow.com/comment/81926415
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/81927630
has body: Why in: import numpy as np a = [1, 2 ,3] b = [4, 5, 6] t= np.array(([a,b]) print(t[1:]) print(t[:0]) print(t[:1]) print(t[:2]) the result of the first column and second column is : [[4 5 6]] [] [[1 2 3]] [[1 2 3] [4 5 6]] If the array is: [[1 2 3] [4 5 6]] Why then the: first row t[1:] is not [4 5 6] and first column t[:0] is not [1, 4] and second column t[:1] is not [2, 5] and second column t[:3] is not [3, 6] ? How to conceptualise this?
upvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/81944640
score: 0
type: Comment
has text: Isn't it a bad idea to mix place with grid in a tkinter app? Wouldn't it be possible to achieve the same goal only with the help of grid?
comment on: http://stackoverflow.com/a/47492547
type: AnswerComment

http://stackoverflow.com/a/47507576
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47506698
upvote count: 1
has body: The part where it is opening the browser window is Oauth2. You are prompting a user to grant you access to their private Gmail data. There used to be a way of doing this with login and password it was called client login. In 2015 Google shut down the option for client login. If you wish to access a users gmail account using login and password you can still go though the IMAP/Smtp servers. that is the only way to do it without popping up that window. Note: if you have a gsuit account you can use domain wide delegation on a service account as well.
accepted answer of: http://stackoverflow.com/q/47506698
score: 1

http://stackoverflow.com/comment/82034305
comment on: http://stackoverflow.com/q/47537675
has text: I edited the question that my OS is Redhat 7 and I'm trying your suggested solutions
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81842882
has text: @Jean-FrançoisFabre: Why not? `any(complex_processing(k, v) for k, v in my_dict.items())`
score: 0
comment on: http://stackoverflow.com/a/47443836
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82030375
type: QuestionComment
comment on: http://stackoverflow.com/q/47536089
score: 0
type: Comment
has text: What about a [mcve] of the issue? At the moment nobody can run the code. Also, state the versions of libraries in use.

http://stackoverflow.com/comment/81921964
type: Comment
score: 0
type: AnswerComment
has text: sorry it was my mistake the name is tax_line not taxe_line
comment on: http://stackoverflow.com/a/47483466

http://stackoverflow.com/comment/81737435
type: Comment
comment on: http://stackoverflow.com/q/47392083
has text: @StefanBloemheuvel thanks for posting your code. Please explain how it fails, i.e. what result does it produce (or possibly what error gets thrown) and how this differs from what you want.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47427920
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47427810
has comment: http://stackoverflow.com/comment/81810377
has body: Like this: s = "a.jpg\tnot.llm\tp.jpg\tc.jpg\te.gif\tnix.txt" all_jpegs = [x for x in s.split('\t') if '.jpg' in x] print(all_jpegs) Output: ['a.jpg', 'p.jpg', 'c.jpg'] guillaume-dedrie made a good point in the comment - this will lead to false positives for s=some.file\tthisisno.jgp.gif\tsomemore.files. Changing it to s = "a.jpg\tnot.llm\tp.jpg\tc.jpg\te.gif\tnix.txt\tnot.jpg.gif\tthis.JPG" better_jpegs = [x for x in s.split('\t') if x.lower().endswith('.jpg')] print(better_jpegs) would eleminate that and also handle '.JpG' or '.JPG'
answers question: http://stackoverflow.com/q/47427810

http://stackoverflow.com/comment/81997088
type: QuestionComment
score: 0
has text: I don't care what the `coefs` are supposed to be, but rather what `evalPoly`'s purpose is. given the array I stated, what should be returned if `xs = np.array([1])`? See my answer for what is the correct answer given my interpretation.
type: Comment
comment on: http://stackoverflow.com/q/47519841

http://stackoverflow.com/a/47441123
downvote count: 0
has comment: http://stackoverflow.com/comment/119208558
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47438330
score: 4
answers question: http://stackoverflow.com/q/47438330
has body: Ok, finally got it to work (using the suggestions provided by @Alasdair). Setting a method decorator(crsf_exempt) on post is not engough it needs to be on dispatch. For anyone struggling with this in the future, it goes like this: from django.views.generic import FormView from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt, csrf_protect @method_decorator(csrf_exempt, 'dispatch') class UploadDataSetView(FormView): def post(self, request, *args, **kwargs): request.upload_handlers = [TemporaryFileUploadHandler(request=request)] return self._post(request) @method_decorator(csrf_protect) def _post(self, request): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) Also it will fail if you remove the {% csrf_token %} from your template (which is what you want).
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/122738927

http://stackoverflow.com/comment/81877909
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47461571
score: 0
has text: What is the error?

http://stackoverflow.com/comment/81930955
has text: Format your code. Especially in a language like Python, and when you're getting indentation errors, unformatted code is nearly useless. I'd fix it, but I don't want to make any assumptions about your indentation.
comment on: http://stackoverflow.com/q/47488091
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/q/47487932
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47487961
accepted answer: http://stackoverflow.com/a/47487961
score: 3
tagged with: callable
tagged with: python
tagged with: pygame
has body: I do not quite know what to google to find a solution for my problem so I will try to find it here. I am creating a Gui in Python 3.5.2 with pygame. I am currenctly working on Error popups that have a different button function depending on the error that is popping up. I want to give the function that is supposed to be executed as an argument in another class. Code looks something like this: def i_want_to_call_this(self): print("Button works.") def button_with_action(self, action): self.button(self.action) The other class will give the argument for which function the button will have like this: popup_instance.popup_with_action(i_want_to_call_this) The problem however is that the argument is parsed into string format and is not callable.
has comment: http://stackoverflow.com/comment/81930817
type: AnsweredQuestion
upvote count: 3
downvote count: 0
answer count: 1
tagged with: methods
tagged with: string
has title: Python: Convert str format to callable method

http://stackoverflow.com/a/47402849
type: Answer
answers question: http://stackoverflow.com/q/47402770
downvote count: 0
has body: Stop copying commands or playbooks from web browser and type them yourself. You have a Unicode dash (u'\u2013') somewhere.
accepted answer of: http://stackoverflow.com/q/47402770
score: 5
upvote count: 5
type: AcceptedAnswer

http://stackoverflow.com/q/47494534
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/8478210
has comment: http://stackoverflow.com/comment/81953463
upvote count: 2
answer count: 0
score: 1
tagged with: pyside2
tagged with: pyside
downvote count: 1
has body: I am trying to go into another window by clicking a button from the current window in Python's third party GUI package, PySide. From the MainWindow class, once the 'Next Window Button' is clicked, it goes to the NewWindow class to create a new window. The problem is that the new window just pops up for about a second. import sys from PySide.QtCore import * from PySide.QtGui import * class NewWindow(QWidget): def __init__(self): super(NewWindow, self).__init__() self.LLayout = QGridLayout() self.btn2 = QPushButton('Present Window') self.LLayout.addWidget(self.btn2) self.setLayout(self.LLayout) self.setWindowTitle('My SWindow') self.show() class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.WLayout = QGridLayout() self.btn = QPushButton('Next Window') self.btn.clicked.connect(self.windowfunction) self.WLayout.addWidget(self.btn) self.setLayout(self.WLayout) self.setWindowTitle('My FWindow') self.show() def windowfunction(self): new_window = NewWindow() def main(): app = QApplication(sys.argv) main = MainWindow() sys.exit(app.exec_()) main()
has title: Displaying a new window from a current window in a simple PySide GUI
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/8478210

http://stackoverflow.com/comment/81939916
has text: you should put this information in question. Did you use the same image for test ? Two images can be compressed in different way. You should have to uncompress before you compare - use `from PIL import Image` and `Image.open()`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47492099
type: Comment

http://stackoverflow.com/q/47503476
tagged with: selenium
has comment: http://stackoverflow.com/comment/81962924
has answer: http://stackoverflow.com/a/47520984
has comment: http://stackoverflow.com/comment/81962814
has answer: http://stackoverflow.com/a/47503601
favorite count: 0
has comment: http://stackoverflow.com/comment/81962980
type: Question
tagged with: xpath
has answer: http://stackoverflow.com/a/47505075
has answer: http://stackoverflow.com/a/47504834
possible better answer: http://stackoverflow.com/a/47504834
has comment: http://stackoverflow.com/comment/81962949
downvote count: 0
has answer: http://stackoverflow.com/a/47504483
upvote count: 1
tagged with: python
answer count: 6
has comment: http://stackoverflow.com/comment/81962825
has answer: http://stackoverflow.com/a/47503636
accepted answer: http://stackoverflow.com/a/47503601
type: AnsweredQuestion
has title: Selenium click on XPath button
score: 1
has body: I have the following code when I inspect on Chrome. New Email I need to click on the label "New Email", but how should invoke it in Selenium (I'm using Python). def CreateMail(): EmailButton="//*[contains(text(),'New Email')]" driver.find_elements_by_xpath(EmailButton) // there is no method to enable click.
has comment: http://stackoverflow.com/comment/81965549

file-format
type: Tag
tags question: http://stackoverflow.com/q/47398291
tag name: file-format

http://stackoverflow.com/q/47530574
downvote count: 0
has comment: http://stackoverflow.com/comment/82018050
upvote count: 1
linked to: http://stackoverflow.com/q/12460139
has comment: http://stackoverflow.com/comment/82017975
tagged with: http
linked to: http://stackoverflow.com/q/10450776
has title: unable to connect any URL in python
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82017589
has comment: http://stackoverflow.com/comment/82017810
tagged with: python
has comment: http://stackoverflow.com/comment/82021244
has comment: http://stackoverflow.com/comment/82017683
linked to: http://stackoverflow.com/q/7697963
has body: Getting the below error &lt;urlopen error [Errno 101] Network is unreachable&gt; Below is my code #!/usr/bin/python # -*- coding: utf-8 -*- from urllib2 import Request, urlopen, URLError request = Request('http://google.com/') try: response = urlopen(request) kittens = response.read() print kittens[559:1000] except URLError, e: print 'No kittez. Got an error code:', e
answer count: 0
score: 1

http://stackoverflow.com/a/47401589
answers question: http://stackoverflow.com/q/47394651
downvote count: 0
upvote count: 1
score: 1
has body: It is hard to understand what you want, but maybe you want to store previous mouse clicking positions in order to draw rectangles? All you have to do is to store then in a different variable. If you want just two click positions at a time, you just use that. Or you can use a Python list to store the positions of an arbitrary number of clicks. import pygame, sys SIZE = 640, 480 screen = pygame.display.set_mode(SIZE) # empty list all_clicks = [] drawn = True while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # store mouse click position in the list: all_clicks.append(event.pos) # event.pos already has the info you'd get by calling pygame.mouse.get_pos() drawn = False print(all_clicks) # at every second click: if not len(all_clicks) % 2 and not drawn: # draw a rectangle having the click positions as coordinates: # pick the minimal x coordinate of both clicks as left position for rect: x = min(all_clicks[-1][0], all_clicks[-2][0]) # ditto for top positionn y = min(all_clicks[-1][1], all_clicks[-2][1]) # and calculate width and height in the same way w = max(all_clicks[-1][0], all_clicks[-2][0]) - x h = max(all_clicks[-1][1], all_clicks[-2][1]) - y pygame.draw.rect(screen, (255, 255, 255), (x, y, w, h)) drawn = True # update screen: pygame.display.flip() # pause a while (30ms) least our game use 100% cpu for nothing: pygame.time.wait(30)
type: Answer

http://stackoverflow.com/q/47413628
has body: Preface: I realize this code is finding Fibonacci numbers, not prime numbers. Question: For some reason, the savework() function is not working. When I run a python interactive session and repeatedly run get_next_prime(), it produces the next number in the sequence as intended within that session. However, when I close the session and open a new one, it should remember the prior entries (because of pickle.dump etc.) but doesn't. It should be calling the pickled byte files each run. Why isn't it? I'm a beginner: Please be gentle. Thank you! Code: # Write a function which, for each run, returns the smallest positive prime number larger than the one returned previously. """ Find and maintain a cumulative list of Prime numbers """ import pickle import atexit try: with open("dict_of_primes","rb") as file1, \ open("last_prime_index_found","rb") as file2: dict_of_primes = pickle.load(file1) last_prime_index_found = pickle.load(file2) # Start fresh if either file could not be found except FileNotFoundError: dict_of_primes = {} last_prime_index_found = -1 def get_next_prime(): """ Get the next prime number """ global last_prime_index_found n = last_prime_index_found + 1 if n in [0,1]: dict_of_primes[n] = n else: dict_of_primes[n] = \ dict_of_primes[n-1] +\ dict_of_primes[n-2] last_prime_index_found = n return dict_of_primes[n] def save_work(): """ Saves data for next session """ with open("dict_of_primes","wb") as file1, \ open("last_prime_index_found","wb") as file2: pickle.dump(dict_of_primes,file1) pickle.dump(last_prime_index_found,file2) # This will insure that save_work() is called # when you end your session atexit.register(save_work) Python Interactive Sessions: `C:\Users\Fiona Murphey\Desktop&gt;python` `Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32` `Type "help", "copyright", "credits" or "license" for more information.` `&gt;&gt;&gt; from lastprime import *` `&gt;&gt;&gt; get_next_prime()` `0` `&gt;&gt;&gt; get_next…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81781428
tagged with: python-interactive
tagged with: pickle
score: 2
downvote count: 0
tagged with: python
tagged with: dictionary
has title: python pickle.dump not activating?
favorite count: 0
tagged with: atexit
type: Question
upvote count: 2
answer count: 0
has comment: http://stackoverflow.com/comment/81781632

http://stackoverflow.com/a/47425461
has body: Here's how to do it with the subprocess module: import subprocess import sys p1 = subprocess.Popen([sys.executable, "loop3.py"], stdout=subprocess.PIPE) output, err = p1.communicate() with open('opt.txt', 'w') as file: file.write(output.decode())
answers question: http://stackoverflow.com/q/47425331
downvote count: 0
upvote count: 1
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/47425331
type: Answer

http://stackoverflow.com/comment/81723930
has text: @juanpa.arrivillaga Basically I would like to group the exceptions in a namespace inside the module. Writing separate class definitions seems redundant and I would not be able to import them all at once.
comment on: http://stackoverflow.com/q/47385354
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47516404
type: Answer
answers question: http://stackoverflow.com/q/47516286
has body: The error message is pretty much telling you exactly what is the problem: ValueError: all the input array dimensions except for the concatenation axis must match exactly But you are doing the opposite, the concatenation axis dimensions match exactly but the others don't. Consider: In [3]: arr1 = np.random.randint(0,10,(20, 5)) In [4]: arr2 = np.random.randint(0,10,(20, 3)) In [5]: arr3 = np.random.randint(0,10,(20, 11)) Note the dimensions. Just give it the correct axis. So use the second rather than the first: In [8]: arr1.shape, arr2.shape, arr3.shape Out[8]: ((20, 5), (20, 3), (20, 11)) In [9]: np.concatenate((arr1, arr2, arr3), axis=1) Out[9]: array([[3, 1, 4, 7, 3, 6, 1, 1, 6, 7, 4, 6, 8, 6, 2, 8, 2, 5, 0], [4, 2, 2, 1, 7, 8, 0, 7, 2, 2, 3, 9, 8, 0, 7, 3, 5, 9, 6], [2, 8, 9, 8, 5, 3, 5, 8, 5, 2, 4, 1, 2, 0, 3, 2, 9, 1, 0], [6, 7, 3, 5, 6, 8, 3, 8, 4, 8, 1, 5, 4, 4, 6, 4, 0, 3, 4], [3, 5, 8, 8, 7, 7, 4, 8, 7, 3, 8, 7, 0, 2, 8, 9, 1, 9, 0], [5, 4, 8, 3, 7, 8, 3, 2, 7, 8, 2, 4, 8, 0, 6, 9, 2, 0, 3], [0, 0, 1, 8, 6, 4, 4, 4, 2, 8, 4, 1, 4, 1, 3, 1, 5, 5, 1], [1, 6, 3, 3, 9, 2, 3, 4, 9, 2, 6, 1, 4, 1, 5, 6, 0, 1, 9], [4, 5, 4, 7, 1, 4, 0, 8, 8, 1, 6, 0, 4, 6, 3, 1, 2, 5, 2], [6, 4, 3, 2, 9, 4, 1, 7, 7, 0, 0, 5, 9, 3, 7, 4, 5, 6, 1], [7, 7, 0, 4, 1, 9, 9, 1, 0, 1, 8, 3, 6, 0, 5, 1, 4, 0, 7], [7, 9, 0, 4, 0, 5, 5, 9, 8, 9, 9, 7, 8, 8, 2, 6, 2, 3, 1], [4, 1, 6, 5, 4, 5, 6, 7, 9, 2, 5, 8, 6, 6, 6, 8, 2, 3, 1], [7, 7, 8, 5, 0, 8, 5, 6, 4, 4, 3, 5, 9, 8, 7, 9, 8, 8, 1], [3, 9, 3, 6, 3, 2, 2, 4, 0, 1, 0, 4, 3, 0, 1, 3, 4, 1, 3], [5, 1, 9, 7, 1, 8, 3, 9, 4, 7, 6, 7, 4, 7, 0, 1, 2, 8, 7], [6, 3, 8, 0, 6, 2, 1, 8, 1, 0, 0, 3, 7, 2, 1, 5, 7, 0, 7], [5, 4, 7, 5, 5, 8, 3, 2, 6, 1, 0, 4, 6, 9, 7, 3, 9, 2, 5], [1, 4, 8, 5, 7, 2, 0, 2, 6, 2, 6, 5, 5, 4, 6, 1, 8, 8, 1], [4, 4, 5, 6, 2, 6, 0, 5, 1, 8, 4, 5, 8, 9, 2, 1, 0, 4, 2]]) In [10]: np.concatenate((arr1, arr2, arr3), axis=1).shape Out[10]: (20, 19)
score: 0

http://stackoverflow.com/q/47414502
has body: I have a shell command that return rows like timestamp=1511270820724797892 eventID=1511270820724797892 eventName="corvil_request_summary" channelID="HTTP: Other" channelDir=false classID="class-default" packetID=2809419165205232 messageOffset=1 warnCSMInvalidSample=false warnCSMOverflow=false warnEventInvalidSample=false Server="nginx/1.10.1" Method="GET" RequestURI="/system/varlogmessages/" UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0" WebSite="backup-server-new" Domain="backup-server-new" SrcIP="172.20.1.13" SrcPort="80" DstIP="172.18.4.181" DstPort="60065" timestamp=1511270820735795372 eventID=1511270820735795372 eventName="corvil_request_summary" channelID="HTTP: Other" channelDir=false classID="class-default" packetID=2809419176202992 messageOffset=1 warnCSMInvalidSample=false warnCSMOverflow=false warnEventInvalidSample=false Server="probe" Method="GET" RequestURI="/system/status" WebSite="probe609:8111" Domain="probe609:8111" SrcIP="172.20.2.109" SrcPort="8111" DstIP="172.18.4.96" DstPort="49714" I am trying to read it as: for i, row in enumerate(csv.reader(execute(cmd), delimiter=' ', skipinitialspace=True)): print i, len(row) if i &gt; 10: break but this is not working correctly as white spaces inside quotes are not ignored. For example channelID="HTTP: Other" is split as two variables because of the space between HTTP: and Other What is the right way to parse this type of input?
has comment: http://stackoverflow.com/comment/81786294
has comment: http://stackoverflow.com/comment/81786935
answer count: 2
has answer: http://stackoverflow.com/a/47415010
possible better answer: http://stackoverflow.com/a/47415241
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81782601
has comment: http://stackoverflow.com/comment/81787722
favorite count: 0
has comment: http://stackoverflow.com/comment/81786457
has title: read space delimited CSV with quoted values
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81786476
linked to: http://stackoverflow.com/q/21527057
has comment: http://stackoverflow.com/comment/81788985
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/81786601
has answer: http://stackoverflow.com/a/47415241
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/47415010
type: Question

http://stackoverflow.com/q/47383380
has title: Sorting user input in a list based on length, and outputting it in a new list?
has comment: http://stackoverflow.com/comment/81719535
score: 0
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/47383409
has body: I have this code here: which takes user input and adds it to a list until they input to stop. At that point, it sorts the list items based on length. What I am trying to do is put each word the user enters into a list of words with the same length. Like 2-letter words are put into one list, 3-letter words are put into another list. When complete, I'm trying to return a list containing all of the individual word lists that were created. def wordsList(): stop = "stop" sentence = [] while True: word = input("Enter a word: ") if word == stop: # exit the loop break sentence.append(word) sentence.sort(key=len) print(sentence)
downvote count: 1
tagged with: user-input
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47383412
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47383638
has comment: http://stackoverflow.com/comment/81719506
upvote count: 1
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/81719466

http://stackoverflow.com/a/47483058
has body: One way it to bind the information to the button upon creation, and pass this information as a parameter when the button is clicked: contacts = { 1: {"Name" : "Max", "Address" : "18 Fake Street, Hollywood", "Mobile" : "07542564872"}, 2: {"Name" : "Brian", "Address" : "17 Fake Boulevard, Hollywood", "Mobile" : "07895465231"}, 3: {"Name" : "Sally", "Address" : "19 Hill Valley, Hollywood", "Mobile" : "07956423145"}, 4: {"Name" : "Steve", "Address" : "22 Fake House, Hollywood", "Mobile" : "07456213895"}, 5: {"Name" : "Sara", "Address" : "46 Fake Drive, Hollywood", "Mobile" : "07652348192"}, 6: {"Name" : "Kevin", "Address" : "18 Labyrinth Avenue, Hollywood", "Mobile" : "07563245196"}, 7: {"Name" : "Paula", "Address" : "38 Fake Drive, Hollywood", "Mobile" : "07354695488"}, 8: {"Name" : "Dave", "Address" : "Haystack Farm, Hollywood", "Mobile" : "07854623198"}, 9: {"Name" : "Mary", "Address" : "Fake Valley, CA", "Mobile" : "07564289315"}, 10:{"Name" : "Anastasia", "Address" : "Some Street, Hollywood", "Mobile" : "07546321595"}} import tkinter window = tkinter.Tk() window.title("Phonebook") lbl = tkinter.Label(window, text="Click a contact to show their details:") lbl.pack() def changeLabel(text): """A 'function' for the 'reconfiguration' of 'labels' (changing their output) """ lbl2.configure(text="Details for " + text) for i in contacts: btn = tkinter.Button(window, text=contacts[i]["Name"], command=lambda text=contacts[i]["Name"]:changeLabel(text)) btn.pack() lbl2 = tkinter.Label(window, text="No contact selected") lbl2.pack() window.mainloop() Alternatively: At @BrianOakley's suggestion in the comments: since contacts is global, the code might be a bit easier to debug and maintain if it passed the index to the function rather than have a complex lambda statement. (see code below for this alternate, and arguably more robust solution) import tkinter window = tkinter.Tk() window.title("Phonebook") lbl = tkinter.Label(window, text="Click a contact to show their details:") lbl…
has comment: http://stackoverflow.com/comment/81920902
has comment: http://stackoverflow.com/comment/81929935
has comment: http://stackoverflow.com/comment/81941595
type: Answer
answers question: http://stackoverflow.com/q/47483010
score: 0
accepted answer of: http://stackoverflow.com/q/47483010
has comment: http://stackoverflow.com/comment/81921031
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81929750

http://stackoverflow.com/q/47393362
has comment: http://stackoverflow.com/comment/81740781
has comment: http://stackoverflow.com/comment/81740446
has comment: http://stackoverflow.com/comment/81741301
has comment: http://stackoverflow.com/comment/81741573
has answer: http://stackoverflow.com/a/64621147
score: 9
tagged with: numpy
upvote count: 12
has title: concatenate two arrays in python with alternating the columns in numpy
answer count: 3
has answer: http://stackoverflow.com/a/47393794
has answer: http://stackoverflow.com/a/47393406
has comment: http://stackoverflow.com/comment/81743331
tagged with: arrays
has body: How to concatenate two arrays in numpy python by taking first column from the first array and fisrt column from the second, then second column from first and second from the other, etc..? that is if I have A=[a1 a2 a3] and B=[b1 b2 b3] I want the resulting array to be [a1 b1 a2 b2 a3 b3]
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47030661
downvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81740330
has comment: http://stackoverflow.com/comment/81742692
tagged with: python

http://stackoverflow.com/a/47417038
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/81788348
upvote count: 6
has comment: http://stackoverflow.com/comment/81788210
has comment: http://stackoverflow.com/comment/81789610
answers question: http://stackoverflow.com/q/47416917
has comment: http://stackoverflow.com/comment/81788428
downvote count: 1
has comment: http://stackoverflow.com/comment/81788246
has body: First, use sets, not lists (and use a list of sets instead of separate variables). master_list = [] master_list.append(set(['London', 'Manchester', 'Liverpool', 'Edimburgh'])) master_list.append(set(['Dublin', 'Cork', 'Galway'])) master_list.append(set(['Berlin', 'Munich', 'Frankfurt', 'Paris', 'Milan', 'Rome', 'Madrid', 'Barcelona', 'Lisbon', ...])) master_list.append(set(['Washington', 'New York', 'San Francisco', 'LA', 'Boston', ...])) (Depending on your use case, a dict with more meaningful keys may be more appropriate than a list.) Second, build a dict that maps each element to its set: # E.g., index['London'] == set(['London', 'Manchester', ...]) index = dict((item, s) for s in master_list for item in s) Now, you just need to check if both items belong to the same set. def in_same_group(i1, i2): return index[i1] is index[i2]

http://stackoverflow.com/q/47445394
type: AnsweredQuestion
tagged with: random
downvote count: 0
has answer: http://stackoverflow.com/a/47445627
accepted answer: http://stackoverflow.com/a/47445627
tagged with: matplotlib
upvote count: 4
has body: I have written a code that plots random walks. There are traj different random walks generated and each consists of n steps. I would like to animate their moves. How can I do that? My code below: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def random_walk_2D(n, traj = 1): for i in range(traj): skoki = np.array([[0, 1], [1, 0], [-1, 0], [0, -1]]) losy = np.random.randint(4, size = n) temp = skoki[losy, :] x = np.array([[0, 0]]) temp1 = np.concatenate((x, temp), axis = 0) traj = np.cumsum(temp1, axis = 0) plt.plot(traj[:, 0], traj[:, 1]) plt.plot(traj[-1][0], traj[-1][1], 'ro') #the last point plt.show()
type: Question
tagged with: numpy
tagged with: animation
answer count: 1
has title: Adding an animation to a random walk plot [Python]
tagged with: python
score: 4
favorite count: 0

http://stackoverflow.com/q/47519554
type: Question
accepted answer: http://stackoverflow.com/a/47525123
answer count: 1
has answer: http://stackoverflow.com/a/47525123
tagged with: python
tagged with: keras
has title: Extremely High Loss with Keras VGG16 transfer learning Image Classification
has body: I'm retraining VGG16 and fine tuning the top 2 convolutional blocks for an image classification task. The retraining itself finished rather uneventfully with mediocre accuracy. The fine tuning program is currently running and it seems like it will take a couple of days at the least. However, the loss is ludicrously high at around 440 after 3 epochs, while accuracy hovers around 0.4. Please confirm whether there is any major flaw in the model so that I can kill the program. I have used some data augmentation and l1_l2 regularisation during the fine tuning stage. The data set is a small set of about 8000 images of tumors, divided into 8 classes. Thus, the data is both small and extremely unrelated to the imagenet images. This is my code for the transfer learning: import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense from keras import applications from keras.utils.np_utils import to_categorical import math img_width, img_height= 224, 224 weight_path= 'bottleneck_fc_model.h5' train_dir= 'Cancer_Data/Train' validation_dir= 'Cancer_Data/Validate' epochs= 150 batch_size= 128 def save_bottleneck_features(): datagen = ImageDataGenerator(rescale= 1./255) model = applications.VGG16(include_top=False, weights='imagenet') print 'Extracting Bottleneck Training Features' generator = datagen.flow_from_directory( train_dir, target_size= (img_width, img_height), batch_size= batch_size, class_mode= None, shuffle= False) nb_train_samples= len(generator.filenames) predict_size_train= int(math.ceil(nb_train_samples / batch_size)) bottleneck_feature_train =model.predict_generator(generator,predict_size_train) np.save(open('bottleneck_feature_train.npy', 'w'), bottleneck_feature_train) print "Bottleneck Training Features Saved" print "Extracting Bottleneck Validation Features" generator2 = datagen.flow_from_directory( validation_dir, target_size= (img_width, img_height), batch_size= b…
type: AnsweredQuestion
score: 0
tagged with: deep-learning

annotations
tags question: http://stackoverflow.com/q/47408001
type: Tag
tag name: annotations

http://stackoverflow.com/q/47533772
downvote count: 0
linked to: http://stackoverflow.com/q/42986405
tagged with: word2vec
upvote count: 1
has comment: http://stackoverflow.com/comment/82068668
favorite count: 0
possible better answer: http://stackoverflow.com/a/68597319
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/65900526
has body: I would like to call model.wv.most_similar_cosmul, on the same copy of model object, using multiple cores, on batches of input pairs. The multiprocessing module requires multiple copies of model, which will require too much RAM because my model is 30+ GB in RAM. I have tried to evaluate my query pairs. It took me ~12 hours for the first round. There may be more rounds coming. That's why I am looking for a threading solution. I understand Python has Global Interpreter Lock issue. Any suggestions?
has title: Gensim word2vec / doc2vec multi-threading parallel queries
score: 1
has comment: http://stackoverflow.com/comment/82073096
accepted answer: http://stackoverflow.com/a/47582012
tagged with: python
tagged with: gensim
has comment: http://stackoverflow.com/comment/82072857
has answer: http://stackoverflow.com/a/47582012
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/68597319
has comment: http://stackoverflow.com/comment/82069150
tagged with: multithreading
tagged with: doc2vec

http://stackoverflow.com/comment/81854418
type: QuestionComment
comment on: http://stackoverflow.com/q/47449516
score: 1
type: Comment
has text: And yeah, in the future I'll know to use [`np.shares_memory(test, test2)`](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.interface.html) instead of any of these.

http://stackoverflow.com/q/47538456
score: -2
tagged with: network-drive
has body: I want to access some files in my network drive. My network drive is called "networkfile". If I just run this on the Window command line, it is working: net use \networkfile\Programs. However, It didn't work when I put it in the Python script (I'm using Python3). I tried: a = os.system("net use O:\networkfile\Programs") a = os.system("net use \networkfile\Programs") a = os.system("net use \networkfile\Programs") a = subprocess.run("net use O:\networkfile\Programs", shell=True, stdout=subprocess.PIPE) None of those work. The error is: "System error 67 has occurred. The network name cannot be found." Anyone has experienced this before? Please advice. Thanks,
downvote count: 2
has comment: http://stackoverflow.com/comment/82034025
answer count: 1
has comment: http://stackoverflow.com/comment/82034002
has comment: http://stackoverflow.com/comment/82033945
accepted answer: http://stackoverflow.com/a/47539017
favorite count: 0
tagged with: net-use
has comment: http://stackoverflow.com/comment/82034107
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47539017
has comment: http://stackoverflow.com/comment/82078246
has title: "net use" didn't work in Python 3 script
has comment: http://stackoverflow.com/comment/82034067
has comment: http://stackoverflow.com/comment/82033861
tagged with: python
has comment: http://stackoverflow.com/comment/82033812
has comment: http://stackoverflow.com/comment/82033971
type: Question
upvote count: 0

http://stackoverflow.com/q/47498095
has comment: http://stackoverflow.com/comment/81951477
upvote count: 1
has comment: http://stackoverflow.com/comment/81951493
tagged with: scipy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47498287
accepted answer: http://stackoverflow.com/a/47498287
tagged with: python-3.x
has title: Python: How do I create a diagonal matrix with block matrices as diagonals
score: -2
has comment: http://stackoverflow.com/comment/81961660
tagged with: python
has body: I need to create a matrix of the form shown in the picture, this is a 9x9 matrix, but I want to create it for NxN matrix for a given value of N. Is it possible to create this by first defining two block matrices, first of which repeats along the diagonal and the second repeats by diagonal offset of 1 and -1? This shows the picture of the final matrix I need:
tagged with: numpy
type: AnsweredQuestion
tagged with: matrix
has comment: http://stackoverflow.com/comment/81954851
downvote count: 3
answer count: 1

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

wand
tags question: http://stackoverflow.com/q/47401160
tags question: http://stackoverflow.com/q/47465218
type: Tag
tag name: wand
tags question: http://stackoverflow.com/q/47408891

http://stackoverflow.com/comment/81856915
comment on: http://stackoverflow.com/a/47433597
has text: using dir and getattr takes care of the inspection (including the whole inheritance hierarchy), and a property get should not have unwanted side effects (if it does then there's an obvious design error)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47522736
has comment: http://stackoverflow.com/comment/82023047
answers question: http://stackoverflow.com/q/47522526
type: Answer
score: 0
has body: Try: import re def get_id(request): id= "100¥a" pattern = re.compile(r'[\\u000-\\u037]', re.UNICODE | re.IGNORECASE) if pattern.findall(id): return HttpResponse(' Escape sequence ') else: return HttpResponse(' OK ') You can extract the pattern compilation to happen once inside your module, so it doesn't need to be done at the handling of each request, but this is the basic idea.
accepted answer of: http://stackoverflow.com/q/47522526
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82002048

http://stackoverflow.com/a/47397606
downvote count: 0
answers question: http://stackoverflow.com/q/47397469
has body: You need to pass it a boolean array, for example: &gt;&gt;&gt; arr_a[arr_b&gt;0] array(['2m_nd', '1m_4wk'], dtype='&lt;U15')
upvote count: 8
type: Answer
score: 8

http://stackoverflow.com/comment/81774261
type: QuestionComment
has text: @akashkarothiya Yeah, I do not know Matlab very well. Is the expected output a list of `[val, idx]`?
score: 0
comment on: http://stackoverflow.com/q/47410425
type: Comment

http://stackoverflow.com/q/47394941
has comment: http://stackoverflow.com/comment/81743373
answer count: 1
has answer: http://stackoverflow.com/a/47400721
tagged with: tensorflow
has title: Error while installing Tensorflow on mac
type: Question
has comment: http://stackoverflow.com/comment/91214757
type: UnansweredQuestion
has body: I have Python 3.5.4 running with Anaconda. I am getting the following error while installing Tensorflow on mac by using pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.4.0-py3-none-any.whl It has something to do with numpy package, I guess Error: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/_q/wmhj5hgn1_97ld78v29tky340000gn/T/pip-build-fo1po1/numpy/
linked to: http://stackoverflow.com/q/17886647
tagged with: python
tagged with: macos
score: 0

http://stackoverflow.com/comment/81959691
type: QuestionComment
has text: Actualy I don't know the solution but I think you havbe to fix your ip camera I have never seen randomly disconnected ip camera before
score: 0
comment on: http://stackoverflow.com/q/47501953
type: Comment

http://stackoverflow.com/q/47526775
has answer: http://stackoverflow.com/a/47601521
favorite count: 0
has answer: http://stackoverflow.com/a/67062828
has title: How to add a new line in the txt field in fpdf cell
tagged with: python
has answer: http://stackoverflow.com/a/57037519
has body: I'm trying to use fpdf to create a pdf file in python, but I have trouble in the "txt" filed in cell function, because I would like some new lines in the text. Here is what I do, but this doesn't work. pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 13.0) text = 'Engagement Summary:' + "\n" + 'opened by: ' + str(shareURL.contact) pdf.cell(ln=0, h=5.0, align='L', w=0, txt=text, border=0) pdfName = request.user.username + ".pdf" pdf.output(pdfName, 'F') ALso, "\n" doesn't work in the email I would like to send.
answer count: 4
tagged with: fpdf
type: Question
upvote count: 2
score: 2
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50794253

http://stackoverflow.com/q/47395061
tagged with: linear-regression
has body: I am using statsmodels to run a linear regression of a pandas dataset, including both a categorical (Handedness; 3 levels) and a continuous (Age) variable as predictors. I am looking for a simple way to test the effects of Handedness, Age and their interaction - that is, beyond the effect of a specific dummy variable. I do the following: res = smf.ols(formula="Score ~ C(Handedness, Sum) * center(Age)", data=myData).fit() print(res3.params) and get the following parameters: Intercept 198.188525 C(Handedness, Sum)[S.Ambidextrous] -12.824061 C(Handedness, Sum)[S.Left] 11.243362 center(Age) 2.659525 C(Handedness, Sum)[S.Ambidextrous]:center(Age) 4.216525 C(Handedness, Sum)[S.Left]:center(Age) -1.568143 I would like to perform f-tests for all the effects in my model: Handedness, Age and their interaction. I was able to perform each of them separately using the f_test method: HandednessEffect = np.array(([ 0, 1, 0, 0, 0, 0 ],[0, 0, 1, 0, 0, 0])) AgeEffect = np.array(([ 0, 0, 0, 1, 0, 0 ])) HandednessXAgeEffect = np.array(([ 0, 0, 0, 0, 1, 0 ],[0, 0, 0, 0, 0, 1])) print("Effect Tests:") print("Handedness\t\t", (res.f_test(HandednessEffect ))) print("Age\t\t", (res.f_test(AgeEffect))) print("Handedness* Age\t", (res.f_test(HandednessXAgeEffect ))) and get: Effect Tests: Handedness &lt;F test: F=array([[ 1.14330425]]), p=0.3248142242736258, df_denom=68, df_num=2&gt; Age &lt;F test: F=array([[ 0.14232477]]), p=0.7071555851484095, df_denom=68, df_num=1&gt; Handedness * Age &lt;F test: F=array([[ 0.03297983]]), p=0.9675735457292447, df_denom=68, df_num=2&gt; I also tried using the wald_test_terms() method to combine the terms, but if I understand correctly, it combines the terms based on names, so if I do: print(res.wald_test_terms(skip_single=True, combine_terms=['Handedness','Age',':center(Age)'])) The first term, for example, combines all the terms with the word Handedness in them: that is, the two categorical terms (which is what I want), but also the interaction term (whic…
has comment: http://stackoverflow.com/comment/81876887
type: Question
has comment: http://stackoverflow.com/comment/81855105
has comment: http://stackoverflow.com/comment/81749443
type: UnansweredQuestion
has title: How to calculate effect tests in linear regression in Python
has comment: http://stackoverflow.com/comment/81872483
tagged with: python
tagged with: statsmodels
score: 0
answer count: 0
tagged with: pandas

http://stackoverflow.com/comment/81745689
comment on: http://stackoverflow.com/q/47394651
score: 0
type: QuestionComment
has text: I can only make one mouse event for a mouse button down and not for multiple. How is this possible
type: Comment

http://stackoverflow.com/a/47394087
has body: One solution using .concat(), set_index(), and .loc[]: # Get index of (shop, previous month, day). # This will serve as a unique index to look up prev. month sale. prev = pd.concat((df.shop, df.month - 1, df.day), axis=1) # Unfortunately need to convert to list of tuples for MultiIndexing prev = pd.MultiIndex.from_arrays(prev.values.T) # old: [tuple(i) for i in prev.values] # Now call .loc on df to look up each prev. month sale. sale_prev_month = df.set_index(['shop', 'month', 'day']).loc[prev] # And finally just concat rather than merge/join operation # because we want to ignore index &amp; mimic a left join. df = pd.concat((df, sale_prev_month.reset_index(drop=True)), axis=1) shop month day sale sale 0 1 7 1 10 8.0 1 1 6 1 8 9.0 2 1 5 1 9 NaN 3 2 7 1 10 8.0 4 2 6 1 8 9.0 5 2 5 1 9 NaN Your new column will be float, not int, because of the presence of NaNs. Update - an attempt with dask I don't use dask day to day so this is probably woefully sub-par. Trying to work around the fact that dask does not implement pandas' MultiIndex. So, you can concatenate your three existing indices into a string column and lookup on that. import dask.dataframe as dd # Play around with npartitions or chunksize here! df2 = dd.from_pandas(df, npartitions=10) # Get a *single* index of unique (shop, month, day IDs) # Dask doesn't support MultiIndex empty = pd.Series(np.empty(len(df), dtype='object')) # Passed to `meta` current = df2.loc[:, on].apply(lambda col: '_'.join(col.astype(str)), axis=1, meta=empty) prev = df2.loc[:, on].assign(month=df2['month'] - 1)\ .apply(lambda col: '_'.join(col.astype(str)), axis=1, meta=empty) df2 = df2.set_index(current) # We know have two dask.Series, `current` and `prev`, in the # concatenated format "shop_month_day". # We also have a dask.DataFrame, df2, which is indexed by `current` # I would think we could just call df2.loc[prev].compute(), but # that's throwing a KeyError for me, so slightly more expensive: sale_prev_month = df2.compute().loc[prev.c…
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81742107
downvote count: 0
answers question: http://stackoverflow.com/q/47392290
has comment: http://stackoverflow.com/comment/81748953
type: Answer

xattr
tags question: http://stackoverflow.com/q/47393426
type: Tag
tag name: xattr

http://stackoverflow.com/a/47498825
answers question: http://stackoverflow.com/q/47498713
accepted answer of: http://stackoverflow.com/q/47498713
score: 3
has comment: http://stackoverflow.com/comment/81953081
has comment: http://stackoverflow.com/comment/81953718
has comment: http://stackoverflow.com/comment/81953793
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81953460
has comment: http://stackoverflow.com/comment/81953185
has body: You can implement Newton's method, an iterative method to solve many equations to arbitrary precision. Applied to the square root the recursion goes as or in Python code: def my_sqrt(a, e): diff = e + 1 # random diff &gt; e sqrt = 1.0 # start must not be 0 while diff &gt; e: sqrt = sqrt - (sqrt * sqrt - a) / (2 * sqrt) diff = sqrt * sqrt - a if diff &lt; 0: # make sure diff is positive without calling abs diff = -1 * diff return sqrt &gt;&gt;&gt; my_sqrt(2, 0.00001) 1.4142156862745099 Admitted, this takes the epsilon into account after resquaring. So the result will actually be more precise than getting the root itself within epsilon.
type: Answer
has comment: http://stackoverflow.com/comment/81953005

algorithm
tags question: http://stackoverflow.com/q/47456079
tags question: http://stackoverflow.com/q/47516877
tags question: http://stackoverflow.com/q/47514666
type: Tag
tags question: http://stackoverflow.com/q/47500832
tags question: http://stackoverflow.com/q/47499255
tag name: algorithm
tags question: http://stackoverflow.com/q/47415441
tags question: http://stackoverflow.com/q/47490284
tags question: http://stackoverflow.com/q/47496753
tags question: http://stackoverflow.com/q/47464418
tags question: http://stackoverflow.com/q/47384440
tags question: http://stackoverflow.com/q/47462255
tags question: http://stackoverflow.com/q/47442220
tags question: http://stackoverflow.com/q/47449818
tags question: http://stackoverflow.com/q/47535889
tags question: http://stackoverflow.com/q/47501336
tags question: http://stackoverflow.com/q/47491574
tags question: http://stackoverflow.com/q/47476655
tags question: http://stackoverflow.com/q/47536188
tags question: http://stackoverflow.com/q/47517640
tags question: http://stackoverflow.com/q/47446568
tags question: http://stackoverflow.com/q/47384490
tags question: http://stackoverflow.com/q/47398441
tags question: http://stackoverflow.com/q/47468174
tags question: http://stackoverflow.com/q/47475240
tags question: http://stackoverflow.com/q/47488668
tags question: http://stackoverflow.com/q/47425676
tags question: http://stackoverflow.com/q/47387090
tags question: http://stackoverflow.com/q/47490033

http://stackoverflow.com/q/47413844
has comment: http://stackoverflow.com/comment/82406637
tagged with: forecasting
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86468364
favorite count: 0
type: Question
has body: I have a data set of 1400 length. I made every operation and trained an LSTM model using Keras on Python in an attempt to predict future points. My trained model learns well. After compiling the model, I added a new random test set. My intent is to predict unseen future, for example 15 days, that are not included in trained data. When I add some test data with a constant value, my predictions become constant. But when I add real values that I try to predict, my model fits well on this test data. So How can I handle it? Why does the model prediction change due to test data ? How can I predict the next 15 days that are not included in my training set ? How can I predict the unseen future? If LSTM models work only on known train and test sets why should I use it?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81781393
score: 1
tagged with: future
tagged with: python
tagged with: recurrent-neural-network
tagged with: lstm
has title: Future Predictions LSTM
answer count: 0
has comment: http://stackoverflow.com/comment/81781107

http://stackoverflow.com/comment/81978641
comment on: http://stackoverflow.com/q/47511463
has text: `Function.my_variable = variable` is a serious antipattern since it creates *global state*, the same for `global my_variable`s, etc.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/78830180
has comment: http://stackoverflow.com/comment/139046494
upvote count: 0
answers question: http://stackoverflow.com/q/47512599
score: -1
has comment: http://stackoverflow.com/comment/138983638
has body: Here is the solution!! check your interpreter and the kernel. Go to File---&gt; invalidate caches, and restart. Hope this solution works :)
has comment: http://stackoverflow.com/comment/138983645
type: Answer
downvote count: 1

http://stackoverflow.com/q/47518131
type: UnansweredQuestion
downvote count: 0
has title: Didactically, how many and which layers can I identify in this CNN model?
has comment: http://stackoverflow.com/comment/81992506
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81992503
has body: This model will receive the pixels of an image as input. def model(data): conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME') hidden = tf.nn.relu(conv + layer1_biases) conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME') hidden = tf.nn.relu(conv + layer2_biases) shape = hidden.get_shape().as_list() reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]]) hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases) return tf.matmul(hidden, layer4_weights) + layer4_biases
tagged with: conv-neural-network
tagged with: deep-learning
score: 1
has comment: http://stackoverflow.com/comment/81992677
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/81992562
type: Question
has comment: http://stackoverflow.com/comment/82020492
answer count: 0

3d
tags question: http://stackoverflow.com/q/47444703
type: Tag
tag name: 3d
tags question: http://stackoverflow.com/q/47408448
tags question: http://stackoverflow.com/q/47417718
tags question: http://stackoverflow.com/q/47523018

http://stackoverflow.com/a/47517519
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47513816
has body: The QTextEdit textChanged signal has a different signature to the QLineEdit textChanged signal, in that it doesn't pass the text that was changed. This is because QTextEdit supports rich-text (i.e. html) as well as plain-text, so you need to explicitly request the content-type you want: self.IP.textChanged.connect(self.textSonDurum) def textSonDurum(self): print("Text changed...&gt;&gt;&gt; " + self.IP.toPlainText())
answers question: http://stackoverflow.com/q/47513816
type: Answer
upvote count: 6
type: AcceptedAnswer
score: 6

http://stackoverflow.com/a/47536975
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47536793
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82036255
answers question: http://stackoverflow.com/q/47536793
has body: Adding .values.tolist() st_or = list (Nsetg['Aip'].iloc[k:k+2].values.tolist() for k in range (0, len(Nsetg['Aip'])-1, 1))

http://stackoverflow.com/a/47526609
has comment: http://stackoverflow.com/comment/82009424
has body: You don't need to read the header separately. If you don't provide a fieldnames argument to DictReader(), the header is read automatically. Next, don't print your lines, you have now read the whole file and dropped all the lines. Open both the input and output files in the same with statement, you can then write lines directly to the output. There is no need to use the csv module here, because you don't need to parse out the rows, then form the rows into lines again. Just loop over the file, uppercase the lines, and write out the result: with open('data_csv.csv', 'r') as input, open('test.csv', 'w') as output: output.writelines(line.upper() for line in input)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82009784
has comment: http://stackoverflow.com/comment/82009497
answers question: http://stackoverflow.com/q/47526522

http://stackoverflow.com/q/47401325
tagged with: python
has title: Can not get TensorFlow working on mac for python
has body: I have created a from scratch AI model but its becoming to cumbersome to make improvements by hand and I would like to do the model in tensor flow instead in order to make it easier to modify. To do this I need to get TF working but when I install it I keep getting an error when importing it. It is as follows: "Could not import tensorflow. Do not import tensorflow from its source directory; change directory to outside the TensorFlow source tree, and relaunch your Python interpreter from there." I am using Pip3 and python 3 on mac so please if you have any idea whats wrong please help.
has comment: http://stackoverflow.com/comment/81760686
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/81759896
tagged with: tensorflow
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/81862930
type: Comment
comment on: http://stackoverflow.com/a/47453630
has text: Edited the answer with an example with your code (moved print total_A out of the for loop, though)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81800201
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47422789
type: AnswerComment
has text: @depperm answer.sort() is in place !!!!!!!

http://stackoverflow.com/q/47445780
type: AnsweredQuestion
score: 0
has title: How to define a function that counts the lower cases letters until reaching a value?
has body: Define a function countLowerFromUntil(...) which receives one string (st) and an integer value (start) as input. The string may potentially also be the empty string. This function should return how many lower case letters there are in the input string st, starting to count (and including) the start position and advancing one position at a time until reaching the end of the string or until reaching a digit (if there is such). The string may contain letters or digits. If the start value is out of the string range the function should return 0. Note: Keep in mind the string method islower() which returns true is applied to a character or a string containing only lower case letters. For example countLowerFromUntil("ABCxAxx1aa") should return 3, because there are three lower case letters (3 "x"'s) before reaching the digit 1 As an example, the following code fragment: val = countLowerFromUntil("ABCxAxx1aa",0) print (val) should produce the output: 3 so far I have this but I get an error: def countLowerFromUntil(st,ch): s = st().strip() count = 1 for i in s: if i.islower(): count = count + 1 return count
tagged with: string
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47445955
tagged with: python
has answer: http://stackoverflow.com/a/47445955

http://stackoverflow.com/q/47519294
accepted answer: http://stackoverflow.com/a/47519419
has comment: http://stackoverflow.com/comment/81994914
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47519419
possible better answer: http://stackoverflow.com/a/47519441
has title: pandas dataframe read csv with rows that have/not have comma at the end
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/47519441
has comment: http://stackoverflow.com/comment/81994902
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
upvote count: 3
tagged with: dataframe
favorite count: 0
type: Question
answer count: 2
has body: my sample file looks like this: 1.50424e+09,164.84,164.94,163.4,164.07,09:30:00,1.50424e+12,eAAPL,1.38904e+07,0,22.45,2.64333e+07,847097,18.49,1.54 1.50459e+09,163.8,164.25,158.26,162.2,09:30:00,1.50459e+12,eAAPL,2.54615e+07,0,22.44,2.64646e+07,847097,18.49,1.54 1.50467e+09,162.71,162.99,160.52,162.01,09:30:00,1.50467e+12,eAAPL,1.67919e+07,0,22.67,2.61136e+07,837180,18.27,1.55 1.50485e+09,160.9,161.15,158.62,158.7,09:30:00,1.50485e+12,eAAPL,2.02651e+07,0,22.73,2.48843e+07,832945,18.18,1.56, 1.50511e+09,160.51,162.05,159.89,161.48,09:30:00,1.50511e+12,eAAPL,2.44948e+07,0,22.54,2.50082e+07,819360,17.88,1.59, 1.50476e+09,162.17,163.69,160.36,161.175,09:30:00,1.50476e+12,eAAPL,1.88933e+07,0,22.68,2.58778e+07,836302,18.25,1.56, please scroll to the very right, you will see first 3 rows do not have comma at the end but the last 3 have comma. When i do f = pd.read_csv("AAPL.csv", header=None) it gives error saying: CParserError: Error tokenizing data. C error: Expected 15 fields in line 4, saw 16 how do i fix it?

http://stackoverflow.com/q/47483741
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81931687
score: 0
has comment: http://stackoverflow.com/comment/81922675
has answer: http://stackoverflow.com/a/47484023
answer count: 1
has comment: http://stackoverflow.com/comment/81922260
upvote count: 1
downvote count: 1
has body: so im building a simple decoder tool currently it is able to decode texting short hand expressions, like lol, to its full phrase based off of values stored in a dictionary read in from a txt file. what i would like to do is reverse this process. I would like to take the phrase laugh out loud out of the string and replace it with its abbreviation, lol. I'm new to python so my knowledge is currently limited substantially. I do know a string in immutable so i know to convert the string to a list but my issue is how do i split the string and still keep the laugh out loud together so i can run it agaisnt the dictionary. here is my code minus the txt file any ideas or comments would be greatly appreciated. class Decry: def __init__(self): self.dic_usr = 0 self.decrypted = "none" self.encrypted = "none" self.f = 0 self.list1 = [] self.list2 = [] self.list3 = [] self.dict1 = [] self.key1 = [] self.key2 = [] self.key3 = "none" def __buildDiction__(self): self.f = open("dict") self.build_list = self.f.read().splitlines() self.d_dict = {} for i in self.build_list: x = i.split(",") self.d_dict[x[0]] = x[1] return self.d_dict def decoder(self, usr): self.f = self.__buildDiction__() self.list1 = usr.split(" ") for i in self.list1: if i in self.f: self.list1[self.list1.index(i)] = self.f[i] self.decrypted = " ". join(self.list1) return self.decrypted def dictionary(self): self.f = self.__buildDiction__() self.list2 = [] self.list3 = [] self.dict1 = [] for i in self.f: self.list3.append(i) self.list2.append(self.f[i]) for n, g in zip(self.list3, self.list2): self.dict1.append(n) self.dict1.append(g) self.key1 = [self.dict1[i:i+2] for i in range(0, len(self.dict1), 2)] self.key2 = [" ".join(x) for x in self.key1] self.key3 = "\n".join(self.key2) return self.key3 def main(): print("\nWelecome to quick decrypt!!!\n" " /~~~~~~~~~~~~~~~~~~~~~~/") print("\n\nUse the number you desire.\n" "Proceed at your own risk:\n" " 1. Decrypts\n" " 2. Read dictionary\n" " 3. Add definitions to dictio…
has title: How do i replace values of a list when found in the dictionary with its key? python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47484023
has comment: http://stackoverflow.com/comment/81931522
has comment: http://stackoverflow.com/comment/81922728
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81922710

http://stackoverflow.com/a/47566134
downvote count: 0
type: Answer
has body: Your get method of PasswordResetConfirmView is responding with 2 different responses. Redirect When user is None it is responding with a Redirect URI if user is None: return redirect(reverse('dashboard-login')) So in that case the status code of response will be HTTP 302 means that you are redirected to some other URL. Render to response When there is user, then the information returned with the response is the method used in the request. return self.render_to_response(self.get_context_data(form=form)) So in that case the status code of response will be HTTP 200 means the request has succeeded. Solution: In order to make your test case pass you can use assertRedirects def test_password_reset_form(self): ... # A URL that redirects can be followed to termination. response = self.client.get(reverse('reset-password-confirm', args=[...]), follow=True) self.assertRedirects(response, reverse('dashboard-login'), status_code=302, target_status_code=200) self.assertEqual(len(response.redirect_chain), 2) If your request used the follow argument, the expected_url and target_status_code will be the url and status code for the final point of the redirect chain. Reference: https://github.com/django/django/blob/master/tests/test_client/tests.py Alternatively you can create two separate test cases (when user is logged-in, when user is not logged-in) and use assertEqual # Test for logged in user. def test_password_reset_form_for_logged_in_user(self): ... # do stuff self.assertEqual(response.status_code, status.HTTP_200_OK) # Test if user not logged in. def test_password_reset_form_if_user_not_logged_in(self): ... # do stuff self.assertEqual(response.status_code, status.HTTP_302_FOUND)
score: 3
answers question: http://stackoverflow.com/q/47511746
upvote count: 3

http://stackoverflow.com/comment/84677708
score: 1
has text: Strange that this code didn't work for me. I wonder whether something happened with a version of pyplot. The legend shows up but there's nothing inside it. It seems that `legend()` clears it out.
comment on: http://stackoverflow.com/a/47529821
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47424759
favorite count: 0
has body: 4) Find out totalMiles: Prompt --&gt; totalMiles = int(odoEnd) - int(odoStart) Prompt --&gt; averageDayMiles = totalMiles/daysRented totalMiles = ? totalMiles = 2222 - 1234 averageDayMiles = input(totalMiles/daysRented) if rentalCode == 'D' and averageDayMiles &lt; 100: mileCharge = 0 if averageDayMiles &gt; 100 and rentalCode == 'D': extraMiles = averageDayMiles - 100 mileCharge = extraMiles * 0.25*daysRented elif rentalCode == 'W': weeksRented = rentalPeriod averageMiles = totalMiles/weeksRented if averageMiles &gt; 900: mileCharge = weeksRented * 100.00 else: mileCharge = 0 I am having a really hard time figuring out how to code the above so that I do not get the following error :TypeError: unorderable types: str() &lt; int() If anyone has suggestions or can lead me in the direction of a link or reading that will help me better understand I would greatly appreciate it. Thank you in advance
has title: I am new to coding and I keep getting : if rentalCode == 'D' and averageDayMiles < 100: TypeError: unorderable types: str() < int()
type: Question
linked to: http://stackoverflow.com/q/46255103
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/46255103
score: -2
has answer: http://stackoverflow.com/a/47424796
tagged with: python
upvote count: 0
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/81815109
has text: In a neural network, you need positive and negative examples of a class. Thus, the algorithm can differentiate what is for example a car, and what is not. So you need more classes to tell them what is good and what is wrong.
score: 2
comment on: http://stackoverflow.com/q/47429267
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81797282
type: AnswerComment
has text: At first sight, I think that the issue was about copying the data correctly, but if you could confirm with actually profiling the two versions of the code it would be clear.
score: 0
comment on: http://stackoverflow.com/a/47407839
type: Comment

http://stackoverflow.com/q/47428132
possible better answer: http://stackoverflow.com/a/47428278
has comment: http://stackoverflow.com/comment/81810605
has title: regex syntax in python
duplicate of: http://stackoverflow.com/q/33582162
type: AnsweredQuestion
score: 0
has body: I have a log file like this [01012017 052235 500][1][INFO]&gt; ----Amount : 200 [01012017 052235 515][1][INFO]&gt; ----Mix : 1 [01012017 052235 515][1][INFO]&gt; ----Currency : LKR [01012017 052243 156][1][INFO]&gt; ----Denomination [01012017 052243 171][1][INFO]&gt; -----CU TYP I want to extract the date after the 1st square bracket and I wrote a python code as follows. transactionDate = re.findall('\[(.*?)\s\w+\s\w+\]\[\w\]\[INFO\]\&gt;\s+\w+Amount',strtosearch2,re.DOTALL) This gives a empty list. The expected output is: 01012017 Can you please help fix this error ?
has comment: http://stackoverflow.com/comment/81810671
accepted answer: http://stackoverflow.com/a/47428399
tagged with: regex
has comment: http://stackoverflow.com/comment/81810944
has answer: http://stackoverflow.com/a/47428278
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/33582162
has answer: http://stackoverflow.com/a/47428399
tagged with: python

http://stackoverflow.com/q/47507428
has comment: http://stackoverflow.com/comment/81990525
has comment: http://stackoverflow.com/comment/82014042
has comment: http://stackoverflow.com/comment/82007167
tagged with: python
has comment: http://stackoverflow.com/comment/81972693
has comment: http://stackoverflow.com/comment/81976448
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81975352
has comment: http://stackoverflow.com/comment/82012644
has comment: http://stackoverflow.com/comment/81975495
has comment: http://stackoverflow.com/comment/82012162
has comment: http://stackoverflow.com/comment/81974755
type: Question
has comment: http://stackoverflow.com/comment/81973032
has comment: http://stackoverflow.com/comment/81971815
tagged with: postgresql
has title: Fill Postgres column with highest available accuracy based on other column-id/table
type: UnansweredQuestion
has body: I have a pretty large database with 4 tables: post (200 Million) CREATE TABLE public."post" ( origin_id int REFERENCES public."origin"(origin_id), post_guid text, PRIMARY KEY (origin_id, post_guid), post_latlng geometry(Point, 4326), --only if lat/lng coordinates are available, otherwise add location information as in place, city or country table place_guid text, FOREIGN KEY (origin_id, place_guid) REFERENCES public."place"(origin_id, place_guid), city_guid text, FOREIGN KEY (origin_id, city_guid) REFERENCES public."city"(origin_id, city_guid), country_guid text, FOREIGN KEY (origin_id, country_guid) REFERENCES public."country"(origin_id, country_guid), ); place (1 Million) CREATE TABLE public."place" ( origin_id int REFERENCES public."origin"(origin_id), place_guid text, PRIMARY KEY (origin_id, place_guid), geom_center geometry(Point, 4326) ); city (500k) - definition synonymous to place country (200) - definition synonymous to place Index: CREATE UNIQUE INDEX idx_post ON public.post(origin_id, post_guid); CREATE UNIQUE INDEX idx_post_place ON public.place(origin_id, place_guid); The Table post is most important, it has among others the columns "origin_id" (integer, either 1, 2 or 3) and "post_guid" which together function as the Primary key. Similarly, place has "source_id" and "place_guid" etc. In table post, I have 4 columns: post_latlng place_guid city_guid country_guid I don't always have the lat/lng coordinates for all posts. In these cases, post_latlng should be substituted by location information (of lower accuracy) from place, city or country tables. I am not there yet to apply triggers to do this automatically, but even manually filling this information takes too long. For example, if I add a new geocode for a place that is already in the place-table, I do the following: insert_sql = ''' INSERT INTO "place" (origin_id, place_guid, geom_center) VALUES (%s,%s,ST_GeomFromText(%s,4326)) ON CONFLICT (origin_id,place_guid) DO UPDATE SET geom_center = EXCLUDED.g…
has comment: http://stackoverflow.com/comment/81976838
tagged with: database

http://stackoverflow.com/q/47497309
tagged with: string
has comment: http://stackoverflow.com/comment/81950453
downvote count: 1
has answer: http://stackoverflow.com/a/52977595
has comment: http://stackoverflow.com/comment/88615098
has answer: http://stackoverflow.com/a/67630576
favorite count: 0
has title: Find text position in PDF file
type: Question
upvote count: 28
linked to: http://stackoverflow.com/q/60557977
linked to: http://stackoverflow.com/q/8971243
tagged with: python
has comment: http://stackoverflow.com/comment/81950026
tagged with: text
possible better answer: http://stackoverflow.com/a/71215544
type: AnsweredQuestion
score: 27
answer count: 3
has answer: http://stackoverflow.com/a/71215544
tagged with: http://stackoverflow.com/tag/pdf
has body: I have a PDF file and I am trying to find a specific text in the PDF and highlight it using Python. I found pypdf, which can highlight part of a PDF when we give the coordinates of the wanted highlight position in the file. I am trying to find a tool which can give me the position of a given text in the PDF.
accepted answer: http://stackoverflow.com/a/52977595

http://stackoverflow.com/q/47426249
tagged with: graphviz
has answer: http://stackoverflow.com/a/57178590
score: 4
has answer: http://stackoverflow.com/a/70899585
tagged with: python-3.x
tagged with: python-2.7
has title: Finding list of edges in graphviz in Python
answer count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/49912714
type: UnansweredQuestion
upvote count: 7
favorite count: 0
has body: Is there any way to get list of edges in graphviz in python. In my program I wanted to check whether edge already exist between nodes before adding edge in the directed graph. I couldn't find any function like get_edge() or has_connected() function in grahviz in python. Is there any other way of doing the above mentioned task? Any help would be appreciated.
type: Question
tagged with: python

http://stackoverflow.com/comment/81954644
comment on: http://stackoverflow.com/a/47499580
has text: UnboundLocalError: local variable 'deadBody' referenced before assignment the list deadBody is a local variable using del() causing an unbound local error
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47447955
downvote count: 1
has comment: http://stackoverflow.com/comment/81851380
tagged with: arrays
has answer: http://stackoverflow.com/a/47448056
possible better answer: http://stackoverflow.com/a/47448064
favorite count: 0
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/432112
accepted answer: http://stackoverflow.com/a/47448056
tagged with: python
has body: I'm trying to find the index of a numpy array by value. The value however is also an array. In other words, it's a multi dimensional array. For example: a = [ [[1, 0], [0, 2], [3, 3]], [[1, 0], [1, 3], [1, 0]], [[4, 0], [2, 3], [3, 0]] ] I want to find the index of [[1, 0], [1, 3], [1, 0]], which is 1. Basically, I want to find the element in the array which matches the array pattern that I have. How can I do this using numpy?
has title: How to find the index of array by a value which is an array?
has answer: http://stackoverflow.com/a/47448064
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81851154
answer count: 2
upvote count: 1

http://stackoverflow.com/a/48651945
has body: I think you need to pip3 install virtualenv virtualenvwrapper and add this to your ~/.bashrc file export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 This is because your virtualenvwrapper is pointing to python3. I just resolved mine now. Thanks to this help
answers question: http://stackoverflow.com/q/47458172
upvote count: 5
score: 5
downvote count: 0
type: Answer

http://stackoverflow.com/q/47385781
has comment: http://stackoverflow.com/comment/81724608
upvote count: 5
has comment: http://stackoverflow.com/comment/81724529
has body: Suppose I have a pipeline for my data which does preprocessing and has an estimator at the end. Now if I want to just change the estimator/model at the last step of the pipeline, how do I do it without preprocessing the same data all over again. Below is a code example pipe = make_pipeline( ColumnSelector(columns), CategoricalEncoder(categories), FunctionTransformer(pd.get_dummies, validate=False), StandardScaler(scale), LogisticRegression(), ) Now I want to change the model to use Ridge or some other model than the LogisticRegression. How do I do this without doing the preprocessing all over again? EDIT: Can I get my transformed data from a pipeline of the following sort pipe = make_pipeline( ColumnSelector(columns), CategoricalEncoder(categories), FunctionTransformer(pd.get_dummies, validate=False), StandardScaler(scale) )
tagged with: python
has comment: http://stackoverflow.com/comment/81724575
has comment: http://stackoverflow.com/comment/81725186
has comment: http://stackoverflow.com/comment/81768331
type: AnsweredQuestion
has title: Using scikit Pipeline for testing models but preprocessing data only once
answer count: 2
has comment: http://stackoverflow.com/comment/81725131
tagged with: deep-learning
downvote count: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/81985155
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/47389468
possible better answer: http://stackoverflow.com/a/72453019
tagged with: data-science
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47389468
has answer: http://stackoverflow.com/a/72453019
score: 5
linked to: http://stackoverflow.com/q/43366561

http://stackoverflow.com/a/47393409
downvote count: 0
answers question: http://stackoverflow.com/q/47393295
type: Answer
score: 2
has body: You can create a dictionary from the list and use the count() function to do so. This will roughly work in the following way: result_occurrences = {i:scores_unique.count(i) for i in scores_unique} print result_occurrences This will work in Python 2.7. For Python 3 you can write: result_occurrences = {i:list(scores_unique.values()).count(i) for i in scores_unique} print(result_occurrences) Another way to do this is by using Collections.Counter.
upvote count: 2

http://stackoverflow.com/comment/81800485
has text: What have you tried, this is a very basic task. Unless you don't know any programming then I would assume you would have something you tried. Otherwise I would recommend going over a tutorial on Python.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47422899
type: Comment

http://stackoverflow.com/a/47445871
answers question: http://stackoverflow.com/q/47445761
score: 0
type: AcceptedAnswer
has body: i don't know about the code around it, but this issue is because your code is trying to use ascii encoding, so it can't handle the special characters to handle special characters with json you can just set ensure_ascii to false import json a = [ { "time": "30/3", "tag": "Iø" }, { "time": "12/4", "tag": "Da" } ] print(json.dumps(a, ensure_ascii=False, indent=4)) output: [ { "time": "30/3", "tag": "Iø" }, { "time": "12/4", "tag": "Da" } ]
accepted answer of: http://stackoverflow.com/q/47445761
type: Answer

http://stackoverflow.com/comment/81782454
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47413572
type: QuestionComment
has text: Just a couple of raw ideas: https://regex101.com/r/pWP0CK/1, https://regex101.com/r/pWP0CK/2 and https://regex101.com/r/pWP0CK/3

http://stackoverflow.com/a/47412501
has comment: http://stackoverflow.com/comment/89144837
answers question: http://stackoverflow.com/q/47406906
has comment: http://stackoverflow.com/comment/89144861
has body: The number of classes you are using is just one and you trained your model with images belonging to the same class and tested it for the same. So the problem is the model is skewed(predicts the same for all images) No matter whatever image you test it on, you will get the same output. Solution: Train you model with an nearly equal number of negative images. Ex:220 images containing the object to be identified(label them as 1) and another nearly 220 images not containing the object(label them as 0) Use F1 score to check your accuracy because it will help you understand if the dataset is skewed or not. Check this to learn about different kinds of accuracy measures. Take this course to learn more about CNNs.
has comment: http://stackoverflow.com/comment/81906027
score: 0
has comment: http://stackoverflow.com/comment/81921133
type: Answer
has comment: http://stackoverflow.com/comment/81927656
has comment: http://stackoverflow.com/comment/81920048
has comment: http://stackoverflow.com/comment/81781553

http://stackoverflow.com/q/47396339
has body: I was using py2exe trying to build a exe file for my python program when I received this error with the following traceback. Traceback (most recent call last): File "orchestrator.py", line 49, in &lt;module&gt; import process_text as proc File "process_text.pyc", line 14, in &lt;module&gt; File "utilfuncs.pyc", line 5, in &lt;module&gt; File "browsercookie\__init__.pyc", line 30, in &lt;module&gt; File "keyring\__init__.pyc", line 6, in &lt;module&gt; File "keyring\core.pyc", line 148, in &lt;module&gt; File "keyring\core.pyc", line 64, in init_backend File "keyring\util\__init__.pyc", line 20, in wrapper File "keyring\backend.pyc", line 179, in get_all_keyring File "keyring\backend.pyc", line 139, in _load_backends File "keyring\backend.pyc", line 131, in _load_backend File "importlib\__init__.pyc", line 37, in import_module ImportError: No module named kwallet my main module (the one that contains the main) is called orchestrator. my setup.py is like the following from distutils.core import setup import py2exe setup( console=['orchestrator.py'], options = {"py2exe":{"includes":["browsercookie"]}} ) I am using windows 10 with python 2.7 I did some digging but with no use. I did not find any exact or close matches to this error with py2exe. thanks a lot in advance.
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48892441
tagged with: python
score: 0
answer count: 1
has title: importerror: no module named kwallet
tagged with: py2exe

http://stackoverflow.com/comment/81957762
score: 0
has text: "This document has been removed from Scribd." --- Usually public shares on google drive or dropbox work fine.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47492363

http://stackoverflow.com/q/47524816
score: 2
upvote count: 2
answer count: 0
downvote count: 0
tagged with: python-requests
has comment: http://stackoverflow.com/comment/82008254
favorite count: 0
tagged with: proxy
type: Question
has body: When I do not use the HTTPS proxy (special), everything is normal! But use "requests" to return errors with the proxy HTTP: proxies = { 'http':"http://175.172.81.174:5324", 'https':"http://175.172.81.174:5324", } import requests r = requests.get("https://weibo.com/signup/signup.php",proxies=proxies,verify=False) HTTPSConnectionPool(host='weibo.com', port=443): Max retries exceeded with url: /signup/signup.php (Caused by SSLError(SSLError(1, u'[SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:661)'),)) When replaced with the following code, it works: from OpenSSL import SSL import socket proxies = { 'http':"http://175.172.81.174:5324", 'https':"http://175.172.81.174:5324", } headers = """GET https://weibo.com/signup/signup.php HTTP/1.1 Host: weibo.com Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Referer: https://weibo.com/ Accept-Language: zh-CN,zh;q=0.8\r\n\r\n """ def verify_cb(conn, cert, errun, depth, ok): return True server = 'weibo.com' port = 443 PROXY_ADDR = ("175.172.81.174", 5324) CONNECT = "CONNECT %s:%s HTTP/1.1\r\nConnection: close\r\n\r\n" % (server, port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(PROXY_ADDR) s.send(CONNECT) print s.recv(4096) ctx = SSL.Context(SSL.TLSv1_METHOD) ctx.set_verify(SSL.VERIFY_PEER, verify_cb) ss = SSL.Connection(ctx, s) ss.set_connect_state() ss.do_handshake() cert = ss.get_peer_certificate() print cert.get_subject() ss.send(headers) print ss.recv(3000) ss.shutdown() ss.close() How do I make "request" work? My system is Windows python2.7.13
tagged with: ssl
tagged with: python
type: UnansweredQuestion
has title: An SSL error occurred using the HTTPS proxy On Python Request
tagged with: python-2.7

http://stackoverflow.com/a/47393525
answers question: http://stackoverflow.com/q/47392457
score: 3
upvote count: 3
has body: You can use get_dummies first: df = pd.get_dummies(df.set_index('user'), prefix='', prefix_sep='').max(level=0) print (df) candy carrot meat user A 1 1 1 B 0 1 1 C 0 1 1 And then count by list comprehension: from itertools import combinations L = [(x[0], x[1],(df[list(x)] == 1).all(1).sum()) for x in list(combinations(df.columns, 2))] print (L) [('candy', 'carrot', 1), ('candy', 'meat', 1), ('carrot', 'meat', 3)] df = pd.DataFrame(L, columns=['food 1','food 2','num users']) print (df) food 1 food 2 num users 0 candy carrot 1 1 candy meat 1 2 carrot meat 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47392457
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81743211

http://stackoverflow.com/comment/81911750
score: 0
comment on: http://stackoverflow.com/q/47447270
has text: but you can use it to find the largest 10 objects.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81884274
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47464697
has text: Do you do the call from the same file as the one that contains the class definition ?
type: QuestionComment

http://stackoverflow.com/q/47475652
upvote count: 1
favorite count: 0
type: Question
has title: Equity Stock Portfolio Management Website using Django
accepted answer: http://stackoverflow.com/a/49894147
has body: I am trying to built a website for stock portfolio management. In that case, I need to take input of certain fields like stock code, buy value and quantity from the user. But I want to display more fields like today's value, today's change etc etc in the portfolio. Do I need to define them in models? As i don't need user input in that but it uses the user input for doing calculations.
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49894147
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82540276
type: QuestionComment
comment on: http://stackoverflow.com/q/47431458
score: 0
type: Comment
has text: @mkl Thank you for taking me across the situation but when I give page number I does extract from particular pdf page.Eg `tempPage = fileObject.getPage(8)` From file `118641.pdf` This line then extracts the image from file.

http://stackoverflow.com/a/47535823
answers question: http://stackoverflow.com/q/47530782
type: Answer
has comment: http://stackoverflow.com/comment/82054063
has comment: http://stackoverflow.com/comment/82049882
has comment: http://stackoverflow.com/comment/82028667
downvote count: 0
upvote count: 1
has body: If you just wan to see which words have "back-fixes" (the correct term is suffix, BTW), you can just use str.endswith in combination with any for w in words_list: if any(w.endswith(b) for b in back_fixs): print(w) Or pass all the suffixes to endswith, but for that they have to be in a tuple, not list: back_fixs = tuple(back_fixs) for w in words_list: if w.endswith(back_fixs): print(w) If you also need to know which suffix matches, you can get the next, or None if non match: for w in words_list: b = next((b for b in back_fixs if w.endswith(b)), None) if b: print(w, b) Or shorter using filter: b = next(filter(w.endswith, back_fixs), None) Or without default, using try/except: for w in words_list: try: print(w, next(filter(w.endswith, back_fixs))) except StopIteration: pass
has comment: http://stackoverflow.com/comment/82088129
score: 1

urllib
tags question: http://stackoverflow.com/q/47502679
tags question: http://stackoverflow.com/q/47418812
type: Tag
tag name: urllib
tags question: http://stackoverflow.com/q/47486901
tags question: http://stackoverflow.com/q/47392822
tags question: http://stackoverflow.com/q/47468510
tags question: http://stackoverflow.com/q/47408653
tags question: http://stackoverflow.com/q/47436883
tags question: http://stackoverflow.com/q/47422307
tags question: http://stackoverflow.com/q/47424088

python-sphinx
tags question: http://stackoverflow.com/q/47515424
tag name: python-sphinx
tags question: http://stackoverflow.com/q/47439594
tags question: http://stackoverflow.com/q/47438082
type: Tag

http://stackoverflow.com/q/47443670
upvote count: 2
downvote count: 0
has title: How to dynamically re-order items in matplotlib legend?
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/47444891
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47444891
score: 2
type: AnsweredQuestion
tagged with: matplotlib
has body: I am trying to create a simple bump chart where the legend order will be determined by the ranking of the most recent observations. I have a pandas DataFrame "y" with rankings across rows that looks like this. In[231]: y Out[231]: Currency AUD CAD CHF EUR GBP JPY NOK NZD SEK USD 2017-09-08 5.0 1.0 8.0 3.0 9.0 7.0 4.0 6.0 2.0 10.0 2017-09-22 8.0 2.0 10.0 1.0 5.0 9.0 4.0 6.0 3.0 7.0 2017-10-06 4.0 5.0 10.0 2.0 7.0 9.0 3.0 8.0 1.0 6.0 2017-10-20 3.0 4.0 10.0 1.0 7.0 5.0 6.0 9.0 2.0 8.0 2017-11-03 5.0 3.0 10.0 1.0 9.0 7.0 2.0 8.0 4.0 6.0 2017-11-17 5.0 4.0 10.0 1.0 9.0 7.0 3.0 8.0 2.0 6.0 The code I have used so far: import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates fig = plt.figure(figsize=(8.5,8.5)) ax = fig.add_subplot(111) l1,l2,l3,l4,l5,l6,l7,l8,l9,l10 = ax.plot_date(y.index.to_pydatetime(), y, '*-') ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=(4),interval=2)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) ax.yaxis.set_ticks(np.arange(1, 11, 1)) ax.set_title('Sample Chart', fontsize=20) plt.gca().invert_yaxis() fig.legend([l1,l2,l3,l4,l5,l6,l7,l8,l9,l10], ['AUD','CAD','CHF','EUR','GBP','JPY','NOK','NZD','SEK','USD'], 'right', fontsize=16, frameon=False, labelspacing=1.4) plt.tight_layout(pad=10) Which generates an output of fig.png My question is how to reorder the legend based on the last observation from '2017-11-17'? i.e. I want EUR, SEK, NOK, etc... I do not want a static alphabetical ordering. Essentially in fig.legend I need [l4,l9,l7,...,l3], although this list will reorder as rows are added to 'y'. I can easily generate a list with the proper ordering the ordering but fig.legend wont accept a list where the elements are in quotations, ie ['l4','l9','l7',...,'l3']. I may be approaching this completely wrong so any help would be great.
favorite count: 0
has comment: http://stackoverflow.com/comment/104647832
type: Question

http://stackoverflow.com/comment/81895101
score: 0
comment on: http://stackoverflow.com/q/47470270
has text: Can you show us your code and what you've tried?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81972007
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47507408
type: Comment
has text: @SACH: I don't see why that is a problem. It's up to the server what it generates for the URL, but you are matching on the same `stream` variable and extracting its value. I find that my answer produces similar changing URLs as other answers that you say work. Am I missing something?

http://stackoverflow.com/a/47412611
score: 0
answers question: http://stackoverflow.com/q/47412241
type: Answer
has body: You said: I want the result to be 300 in the first instance and 700 in the next instance, kind of generate a iterator object. So you simply need to turn the .provide method into a generator, and then call it appropriately. Like this: def append_zeros(x,y): x = int(str(x) + '00') y = int(str(y) + '00') #print x+y return x + y class Add_Nos(): def __init__(self,input_array): self.input_array = input_array def provide(self,callback): for each in self.input_array: x,y = each yield callback(x,y) add_nos = Add_Nos([(1,2),(3,4)]) for t in add_nos.provide(append_zeros): print t output 300 700 That append_zeros function is a bit strange. Rather than converting the args to strings so you can append the zeros and then converting the results back to ints to do the arithmetic yu should simply multiply each arg by one hundred. Also, you can make the .provide method a little more streamlined by using "splat" unpacking. And as tyteen4a03 mentioned, in Python 2 your Add_Nos class ought to inherit from object so that you get a new-style class instead of the deprecated old-style class. So here's another version with those changes; it produces the same output as the above code. def append_zeros(x, y): return x * 100 + y * 100 class Add_Nos(object): def __init__(self, input_array): self.input_array = input_array def provide(self, callback): for each in self.input_array: yield callback(*each) add_nos = Add_Nos([(1,2),(3,4)]) for t in add_nos.provide(append_zeros): print t

http://stackoverflow.com/q/47435751
tagged with: django-models
tagged with: python
tagged with: django-serializer
type: Question
upvote count: 2
downvote count: 0
answer count: 1
tagged with: django
favorite count: 0
has title: AttributeError when serializing model object on deletion
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47437521
accepted answer: http://stackoverflow.com/a/47437521
tagged with: http://stackoverflow.com/tag/json
has body: I work an a django project and want to keep objects deleted by users for databases synchronization, so I decided to store them in a json file. For this I override the delete() method of the model. I first retreive previously deleted objects from the file, and then add the one being deleted. When serializing this new list, I get an AttributeError: AttributeError: 'DeserializedObject' object has no attribute '_meta' What am I doing wrong ? Here is the delete() code : def delete(self, *args, **kwargs): force = kwargs.pop("force", None) if force is None: objects_to_delete = list() user_dir_path = os.path.join(STATIC_ROOT, self.user.username) if not os.path.exists(user_dir_path): os.makedirs(user_dir_path) path = os.path.join(user_dir_path, "obj_to_delete.json") if os.path.exists(path): with open(path, "r") as fp: json_str = fp.read() if len(json_str) &gt; 0: objects_to_delete = list(serializers.deserialize( "json", json_str, indent=4, use_natural_foreign_keys=True, fields=('pk', 'user', 'slug') )) objects_to_delete.append(self) if objects_to_delete: with open(path, "w") as fp: jsonData = serializers.serialize("json", objects_to_delete, indent=4, use_natural_foreign_keys=True, fields=('pk', 'user', 'slug') ) fp.write(jsonData) super(UserOwnedModel,self).delete(*args, **kwargs)

http://stackoverflow.com/q/47384294
tagged with: python
has title: Python: record video on motion, but release VideoWriter when motion not present
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47475849
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: opencv
accepted answer: http://stackoverflow.com/a/47475849
has body: My goal of this script is to start recording to a video file when motion is detected. When motion is no longer detected, the writer will be released and the script will create a new video the next time that motion is detected...and so on. With the below script, I'm able to start writing to a video file once motion is detected, but I have to press the q button to release the writer and make the video playable. If I don't press q, the recording will stop, but the next time there's motion it will just be added to the existing video. I've tried writer.release() in a few places without success. # import the necessary packages from pyimagesearch.tempimage import TempImage import argparse import warnings import datetime import imutils import json import numpy as np import time import cv2 print("[INFO] Kicking off script - " + datetime.datetime.now().strftime("%Y-%m-%d_%H_%M_%S")) # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-c", "--conf", required=True, help="path to the JSON configuration file") args = vars(ap.parse_args()) # filter warnings, load the configuration and initialize the Dropbox # client warnings.filterwarnings("ignore") conf = json.load(open(args["conf"])) client = None # initialize the camera and grab a reference to the raw camera capture # if the video argument is None, then we are reading from webcam if not conf["use_ip_cam"]: camera = cv2.VideoCapture(0) time.sleep(0.25) # otherwise, we are reading from a video input else: camera = cv2.VideoCapture(conf["ip_cam_addr"]) # allow the camera to warmup, then initialize the average frame, last # uploaded timestamp, and frame motion counter print("[INFO] warming up...") time.sleep(conf["camera_warmup_time"]) avg = None lastUploaded = datetime.datetime.now() motionCounter = 0 fourcc = 0x00000020 # a little hacky, but works for now writer = None (h, w) = (None, None) zeros = None output = None # capture frames from the camera # for f in camera.capture_con…

http://stackoverflow.com/q/47446674
tagged with: list
score: 0
has body: I need a function or code to concatenate some lists in a list. I searched here in this site for a solution but I didn't find a suitable one with my need, also I tried many solutions without result. I have this example from my code: the list is: [['He', 'is', [0, 1, 2, 3, 4, 5, 6, 7]], ['is', 'angry.', [0, 1]], ['is', 'happy.', [2, 3]], ['is', 'sleep.', [4]], ['angry.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['happy.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['going.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['sleep.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['sad.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]]] I need to group the lists that have same first value e.g. by 'is' the output should be like: [['He', 'is', [0, 1, 2, 3, 4, 5, 6, 7]], ['is', ['angry.',' happy.', 'sleep.'], [[0, 1], [2, 3], [4]]], ['angry.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['happy.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['going.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['sleep.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]], ['sad.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]]] any suggestions?
answer count: 1
has comment: http://stackoverflow.com/comment/81940104
type: Question
has comment: http://stackoverflow.com/comment/81848813
has title: concatenate lists in a list by comparing first element Python
has answer: http://stackoverflow.com/a/47447093
accepted answer: http://stackoverflow.com/a/47447093
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47383825
tagged with: python
has body: When I try to make the code function, I get a 400 error, however, I am looking for a 250 Okay success messages. The different messages are designed to display if the programs functions properly or not. There are two parts to this: the client code and the server code. Any suggestion as to what could be causing this problem? Client Server Code # Client to implement simplified RSA algorithm. # The client says hello to the server, and the server responds with a Hello # and its public key. The client then sends a session key encrypted with the # server's public key. The server responds to this message with a nonce # encrypted with the server's public key. The client decrypts the nonce # and sends it back to the server encrypted with the session key. Next, # the server sends the client a message with a status code. If the status code # is "250" then the client can ask for the server to roll the dice. Otherwise, # the client's connection to the server will be terminated. #!/usr/bin/python3 import socket import math import random import sys import time import simplified_AES def expMod(b,n,m): """Computes the modular exponent of a number returns (b^n mod m)""" if n==0: return 1 elif n%2==0: return expMod((b*b)%m, n/2, m) else: return(b*expMod(b,n-1,m))%m def RSAencrypt(m, e, n): """Encryption side of RSA""" return expMod(m,e,n) ## Add code to encrypt. You _must_ use the expMod method. ##return 3 def RSAdecrypt(c, d, n): """Decryption side of RSA""" return expMod(c,d,n) ## Add code to decrypt. You _must_ use the expMod method. def serverHello(): """Sends server hello message""" status = "100 Hello" return status def sendSessionKey(s): """Sends server session key""" status = "110 SessionKey " + str(s) return status def sendTransformedNonce(xform): """Sends server nonce encrypted with session key""" status = "130 Transformed Nonce " + str(xform) return status def computeSessionKey(): """Computes this node's session key""" sessionKey = random.randint(1, 65536) return sessionKey …
favorite count: 0
score: 1
tagged with: unix
tagged with: aes
type: Question
has title: I have an issue with this python socket coding, client/server not functioning properly
answer count: 0
type: UnansweredQuestion
tagged with: sockets
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81971980
comment on: http://stackoverflow.com/q/47508003
type: QuestionComment
has text: Thanks for your comment, I've updated my question correspondingly.
score: 0
type: Comment

http://stackoverflow.com/comment/81876948
score: 0
type: Comment
has text: @Bharath, I'm new to this. Yours was the best answer for what I was looking for. Happy Thanksgiving!
type: AnswerComment
comment on: http://stackoverflow.com/a/47439727

http://stackoverflow.com/a/68666734
answers question: http://stackoverflow.com/q/47533450
upvote count: 3
downvote count: 0
has body: It's 3 years late, but I hope that it will help someone. When you remove primary_key attr in all your model fields, Django will try to create an AutoField field named id, which will be the primary_key of your model, but when you already have data in the DB, you must set a default value for existing entries which will cause another issue because primary_key is unique. But a solution can be to create manually an primary_key field named id in your SQL table. Remove the current primary key ALTER TABLE tablename DROP PRIMARY KEY; Create a new primary key field ALTER TABLE tablename ADD id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST; If you want that Django takes this field as default primary key, you must set its name as id. Make migrations on you django app. Delete all your migrations files in the corresponding app and re-run python manage.py makemigrations. Your code must be like: class MyModel(models.Model): sessionid = models.ForeignKey('Session', models.DO_NOTHING, db_column='sessionID') datetime = models.BigIntegerField() ...
type: Answer
score: 3

http://stackoverflow.com/comment/81815190
has text: I meant: What's the goal of the algorithm?
score: 1
comment on: http://stackoverflow.com/q/47430030
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47480354
accepted answer: http://stackoverflow.com/a/47856302
tagged with: flask
tagged with: jinja2
favorite count: 0
has body: I use WTForms to define form for data filtering it is defined like this (My goal is to have user specified labels for BooleanFields set, I let each user to name labels for fields and I save name of fields to Google Datastore): class MainFilterForm(FlaskForm): """ Represents main filter form. """ start_date = pendulum.parse( str(pendulum.today().year) + str(pendulum.today().month) + '01') end_date = pendulum.today() calendar_colors_descriptions = CalendarColorsDescription( users.get_current_user().user_id() ).get_colors_description() search_query = StringField( 'Search', [ validators.Length(min=1, max=128), validators.optional()], default=None) start_date = DateField( 'Start date', [validators.required()], format='%Y-%m-%d', default=start_date) end_date = DateField( 'End date', [validators.required()], format='%Y-%m-%d', default=end_date) i_am_owner = BooleanField( 'I am owner', default=False) include_all_day_events = BooleanField( 'Include all day events', default=False) selected_colors_calendar_color = BooleanField( calendar_colors_descriptions[0], default=True) selected_colors_color1 = BooleanField( calendar_colors_descriptions[1], default=True) selected_colors_color2 = BooleanField( calendar_colors_descriptions[2], default=True) selected_colors_color3 = BooleanField( calendar_colors_descriptions[3], default=True) selected_colors_color4 = BooleanField( calendar_colors_descriptions[4], default=True) selected_colors_color5 = BooleanField( calendar_colors_descriptions[5], default=True) selected_colors_color6 = BooleanField( calendar_colors_descriptions[6], default=True) selected_colors_color7 = BooleanField( calendar_colors_descriptions[7], default=True) selected_colors_color8 = BooleanField( calendar_colors_descriptions[8], default=True) selected_colors_color9 = BooleanField( calendar_colors_descriptions[9], default=True) selected_colors_color10 = BooleanField( calendar_colors_descriptions[10], default=True) selected_colors_color11 = BooleanField( calendar_colors_de…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59527398
tagged with: google-app-engine
possible better answer: http://stackoverflow.com/a/59527398
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/47856302
type: Question
answer count: 2
downvote count: 0
has title: How to make Flask-WTFoms update labels dynamically from list of label names?
tagged with: wtforms
score: 4

http://stackoverflow.com/comment/81976838
comment on: http://stackoverflow.com/q/47507428
has text: Absolutely correct joop - thanks for pointing this out. At the moment, I haven't started transferring entries which have exact lat/lng but I will need to take care of that in the future.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81906505
score: 0
type: Comment
has text: I see this.. where would I put it in the code I already have? I have seen this try-except method and attempted to put it into my code for about 30 min. Couldn't figure it out.
comment on: http://stackoverflow.com/a/47475632
type: AnswerComment

http://stackoverflow.com/q/47539919
has comment: http://stackoverflow.com/comment/82037026
has comment: http://stackoverflow.com/comment/82037330
type: UnansweredQuestion
answer count: 1
has title: Sort descending count column for same row of test
upvote count: 1
tagged with: sorting
downvote count: 1
has comment: http://stackoverflow.com/comment/82037398
score: 0
has answer: http://stackoverflow.com/a/47540200
tagged with: pandas
tagged with: python
has body: I want to sort one column based on the other column. I don't know how to do it in python using pandas. Basically I want to suggest recommendation for the test column in descending order This is what my data frame : ] This is what I tried to do. Group by test column then sort on count column but it didn't work. My Code :: final.groupby(['test']) final.sort_values(['count'], ascending=False) This is what i exactly want.
favorite count: 0
has comment: http://stackoverflow.com/comment/82037187
has comment: http://stackoverflow.com/comment/82037154
type: Question

http://stackoverflow.com/comment/81907235
type: Comment
comment on: http://stackoverflow.com/q/47476261
type: QuestionComment
score: 2
has text: @Mohd It sound like your problem is with size of the file, which you put into a memory, not with select function.

http://stackoverflow.com/comment/81828165
type: AnswerComment
has text: Sure it will! Change your CharField to be a DateTimeField and you can flexibly query on it :) `range` should work great for example: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#range
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47436483

http://stackoverflow.com/q/47404605
upvote count: 0
has title: how can i retrive the attributes which influence the result in a dataset in python
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
score: -2
has body: I am a beginner. I am doing gpa prediction. My dataset have variables like travel time of the student,study time , parents occupation , their grades,mother occupation etc.how can i retrieve the attributes which influence the gpa of the student? My data has both categorical and discrete values.
downvote count: 2
has answer: http://stackoverflow.com/a/47408520
has comment: http://stackoverflow.com/comment/81763408
favorite count: 0
type: Question
tagged with: prediction
answer count: 2
has answer: http://stackoverflow.com/a/47452902
tagged with: feature-selection

http://stackoverflow.com/comment/81755794
type: Comment
has text: I am happy that it was helpful to you :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47385802

http://stackoverflow.com/comment/81918244
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47474155
score: 1
has text: In addition to the above, images stored on your disk as PNG or JPEG are compressed by the nature of those formats, and `imread` decompresses them to put the data into an array.

http://stackoverflow.com/q/47480516
has body: Can someone tell me how do this? I got main.py and gui.py (made in pyqt4). The main.py runs some code, whatever, print "hello world" and I want to pass this string to gui.py in listWidget.addItem(). So in main.py I did: from gui import Ui_Form send_str = "hello all" ui.listWidget.addItem(send_str) and I get the error: NameError: global name 'ui' is not defined. which points to gui.py as in gui.py is if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) If i put both code in one py, all if working. How to separate these two, since i want my main.py to execute in endless loop, and from time to time i want to open gui and check whats new value main.py going to send to window?
tagged with: python
has title: Passing string from one py to gui
score: 0
tagged with: pyqt
answer count: 1
has comment: http://stackoverflow.com/comment/81929699
has comment: http://stackoverflow.com/comment/81915977
type: Question
has comment: http://stackoverflow.com/comment/81930110
has comment: http://stackoverflow.com/comment/81930353
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81930530
tagged with: pyqt4
has answer: http://stackoverflow.com/a/47480802

http://stackoverflow.com/comment/82002153
comment on: http://stackoverflow.com/q/47522357
score: 0
has text: Got it, thanks for your help!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47500315
type: Question
tagged with: python-3.x
has body: I have a Pandas dataframe that collects the names of vendors at which a transaction was made. As this data is automatically collected from bank statements, lots of the vendors are similar... but not quite the same. In summary, I want to replace the different permutations of the vendors' names with a single name. I think I can work out a way to do it (see below), but I'm a beginner and this seems to me like it's a complex problem. I'd be really interested to see how more experienced coders would approach it. I have a dataframe like this (in real life, it's about 20 columns and a maximum of around 50 rows): Groceries Car Luxuries 0 Sainsburys Texaco wst453 Amazon 1 Sainsburys bur Texaco east Firebox Ltd 2 Sainsbury's east Shell wstl Sony 3 Tesco Shell p/stn Sony ent nrk 4 Tescos ref 657 Texac Amazon EU 5 Tesco 45783 Moto Amazon marketplace I'd like to find the similar entries and replace them with the first instance of those entries, so I'd end up with this: Groceries Car Luxuries 0 Sainsburys Texaco wst453 Amazon 1 Sainsburys Texaco wst453 Firebox Ltd 2 Sainsburys Shell wstl Sony 3 Tesco Shell wstl Sony 4 Tesco Texaco wst453 Amazon 5 Tesco Moto Amazon My solution might be far from optimum. I was thinking of sorting alphabetically, then going through bitwise and using something like SequenceMatcher from difflib to compare each pair of vendors. If the similarity is above a certain percentage (I'm expecting to play with this value until I'm happy) then the two vendors will be assumed to be the same. I'm concerned that I might be using a sledgehammer to crack a nut, or it might take a long time (I'm not obsessed with performance, but equally I don't want to wait hours for the result). Really interested to hear people's thoughts on this problem!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81957422
score: 2
tagged with: python
has title: Replace similar strings in a column with the same string
tagged with: pandas
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/81957162
linked to: http://stackoverflow.com/q/64704015
has answer: http://stackoverflow.com/a/47502290
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47441899
favorite count: 0
has comment: http://stackoverflow.com/comment/81839314
type: Question
has title: How to know when client disconnects in Flask app
has comment: http://stackoverflow.com/comment/81839846
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81839056
upvote count: 7
tagged with: long-polling
tagged with: flask
has comment: http://stackoverflow.com/comment/81839253
has body: I'm trying to use HTTP long polling, roughly something like this: @app.route('/get_stuff', methods=["GET"]) def get_stuff(): while True: stuff = database.lookupSomething() if stuff: return json.dumps(stuff) else: time.sleep(1) This works excellent however if the client cuts the connection, the server will still run the loop. I would like to replace the loop with something like this: while client.is_connected(): .... However, I cannot find any way of knowing if the connection is still valid. Others have asked the same question, and the answer has been to use SocketIO. I cannot do this however and would rather use a simple GET request like above. Is there a way of knowing if the client has closed his connection?
score: 7
tagged with: connection
has comment: http://stackoverflow.com/comment/81839240

http://stackoverflow.com/a/47464463
type: Answer
has body: I found the solution: def mark_complete(self): while True: try: mark_complete = self.driver.find_element_by_xpath('//button[contains(.,"Mark complete")]') mark_complete.click() except NoSuchElementException: break
answers question: http://stackoverflow.com/q/47446489
has comment: http://stackoverflow.com/comment/89091872
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47446489
score: 1
has comment: http://stackoverflow.com/comment/89024693

http://stackoverflow.com/q/47397412
tagged with: python
type: UnansweredQuestion
answer count: 1
tagged with: automated-tests
score: 0
has body: I am trying to get all xpaths that start with something, but when I test it out, it says my xpath is invalid. This is my xpath: xpath = "//*[contains(@id,'ClubDetails_"+ str(team) +"']" Which outputs when I print: //*[contains(@id,'ClubDetails_1'] Here is HTML: Bev Garman armadaswim@aol.com Rolling Hills Country Day School 26444 Crenshaw Blvd Rolling Hills Estates, CA 90274 This club also swims at other locations show them... What am I missing ?
has title: invalid xpath expression python
tagged with: selenium
has comment: http://stackoverflow.com/comment/81748051
has answer: http://stackoverflow.com/a/53512808
tagged with: xpath
type: Question

http://stackoverflow.com/q/47472245
favorite count: 0
type: Question
tagged with: iterator
has answer: http://stackoverflow.com/a/47472854
upvote count: 0
has answer: http://stackoverflow.com/a/47472569
has body: I a have JSON file that contains a list likes this: "locales": { "de": { "default": { "vegetables": [ "apple", "melon", "grape", "pear" ] } }, "fr": { "default": { "vegetables": [ "apple", "melon", "grape", "pear" ] } }, "nl": { "default": { "vegetables": [ "apple", "melon", "grape", "pear" ] } }, (...) } I would like to iterate over the locales ad manipulate vegetables depending on the locale (de, fr, nl etc.). How can I achieve that with python? I tried something like import json _MY_CUSTOM_ORDER_DE = [ "pear", "grape", "apple", "melon"] _MY_CUSTOM_ORDER_NL = [ "melon", "pear", "apple", "grape"] def updateJsonFile(): jsonFile = open('vegetables.json', 'r') data = json.load(jsonFile) jsonFile.close() for item in data["locales"]: if item == "de": item["default"]["vegetables"] = _MY_CUSTOM_ORDER_DE elif item == "nl": item["default"]["vegetables"] = _MY_CUSTOM_ORDER_NL else: ## do nothing ## with open('sortedvegetables.json', 'w') as outfile: json.dump(data, outfile, indent=4, sort_keys=True) def main(): updateJsonFile() if __name__ == '__main__': main() Unfortunately this does not work but there is now error in terminal after I executed the script. sortedvegetables.json looks exactly the same like vegetables.json
tagged with: python
score: -1
tagged with: sorting
has title: Iterate over list of JSON objects
has comment: http://stackoverflow.com/comment/81899075
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47472854
accepted answer: http://stackoverflow.com/a/47472569
has comment: http://stackoverflow.com/comment/81898863
answer count: 2
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
has comment: http://stackoverflow.com/comment/81898782
has comment: http://stackoverflow.com/comment/81898842

http://stackoverflow.com/comment/81831062
score: 4
has text: Forget about C, this is Python! You do not need to define list's length before.
comment on: http://stackoverflow.com/q/47438248
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47529297
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47527222
accepted answer of: http://stackoverflow.com/q/47527222
score: 1
has body: You can use BeautifulSoup to find all tags with class="post". Then for each tag, you search a &lt;a&gt; tag in a descendant from its parent, and test whether its text is the topic you are interested in. If true, you add the postname to a result list. Code could be: def findposts(soup, topic): '''Finds all postname associated to topic in a BeautifulSoup element''' posts = [] # initialize an empty result list # search postnames by class for postname in soup.findAll('a', attrs = {'class': 'post'}): # find associated topic in immediate parent if postname.findParent().find('a').text == topic: posts.append(postname.text) # Ok add to result list return posts With your example data, you could do: soup = BeautifulSoup('data', 'html.parser') print(findpost(soup, 'topic') and the result would be as expected: ['postname']
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82021624
type: Comment
comment on: http://stackoverflow.com/a/47530371
score: 0
type: AnswerComment
has text: I've seen a "hacky" solution import all needed modules in the initial __init__.py of each subfolder, then the __init__.py of the main module would import each of those.

http://stackoverflow.com/comment/81829688
type: AnswerComment
comment on: http://stackoverflow.com/a/47437516
has text: That's why I said it's not quite as simple :) I see the question has been flagged as a duplicate. The other questions/answers actually explain why your statement evaluates to `True`. I expect that if you perform the `id` check after changing `value` in your second example, it will no longer be the same.
type: Comment
score: 0

http://stackoverflow.com/comment/82009704
score: 0
comment on: http://stackoverflow.com/q/47526363
type: QuestionComment
type: Comment
has text: multiprocessing uses [pickle](https://docs.python.org/3/library/pickle.html) to serialize data, and can handle classes as well as recursive structures.

http://stackoverflow.com/q/47477190
tagged with: elementtree
favorite count: 0
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/81927994
has body: I have a large XML file which is more than 1 GB. I want to pull out the text from it and write to a text file. The problem is that the file contains some invalid characters like '&amp;' (and I don't even need to write them, I can remove totally). First, I used ElementTree to parse the file as below: import xml.etree.ElementTree as ET import re newFile = open('using_element_tree.xml', 'w', encoding="utf8") file = "newscor.xml" context = ET.iterparse(file, events=("start", "end")) context = iter(context) for event, elem in context: tag = elem.tag tag = re.sub('{http://www.xml-ces.org/schema}', '', tag) if event == 'start' and (tag == 's' or tag == 'q'): value = elem.text if value: value = value.strip("&amp;, &lt;, &gt;") value = value.strip() newFile.write(value) print(value) elem.clear() However, it gave me xml.etree.ElementTree.ParseError: not well-formed (invalid token) error on this line: for event, elem in context: This is because of an &amp; character. I could not find a way to escape invalid characters before entering the for loop. I tried to use lxml with a recover=True parameter, but it has no iterparse() function with this option. Then, I used BeautifulSoup to parse my file as below: from bs4 import BeautifulSoup from bs4 import SoupStrainer newFile = open('using_bs4.xml', 'w', encoding="utf-8") def only_s_and_q_tags(): return "s" or "q" s_and_q_tags = SoupStrainer(only_s_and_q_tags()) with open("newscor.xml", encoding="utf-8") as fp: soup = BeautifulSoup(fp, "xml", parse_only=s_and_q_tags) for string in soup.strings: if string not in ['\n', '\r\n']: print(repr(string)) newFile.write(string) This did not give me any error, (exited with code 0) and write to the text file, but only a tiny portion of my file. I could not understand what should I do since there is no error. What should I do to avoid invalid characters and parse my file? Please point me to a direction to handle this issue.
linked to: http://stackoverflow.com/q/44765194
answer count: 0
has title: Parsing large XML file which contains invalid characters
score: 1
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/44765194

http://stackoverflow.com/q/47471516
has comment: http://stackoverflow.com/comment/81897789
has comment: http://stackoverflow.com/comment/81898012
linked to: http://stackoverflow.com/q/1112343
has title: How to run a command before stopping a python script
has comment: http://stackoverflow.com/comment/81897528
accepted answer: http://stackoverflow.com/a/47472144
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4205317
score: 0
has comment: http://stackoverflow.com/comment/81897575
upvote count: 1
has comment: http://stackoverflow.com/comment/81897881
has answer: http://stackoverflow.com/a/47472144
answer count: 1
has comment: http://stackoverflow.com/comment/81897909
has comment: http://stackoverflow.com/comment/81898048
has comment: http://stackoverflow.com/comment/81897467
downvote count: 1
has body: I have a python code which start a UDP communication on a port 5002. So what happens is when I first run the code, it works normally then I close the python script using ctlr z/ctrl c and then again run the code it shows me below error: sock.bind(address) OSError: [Errno 98] Address already in use This may be because the python script is running and keeping the port busy. So it shows me the above error. To resolve this, I thought of running these two commands right before the code kills sock.close() to close the socket and sys.exit() to exit the python script properly. Thats why I need to know how can I run these commands right before the code is killed. I cannot use KeyboardInterrupt exception because in future this will be running as a service. I found this answer but not able to implement it. For example, if I do: import atexit import time def exit_handler(): print("STOPPED") while True: print("Running....") time.sleep(1) atexit.register(exit_handler) This keeps on running but when I kill the code it doesn't print Stopped. How to implement it or is there any alternative way of handling my situation. Thanks
favorite count: 0
linked to: http://stackoverflow.com/q/3850261
has comment: http://stackoverflow.com/comment/81898072
type: Question

http://stackoverflow.com/a/47482121
downvote count: 0
answers question: http://stackoverflow.com/q/47481607
upvote count: 1
has comment: http://stackoverflow.com/comment/81919334
has body: You could try this: def sub_order(string1, string2): # get all the matches in the second string matches = [char for char in string2.lower() if char in string1.lower()] # record the found characters that match found = [] # create stack of string1, to ensure which characters have been found stack = list(string1.lower()) # Go through each character in the substring for match in matches: # If the stack is not empty, keep checking if stack: # if a character matches the character at the top of the stack if match == stack[0]: # append what character was found, and pop the stack found.append(match) stack.pop(0) # check if the string found matches string1 if "".join(found) == string1.lower(): return True return False The method used here: Get all the of the matching characters from string2 which occur in string1. Go through each of the matching characters, and check them, using a stack based approach of knocking down characters that have already been found. if an ordering was found that matches the ordering of string1, return, otherwise keep searching if possible.
type: Answer
score: 1

http://stackoverflow.com/q/47513024
has answer: http://stackoverflow.com/a/52637130
downvote count: 1
answer count: 13
favorite count: 0
upvote count: 89
has answer: http://stackoverflow.com/a/53831901
has answer: http://stackoverflow.com/a/53985672
has answer: http://stackoverflow.com/a/49295044
has answer: http://stackoverflow.com/a/47721925
tagged with: bash
has body: When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do: $ brew link python After entering that the same error message appears: permission denied @ dir_s_mkdir - /usr/local/lib I have tried to do: $ sudo chown -R $(whoami) /usr/local And I get an error message that reads: chown: /usr/local: Operation not permitted
score: 88
linked to: http://stackoverflow.com/q/33268389
has comment: http://stackoverflow.com/comment/95695047
has title: How to Fix Permissions on Home-brew on MacOS High Sierra
tagged with: python
has answer: http://stackoverflow.com/a/50849890
has answer: http://stackoverflow.com/a/47788232
has comment: http://stackoverflow.com/comment/82339834
has comment: http://stackoverflow.com/comment/82330194
type: Question
has answer: http://stackoverflow.com/a/47686392
has answer: http://stackoverflow.com/a/51736916
has answer: http://stackoverflow.com/a/63247687
has answer: http://stackoverflow.com/a/47687960
has comment: http://stackoverflow.com/comment/82329897
tagged with: homebrew
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47732558
has answer: http://stackoverflow.com/a/54549414
has comment: http://stackoverflow.com/comment/95687615

http://stackoverflow.com/comment/81741734
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47394322
has text: The transformers are separated for readability. So you'd advice to have the outmost function `yield` instead of returning a generator?
type: Comment

http://stackoverflow.com/comment/81768319
type: Comment
has text: @roganjosh not so sure I understand your question right but I would say all the errors I got are not related to memory
type: QuestionComment
comment on: http://stackoverflow.com/q/47407576
score: 0

http://stackoverflow.com/a/47514798
score: 3
has body: All you have to do is to loop through self.obox_Type_idx and use the get method of the StringVar to get the current selection of the optionmenu: def on_press(self): self.list_Role = [var.get() for menu, var in self.obox_Role_idx] and create a button whose command is on_press. When this button is pressed, then the list of selected roles is stored in self.list_Role.
accepted answer of: http://stackoverflow.com/q/47514567
type: Answer
answers question: http://stackoverflow.com/q/47514567
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47409595
answers question: http://stackoverflow.com/q/47409365
has comment: http://stackoverflow.com/comment/81772530
score: 3
upvote count: 3
type: AcceptedAnswer
has body: You could simply pass __file__ as a parameter in files.py import os def get_current_dir(file): return os.path.abspath(os.path.dirname(file)) in service.py from utils.files import get_current_dir print(get_current_dir(__file__))
accepted answer of: http://stackoverflow.com/q/47409365
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82029143
type: QuestionComment
has text: BTW: when you do `var = Widget(...).pack(...)` then you assign `None` to `var` because `pack()/grid()/place()` return `None`. If you don't need this `var` then you can skip it and do `Widget(...).pack(...)`. If you need this `var` then you have to do it in two lines: `var = Widget(...)` and `var.pack(...)`
score: 0
comment on: http://stackoverflow.com/q/47533609
type: Comment

http://stackoverflow.com/comment/81748509
has text: Can't you use 'groupby' with 'max'?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47397696
type: Comment

http://stackoverflow.com/a/47489655
has comment: http://stackoverflow.com/comment/81934728
downvote count: 0
has comment: http://stackoverflow.com/comment/81934712
has comment: http://stackoverflow.com/comment/81934428
has body: Use unstack for reshape, to_frame for one column df and then transpose by T. Last create columns by flattening MultiIndex by map and join: #select first value of level id id1 = df_fdw.index.get_level_values('id')[0] df = df.unstack().to_frame(id1).T df.columns = df.columns.map('_'.join) print (df) x_amax x_amin x_std x_func1 x_func2 z_amax z_amin z_std \ 1 5.0 1.0 1.581139 3.0 15.0 6.0 1.0 2.48998 z_func1 z_func2 1 2.8 14.0 Solution for multiple id (working nice for unique id too): df = pd.DataFrame({"id":[1]*2 + [2]*3,"x":[1,2,3,4,5], "z":[1,1,1,5,6]}) df.set_index("id", drop=True, append=True, inplace=True) #sample functions def func1(x): return x.mean() def func2(x): return x.sum() funcs = [np.max, np.min, np.std, func1, func2] df = df.groupby(level='id').aggregate(funcs) df.columns = df.columns.map('_'.join) print (df) x_amax x_amin x_std x_func1 x_func2 z_amax z_amin z_std \ id 1 2 1 0.707107 1.5 3 1 1 0.000000 2 5 3 1.000000 4.0 12 6 1 2.645751 z_func1 z_func2 id 1 1 2 2 4 12
type: Answer
has comment: http://stackoverflow.com/comment/81934464
has comment: http://stackoverflow.com/comment/81934489
answers question: http://stackoverflow.com/q/47489595
score: 3
accepted answer of: http://stackoverflow.com/q/47489595
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/47422338
has answer: http://stackoverflow.com/a/47422404
has body: I have succesfully made a code which starts a server which can be connected by other devices on my LAN with the CMD command telnet hostname port when the new "client" enters a word and presses enter the word is then sent back to them through the server. My question is if i connected 2 devices to the server how would i get the message to get sent from one to the server then back to the other. Like a messaging programme. The code i have used is shown below import socket import sys from _thread import * host = '' port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((host, port)) except socket.error as e: print(str(e)) s.listen(5) print('Waiting for a connection.') def threaded_client(conn): conn.send(str.encode('Welcome, type your info\n')) final_char = "" while True: data = conn.recv(2048) char = data.decode("utf-8") print(data) if data != b'\r\n': final_char += char print(final_char) else: reply = 'Server output: '+ final_char+"\n" if not data: break conn.sendall(str.encode(reply)) final_char = "" conn.close() while True: conn, addr = s.accept() print(addr) print(conn) print('connected to: '+addr[0]+':'+str(addr[1])) start_new_thread(threaded_client,(conn,))
score: 0
has answer: http://stackoverflow.com/a/47422556
type: Question
has title: network communication using python and socket
type: UnansweredQuestion
tagged with: sockets
tagged with: python
answer count: 2

http://stackoverflow.com/a/47503449
has comment: http://stackoverflow.com/comment/81963230
has comment: http://stackoverflow.com/comment/82130074
has comment: http://stackoverflow.com/comment/81962966
has comment: http://stackoverflow.com/comment/82130011
downvote count: 0
has comment: http://stackoverflow.com/comment/81963436
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81962803
has comment: http://stackoverflow.com/comment/82129036
has comment: http://stackoverflow.com/comment/81963213
has comment: http://stackoverflow.com/comment/81963140
accepted answer of: http://stackoverflow.com/q/47503396
has comment: http://stackoverflow.com/comment/81963078
has comment: http://stackoverflow.com/comment/82129594
has comment: http://stackoverflow.com/comment/82752753
has comment: http://stackoverflow.com/comment/81962734
answers question: http://stackoverflow.com/q/47503396
has comment: http://stackoverflow.com/comment/81963234
has body: You can just create a new column (e.g. flag) to indicate whether or not the boolean check is true. df = df.assign(flag=df['apm'].gt(df['apm'].shift())) Then you could perform your action based on the value of this column.
type: Answer

http://stackoverflow.com/comment/81863348
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47448201
score: 0
has text: yes true. But why I am getting **expected f35215 in input data** while predicting test set?

http://stackoverflow.com/q/47384454
has body: I recently tried refactoring some parallel processes into a pool and was surprised that the pool took almost twice as long as pure processes. Please assume they are running on the same machine with the same number of cores. I hope that someone can explain why my implementation using Pool is taking longer and perhaps offer some advice: Shared dependency: https://github.com/taynaud/python-louvain from community import best_partition Here is the faster implementation using Process. [UPDATE] refactored to control the number of active processes same as the Pool implementation, still faster: processes = [] pipes = [] def _get_partition(send_end): send_end.send(best_partition(a_graph, resolution=res, randomize=rand)) for idx in range(iterations): recv_end, send_end = Pipe(False) p = Process(target=_get_partition, args=(send_end,)) processes.append(p) pipes.append(recv_end) running_procs = [] finished_procs = [] while len(finished_procs) &lt; iterations: while len(running_procs) &lt; n_cores and len(processes): proc = processes.pop() proc.start() running_procs.append(proc) for idx, proc in enumerate(running_procs): if not proc.is_alive(): finished_procs.append(running_procs.pop(idx)) for p in finished_procs: p.join() partitions = [pipe.recv() for pipe in pipes] And here is the slower, Pool implementation. This is still slower no matter how many processes the pool is given: pool = Pool(processes=n_cores) results = [ pool.apply_async( best_partition, (a_graph,), dict(resolution=res, randomize=rand) ) for i in range(iterations) ] partitions = [res.get() for res in results] pool.close() pool.join()
tagged with: python
has comment: http://stackoverflow.com/comment/81721740
has comment: http://stackoverflow.com/comment/81721930
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/81722257
has comment: http://stackoverflow.com/comment/81721765
has comment: http://stackoverflow.com/comment/81721721
has comment: http://stackoverflow.com/comment/81721736
has comment: http://stackoverflow.com/comment/81721692
has comment: http://stackoverflow.com/comment/81721760
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47417699
has comment: http://stackoverflow.com/comment/81750478
has title: Why is Pool slower than the same number of Processes
answer count: 1
has answer: http://stackoverflow.com/a/47417699

http://stackoverflow.com/q/47481714
tagged with: django
tagged with: python
has title: Django translating MySQL query to Django Query
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: django-views
has answer: http://stackoverflow.com/a/47497563
possible better answer: http://stackoverflow.com/a/47497563
tagged with: django-models
tagged with: mysql
has comment: http://stackoverflow.com/comment/81918432
has comment: http://stackoverflow.com/comment/81950474
has answer: http://stackoverflow.com/a/47485406
accepted answer: http://stackoverflow.com/a/47485406
type: Question
has comment: http://stackoverflow.com/comment/81919147
has body: How can i get the equivalent of this MySQL script in Django views? The depart_city, arrive_city, and travel_date will be inputed by the user. Here is my Models class Driver(models.Model): first_name = models.CharField(max_length=30, null=True, blank=False) last_name = models.CharField(max_length=30, null=True, blank=False) class Schedule(models.Model): depart_time = models.TimeField() arrive_time = models.TimeField() class TravelDate(models.Model): start_date = models.DateField(null = True) interval = models.IntegerField(null = True) class Route(models.Model): depart_city = models.CharField(max_length=50, null=True, blank=False) arrive_city = models.CharField(max_length=50, null=True, blank=False) driver = models.ForeignKey(Driver) schedule = models.ForeignKey(Schedule) traveldate = models.ForeignKey(TravelDate) Here is my MySQL script. This works when i run it on MySQL workbench but I'm not sure how to translate this to Django Query SELECT busapp_route.depart_city, busapp_route.arrive_city, busapp_driver.first_name, busapp_schedule.depart_time FROM (((busapp_route INNER JOIN busapp_driver ON busapp_route.driver_id = busapp_driver.id) INNER JOIN busapp_schedule ON busapp_route.schedule_id = busapp_schedule.id) INNER JOIN busapp_traveldate ON busapp_route.traveldate_id = busapp_traveldate.id) WHERE busapp_route.depart_city='Tropoje' AND busapp_route.arrive_city='Tirane' AND (DATEDIFF('2017-11-26', busapp_traveldate.start_date) % busapp_traveldate.interval = 0);

http://stackoverflow.com/comment/81924918
type: QuestionComment
has text: i'm try to set my own event listener using only key code number .some thing like below : keyboard_listener('0x24',custom_event_listener())
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47412460

http://stackoverflow.com/a/47510352
type: Answer
has body: With these two functions you can check all keys in your dictionaries if the keys are equal it will return True def get_keys(obj, keys=[]): ''' creates a list with all keys from a nested, json valid dictionary ''' if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, dict) or isinstance(v, list) and all(isinstance(item,dict) for item in v): keys.append(k) return get_keys(v, keys) else: keys.append(k) #calls get_keys with the list of keys as object this will trigger the else statement and return the object else: return get_keys(keys) elif isinstance(obj, list) and all(isinstance(item, dict) for item in obj): #checks if obj is a list and if all obj in a list are dictionaries for dct in obj: for k, v in dct.items(): if isinstance(v, dict) or isinstance(v, list) and isinstance(v[0], dict): keys.append(k) return get_keys(v, keys) else: keys.append(k) #same as above else: return get_keys(keys) else: return obj def has_same_structure(dct_1,dct_2): ''' checks if two (nested) dictionaries have the same keys ''' if get_keys(dct_1) == get_keys(dct_2, keys=[]): return True else: return False I hope this helps
answers question: http://stackoverflow.com/q/47508516
score: 0

http://stackoverflow.com/q/47441250
type: Question
accepted answer: http://stackoverflow.com/a/47441290
has answer: http://stackoverflow.com/a/47441290
answer count: 1
downvote count: 0
tagged with: neural-network
upvote count: 1
has title: NameError: name 'self' is not defined in Neural Network example
has comment: http://stackoverflow.com/comment/81837512
type: AnsweredQuestion
score: 1
tagged with: python
favorite count: 0
has body: I'm running the following code straight from Tariq Rashid's "Make Your Own Neural Network". It says "NameError: name 'self' is not defined". But it is defined. The code is straight from the book. import numpy #neural network class definition class neuralNetwork: #initialize the neural network def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate): # set number of nodes in each input, hidden, output layer self.inodes = inputnodes self.hnodes = hiddennodes self.onodes = outputnodes #learning rate self.lr = learningrate pass #train the neural network def train(): pass #query the neural network def query(): pass #number of input, hidden and output nodes input_nodes = 3 hidden_nodes = 3 output_nodes = 3 #learning rate is 0.3 learning_rate = 0.3 #create instance of neural network n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate) numpy.random.rand(3, 3)-0.5 #link weight matrices, wih and who #weights inside the arrays are w_i_j, where link is from node i to node j in the next layer #w11 w21 #w12 w22 etc self.wih = (numpy.random.rand(self.hnodes, self.inodes) - 0.5) self.who = (numpy.random.rand(self.onodes, self.hnodes) - 0.5)

http://stackoverflow.com/q/47518405
has comment: http://stackoverflow.com/comment/81992985
tagged with: if-statement
has comment: http://stackoverflow.com/comment/81993440
has body: Ok, I dont understand what is happening. I am looping over output from my query. A pretty normal loop and if. The issue is when I try to do results[o] &lt; 30. It does not print out the variable. There are column data less than 30 for some reason they don't print. Even if I print a string. Nothing happens. The else statement will print but not the if. On my flask template I have similar code and it works. What am I doing incorrectly. The results[0] is of type int. So I don't know what the issue is. I am not getting any errors. for recordset in return_stored_procedure: results.append(dict(zip(sp_column_names, recordset))) if results[0]['days_column'] &lt;= 30: print variable else: print variable ***update***** Figured out the issues thanks everyone. Made the corrections now I will remove what I don't want from the list. for l in sp_results: if l['column'] &lt; 30: newlist.append(l) Now on to making a list comprehension. Instead of this loop.
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81993473
has comment: http://stackoverflow.com/comment/82022689
has title: Python loop and if statment weird issues
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47518585
has comment: http://stackoverflow.com/comment/81993110
has answer: http://stackoverflow.com/a/47518585
downvote count: 2
answer count: 1
tagged with: sap-ase
tagged with: loops
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81993330

http://stackoverflow.com/a/47417459
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/47416605
has body: I received the same error. I would suggest you to work on several things. First, check if you have string data type and either convert it to float or not add for pairplot, slice up your dataset and then work in it. I actually mean, dimensional reduction. 81 columns may not be the best choice to experiment. As you mentioned you have half a million rows and 81 columns. First try on smaller dataset and then go for larger one. Seaborn plot sometimes fails to accommodate so many rows and columns on local systems. If you try on some cluster with larger RAM, it might work fine but this error is not new. Try working on exp = test_data[0:10][:1000] sns.pairplot(exp) Before applying this, first remove all string columns and experiment only on float , int value columns. I hope this helps.
has comment: http://stackoverflow.com/comment/81789871
has comment: http://stackoverflow.com/comment/81789908
type: AcceptedAnswer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/47416605

http://stackoverflow.com/comment/127596412
type: AnswerComment
has text: @DC007744 Thx! I couldn't get anything else to work expect using a string with '1.0'. Why is this not documented? Absurd since the others just take a `0`
comment on: http://stackoverflow.com/a/47502375
type: Comment
score: 0

http://stackoverflow.com/q/47520872
has comment: http://stackoverflow.com/comment/81998656
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/81998304
has comment: http://stackoverflow.com/comment/81998465
has title: How can I delete the top row of my csv file using python?
score: 0
has answer: http://stackoverflow.com/a/47522031
has comment: http://stackoverflow.com/comment/81999057
has comment: http://stackoverflow.com/comment/81998475
answer count: 1
has body: My code extracts information from an xhtml file to csv. Cannot seem to delete the topmost row reading "NYSE,, ,Price,Chg,Chg". Using "del data[0]" for example gets rid of the whole column. Any help is greatly appreciated. import sys import re import xml.dom.minidom document = xml.dom.minidom.parse("2017-11-27-16-20-15.xhtml") tableElements = document.getElementsByTagName('table')[2] for tr in tableElements.getElementsByTagName('tr'): data = [] for a in tr.getElementsByTagName('a'): for node in a.childNodes: if node.nodeType == node.TEXT_NODE: data.append(node.nodeValue) for td in tr.getElementsByTagName('td'): for node in td.childNodes: if node.nodeType == node.TEXT_NODE: data.append(node.nodeValue) del data[-1] del data[1] del data[1] del data[1] symbol = data[0] symm = re.findall(r"\(([A-Za-z0-9_]+)\)", symbol) sym = (''.join(symm)) company = data[0] comp = re.sub("\(.*\)\n","", company) volume = data[1] lst = volume.replace(',', '') price = data[2] lstt = price.lstrip('$') change = data[-1] fullList = [sym] + [comp] + [lst] + [lstt] + [change] fullList.insert(0, "NYSE") print(','.join(fullList)) output pic xhtml table(sample pic)
type: Question
has comment: http://stackoverflow.com/comment/81998932
type: UnansweredQuestion

http://stackoverflow.com/comment/82035728
has text: I downloaded Python 2.7.13 on my Mac and it only installed IDLE and Python Launcher. IDLE automatically opens a screen called '*Python 2.7.13 Shell*'. Is there a different form of this code I should type into the shell?
comment on: http://stackoverflow.com/q/47521214
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81886474
has text: Is it possible to have a list with more than one element in it without commas?
comment on: http://stackoverflow.com/q/47465922
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47497418
type: Answer
score: 0
has body: One work around can be,to recreate the dataframe changing the column names. It's always better to have unique column names. &gt;&gt;&gt; df = spark.createDataFrame([('value1','value2'),('value3','value4')],['manager','manager']) &gt;&gt;&gt; df.show() +-------+-------+ |manager|manager| +-------+-------+ | value1| value2| | value3| value4| +-------+-------+ &gt;&gt;&gt; df1 = df.toDF('manager1','manager2') &gt;&gt;&gt; from pyspark.sql.functions import lit &gt;&gt;&gt; df1.withColumn('manager1',lit('x1')).show() +--------+--------+ |manager1|manager2| +--------+--------+ | x1| value2| | x1| value4| +--------+--------+
answers question: http://stackoverflow.com/q/47494439

http://stackoverflow.com/comment/81872666
type: Comment
has text: That is interesting, when I print keys from freshly created ExcelWriter.sheets, it is empty. Pandas 0.20.3 XlsxWriter 1.0.2
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47454182

http://stackoverflow.com/q/47428346
type: Question
tagged with: seaborn
tagged with: data-visualization
tagged with: python
type: UnansweredQuestion
answer count: 1
has body: I have a DataFrame with the variables below. I am trying to find the relationship by plotting "profit" with other variables excluding "Date". Date Billable_Fixed Bid Billable_Time_Material Billable_Transaction_Based Non_Billable Indirect_Costs Unbilled_CP_and_AM Direct_Costs Profit Code: cols = [ 'Billable_Fixed Bid', 'Billable_Time_Material', 'Billable_Transaction_Based', 'Non_Billable', 'Unbilled_CP_and_AM', 'Direct_Costs' ] sns.pairplot(data1,x_vars=cols,y_vars='Profit',size =5,kind='reg') Problem is the plots are getting displayed in a single line, which is not clearly visible. I want it to display 2 plots per line so that it is clearly visible. Can anyone help?
score: 0
has answer: http://stackoverflow.com/a/47486844
has comment: http://stackoverflow.com/comment/81821704
has title: Seaborn pairplot not displaying in matrix form

http://stackoverflow.com/comment/81920447
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47482506
has text: I tested this, it works for the input in my question as well.
type: Comment

canvas
tags question: http://stackoverflow.com/q/47466995
tag name: canvas
tags question: http://stackoverflow.com/q/47534067
type: Tag
tags question: http://stackoverflow.com/q/47460068

http://stackoverflow.com/comment/81742136
type: AnswerComment
comment on: http://stackoverflow.com/a/47393513
has text: Thanks Nicola, but the same query works when sent through postman, maybe the problem lies in either the Ajax call I'm making? I will edit above with more details
score: 0
type: Comment

http://stackoverflow.com/q/47406557
has title: redirecting every url to 500 server error django
has comment: http://stackoverflow.com/comment/81766416
tagged with: whitenoise
tagged with: heroku
has comment: http://stackoverflow.com/comment/81767450
has comment: http://stackoverflow.com/comment/81766726
score: 1
has comment: http://stackoverflow.com/comment/81766560
tagged with: python
has body: my django application works in local development server. To deploy in heroku I had to use whitenoise for serving static files. The app is deployed successfully but now when I switch debug flag to False, i get server side error on both development and production server. This is my confiugration local_settings.py from decouple import config import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', } } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) import os from decouple import config import dj_database_url # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ['*'] # Application definition DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'allauth', 'allauth.account', ] OUR_APPS = [ 'inventory', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + OUR_APPS SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'IMS.urls' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static_collected") STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py urlpatterns = [ url(r'^accounts/', include('allauth.urls')), url(r'^', include('inven…
has comment: http://stackoverflow.com/comment/81767414
has answer: http://stackoverflow.com/a/47406714
favorite count: 0
has comment: http://stackoverflow.com/comment/81766451
type: Question
has comment: http://stackoverflow.com/comment/81766590
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81766983
linked to: http://stackoverflow.com/q/24857158
has comment: http://stackoverflow.com/comment/81766834
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81767135
answer count: 1
has comment: http://stackoverflow.com/comment/81766454
downvote count: 0
upvote count: 1
tagged with: django

http://stackoverflow.com/q/47414575
has title: A simple Google Chrome app to fetch details from a web form after each submission
answer count: 2
tagged with: javascript
tagged with: python
type: UnansweredQuestion
has body: There is this simple form that has two radio buttons, some text fields and a submit button. Since, I have no access to the DB I want to make a Google Chrome extension that creates a DB/sheet from the browser that records/counts every form submission with a particular radio button clicked.
tagged with: google-chrome-app
has answer: http://stackoverflow.com/a/47414799
type: Question
tagged with: google-chrome-extension
has answer: http://stackoverflow.com/a/47415923
tagged with: google-chrome-devtools
has comment: http://stackoverflow.com/comment/81783044
downvote count: 1
score: -1
favorite count: 0
upvote count: 0

http://stackoverflow.com/comment/81760529
score: 0
has text: I now understand the issue, and I'll work with "values" to make it into a list of integers for this particular issue. I also understand tuples are immutable now. I don't appreciate the negative score on my question - I still believe it was a valid question that I wanted answered which will affect whether I choose to use tuples going forward in my code.
type: Comment
comment on: http://stackoverflow.com/a/47402839
type: AnswerComment

http://stackoverflow.com/comment/81810222
score: 0
comment on: http://stackoverflow.com/q/47416768
type: Comment
type: QuestionComment
has text: yes i did it it does not remove them.

http://stackoverflow.com/a/47401872
accepted answer of: http://stackoverflow.com/q/47401818
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/47401818
type: Answer
upvote count: 6
has body: How about: str(tuple(sample_list)) Returns: "('abcd', 'chicken', 'wasd', 1, 'blah', 3, 'foo', 'bar')"

http://stackoverflow.com/comment/81829026
comment on: http://stackoverflow.com/q/47437308
has text: Try to use lxml with the HTML parser instead of the standard XML parser. The HTML parser is more forgiving with invalid input. Alternatively you can try to use [HTML tidy](http://www.html-tidy.org/) in XML mode to repair the file. There even is a Python package for it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47459299
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/47463833
accepted answer: http://stackoverflow.com/a/47463833
has comment: http://stackoverflow.com/comment/81875086
answer count: 1
downvote count: 0
has title: Network outputs from tf.session.run greatly differ from the ones obtained with keras.Model.predict
tagged with: python
tagged with: keras
score: 4
type: AnsweredQuestion
has body: I'm trying to use Keras model through Tensorflow session. But results form model.predict and sess.run different. Is there any way to work with Kers model through Tensorflow session? Tensorflow version: 1.4.0 Keras version: 2.1.1 from sklearn.datasets.samples_generator import make_circles from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD import numpy as np import tensorflow as tf from keras import backend as K sess = tf.Session() K.tensorflow_backend.set_session(sess) X, y = make_circles(n_samples=1000, noise=0.1, factor=0.2, random_state=0) model = Sequential() model.add(Dense(4, input_shape=(2,), activation='tanh')) model.add(Dense(1, activation='sigmoid')) model.compile(SGD(lr=0.5), 'binary_crossentropy', metrics=['accuracy']) model.fit(X, y, epochs=20) print("Keras model. First prediction: " + str(model.predict(np.c_[0, 0]))) print("Keras model. Second prediction: " + str(model.predict(np.c_[1.5, 1.5]))) with sess.as_default(): y_tensor = model.outputs[0] x_tensor = model.inputs[0] sess.run(tf.global_variables_initializer()) print("TF model. First prediction: " + str(sess.run(y_tensor, feed_dict={x_tensor: np.c_[0, 0]} ))) print("TF model. Second prediction: " + str(sess.run(y_tensor, feed_dict={x_tensor: np.c_[1.5, 1.5]} )))
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/81879192
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47462246
has text: Those are *old-style classes* in Python 2.x.
score: 3

http://stackoverflow.com/comment/82033482
type: Comment
type: QuestionComment
score: 0
has text: Can you show what `m` looks like?
comment on: http://stackoverflow.com/q/47538283

http://stackoverflow.com/q/47470557
has comment: http://stackoverflow.com/comment/81966150
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81904815
tagged with: python
has body: I am currently working on a Linux Server where I need to write a Python Script to parse an XML and store it in a Sybase based Database. When I started looking for available Libraries I found out that most of them have a dependency on FreeTDS. Since my organization is very reluctant to get new tools installed I am looking if there is an alternate way to connect to Sybase Database from Python on my Linux Server. Thanks in advance.
score: 0
tagged with: linux
tagged with: database
tagged with: sqlanywhere
has title: Can we connect to Sybase Database from Python on Linux server without FreeTDS installed?
tagged with: sybase-asa
type: Question
answer count: 0

http://stackoverflow.com/q/47465930
type: Question
has comment: http://stackoverflow.com/comment/81887074
has title: How to extract a labelled dataset from a JSON API? (NLM RxImage)
tagged with: database
answer count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81887139
type: UnansweredQuestion
tagged with: api
has comment: http://stackoverflow.com/comment/81887122
has body: I am hoping to do some image classification on pills. The National Library of Medicine has an pill image database, RxImage website. It has an API which you can retrieve images with specific requests in the form of JSON files. (Sample API request builder). I want to download the labelled image dataset in order to do some image classification on it in python. Is there a way to do this? (preferably in python)
tagged with: http://stackoverflow.com/tag/json
score: 0
linked to: http://stackoverflow.com/q/13137817
has comment: http://stackoverflow.com/comment/81886494
has comment: http://stackoverflow.com/comment/81887033

http://stackoverflow.com/comment/81847399
has text: Do you want to print to the Flask logs, or *return a JSON response in the browser*?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47446008

http://stackoverflow.com/comment/81740236
comment on: http://stackoverflow.com/q/47393549
type: QuestionComment
has text: is PyCharm using Python 3.6 interpreter? Show us project setup.py file.
score: 0
type: Comment

http://stackoverflow.com/comment/81897394
has text: @JimFasarakisHilliard Sure, but I don't see how posting a comment that answers the question has anything to do with whether you're looking for a duplicate.
type: Comment
comment on: http://stackoverflow.com/q/47471412
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81800226
type: AnswerComment
has text: Have you tested your code? It [doesn't work](https://repl.it/repls/ShabbyValidIcelandichorse) for me.
comment on: http://stackoverflow.com/a/47422788
score: 1
type: Comment

http://stackoverflow.com/q/47454693
upvote count: 1
has title: InstaBot API Follow not Working
tagged with: instagram
score: 1
tagged with: python
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I am using InstaBot Python API its working fine for Instagram Likes, But if i set only follow then nothing is happened. I tried a lot to fix this but did not get Proper solution. Could any one please let me know where i am worng in the code ? Here is my code : bot = InstaBot( login = 'xyz', password = 'xyz', like_per_day = 0, comments_per_day = 0, tag_list = '', tag_blacklist = ['rain', 'thunderstorm'], user_blacklist = {}, max_like_for_one_tag= 50, follow_per_day = 10, follow_time = 1 * 60, unfollow_per_day = 0, unfollow_break_min = 120, unfollow_break_max = 180, log_mod = 0, proxy = '', comment_list=[ ["photo", "picture", "pic", "shot", "snapshot"], ], # Use unwanted_username_list to block usernames containing a string ## Will do partial matches; i.e. 'mozart' will block 'legend_mozart' ### 'free_followers' will be blocked because it contains 'free' unwanted_username_list=[ 'second', 'stuff', 'art', 'sex', 'food', 'blog', ], unfollow_whitelist=['example_user_1', 'example_user_2'] ) Please Help me to Fix my problem
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47454770

http://stackoverflow.com/comment/81928087
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47486220
score: 0
has text: Except for one common gotcha: Unlike what happens for a Python `list`, `[:]` does *not* shallow copy an `np.ndarray`; instead, it gives you a view of the original array: If you let `c = b[:]` and change any part of `c`, then the contents referred to by `b` will also change.

http://stackoverflow.com/q/47527330
has comment: http://stackoverflow.com/comment/82010904
has answer: http://stackoverflow.com/a/47535433
has body: I am learning python/ML and have come across these errors. I have no clue since the code is good. Code from sklearn import datasets from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import train_test_split X, y = mglearn.datasets.make_forge() X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) fig, axes = plt.subplots(1, 3, figsize=(15, 4)) line = np.linspace(-3, 3, 1000).reshape(-1, 1) for n_neighbors, ax in zip ([1,3,9], axes): reg = KNeighborsRegressor(n_neighbors=n_neighbors) reg.fit(X_train, y_train) ax.plot(line, reg.predict(line)) ax.plot(X_train, y_train, '^', c=mglearn.cm2(0), markersize=8) ax.plot(X_test, y_test, 'v', c=mglearn.cm2(1), markersize=8) ax1.set_title( "{} neighour(s)\n train score: {:.2f} test score: {:.2f}".format( n_neighbors, reg.score(X_train, y_train), reg.score(X_test, y_test))) ax.set_xlabel("feature") ax.set_ylabel("target") axes[0].legend(['model predictions', 'training data/target', 'test data/target'], loc='best') Errors Traceback (most recent call last): File "ch2.py", line 161, in &lt;module&gt; ax.plot(line, reg.predict(line)) File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\neighbors\regression.py", line 144, in predict neigh_dist, neigh_ind = self.kneighbors(X) File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\neighbors\base.py", line 385, in kneighbors for s in gen_even_slices(X.shape[0], n_jobs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\externals\joblib\parallel.py", line 779, in __call__ while self.dispatch_one_batch(iterator): File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\externals\joblib\parallel.py", line 625, in dispatch_one_batch self._dispatch(tasks) File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\externals\joblib\parallel.py", line 588, in _dispatch job = self._backend.apply_async(batch, callback=cb) File "C:\Program Files (x86)\Python36-32\lib\site-packages\sklearn\ext…
has title: Errors from Sklearn, python
type: Question
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82010797
has answer: http://stackoverflow.com/a/55139209
type: UnansweredQuestion
score: -3
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
favorite count: 0
downvote count: 3

http://stackoverflow.com/q/47531584
has title: NumPy where as range indices
tagged with: indexing
type: AnsweredQuestion
upvote count: 1
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47531969
accepted answer: http://stackoverflow.com/a/47531969
favorite count: 0
type: Question
tagged with: numpy
downvote count: 0
has body: I have a numpy array like that: a = numpy.array([1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0]) The goal is to find the ranges of zeros and ones, start and end indices. I want to use this ranges in another numpy array which contains time stamps to find out how much time each zero phase takes. Something like that: dur = numpy.diff(time[start idx, end idx]) However, numpy where gives me all indices: numpy.where(a==0) (array([ 3, 4, 5, 9, 10, 11], dtype=int64),) I would need only start and end idx of each zero phase, like [[3,5],[9,11]]. How can I achieve that?
answer count: 1
tagged with: arrays

http://stackoverflow.com/q/47477492
has title: Socket doesn't send data until it is closed
has comment: http://stackoverflow.com/comment/81909919
has comment: http://stackoverflow.com/comment/81909816
type: Question
has comment: http://stackoverflow.com/comment/81909964
answer count: 1
has body: i have a simple application which create a socket between java(server) and python(client). The main function of the python code is to take data from user and send it to the server(java code) here's the python code import socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("localhost", 5000)) while True: data = input("Enter data to send : ") if(data == 'q'): break client_socket.sendall(data.encode('utf-8')) client_socket.close() and here's the java code String fromclient; ServerSocket Server = new ServerSocket (5000); while(true) { Socket connected = Server.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream())); fromclient = inFromClient.readLine(); if ( fromclient.equals("q") ){ connected.close(); break; }else { System.out.println(fromclient); } } when I write any text and click Enter, nothing goes to java code and nothing printed to the console, but when i send 'q' from python, the python code closed and all the data i wrote are now printed in java console. I have no idea what is the reason of this, and how i can fix it.
has comment: http://stackoverflow.com/comment/81909807
accepted answer: http://stackoverflow.com/a/47477599
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47477599
tagged with: sockets
tagged with: java
has comment: http://stackoverflow.com/comment/81910119
tagged with: python

http://stackoverflow.com/comment/81883365
type: Comment
type: QuestionComment
has text: @ElisByberi I've edited my question with what the program will do.
comment on: http://stackoverflow.com/q/47464317
score: 0

http://stackoverflow.com/a/47399254
has comment: http://stackoverflow.com/comment/81757973
score: 1
upvote count: 1
has body: That sql looks fishy to me but I'm not that smart. You don't have to have the database to try it out though. If it's meant to work with say, MySQL, then you could quickly whip up a couple of tables with the right column names and then see if MySQL howls if you try to execute that query. I don't think you'd even need trial data.
type: Answer
answers question: http://stackoverflow.com/q/47395334
downvote count: 0

http://stackoverflow.com/q/47486953
answer count: 1
tagged with: decorator
has title: How is a python decorator actually defined?
has comment: http://stackoverflow.com/comment/81929213
type: AnsweredQuestion
score: 0
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47487025
accepted answer: http://stackoverflow.com/a/47487025
has body: First of all I know what a decorator is. I would like to understand some small aspects. TL;DR is decorator func1 = func2(func1) # True is decorator func3 = func2(func1) # ??? Let's look at Wiki which describes two equivalent ways to decorate a function: @viking_chorus def menu_item(): print("spam") def menu_item(): print("spam") menu_item = viking_chorus(menu_item) Now, let's see the description on this website, particularly in the section Getting back to decorators. There are two functions defined: def make_pretty(func): def inner(): print("I got decorated") func() return inner def ordinary(): print("I am ordinary") And then an author decorates the function and calls it: &gt;&gt;&gt; pretty = make_pretty(ordinary) &gt;&gt;&gt; pretty() I got decorated I am ordinary We can notice that the author doesn't use: &gt;&gt;&gt; ordinary = make_pretty(ordinary) which is a recommended way by Wiki (I know that Wiki can be sometimes wrong). So I decided to use the last way to decorate the Fibonacci numbers function taken from this tutorial: def memoize(f): memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) This call: &gt;&gt;&gt; fib_element = memoize(fib) &gt;&gt;&gt; fib_element(40) takes a long time on my machine which means that the fib() has been not decorated properly. The execution time is comparable with fib(40). These calls: &gt;&gt;&gt; fib = memoize(fib) &gt;&gt;&gt; fib_element = fib # assigned after decoration &gt;&gt;&gt; fib(40) &gt;&gt;&gt; fib_element(40) execute fast. So the question is: can we say that we decorate the ordinary function in pretty = make_pretty(ordinary) assignment?

http://stackoverflow.com/q/47498642
answer count: 3
duplicate of: http://stackoverflow.com/q/14928860
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47505291
has answer: http://stackoverflow.com/a/47498824
has answer: http://stackoverflow.com/a/47504662
favorite count: 0
has body: Im trying to run this bash command using python subprocess find /Users/johndoe/sandbox -iname "*.py" | awk -F'/' '{ print $NF}' output:- helld.xl.py parse_maillog.py replace_pattern.py split_text_match.py ssh_bad_login.py Here is what i have done in python2.7 way, but it gives the output where awk command filter is not working &gt;&gt;&gt; p1=subprocess.Popen(["find","/Users/johndoe/sandbox","-iname","*.py"],stdout=subprocess.PIPE) &gt;&gt;&gt; p2=subprocess.Popen(['awk','-F"/"','" {print $NF} "'],stdin=p1.stdout,stdout=subprocess.PIPE) &gt;&gt;&gt;p2.communicate() ('/Users/johndoe/sandbox/argparse.py\n/Users/johndoe/sandbox/custom_logic_substitute.py\n/Users/johndoe/sandbox/finditer_html_parse.py\n/Users/johndoe/sandbox/finditer_simple.py\n/Users/johndoe/sandbox/group_regex.py\n/Users/johndoe/sandbox/helo.py\n/Users/johndoe/sandbox/newdir/helld.xl.py\n/Users/johndoe/sandbox/parse_maillog.py\n/Users/johndoe/sandbox/replace_pattern.py\n/Users/johndoe/sandbox/split_text_match.py\n/Users/johndoe/sandbox/ssh_bad_login.py\n', None) I could also get output by using p1 alone here like below,but i cant get the awk working here list1=[] result=p1.communicate()[0].split("\n") for item in res: a=item.rstrip('/').split('/') list1.append(a[-1]) print list1
type: Question
linked to: http://stackoverflow.com/q/10067266
tagged with: subprocess
type: UnansweredQuestion
has title: How to correctly escape special characters in python subprocess?
linked to: http://stackoverflow.com/q/14928860
score: 2
upvote count: 3
tagged with: python-2.7
linked to: http://stackoverflow.com/q/3172470

http://stackoverflow.com/a/47396052
downvote count: 0
type: AcceptedAnswer
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/47395993
type: Answer
accepted answer of: http://stackoverflow.com/q/47395993
has body: Use apply, because each row has to be process separately: my_df['new_col'] = my_df.apply(lambda x: x['col3'][x['col1']-1:x['col2']], 1) print (my_df) col1 col2 col3 new_col 0 1 3 ABCDEFG ABC 1 1 5 HIJKLMNO HIJKL 2 1 2 PQRSTUV PQ

http://stackoverflow.com/q/47474002
has title: How to sum together all values associated with duplicates in list of lists?
has body: I have a following list: x = [['A', 300], ['C', 200], ['B', 1500], ['A', 1000], ['C', 1000]] Now I want to generate a new list in which the format is similar, but all the integers of duplicate strings in the list of lists are summed together. My desired result would be: x2 = [['A', 1300], ['B', 1500], ['C', 1200]] How can this be done?
score: 0
answer count: 1
tagged with: duplicates
type: Question
tagged with: nested-lists
has answer: http://stackoverflow.com/a/47474117
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81902446

http://stackoverflow.com/comment/82017019
score: 0
type: AnswerComment
has text: Thank you! This is a hobby project, so it may take some time to truly test if it is the right solution, but it seems to be working!
comment on: http://stackoverflow.com/a/47515541
type: Comment

http://stackoverflow.com/a/47421444
type: Answer
upvote count: 3
downvote count: 0
has body: knowing a.shape, an other solution is : def fill (b,shape): a=np.zeros(shape,dtype=b.dtype) x = a.shape[0]//b.shape[0]+1 y = a.shape[1]//b.shape[1]+1 a[::x,::y]=b return a Try : In [247]: fill(b,a.shape) Out[247]: array([[11, 0, 0, 14, 0], [ 0, 0, 0, 0, 0], [31, 0, 0, 34, 0], [ 0, 0, 0, 0, 0], [51, 0, 0, 54, 0]])
has comment: http://stackoverflow.com/comment/81797289
answers question: http://stackoverflow.com/q/47420904
score: 3

http://stackoverflow.com/comment/82008660
type: QuestionComment
has text: @berna1111 Distribution curve would be better. But histogram could also help
comment on: http://stackoverflow.com/q/47525308
score: 0
type: Comment

http://stackoverflow.com/comment/81929314
type: Comment
comment on: http://stackoverflow.com/a/47487233
type: AnswerComment
has text: for further information on parsing these type of dates you can look https://stackoverflow.com/questions/10298032/parsing-date-and-timestamps-in-python-with-time-strptime-format
score: 0

http://stackoverflow.com/a/47410579
has body: Thanks everyone for the help. The answer is here: import time, threading from time import sleep from tkinter import * from tkinter import messagebox global listb class App(object): def __init__(self, root): def onselect(evt): w = evt.widget index = int(w.curselection()[0]) value = w.get(index) detail.delete('1.0', END) detail.insert(END,str(value*value)) lbl1 = Label(root, text="Result:", fg='black', font=("Helvetica", 16, "bold")) lbl2 = Label(root, text="Detail:", fg='black', font=("Helvetica", 16, "bold")) lbl1.grid(row=0, column=0, sticky=W) lbl2.grid(row=2, column=0, sticky=W) frm = Frame(root) frm.grid(row=1, columnspan=2, sticky=N + S + W + E) scrollbar = Scrollbar(frm, orient=VERTICAL) global listb listb = Listbox(frm, yscrollcommand=scrollbar.set, width=50) scrollbar.config(command=listb.yview) scrollbar.pack(side=RIGHT, fill=Y) listb.pack(fill=BOTH, expand=YES) detail = Text(root, height=10, font=("Helvetica", 12)) detail.grid(row=6, columnspan=2, sticky=E + W + N) listb.bind('&lt;&lt;ListboxSelect&gt;&gt;', onselect) def InfiniteProcess(): global listb sleep(0.1) for i in range(1000): sleep(0.3) vw = listb.yview() listb.insert(END, i) listb.yview_moveto(vw[-1]) #print(i) finish = False Process = threading.Thread(target=InfiniteProcess) Process.start() mainWindow = Tk() app = App(mainWindow) mainWindow.mainloop() finish = True Process.join()
accepted answer of: http://stackoverflow.com/q/47409437
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47409437

http://stackoverflow.com/q/47439594
has comment: http://stackoverflow.com/comment/81835974
has comment: http://stackoverflow.com/comment/81835256
has body: Let's start with this: class Example(object): change_docstring = True @add_to_docstring(" (additional content!)") def example_method(self): """Example docstring.""" pass What I am trying to do is allow the @add_to_docstring decorator to append its parameter string to the docstring of the method only if the change_docstring attribute is True. I do not want to pass anything else into the decorator. This solution works, but it is not exactly what I'm looking for. def add_to_docstring(text): def decorator(original_method): def wrapper(self): """wrapper docstring.""" wrapper.__doc__ = original_method.__doc__ if self.change_docstring: wrapper.__doc__ += text return original_method(self) return wrapper return decorator Let me explain. The above solution only changes the docstring if example_method is executed. The docstring does not change when the class, method, etc. is loaded. &gt;&gt;&gt; Example.example_method.__doc__ "wrapper docstring." &gt;&gt;&gt; &gt;&gt;&gt; Example().example_method() &gt;&gt;&gt; Example.example_method.__doc__ "Example docstring. (additional content!)" This is what I would like the output of the above command to be: &gt;&gt;&gt; Example.example_method.__doc__ "Example docstring. (additional content!)" Again, I do not want to pass anything else into the decorator. Update For additional clarification, this is to allow for a decorator to change the docstring of a method, and to have that change be reflected in Sphinx generated documentation. Sphinx loads everything and gathers docstrings, but it does not do anything more. Based on the selected solution, I added a module variable in the decorators module and exposed a method to disable the docstring change feature in the decorators. In order to disable the feature universally, I then called that disable function within my Sphinx conf.py files like so: # import the decorators module from some_modules import decorators # disable the docstring change feature decorators.disable_docstring_change() Then t…
tagged with: python
has comment: http://stackoverflow.com/comment/81835280
has comment: http://stackoverflow.com/comment/81835905
possible better answer: http://stackoverflow.com/a/47441572
linked to: http://stackoverflow.com/q/47223764
tagged with: python-decorators
linked to: http://stackoverflow.com/q/13905741
type: AnsweredQuestion
score: 3
answer count: 2
has answer: http://stackoverflow.com/a/47441572
accepted answer: http://stackoverflow.com/a/47440645
has comment: http://stackoverflow.com/comment/81835419
upvote count: 3
has answer: http://stackoverflow.com/a/47440645
downvote count: 0
has comment: http://stackoverflow.com/comment/81835005
has title: Change the docstring of a class method within a decorator based on class attribute
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81835780
tagged with: python-sphinx

http://stackoverflow.com/comment/81872893
score: 0
type: Comment
has text: Awesome wasnt aware of selecting at all. Thank you @MedAli
type: AnswerComment
comment on: http://stackoverflow.com/a/47459164

http://stackoverflow.com/comment/81840463
type: QuestionComment
comment on: http://stackoverflow.com/q/47442708
score: 0
has text: In python it is just a list, unlike java
type: Comment

http://stackoverflow.com/comment/81883926
comment on: http://stackoverflow.com/q/47464509
score: 0
has text: @MattyS11 is my answer not what you wanted?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81747908
score: 0
type: Comment
has text: @glibdud I added a working example of the issue. Many thanks in advance!
type: QuestionComment
comment on: http://stackoverflow.com/q/47396416

http://stackoverflow.com/q/47449531
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81854194
has comment: http://stackoverflow.com/comment/81855270
score: 1
accepted answer: http://stackoverflow.com/a/47449764
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47449764
favorite count: 0
type: Question
tagged with: python-3.x
has body: In Chapter 7, the author creates an iterator that builds rules for transforming singular English nouns into plurals: class LazyRules: rules_filename = 'plural5-rules.txt' def __init__(self): self.pattern_file = open(self.rules_filename, encoding='utf-8') self.cache = [] def __iter__(self): self.cache_index = 0 return self def __next__(self): self.cache_index += 1 if len(self.cache) &gt;= self.cache_index: return self.cache[self.cache_index - 1] if self.pattern_file.closed: raise StopIteration line = self.pattern_file.readline() if not line: self.pattern_file.close() raise StopIteration pattern, search, replace = line.split(None, 3) funcs = build_match_and_apply_functions( pattern, search, replace) self.cache.append(funcs) return funcs rules = LazyRules() While the book provides a very clear and thorough explanation for every bit of this code, it doesn't explain how one can use it? How do I use these rules to change nouns? I tried to add this bit to the class: def build_match_and_apply_functions(self, pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, word) return (matches_rule, apply_rule) def plural(self, noun): for matches_rule, apply_rule in self.__next__(): if matches_rule(noun): return apply_rule(noun) raise ValueError('no matching rule for {0}'.format(noun)) Upd: I changed the code accroding to the comment from janos. So it now looks like this: class LazyRules: rules_filename = 'plural5-rules.txt' def __init__(self): self.pattern_file = open(self.rules_filename, encoding='utf-8') self.cache = [] def __iter__(self): self.cache_index = 0 return self def __next__(self): self.cache_index += 1 if len(self.cache) &gt;= self.cache_index: return self.cache[self.cache_index - 1] if self.pattern_file.closed: raise StopIteration line = self.pattern_file.readline() if not line: self.pattern_file.close() raise StopIteration pattern, search, replace = line.split(None, 3) funcs = build_match…
has title: Dive into Python Chapter 7: How do I use this iterator?
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47404516
has answer: http://stackoverflow.com/a/47404603
favorite count: 0
score: 1
has comment: http://stackoverflow.com/comment/81763043
tagged with: python
has body: I would like to import a text file using Numpy's genfromtxt function. I am not able to do so as it says there are too many values to unpack. Traceback (most recent call last): File "C:\Users\loges\AppData\Roaming\Sublime Text 3\Packages\User\test4.py", line 12, in &lt;module&gt; filling_values={-1:0}) ValueError: too many values to unpack (expected 4) [Finished in 1.1s] I tried to define the variables as well according to the examples that I found online but none seem to work for me. Can anyone help me identify my error? This is an example of my text file which is respectively the XYZ coord and temp at that point. -7 -9.000000000000002 -3 622.0582425616101 -6.500000000000001 -9.000000000000002 -3 622.1498719223513 -6 -9.000000000000002 -3 622.2415012830924 This is my code. I would like to find the highest and mean temperature values. This is just the first 3 lines though. Its a file with alot of lines of data. import numpy as np x, y, z, t = np.genfromtxt('C:\\Users\\loges\\OneDrive\\Documents\\School\\ME4101A FYP\\temperature600.txt', skip_header=0, skip_footer=0, unpack = True, names= ['x', 'y', 'z', 't'], dtype = [('x', float), ('y', float), ('z', float), ('t', float)], usecols = (-1), missing_values={-1:""}, filling_values={-1:0}) print("Max Temp :", t.max())
has title: Importing Text files in python with numpy using np.genfromtxt
type: Question
tagged with: numpy
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47404684
tagged with: arrays
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47482869
type: Answer
upvote count: 4
has body: Because of the format specifier you're using: In [1]: '%d' % 3.14 Out[1]: '3' %d (the C-style string formatter for int) will truncate any float if you pass it that. Instead, the correct format specifier string to use would be %f: In [2]: '%f' % 3.14 Out[2]: '3.140000' However, I'd recommend using str.format instead, so you don't have to worry about what format specifier to use. def __str__(self): return 'I am a {} with area of {}'.format(self.__class__.__name__, self.area()) str.format also gives you better control over display for floating point numbers: In [3]: '{:.2f}'.format(3.1415) Out[3]: '3.14' Read more about the format functions at PyFormat.info.
answers question: http://stackoverflow.com/q/47482833
score: 4
downvote count: 0

http://stackoverflow.com/comment/82032566
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47526788
has text: you mean if '+' in url , you want to get that string which contain that '+' ?
type: QuestionComment

http://stackoverflow.com/a/47538940
score: 0
answers question: http://stackoverflow.com/q/47538904
has comment: http://stackoverflow.com/comment/82034814
has comment: http://stackoverflow.com/comment/82034931
has comment: http://stackoverflow.com/comment/82035225
has body: The reason you cannot replace characters directly is due to the immutability of strings. I.e. you cannot change them. So the way to replace a character at an index is to take a slice up to that index and then concatenate the character and then finally concatenate the rest of the string. This method can be seen here: word = "cat" index = 1 replacement = "o" new_word = word[:index] + replacement + word[index+1:] #new_word --&gt; 'cot'
has comment: http://stackoverflow.com/comment/82034831
type: Answer
has comment: http://stackoverflow.com/comment/82035122
has comment: http://stackoverflow.com/comment/82034741

http://stackoverflow.com/q/47518937
has comment: http://stackoverflow.com/comment/81996650
upvote count: 1
tagged with: spectrogram
favorite count: 0
tagged with: signal-processing
type: Question
tagged with: python-3.x
has body: Here is my code, But it doesn't work Load the dataset dataset = np.loadtxt("filename", delimiter=",") X = dataset[:,0:5] Y = dataset[:,5] compute spectrogram N = 1e5 amp = 2 * np.sqrt(2) noise_power = 0.001 * X / 2 time = np.arange(dataset) / X freq = np.linspace(1e3, 2e3, N) x = amp * np.sin(2*np.pi*freq*time) x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape) Compute and plot the spectrogram. f, t, Sxx = signal.spectrogram(x, X) plt.pcolormesh(t, f, Sxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.show() this is a part of my dataset 33,4.9106E+13,-0.6946377,12.680544,0.50395286 33,4.91061E+13,5.012288,11.264028,0.95342433 33,4.91061E+13,4.903325,10.882658,-0.08172209 33,4.91062E+13,-0.61291564,18.496431,3.0237172
tagged with: accelerometer
has title: How to obtain spectrogram of a 3D accelerometer file in python?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47538738
tagged with: python
has comment: http://stackoverflow.com/comment/82006838
has comment: http://stackoverflow.com/comment/81995179
has comment: http://stackoverflow.com/comment/81995236
score: 1
has comment: http://stackoverflow.com/comment/81994184
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47517976
has comment: http://stackoverflow.com/comment/104594059
score: 3
answers question: http://stackoverflow.com/q/47517831
type: Answer
has body: Inorder to add new column in the dataframe with the existing column data from same or different dataframe : Dataframe_name['new_column_name'] = Dataframe_name['existing_column_name']
accepted answer of: http://stackoverflow.com/q/47517831
upvote count: 4
downvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47480246
answers question: http://stackoverflow.com/q/47480146
type: Answer
score: 0
has body: OpenCV definitely works with python3. But http://cyaninfinite.com/tutorials/installing-opencv-in-ubuntu-for-python-3/ suggests that the packaging situation is not straightforward, as some platforms are better supported than others. It looks like you're encountering a package that was only intended for python2, hence the conflict. You may be facing a "build from source" situation here.

http://stackoverflow.com/q/47388717
has body: I wrote the following code: frame1=DataFrame(np.arange(9).reshape(3,3), index=['a','b','c'], columns=['Ohio','Texas','California']), states= ['Texas','Utah','California'] Then, frame1.reindex(index=['a','b','c','d'],method='ffill',columns=states) It returns an error stating 'index must be monotonic increasing or decreasing'. I have read the answer to this question. Then I re-wrote it as frame1.reindex(index=['a','b','c','d'],method='ffill',columns=states.sort()). Now the result is : Ohio Texas California a 0 1 2 b 3 4 5 c 6 7 8 d 6 7 8 As you can see, the columns are not changed as I expected. Why here the columns don't change, though I use the reindex function?
has title: python reindexing with method='ffill'
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47390855
possible better answer: http://stackoverflow.com/a/47390855
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47391909
answer count: 2
accepted answer: http://stackoverflow.com/a/47391909
tagged with: pandas
upvote count: 2
linked to: http://stackoverflow.com/q/37982170
downvote count: 0

http://stackoverflow.com/comment/81841691
type: Comment
type: QuestionComment
score: 8
has text: I guess you need to post this question to https://codereview.stackexchange.com/.
comment on: http://stackoverflow.com/q/47443332

http://stackoverflow.com/comment/81845590
comment on: http://stackoverflow.com/q/47444738
type: QuestionComment
score: 0
has text: Also I assume you're trying to iterate through pages, but I don't see your `pg` variable used anywhere
type: Comment

http://stackoverflow.com/q/47533221
has answer: http://stackoverflow.com/a/47580087
tagged with: python-3.x
has title: OCR and coordinate association on image for each character
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
downvote count: 1
favorite count: 0
has body: I'm working on a project to help my visually impaired friend, a python script will first take a screenshot every second and whatever is on the image will be converted to text, and the character which is nearest to the coordinate of curser, will be the output. User can move the curser anywhere on screen and nearest alphabet to curser will be the output of program. Don't worry about the form of output, it will be in form audio. But for the sake of simplicity of question lets assume it's in the form of a single character text. Every tutorial I could find explained how to use OCR dependencies just to convert all the text to a continuous text file. For my particular application, each alphabet will be associated with a specific co-ordinate. But I just couldn't find a single resource to learn how to identify the location of converted character on the image. Please enlighten me how to extract the coordinates of a character from an image.
tagged with: opencv3.1
has comment: http://stackoverflow.com/comment/102114407
score: -1
tagged with: image-processing
tagged with: ocr
type: Question

http://stackoverflow.com/q/47423045
accepted answer: http://stackoverflow.com/a/47423145
has body: I have a daily data dataframe (df) indexed by date - the head is below: nominal date 2016-01-04 114185.481138 2016-01-04 17841.990960 2016-01-04 -8799.514730 2016-01-04 0.000000 2016-01-04 -3028.765682 I can find the max date using maxDate = df.index.max() How would I find the date 260 working days (1 working year) before this date? How could I go about retrieving the date 260 days ago from the maxDate?
possible better answer: http://stackoverflow.com/a/47423278
type: Question
has answer: http://stackoverflow.com/a/47423278
answer count: 3
has comment: http://stackoverflow.com/comment/81800916
tagged with: python
has answer: http://stackoverflow.com/a/47423145
has answer: http://stackoverflow.com/a/47423317
type: AnsweredQuestion
score: 0
has title: Return date 260 working days from reference date
tagged with: pandas

http://stackoverflow.com/a/47393188
score: 1
has body: 'wb' has to be replaced for 'ab' in order to actually append the file for an object.
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47391799

http://stackoverflow.com/a/47488255
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Ok, we are using rolling and max df['cumulative_perf'].rolling(window=len(df), min_periods=1).max() Out[487]: 0 36528.11368 1 65562.88563 2 113486.38980 3 166227.08310 4 166227.08310 5 166227.08310 6 166227.08310 7 166227.08310 8 221765.88590 9 221765.88590 10 221765.88590 Name: cumulative_perf, dtype: float64
has comment: http://stackoverflow.com/comment/81931395
answers question: http://stackoverflow.com/q/47486190
has comment: http://stackoverflow.com/comment/81931357

http://stackoverflow.com/comment/81904966
score: 0
comment on: http://stackoverflow.com/q/47473531
has text: `sub process kills` it's expected. you need to create daemon if you want it to be running after starting from your code. In case of daemon - you will be able to handle it using your init process (systemd, upstart, ..etc)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47443992
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47448476
tagged with: python
has body: I have three different arrays. One is a latitude array (-90 to 90) another is a longitude array (0 to 360) and the last is a 2D temperature array with the shape (len(lats), len(lons) where len(lats) != len(lons). I have obtained a longitude mask via other means and have created a latitude mask via: latmask = np.ma.masked_where(np.logical_or(lat &lt; -60, lat &gt; 60), lat).mask So now I have two 1D masks that I want to apply to the 2D data along the appropriate axis with "or" logic (aka if either the lat or lon in that index was masked, then the 2D data should be masked). I have tried combining the two 1D masks into a 2D mask using : 2dmask = np.logical_or(latmask , lonmask) 2dmask = latmask * lonmask but these give an error saying the two arrays are not the same shape. 2dmask = latmask[np.newaxis, :] &amp; lonmask[:, np.newaxis] but when I try to apply this mask to my data like so and plot the result: testdata = np.ma.masked_array(nt[0,50,:,:], mask = 2dmask) I get the following plot: but this plot should have data above and below +/- 60 degrees lat masked and data except some continuous strip of longitudes masked (basically plucking out a rectangle of data). I have spent the last 30-45 minutes searching the documentation and stack overflow for similar problems with no luck. Thanks for any help! -Will
tagged with: geo
accepted answer: http://stackoverflow.com/a/47448476
tagged with: numpy
score: 0
answer count: 1
has title: Mask a 2D array with different masks for each dimension
type: Question

http://stackoverflow.com/q/47499255
has answer: http://stackoverflow.com/a/47499332
tagged with: python
has answer: http://stackoverflow.com/a/47500268
has body: I'm having trouble writing a function to display all of the permutations of a list. Here is my code. The main function is given and I cannot change it. When I ran the code, nothing showed up. What's wrong with my code? def perm(lst): if len(lst) == 0: return [] if len(lst) == 1: return [lst] l = [] for i in range(len(lst)): m = lst[i] rem = lst[:i] + lst[i+1:] for p in perm(rem): l.append([m] + p) return l def main(): list = input().split(',') start = [] perm(list) if __name__ == "__main__": main() The input is: A,B,C The expected output is: ['A', 'B', 'C'] ['A', 'C', 'B'] ['B', 'A', 'C'] ['B', 'C', 'A'] ['C', 'A', 'B'] ['C', 'B', 'A']
answer count: 4
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47499727
has answer: http://stackoverflow.com/a/47499721
downvote count: 1
has comment: http://stackoverflow.com/comment/81954369
has title: Python permutation with recursion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81954511
tagged with: algorithm
type: UnansweredQuestion

http://stackoverflow.com/q/47407985
linked to: http://stackoverflow.com/q/43027980
downvote count: 1
tagged with: plot
has answer: http://stackoverflow.com/a/53686100
score: 2
has answer: http://stackoverflow.com/a/48417416
answer count: 3
tagged with: pandas
upvote count: 3
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48756831
has body: I wanted to use Python instead of JavaScript for drawing UpSet diagram and find the py-upset on github: https://github.com/ImSoErgodic/py-upset/ I'm using PyCharm as an IDE and downloaded every requirements. I tried the code below; import pyupset as pyu from pickle import load with open('./test_data_dict.pckl', 'rb') as f: data_dict = load(f) pyu.plot(data_dict) after run the code it says "Process finished with exit code 0" but gives no graph/ diagram. How can I get the diagram? any help?
favorite count: 0
type: Question
tagged with: python-3.x
has title: Need help for py-upset?
has comment: http://stackoverflow.com/comment/81769269
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9622163
has comment: http://stackoverflow.com/comment/81775722
tagged with: python

http://stackoverflow.com/q/47516507
has comment: http://stackoverflow.com/comment/81989202
has body: I'm trying to split a string by commas that are not inside brackets (i.e the string contains items that are separated by commas, but it also contains commas within brackets that I don't want to separate on). Like so: A='[1, "A"], [2, "B"], [3, "C"], [4, "D"], [5, "E"], [6, "F"], [7, "G"], [8, "H"], [9, "I"], [10, "J"], [100, "JJ"]' Which should result in: ['[1, "A"]', ' [2, "B"]', ' [3, "C"]', ' [4, "D"]', ' [5, "E"]', ' [6, "F"]', ' [7, "G"]', ' [8, "H"]', ' [9, "I"]', ' [10, "J"]', '[100, "JJ"]'] I tried using negative lookbehind like this: B=re.split(r'(?&lt;![[][\d]),',A) However, this does not work when the number within the brackets goes above one digit such as in the case of [10, "J"]. Any help would be greatly appreciated!
tagged with: python
has answer: http://stackoverflow.com/a/47517619
score: 0
has title: Regular expression negative lookbehind python
has answer: http://stackoverflow.com/a/47516667
tagged with: regex
type: Question
has answer: http://stackoverflow.com/a/47516626
tagged with: split
has comment: http://stackoverflow.com/comment/81989083
has answer: http://stackoverflow.com/a/47517066
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47516675

http://stackoverflow.com/a/47420648
accepted answer of: http://stackoverflow.com/q/47416699
has comment: http://stackoverflow.com/comment/120696266
has comment: http://stackoverflow.com/comment/81836780
answers question: http://stackoverflow.com/q/47416699
has comment: http://stackoverflow.com/comment/81799885
type: Answer
has comment: http://stackoverflow.com/comment/81799798
has comment: http://stackoverflow.com/comment/81800797
upvote count: 8
score: 8
has comment: http://stackoverflow.com/comment/81825219
has comment: http://stackoverflow.com/comment/81802145
downvote count: 0
has body: As stated in the SQLAlchemy documentation, "The delimeters must be URL escaped" when using a pass-through exact pyodbc string. So, this will fail ... import pyodbc from sqlalchemy import create_engine params = r'DRIVER={SQL Server};SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes' conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params) engine = create_engine(conn_str) ... but this will work: import pyodbc from sqlalchemy import create_engine import urllib params = urllib.parse.quote_plus(r'DRIVER={SQL Server};SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes') conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params) engine = create_engine(conn_str)
type: AcceptedAnswer

http://stackoverflow.com/comment/81996664
type: QuestionComment
comment on: http://stackoverflow.com/q/47520092
type: Comment
has text: `sum(1 for w in l.split() if len(w)==5)` should do it.
score: 1

http://stackoverflow.com/comment/81950353
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47496287
type: QuestionComment
has text: @Silencer Did you use Orb or SIFT?

http://stackoverflow.com/comment/81877635
score: 0
type: Comment
type: QuestionComment
has text: Because a backspace character isn't valid Python code.
comment on: http://stackoverflow.com/q/47461480

http://stackoverflow.com/comment/81743232
score: 0
comment on: http://stackoverflow.com/q/47394969
type: Comment
type: QuestionComment
has text: Put it somewhere on the web.

plot
tags question: http://stackoverflow.com/q/47453254
tags question: http://stackoverflow.com/q/47449741
tags question: http://stackoverflow.com/q/47446644
tags question: http://stackoverflow.com/q/47388698
tags question: http://stackoverflow.com/q/47391136
tags question: http://stackoverflow.com/q/47512208
tags question: http://stackoverflow.com/q/47530901
tags question: http://stackoverflow.com/q/47425692
tags question: http://stackoverflow.com/q/47395797
type: Tag
tags question: http://stackoverflow.com/q/47538718
tags question: http://stackoverflow.com/q/47500216
tags question: http://stackoverflow.com/q/47383320
tags question: http://stackoverflow.com/q/47437134
tags question: http://stackoverflow.com/q/47455969
tags question: http://stackoverflow.com/q/47457983
tags question: http://stackoverflow.com/q/47399830
tags question: http://stackoverflow.com/q/47485768
tags question: http://stackoverflow.com/q/47528955
tags question: http://stackoverflow.com/q/47434701
tags question: http://stackoverflow.com/q/47521452
tags question: http://stackoverflow.com/q/47404653
tags question: http://stackoverflow.com/q/47488873
tags question: http://stackoverflow.com/q/47491303
tags question: http://stackoverflow.com/q/47473125
tags question: http://stackoverflow.com/q/47387173
tags question: http://stackoverflow.com/q/47480741
tags question: http://stackoverflow.com/q/47494557
tag name: plot
tags question: http://stackoverflow.com/q/47463413
tags question: http://stackoverflow.com/q/47482052
tags question: http://stackoverflow.com/q/47492783
tags question: http://stackoverflow.com/q/47518631
tags question: http://stackoverflow.com/q/47478506
tags question: http://stackoverflow.com/q/47444703
tags question: http://stackoverflow.com/q/47467077
tags question: http://stackoverflow.com/q/47466371
tags question: http://stackoverflow.com/q/47432366
tags question: http://stackoverflow.com/q/47444332
tags question: http://stackoverflow.com/q/47390069
tags question: http://stackoverflow.com/q/47400806
tags question: http://stackoverflow.com/q/47514526
tags question: http://stackoverflow.com/q/47540218
tags question: http://stackoverflow.com/q/47422507
tags question: http://stackoverflow.com/q/47538805
tags question: http://stackoverflow.com/q/47476179
tags question: http://stackoverflow.com/q/47488668
tags question: http://stackoverflow.com/q/47539035
tags question: http://stackoverflow.com/q/47538496
tags question: http://stackoverflow.com/q/47398380
tags question: http://stackoverflow.com/q/47533128
tags question: http://stackoverflow.com/q/47480836
tags question: http://stackoverflow.com/q/47407985

http://stackoverflow.com/comment/81849563
score: 0
has text: @Vaishali Sorry - hope that helps?
type: QuestionComment
comment on: http://stackoverflow.com/q/47447033
type: Comment

http://stackoverflow.com/comment/81960503
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47493345
has text: @Wen Thanks! Sorry for deleting my previous comment. I figured it out myself, but then as soon as I deleted my comment I saw that you responded to it. Thanks a bunch though, really do appreciate your help!

http://stackoverflow.com/a/47388968
accepted answer of: http://stackoverflow.com/q/47387713
has body: It is very common problem with lambda in loop. It doesn't copy value from i when you create lambda function but it keeps reference to i. So all functions have reference to the same variable (the same place in memory) and they get value from i when they are exceuted. You have to assign i to argument in lambda (for example x=i) and use this argument x in your function. This way it will copy current value from i and use in lambda function lambda event, x=i : self.but_callback(event, x)
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47387713
type: Answer
upvote count: 4

http://stackoverflow.com/comment/81864858
has text: I see, that makes sense. So where can I obtain those images after saving them? I am sorry, I do not have experience with ByteIO and wondering where exactly does it save. Also, the arr shows all the values to be 255, is that correct?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47454950
type: AnswerComment

http://stackoverflow.com/q/47445043
has comment: http://stackoverflow.com/comment/81845750
has answer: http://stackoverflow.com/a/47445311
has comment: http://stackoverflow.com/comment/81845442
has comment: http://stackoverflow.com/comment/81845645
upvote count: 2
score: 2
has body: I have my flask file and a seperate file which contains a pygame. Both work seperately, How would i combine the flask so that when i press my link on my webpage it starts running the external file, how would I call it? from flask import Flask, render_template import going app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/my-link/') def my_link(): return going.main() if __name__ == '__main__': app.run(debug=True) At the moment I am trying to run the main() method to initialize the program. import pygame ##1100 * 800 size = [1100, 800] score1 = 0 score2 = 0 blue = (100, 149, 237) black = (0, 0, 0) brown = (165,42,42) white = (255, 255, 255) green =(0,100,0) red = (255,0,0) dark_red = (200,0,0) grey = (100,100,100) other_grey = (0,0,100) background = 'Mahogany.jpg' pass_count = 0 player = 1 clock = pygame.time.Clock() class Player(object): def ___init__(self,id): self.id = 1 def quitGame(self): pygame.quit() quit() def pass_turn(self): global pass_count pass_count += 1 if pass_count == 2: quitGame() def score(player_text, score): return player_text + str(score) class Stone(object): def __init__(self,board,position,color): self.board = board self.position = position self.color = color self.placeStone() def placeStone(self): coords = (self.position[0] * 50, self.position[1] * 50) pygame.draw.circle(self.board,self.color,coords,20,0) pygame.display.update() class Board(object): def draw_board(self): for i in range(12): for j in range(12): rect = pygame.Rect(55 + (50 * i), 100 + (50 * j), 50, 50) pygame.draw.rect(background, blue, rect, 1) screen.blit(background, (0,0)) pygame.display.update() def text_objects(self,text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def button(self,msg,x,y,w,h,ic,ac,action = None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x+w &gt; mouse[0] &gt; x and y+h &gt; mouse[1] &gt; y: pygame.draw.rect(screen, ac,(x,y,w,h))…
has comment: http://stackoverflow.com/comment/81854804
has comment: http://stackoverflow.com/comment/81845450
downvote count: 0
has comment: http://stackoverflow.com/comment/81845459
answer count: 1
has title: Python flask game not initializing
favorite count: 0
has comment: http://stackoverflow.com/comment/81845471
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: pygame
tagged with: flask
has comment: http://stackoverflow.com/comment/81845497

http://stackoverflow.com/comment/81973306
comment on: http://stackoverflow.com/a/47489625
type: Comment
has text: Ok, I did it early in the morning, and we are correct. Thank you so much for help.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47394651
has title: storing Mousebutton events in Pygame
tagged with: pygame
has comment: http://stackoverflow.com/comment/81755468
has comment: http://stackoverflow.com/comment/81742614
type: Question
has body: Is it possible to click with the mouse on to different rectangle buttons in Pygame,getting the x-y position and make an if statement with them as variables. for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() . . . if button_cliked_one and button_cliked_two: print ('buttons clicked') else: print('something is wrong')
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47402637
tagged with: python
has comment: http://stackoverflow.com/comment/81765752
has comment: http://stackoverflow.com/comment/81746069
has comment: http://stackoverflow.com/comment/81757844
has comment: http://stackoverflow.com/comment/81742547
has comment: http://stackoverflow.com/comment/81755750
has answer: http://stackoverflow.com/a/47401589
score: 0
has comment: http://stackoverflow.com/comment/81745689

http://stackoverflow.com/q/47482381
has body: I have a dictionary whose keys are some user IDs and values are lists of dictionaries, take one key-value pair for example: my_dict['10020'] = [{'type': 'phone', 'count': 3}, {'type': 'id_card', 'count': 1}, {'type': 'email', 'count': 2}] Now I would like to create a pandas DataFrame, each row for a key-value pair, columns are the 'type' field within the list of dictionaries above, and values are the 'count' field respectively, like: ID phone id_card email 10020 3 1 2 I have no idea how many potential 'types' are there in the dictionary, so instead of traversing the dictionary and get all 'types', is there a handy way to get the job done?
has comment: http://stackoverflow.com/comment/81919889
has answer: http://stackoverflow.com/a/47482506
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47482648
has answer: http://stackoverflow.com/a/47482648
type: Question
has title: Pandas create dataframe from lists of dictionaries
answer count: 2
possible better answer: http://stackoverflow.com/a/47482506
tagged with: python

http://stackoverflow.com/comment/81824435
type: QuestionComment
comment on: http://stackoverflow.com/q/47434724
has text: @Elis yes I did, you should make a better question if you want a different answer.
type: Comment
score: 0

http://stackoverflow.com/a/47458191
answers question: http://stackoverflow.com/q/47458136
type: Answer
accepted answer of: http://stackoverflow.com/q/47458136
score: 2
upvote count: 2
has body: Use combine_first and if necessary first set_index: df11 = df1.set_index('subject_id') df22 = df2.set_index('subject_id') df3 = df22.combine_first(df11).reset_index() print (df3) subject_id first_name last_name 0 1 Alex Anderson 1 2 Amy Ackerman 2 3 Allen Ali 3 4 Billy Bonder 4 5 Brian Black 5 6 Bran Balwner 6 7 Bryce Brice 7 8 Betty Btisan df3 = df11.combine_first(df22).reset_index() print (df3) subject_id first_name last_name 0 1 Alex Anderson 1 2 Amy Ackerman 2 3 Allen Ali 3 4 Alice Aoni 4 5 Ayoung Atiches 5 6 Bran Balwner 6 7 Bryce Brice 7 8 Betty Btisan
downvote count: 0
has comment: http://stackoverflow.com/comment/81870968
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81870912

http://stackoverflow.com/comment/81855029
type: AnswerComment
has text: You could probably use regex without needing to split and compare every single split part.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47450088

http://stackoverflow.com/comment/81898975
comment on: http://stackoverflow.com/q/47460535
has text: I updated the question to include these bits.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81973319
has text: `convert_xls_datetime(42747).date()` will give you just the date.
type: AnswerComment
score: 2
type: Comment
comment on: http://stackoverflow.com/a/47508307

http://stackoverflow.com/comment/82009680
type: AnswerComment
has text: Fixed in the edit! It's a behavior of min()/max() for empty lists - it must have occurred in a situation where a cell with value 2 had all neighbors =2 (so the list came out empty.
comment on: http://stackoverflow.com/a/47525926
type: Comment
score: 0

http://stackoverflow.com/comment/128695707
has text: @alexis I agree that `explicit is better than implicit`, but the `dict` created by `locals()` is as "real" as any other. Just keep in mind that [modifying it may not work like you expect](https://stackoverflow.com/questions/4997184/why-is-it-bad-idea-to-modify-locals-in-python).
comment on: http://stackoverflow.com/a/47496649
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47399848
type: Answer
answers question: http://stackoverflow.com/q/47399789
has body: Your indent blocks are off. The with statement closes the file when you go to the for block. This code should do what you want. admin_username_choice = input("Enter the user's username: ") with open("data.txt") as f: for line in f: if admin_username_choice in line.split(): print(line) else: print("Incorrect information")
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/52575457
has comment: http://stackoverflow.com/comment/92090270
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47537823
type: Answer
has comment: http://stackoverflow.com/comment/92099289
upvote count: 4
has body: pd.Categorical(pd.Series(['a','b','b']), categories = ['a', 'b', 'c']) Also you can use the ordered parameter to create a categorical hierarchy result = pd.Categorical(pd.Series(['a','b','b']), categories = ['a', 'b', 'c'], ordered = True) Update to convert to Series dtype pd.Series(result)

http://stackoverflow.com/comment/82036670
score: 0
has text: @JakobLovern I thought current version is 3.6 and most beginners like "the newest version" :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47538904

http://stackoverflow.com/a/47387799
answers question: http://stackoverflow.com/q/47384442
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Inside matplotlib.pyplot there is a line saying from matplotlib.lines import Line2D Hence, if you import matplotlib.pyplot, Line2D is available from the pyplot namespace, import matplotlib.pyplot as plt plt.Line2D(...) Because the availability in the namespace itself is not a documented feature, one should probably not rely on it. Also it is better style to use the functions/objects imported from their original submodule. On the other hand it is very convenient to just write plt.Rectangle instead of having to import the patches module first. I guess at the end you need to decide for yourself which case applies.
accepted answer of: http://stackoverflow.com/q/47384442
type: AcceptedAnswer

http://stackoverflow.com/comment/81786175
score: 0
has text: @thanasisp I didn't know about this option. Thanks for the information.
comment on: http://stackoverflow.com/a/47400492
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81837200
type: QuestionComment
comment on: http://stackoverflow.com/q/47424458
score: 0
type: Comment
has text: That's clear, but my samples are like that 19*1000. 19 different signals of length 1000 for every sample. How do you process that into a 1D vector of float ? Is it ok to do SKLearn on discrete signals ? Or can you only use it with features like avg, max, min, ... values ! Like for instance on finance, when you use only values and not signals... That's the point I don't get. Can I use it with signals ?

http://stackoverflow.com/comment/81758577
type: Comment
score: 1
comment on: http://stackoverflow.com/a/47402370
type: AnswerComment
has text: I like your method better. +1

http://stackoverflow.com/comment/81796061
score: 0
has text: I assume you mean `Belgium\tBrussels` in your expected output?
comment on: http://stackoverflow.com/q/47420901
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47407937
score: 0
has body: So, this will only work on Linux systems and only with ASCII characters: import termios import sys def uppercase_input(prompt): sys.stdout.write(prompt) sys.stdout.flush() old = termios.tcgetattr(sys.stdout.fileno()) new = old[:] new[1] |= termios.OLCUC termios.tcsetattr(sys.stdout.fileno(), termios.TCSANOW, new) try: return input().upper() finally: termios.tcsetattr(sys.stdout.fileno(), termios.TCSANOW, old) result = uppercase_input("all uppercase? ") print("yes: {}".format(result)) This uses some interesting ancient settings to convert I/O to/from uppercase from the old times when there were terminals only supporting upper-case ASCII. From man tcsetattr: OLCUC (not in POSIX) Map lowercase characters to uppercase on output. So this solution is not really portable. For a fully portable solution, you would need to implement echoing yourself.
answers question: http://stackoverflow.com/q/47407179
has comment: http://stackoverflow.com/comment/81850049
type: Answer
has comment: http://stackoverflow.com/comment/81887237
has comment: http://stackoverflow.com/comment/81864693
has comment: http://stackoverflow.com/comment/81772637
has comment: http://stackoverflow.com/comment/81771126

http://stackoverflow.com/a/47543881
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47521124
upvote count: 1
has comment: http://stackoverflow.com/comment/82070975
answers question: http://stackoverflow.com/q/47521124
has body: By defining urls with braces, you made it a set, which is unordered. You need to define urls as a tuple which can be done using parentheses. This answer explains it well: https://stackoverflow.com/a/46633252/2150542
type: Answer
score: 1

http://stackoverflow.com/a/47518564
has comment: http://stackoverflow.com/comment/82005309
type: Answer
has comment: http://stackoverflow.com/comment/81997888
answers question: http://stackoverflow.com/q/47516976
has comment: http://stackoverflow.com/comment/81998249
has body: Your JSON file seems to be written wrong (the example one). It is not a list. It is just a single associated array (or dictionary, in Python). Additionally, you don't seem to be using json.dumps properly. It only takes 1 argument. I also figured it would be easier to just create the dictionary inline. And you don't seem to be splitting the min_max properly. Here's the correct input: [{ "title": "Person", "type": "object", "required": "firstName", "min_max": "20/60" }] Here's your new code: import json with open('input.json', 'r') as inp, open('test.json', 'w') as outp: json_decode=json.load(inp) result = [] for temp in json_decode: minMax = temp["min_max"].split("/") result.append({ "title":temp["title"], "min":minMax[0], "max":minMax[1] }) data=json.dumps(result) outp.write(data)
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81998102
has comment: http://stackoverflow.com/comment/81998421
has comment: http://stackoverflow.com/comment/81998888
score: 1
has comment: http://stackoverflow.com/comment/81998816

pyodbc
tags question: http://stackoverflow.com/q/47416699
tags question: http://stackoverflow.com/q/47454455
tags question: http://stackoverflow.com/q/47535578
type: Tag
tags question: http://stackoverflow.com/q/47540412
tag name: pyodbc

http://stackoverflow.com/comment/94187069
type: AnswerComment
has text: I calculate confidence intervals for mean response. It is binary classification, so the prediction interval is always {0}, {1}, or [0, 1]. I don't think such intervals make a lot of sense.
comment on: http://stackoverflow.com/a/47419474
type: Comment
score: 0

http://stackoverflow.com/comment/81977917
type: Comment
score: 0
has text: So, you want a `pivot` operation.
comment on: http://stackoverflow.com/q/47511048
type: QuestionComment

http://stackoverflow.com/q/47492752
has body: im trying to insert some rows into my mysql database, but i get this error: TypeError: not enough arguments for format string My code is: cursor.execute("""INSERT INTO galgos (`hora`,`circuito`,`metros`,`puesto`,`nombre`,`entrenador`,`edad`,`peso`,`curva`,`tiempo`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')""", (hora[0],hora[1],saludos[:3],nombre,entrenador,edad,peso,curva,tiempo))
score: 0
has title: Python + Mysql TypeError
has comment: http://stackoverflow.com/comment/81940800
answer count: 1
tagged with: mysql
has answer: http://stackoverflow.com/a/47492964
type: Question
type: UnansweredQuestion
tagged with: python

methods
tags question: http://stackoverflow.com/q/47464697
tags question: http://stackoverflow.com/q/47392998
tags question: http://stackoverflow.com/q/47407741
tags question: http://stackoverflow.com/q/47520949
tags question: http://stackoverflow.com/q/47487932
tags question: http://stackoverflow.com/q/47481475
tag name: methods
tags question: http://stackoverflow.com/q/47398189
type: Tag
tags question: http://stackoverflow.com/q/47405748
tags question: http://stackoverflow.com/q/47500101
tags question: http://stackoverflow.com/q/47465825
tags question: http://stackoverflow.com/q/47460260
tags question: http://stackoverflow.com/q/47461806

http://stackoverflow.com/comment/81821957
type: AnswerComment
type: Comment
has text: I mean, try to connect to your database with any tools, for example with PgAdmin3 which is most common for postgres, when you will sure that db is available on localhost and sure in your user/pass you should make right connection string to flask variable SQLALCHEMY_DATABASE_URI
comment on: http://stackoverflow.com/a/47433432
score: 0

deap
tags question: http://stackoverflow.com/q/47429746
tag name: deap
type: Tag

http://stackoverflow.com/comment/81874149
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47433597
has text: @brunodesthuilliers Thank you for your feedback. Tomorrow I will update my answer regarding the class inspection. With `dir` it is much easier that I thought. However I still see the risk of side-effects as real. For example anything communicating with hardware might produce timeouts, OSErrors and similar.
score: 0

http://stackoverflow.com/a/47515009
has comment: http://stackoverflow.com/comment/81985926
has comment: http://stackoverflow.com/comment/81986203
answers question: http://stackoverflow.com/q/47514913
has comment: http://stackoverflow.com/comment/81986880
has comment: http://stackoverflow.com/comment/81986101
upvote count: 3
has body: My goal is to extract all the strings within each list that 3 characters long. A nested list comprehensions will do the trick. &gt;&gt;&gt; l = ['a-bc-def-ghij-klm', 'abc-de' 'fg-hi'] &gt;&gt;&gt; [[x for x in s.split('-') if len(x) == 3] for s in l] [['def', 'klm'], ['abc']]
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81985975
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/81986143
accepted answer of: http://stackoverflow.com/q/47514913

http://stackoverflow.com/q/47501831
has body: I am trying out a sample common data crawl example based on https://engineeringblog.yelp.com/2015/03/analyzing-the-web-for-the-price-of-a-sandwich.html I am running this below command in my local windows PC based on the instructions. python mr_crawl_phonenumbers.py -r emr s3://aws-publicdatasets/common-crawl/crawl-data/CC-MAIN-2014-52/wet.paths.gz s3://yelp/business_data.txt But I am getting the below error. raise NoCredentialsError botocore.exceptions.NoCredentialsError: Unable to locate credentials I am new to this, Do I need to set any credentials. If yes, how to set this up in local PC. Any help is much appreciated.
tagged with: python
has comment: http://stackoverflow.com/comment/81964025
tagged with: boto
tagged with: common-crawl
answer count: 0
tagged with: amazon-s3
has title: No Credentials error with python , common data crawl
score: 0
has comment: http://stackoverflow.com/comment/81960340
has comment: http://stackoverflow.com/comment/81960191
type: Question
has comment: http://stackoverflow.com/comment/81959549
type: UnansweredQuestion

memorycache
tag name: memorycache
tags question: http://stackoverflow.com/q/47532002
type: Tag

http://stackoverflow.com/q/47391785
has answer: http://stackoverflow.com/a/47391867
tagged with: python
has comment: http://stackoverflow.com/comment/81741143
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47391863
has title: Changing the default python without changing the $PATH variable?
downvote count: 0
has body: I want to change the default python version I use, without affecting any other defaults. Appending the python path to the $PATH environment variable only accomplishes that as long as there is only the python executable at that given location, which is not the case if I want to use the /usr/bin version (export PATH=\usr\bin:$PATH). I know I could theoretically create a symbolic link in some other folder of my choosing, but this is not very elegant. Is there any other way of changing the default python (like a nice environment variable that python uses which takes precedence over the $PATH environment variable)?
upvote count: 1
accepted answer: http://stackoverflow.com/a/47392217
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47392217
answer count: 3
possible better answer: http://stackoverflow.com/a/47391867
score: 1
has comment: http://stackoverflow.com/comment/81736564

http://stackoverflow.com/q/47440782
tagged with: python
score: -1
type: AnsweredQuestion
has body: In a list ['x', 'x', 'x..', 'x'] I wish to replace each x in the list (by reading the list into a string) with . and - in all possible permutations. Thus the output could be ['. . ... .'], ['- - -.. -'], ['. - -.. .'] and all similar permutations. I have tried the below script but I was able to get just two patterns as output. def fun(inputStringList): message_received = inputStringList message_received = ' '.join(inputStringList) for i in range(len(message_received)): x = 'x' y = '.' message = message_received.replace(x, y) message1 = message.split(",") print message1 for i in range(len(message_received)): x = 'x' y = '-' message = message_received.replace(x, y) message2 = message.split(",") print message2 def funTest(): test = ['x', 'x', 'x..', 'x'] print fun(test) funTest() Output: ['. . ... .'] ['- - -.. -'] What to do?
upvote count: 0
answer count: 1
tagged with: permutation
accepted answer: http://stackoverflow.com/a/47440908
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47440908
type: Question
has title: replacement of the members of a list to produce all possible permutations

http://stackoverflow.com/q/47408447
tagged with: oop
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81770265
has comment: http://stackoverflow.com/comment/81770488
accepted answer: http://stackoverflow.com/a/47408599
has comment: http://stackoverflow.com/comment/81770752
has comment: http://stackoverflow.com/comment/81770294
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47408599
upvote count: 4
has body: I have a structure representing some data in a following way: class GenericDataHolder(object): def __init__(self): self.xxx=[] self.yyy=[] class A(object): def __init__(self): self.a1=GenericDataHolder() self.a2=GenericDataHolder() class B(object): def __init__(self): self.b1=GenericDataHolder() self.b2=GenericDataHolder() self.b3=A() I would like to iterate over class B elements so that i will be able to access all nested objects like below: b=B() for i in b: print i.xxx print i.yyy I have read that there are a few possible solutions to solve this: using metaclass implementing iterator protocol using itertools This is all fine on basic examples, but I couldn't find any solution to the problem I am facing directly - having class which's elements are composed of other classes.
type: Question
has comment: http://stackoverflow.com/comment/81770383
has title: Iterate over a class composed of other classes
has comment: http://stackoverflow.com/comment/81770652
tagged with: python
has comment: http://stackoverflow.com/comment/81770285
has comment: http://stackoverflow.com/comment/81771465

http://stackoverflow.com/comment/81856668
type: AnswerComment
has text: @ArthurTacca: You cannot sort `ypos` without also reorganizing `y`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47443369

http://stackoverflow.com/q/47437750
answer count: 1
downvote count: 0
upvote count: 1
score: 1
tagged with: keras
has answer: http://stackoverflow.com/a/47438205
favorite count: 0
type: Question
has body: def Generate(): i = 0 while 1: i = i%int(Numb/batch_size) my_input_batch = my_input[i*batch_size : (i+1)*batch_size] my_output_batch = my_output[i*batch_size : (i+1)*batch_size] encoder_input_data = np.array(np.zeros((batch_size, max_encoder_text_length, num_dictonary),dtype='float32')) decoder_input_data = np.array(np.zeros((batch_size, max_decoder_text_length, num_dictonary),dtype='float32')) decoder_target_data = np.array(np.zeros((batch_size, max_decoder_text_length, num_dictonary),dtype='float32')) for i, (text_input, text_output) in enumerate(zip(my_input_batch, my_output_batch)): for t, word in enumerate(my_input_batch): encoder_input_data[i, t, word] = 1. for t, word in enumerate(my_output_batch): decoder_input_data[i, t, word] = 1. if t &gt; 0: decoder_target_data[i, t - 1, word] = 1. i = i + 1 yield ({encoder_input_data, decoder_input_data}, {decoder_target_data}) I would like to train my model with fit_generator() in Keras. But when I start train I get mistakes: File "test.py", line 146, in Generate yield ({encoder_input_data, decoder_input_data}, {decoder_target_data}) TypeError: unhashable type: 'numpy.ndarray' How I can solve this problem? What I do wrong?
tagged with: python
has title: fit_generator() in keras model
tagged with: lstm
type: UnansweredQuestion

http://stackoverflow.com/comment/82033471
has text: @DanielRoseman Is a bunch of code that doesn't work necessary to understand the problem and solution? If this was homework and I needed to show my work I would understand, but the point of the site is for people with similar problems to be able to look up questions and find answers. I felt synthesizing my much more specific problem to a generalized, reproducible one was more in the spirit of the site rather than a code dump of things I had tried.
score: 0
comment on: http://stackoverflow.com/q/47538169
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81784910
has text: Why the downvote? Could you explain why is not a correct solution?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47415304

http://stackoverflow.com/comment/81884446
comment on: http://stackoverflow.com/q/47462664
type: Comment
type: QuestionComment
has text: Do you want to pick [with replacement or without replacement](https://www.ma.utexas.edu/users/parker/sampling/repl.htm)?
score: 0

http://stackoverflow.com/a/47475552
downvote count: 0
has body: It's not entirely clear to me what you want to achieve or what kind of channels you want to store. According to the PNG color options table here, there is only one option: using the Grayscale + alpha-channel. Of course you can store your data like that, but: this implies a bit-depth of 16 or 32; maybe not what you want libraries will by default interpret it as Grayscale + alpha-channel TIFF is actually much more flexible, and seems to support arbritrary channels, but according to this libtiff does not support 2-channels. (maybe outdated information; not sure). So it probably depends on what you really want to do. If you just want to store 2 channels (because you want to save bytes and you don't need more channels), while every step in your pipeline can be tuned to interpret it as you like, i recommend just storing 3 channels, where one is empty (e.g. all zeros). PNGs filters will be able to compress it efficiently. Of course, when reading/using these later, you need to modify your code to interpret it as done when saving. If this is just for some kind of task involving python's scientific-stack only, you can just store your array using numpy's savez_compressed. (remark: there will be general-purpose compression; but no filter-usage like x+1 - x -> pixels: 0, 1, 2, 3 hard to compress; but using delta-filter: 0, 1, 1, 1 are easy to compress; meaning: compression efficiency compared to PNG depends on your images)
has comment: http://stackoverflow.com/comment/81911792
upvote count: 1
has comment: http://stackoverflow.com/comment/124452694
score: 1
answers question: http://stackoverflow.com/q/47471491
type: Answer

http://stackoverflow.com/q/47517323
has comment: http://stackoverflow.com/comment/81991411
has answer: http://stackoverflow.com/a/47579871
has body: When calling a program from the command line, I can pipe the output to grep to select the lines I want to see, e.g. printf "hello\ngood day\nfarewell\n" | grep day I am in search for the same kind of line selection, but for a C library called from Python. Consider the following example: import os # Function which emulate a C library call def call_library(): os.system('printf "hello\ngood day\nfarewell\n"') # Pure Python stuff print('hello from Python') # C library stuff call_library() When running this Python code, I want the output of the C part to be grep'ed for the string 'day', making the output of the code hello from Python good day So far I has fiddled around with redirection of stdout, using the methods described here and here. I am able to make the C output vanish completely, or save it to a str and print it out later (which is what the two links are mainly concerned with). I am not however able to select which lines get printed based on its content. Importantly, I want the output in real time while the C library is being called, so I cannot just redirect stdout to some buffer and do some processing on this buffer after the fact. The solution need only to work with Python 3.x on Linux. If in addition to line selection, the solution makes it possible for line editing, that would be even greater. I think the following should be possible, but I do not know how to set it up Redirect stdout to a "file" in memory. Spawn a new thread which constantly reads from this file, does the selection based on line content, and writes the wanted lines to the screen, i.e. the original destination of stdout. Call the C library Join the two threads back together and redirect stdout back to its original destination (the screen). I do not have a firm enough grasp of file descriptors and the like to be able to do this, nor to even know if this is the best way of doing it. Edit Note that the solution cannot simply re-implement the code in call_library. The code must call call_librar…
linked to: http://stackoverflow.com/q/3197509
linked to: http://stackoverflow.com/q/24277488
has answer: http://stackoverflow.com/a/47561073
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47561073
downvote count: 2
has comment: http://stackoverflow.com/comment/81992222
tagged with: grep
accepted answer: http://stackoverflow.com/a/47579871
upvote count: 8
has comment: http://stackoverflow.com/comment/81991941
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47381835
answer count: 2
tagged with: linux
linked to: http://stackoverflow.com/q/18421757
has comment: http://stackoverflow.com/comment/82377034
has title: grep library output from within Python
score: 6
has comment: http://stackoverflow.com/comment/82024076
tagged with: python
tagged with: http://stackoverflow.com/tag/c

http://stackoverflow.com/q/47426810
tagged with: subprocess
answer count: 0
tagged with: ffmpeg
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81810271
has comment: http://stackoverflow.com/comment/81815510
downvote count: 0
has body: I'm not sure if this is the best way to go about this, but I have another question here which I don't think was asked very well (or more to the point I realised the actual problem and have a simpler way of asking for help). If you can answer this question you'll have the answer to the other. I'm using python 3.5.2 and ffmpeg 3.3.4-2 and have this function to run my ffmpeg commands: def ffmpegPro(args): err = None for i, arg in enumerate(args): if(" " in arg or "(" in arg or "[" in arg): args[i] = "\"" + arg + "\"" command = [ ffmpegcmd, '-y', '-loglevel', loglevel ] + args commandStr = " ".join(command) ffmpeg = subprocess.Popen(commandStr, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, shell=True) out, err = ffmpeg.communicate() if ffmpeg.returncode != 0: print(commandStr + "\n" + "ERROR CODE: " + str(ffmpeg.returncode)) raise Exception(err) When I pass the following args the returncode is 137 and the process is Killed. This only occurs when executed in python, when I run the same command at the command line it executes as expected. ['-i', '/var/www/temp/film.mp4', '-vf', 'scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:x=(1920-iw)/2:y=(1080-ih)/2:color=black', '/var/www/temp/videoHD.mp4'] The resulting command is: ffmpeg -y -loglevel verbose -i /var/www/temp/film.mp4 -vf "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:x=(1920-iw)/2:y=(1080-ih)/2:color=black" /var/www/temp/videoHD.mp4 When executed through python: ERROR CODE: 137 Traceback (most recent call last): File "getInsta2.py", line 740, in &lt;module&gt; populate(media_feed, last, saved) File "getInsta2.py", line 679, in populate videoPost(media, hasVids, thisSaved) File "getInsta2.py", line 639, in videoPost processVideo(film, final, noMusic, audios, lengths) File "getInsta2.py", line 358, in processVideo ffmpegPro(args) File "getInsta2.py", line 170, in ffmpegPro raise Exception(err) Exception: ffmpeg version 3.3.4-2~1…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81810865
has title: FFMPEG process Killed and raises returncode 137 when executed through python3 subprocess.Popen but runs fine from the command line
score: 3
has comment: http://stackoverflow.com/comment/81825660
tagged with: popen
has comment: http://stackoverflow.com/comment/81810046
tagged with: python
linked to: http://stackoverflow.com/q/47414122
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81811284

http://stackoverflow.com/comment/81923151
has text: what are you trying to achieve as such?
comment on: http://stackoverflow.com/q/47412460
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47430750
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47429981
has body: Many solutions trying same old approach here using two loop: Here is different approach: One line solution without any loop: You can use lambda function with map: data={'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}], 'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]} print(list(map(lambda x:list(map(lambda y:y['name'],x)),data.values()))) output: [['john', 'steve'], ['jack', 'anna']]
score: 1
type: Answer

http://stackoverflow.com/q/47497466
downvote count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/57358146
has answer: http://stackoverflow.com/a/47497495
has answer: http://stackoverflow.com/a/57358146
favorite count: 0
type: Question
score: 3
has title: Python: Fill 'na' in pandas column with random elements from a list
has body: I am trying to fill 'NA' in a pandas column by randomly selecting elements from a list. For example: import pandas as pd df = pandas.DataFrame() df['A'] = [1, 2, None, 5, 53, None] fill_list = [22, 56, 84] Is it possible to write a function which takes the pandas DF with column name as input and replaces all NA by randomly selecting elements from the list 'fill_list'? fun(df['column_name'], fill_list])
accepted answer: http://stackoverflow.com/a/47497495
tagged with: python
type: AnsweredQuestion
upvote count: 3
answer count: 2

http://stackoverflow.com/a/47484806
has comment: http://stackoverflow.com/comment/81926588
answers question: http://stackoverflow.com/q/47435152
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81944760
has comment: http://stackoverflow.com/comment/81924594
score: 1
has body: Adding to the existing answers, I'd like to draw your attention to the canny similarity between - df A B 0 1 1 1 2 3 2 3 4 3 4 7 df.T['C'] = 3 df A B 0 1 1 1 2 3 2 3 4 3 4 7 And, a similar case with python lists - l = [1, 2, 3, 4, 5] l[:].append(6) l [1, 2, 3, 4, 5] What happens in both cases is that a new object is created! The operation is then applied to that newly created object, following which, that object is garbage collected since there are no active references pointing to it. You see that with this - import sys sys.getrefcount(df.T) 1 There's only one reference to that object (the reference at that point of time, which is subsequently lost). This becomes easy to understand once you accept the fact that df.T returns a completely new object (I've said this already, but I'm trying to drive home the point) - id(df.T) 4612098928 id(df.T) 4612098872 id(df.T) 4612098592 In summary, you are attempting to modify a fresh object to which you have no reference, and you do not see any changes to the original because you did not make any.
upvote count: 1
has comment: http://stackoverflow.com/comment/81938293
has comment: http://stackoverflow.com/comment/81926820

http://stackoverflow.com/q/47436641
has comment: http://stackoverflow.com/comment/81827877
has comment: http://stackoverflow.com/comment/81827948
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81827805
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81828149
tagged with: loops
has body: The code is supposed to take each pixel rgb value and store it in a 2d array (e.g. pixels[pixelNumber][r, g, b]), where it then gets sent to a user defined method to, in this case, blur it (using Gaussian blur). Width and height are pixel width and height definitions taken from the image, and radius is the user defined radius of which pixels get averaged to be blurred. It gave me a divide by 0 error at weight_r = pixels[j][0] * weight weight_g = pixels[j][1] * weight weight_b = pixels[j][2] * weight before I changed total_weight from 0 to 1 when defined just below the first for loop, if that helps def blur(pixels, radius, width, height): for i in range(len(pixels)): total_weight = 1 pix_weight = 0 r_temp = radius pixels_2 = copy.deepcopy(pixels) x = i % width y = (i // width) + 1 for j in range(len(pixels)): x_2 = j % width y_2 = (j // width) + 1 dist = math.sqrt(((x_2 - x) ** 2) + ((y_2 - y) ** 2)) while(r_temp &gt; 0): if((x_2 - radius == x or x_2 + radius == x) and (y_2 - radius == y or y_2 + radius == y) and dist != 0): weight = ((math.e ** (-((dist ** 2) / (2 * (radius ** 2))))) / (2 * math.pi * (radius ** 2))) total_weight = total_weight + weight weight_r = pixels[j][0] * weight weight_g = pixels[j][1] * weight weight_b = pixels[j][2] * weight pix_weight = pix_weight + weight_r + weight_g + weight_b r_temp = r_temp - 1 final_blur = int((pix_weight / total_weight) / 255) pixels_2[i][0] = int(pixels[i][0] * final_blur) pixels_2[i][1] = int(pixels[i][1] * final_blur) pixels_2[i][2] = int(pixels[i][2] * final_blur) return pixels_2 Method above, pixels is a 2d array, radius, width, and height are all integers.
has comment: http://stackoverflow.com/comment/81828520
has answer: http://stackoverflow.com/a/47436911
accepted answer: http://stackoverflow.com/a/47436911
has title: Function stuck in infinite loop, cannot find reason
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81828000
tagged with: python-3.x
tagged with: infinite-loop
downvote count: 0
has comment: http://stackoverflow.com/comment/81828024
answer count: 1
has comment: http://stackoverflow.com/comment/81827922
has comment: http://stackoverflow.com/comment/81827881
tagged with: python

http://stackoverflow.com/comment/81998008
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47520105
type: Comment
has text: Included asgi.py; after poking around more, I think the problem is partially with an nginx proxy, which has proxy timeouts set to 20 seconds. It should still be ok with Daphne sending pings after 15 seconds, though, so I think something else is still wrong.

http://stackoverflow.com/comment/111008842
comment on: http://stackoverflow.com/a/47571289
type: Comment
type: AnswerComment
has text: I am getting `Assertion fctx->async_lock failed at libavcodec/pthread_frame.c:155` when trying to use multiple clients.
score: 1

http://stackoverflow.com/q/47514185
type: UnansweredQuestion
tagged with: environment-variables
score: 0
has comment: http://stackoverflow.com/comment/82010629
has comment: http://stackoverflow.com/comment/82027876
tagged with: python
has comment: http://stackoverflow.com/comment/82025399
tagged with: openstack
tagged with: linux
tagged with: bash
has title: python scripting ,environment variables and openstack
has body: I'm currently working on jenkins and i want to automate my vm's backup on openstack. So I found a script that is apparently doing what i want ( https://dev.cloudwatt.com/en/blog/instance-backup-script.html ) To start the program i must do: python backup.py &lt;server_id&gt; &lt;server_name&gt; &lt;weekly|daily&gt; &lt;rotation&gt; It also asks to load some environment variables (on linux ?) containing the ID, the PASSWORD etc... I see some inconvenience with thoses environment variables because then the password is stored localy and uncrypted. I may be wrong but the script also send the uncrypted password trough the network ans its a big problem. If someone can provide any clarification about how is the password sent or if you have any other method. It must be a dumb question but the script is made for cloudwatt (which is using openstack) and i want to use it on openstack only will it works ? Sorry for bad english and thank you a lot for any answers, Tristan.
type: Question
has comment: http://stackoverflow.com/comment/81993313
answer count: 0

python-3.6
tags question: http://stackoverflow.com/q/47395007
tags question: http://stackoverflow.com/q/47407970
tags question: http://stackoverflow.com/q/47438832
tags question: http://stackoverflow.com/q/47462282
tags question: http://stackoverflow.com/q/47446349
tags question: http://stackoverflow.com/q/47536568
tags question: http://stackoverflow.com/q/47458283
tags question: http://stackoverflow.com/q/47394996
tags question: http://stackoverflow.com/q/47517110
tags question: http://stackoverflow.com/q/47390161
tags question: http://stackoverflow.com/q/47419305
tags question: http://stackoverflow.com/q/47492446
tags question: http://stackoverflow.com/q/47531456
type: Tag
tags question: http://stackoverflow.com/q/47488646
tag name: python-3.6
tags question: http://stackoverflow.com/q/47522199
tags question: http://stackoverflow.com/q/47383174
tags question: http://stackoverflow.com/q/47434442
tags question: http://stackoverflow.com/q/47514225
tags question: http://stackoverflow.com/q/47426051
tags question: http://stackoverflow.com/q/47500793

http://stackoverflow.com/comment/82009377
has text: Also this SO post may be helpful - https://stackoverflow.com/questions/26911882/python-multiprocessing-why-much-slower If you can, you can have each process read from a separate file the data that it should work on, and this would be faster than your main process reading everything in and then distributing the data to its children via IPC.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47526603

http://stackoverflow.com/a/47522429
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: If you require an API like the one you describe, that returns exactly what you describe, then you may need to write something yourself. There are, however, modules that are designed to diff two text bodies, for example: diff-match-patch. One simple example is: diff_main("Good dog", "Bad dog") =&gt; [(-1, "Goo"), (1, "Ba"), (0, "d dog")] And a direct link to Google Code's wiki on the topic: https://code.google.com/archive/p/google-diff-match-patch/wikis/API.wiki There a more extensive explanation of this library on this SO itself: https://stackoverflow.com/a/16086633/3084820
answers question: http://stackoverflow.com/q/47522299

http://stackoverflow.com/comment/82034564
score: 0
type: QuestionComment
has text: It works for interactive prompt, thanks again!
type: Comment
comment on: http://stackoverflow.com/q/47536463

http://stackoverflow.com/comment/81988116
type: AnswerComment
comment on: http://stackoverflow.com/a/47516002
type: Comment
has text: @RobiNoob Eddited my answer. I just had to do this myself.
score: 0

http://stackoverflow.com/q/47523824
has body: I just forayed into tkinter for the first time and am running into some issues. I want to display several lists to users, and store their selections for each list in a dictionary (used to filter several columns of a dataframe later). Suppose, for instance, there are two lists: 1) One labeled "Brand", containing 'Brand X' and 'Brand Y' as options, 2) another "Customer Type", containing "New," "Existing," "All." In sum, when all is said and done, if a user picks "Brand X", "New", and "All", then I'd get a dictionary back of {'Brand':['Brand X'],'Customer Type':['New','All']}. Getting one list is easy... but looping through the lists is presenting problems. I have the below code so far: from tkinter import * from tkinter import ttk class checkList(Frame): def __init__(self, options, parent=None): Frame.__init__(self, parent) self.makeHeader() self.options = options self.pack(expand=YES, fill=BOTH, side=LEFT) self.makeWidgets(self.options) self.selections = [] def makeHeader(self): header = ttk.Label(self,text='Please select options to limit on.') header.pack(side=TOP) self.header = header def makeWidgets(self, options): for key in self.options.keys(): lbl = ttk.Label(self, text=key) lbl.pack(after=self.header) listbox = Listbox(self, selectmode=MULTIPLE, exportselection=0) listbox.pack(side=LEFT) for item in self.options[key]: listbox.insert(END, item) listbox.bind('&lt;&lt;ListboxSelect&gt;&gt;', self.onselect) self.listbox = listbox def onselect(self, event): selections = self.listbox.curselection() selections = [int(x) for x in selections] self.selections = [self.options[x] for x in selections] if __name__ == '__main__': options = {'Brand':['Brand','Brand Y'], 'Customer Type': ['All Buyers','New Buyers','Existing Buyers']} checkList(options).mainloop() Needless to say, the [self.options[x] for x in selections] works great with just one list, but since I have a dictionary, I really need [self.options[key][x] for x in selections]. However, I can't figure out how to pa…
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47524255
tagged with: tkinter
has title: How can I pass another argument when binding with tkinter?
has answer: http://stackoverflow.com/a/47524255
has answer: http://stackoverflow.com/a/47524284
type: Question
accepted answer: http://stackoverflow.com/a/47524284
tagged with: python

http://stackoverflow.com/q/47403756
tagged with: dataframe
tagged with: python
upvote count: 2
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47403804
score: 1
has answer: http://stackoverflow.com/a/47403804
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: How to extract value from a dataframe
has body: How can I extract the last value, 102.584855? I have tried df[-1:].iloc[0] but it will return the 20 as well. Howe to get only 102.58485? Thanks!

http://stackoverflow.com/comment/81951285
comment on: http://stackoverflow.com/a/47497900
score: 0
type: Comment
type: AnswerComment
has text: In python 3.x input works like raw_input(), which always returns a string. But in python 2.7 input() returns the type of the type of whatever expression the user types in. It's better to use raw_input() instead of input() in Python 2.7. There was nothing mentioned about the version of python being used, so I think it's better to have the str() if it's Python2.7. If it's Python 3.0, str() is not required.

http://stackoverflow.com/a/47457060
has comment: http://stackoverflow.com/comment/81871330
type: Answer
has body: I would go like this ... d = re.compile(delim) # np.nonzero in this case returns a 1-uple of arrays, we have to unwrap ixs = np.nonzero([d.search(item) for item in ar])[0] splitted = np.split(ar, ixs if ixs[0] else ixs[1:]) ... The ixs if ixs[0] else ixs[1:] expression takes care of the possibility of a valid "delimiter" in the first record, to achieve the type of result (i.e., no void record of records) that you have shown in the original question.
score: 0
answers question: http://stackoverflow.com/q/47452222

http://stackoverflow.com/q/47411156
favorite count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: selenium
has title: Why do I get 'easyprocess' output when using 'pyvirtualdisplay' in selenium tests?
upvote count: 1
has body: I am trying to use pyvirtualdisplay in selenium tests in order to create screenshots. Here is how I do it in the tests within a TestSuite python class: self.display = Display(visible=0, size=(1366, 768)) self.display.start() before creating the driver, and to take the screenshot I use self.driver.save_screenshot('example.png') However, when running the test with nosetests I get some strange output like follows: easyprocess: DEBUG: version=0.2.3 pyvirtualdisplay: DEBUG: version=0.2.1 easyprocess: DEBUG: param: "['Xvfb', '-help']" easyprocess: DEBUG: command: ['Xvfb', '-help'] easyprocess: DEBUG: joined command: Xvfb -help easyprocess: DEBUG: process was started (pid=21) easyprocess: DEBUG: process has ended easyprocess: DEBUG: return code=0 easyprocess: DEBUG: stdout= easyprocess: DEBUG: stderr=use: X [:&lt;display&gt;] [option] -a # default pointer acceleration (factor) -ac disable access control restrictions -audit int set audit trail level -auth file select authorization file -br create root window with black background +bs enable any backing store support -bs disable any backing store support -c turns off key-click c # key-click volume (0-100) -cc int default color visual class -nocursor disable the cursor -core generate core dump on fatal error -displayfd fd file descriptor to write display number to when ready to connect -dpi int screen resolution in dots per inch -dpms disables VESA DPMS monitor control -deferglyphs [none|all|16] defer loading of [no|all|16-bit] glyphs -f # bell base (0-100) -fc string cursor font -fn string default font name ... What is this output? Why do I get it and how to 'avoid' it?
has answer: http://stackoverflow.com/a/52442223
type: Question
tagged with: debugging
score: 1
tagged with: pyvirtualdisplay
tagged with: python

http://stackoverflow.com/comment/81800232
comment on: http://stackoverflow.com/q/47422837
type: QuestionComment
score: 0
has text: Matplotlib needs numpy. Also pandas is based on numpy.
type: Comment

http://stackoverflow.com/q/47517606
favorite count: 0
has comment: http://stackoverflow.com/comment/81991306
accepted answer: http://stackoverflow.com/a/47517643
type: Question
has answer: http://stackoverflow.com/a/47517643
has title: Whether each word in a sentence is 'valid' - python
tagged with: python
has comment: http://stackoverflow.com/comment/81991365
possible better answer: http://stackoverflow.com/a/47517657
has answer: http://stackoverflow.com/a/47517658
has answer: http://stackoverflow.com/a/47517657
type: AnsweredQuestion
score: 0
has body: I am trying to create a code where the user enters a sentence and the computer tells them if each word in the sentence is 'valid' (so in terms of python, if each of the words in their sentence is in the 'validwords' list.) sentence = input("Please enter a sentence: ") validwords = ["hello","i","like","python"] word = sentence.split(" ") for word in sentence: if word in validwords: print ("I found a valid word: "+str(word)) else: print ("I found an invalid word: "+str(word)) however, the final five lines do not seem to work as they split up each letter in the sentence instead of each word.
answer count: 3
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/47444916
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47444841
has body: Here is an example that uses a set: lolwat = [] for line in open('scores.txt'): numbers = set(line.split(',')) if '5' in numbers and '7' in numbers: print('okay 5,7') elif '9' in numbers: print('okay 9') lolwat.append(numbers) do_stuff_with(lolwat) Set de-duplicates the numbers ensuring each is unique like 5,7,9 only occur once.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81845624
has comment: http://stackoverflow.com/comment/81845311
answers question: http://stackoverflow.com/q/47444841
has comment: http://stackoverflow.com/comment/81845169

http://stackoverflow.com/comment/81965166
score: 0
has text: Hi Amit, many thanks for your quick reply. I have already read several of howto‘s specially those from the official documentation. Bur for me it‘s still unclear where to include the configuration. I think I got the point which is about inherit from parent logger instances with the `__name__` as instance-name. The other question I have is: Am I structuring the project right or is there something like a best practise in how to structure a project with logging inside ?
comment on: http://stackoverflow.com/q/47499205
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81980037
type: Comment
type: QuestionComment
has text: In any event, having the `input()` functions directly inside of `radians()` is poor design -- even if you fix the immediate problem by using `float()`. The basic computation should be its own function which expects floats and returns the floats. The code which *uses* this function should handle the user input and output.
comment on: http://stackoverflow.com/q/47512072
score: 0

http://stackoverflow.com/comment/81919820
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47482473
has text: Exactly what I needed. Thank you

http://stackoverflow.com/q/47525521
score: 1
upvote count: 1
has title: Pandas Column values between range like 1-250, 251-500, so on
answer count: 1
downvote count: 0
has body: Dataset: id MarketPlaceValuation 0 100 1 250 2 200 3 100 4 325 5 175 6 150 7 125 8 225 9 325 10 625 11 100 12 75 13 100 14 200 15 225 .. .. 40 425 41 100 42 275 43 200 44 250 45 500 46 225 47 400 48 75 49 200 and so on. Where MarketPlaceValuation Values are between 1-100000. Sample Output Should be: Valuation Segment 1-250 251-500 501-1000 1001-1500 1501-2000 2001-3000 3001-4000 4001-5000 5001-100000 I tried following: df.groupby(pd.cut(df['MarketPlaceValuation'], np.arange(0,501,250))).count() But not getting proper output. Next, I want to get an average of other columns as per this column range.
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47525601
tagged with: python
accepted answer: http://stackoverflow.com/a/47525601
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/81834175
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47439322
type: Comment
has text: @Bharath, Sorry! I missed that topic.

http://stackoverflow.com/comment/81765718
comment on: http://stackoverflow.com/q/47406095
type: Comment
type: QuestionComment
has text: ok, this has nothing to do with python. It's a bash/shell question.
score: 0

http://stackoverflow.com/comment/81868977
type: Comment
has text: You can [set the x ticks](http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xticks.html#matplotlib.axes.Axes.set_xticks) and [labels](http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xticklabels.html#matplotlib-axes-axes-set-xticklabels) and [scale the x axis](http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xscale.html#matplotlib-axes-axes-set-xscale) at will.
type: QuestionComment
comment on: http://stackoverflow.com/q/47455969
score: 1

http://stackoverflow.com/comment/81811489
has text: first question which version of oracle are you using 11 , 12 ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47391331
type: AnswerComment

http://stackoverflow.com/comment/81847959
comment on: http://stackoverflow.com/q/47425595
type: Comment
score: 0
has text: Have you looked at the source data for your email? You might want to add that to the question.
type: QuestionComment

http://stackoverflow.com/a/77209232
answers question: http://stackoverflow.com/q/47430544
score: 0
type: Answer
has body: Most Easiest Way I Found Mount your google drive first import pandas as pd from google.colab import drive drive.mount('/content/gdrive') Get the file path and use pd.read_excel() df = pd.read_excel('/content/gdrive/MyDrive/data.xlsx') df.head()

constraints
type: Tag
tags question: http://stackoverflow.com/q/47425235
tags question: http://stackoverflow.com/q/47441934
tag name: constraints

http://stackoverflow.com/comment/81818576
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47431288
has text: Find out the full path to python 3.5.2, e.g. using `which python3`, then use the *full path* with `nohup`, e.g. `nohup /usr/local/bin/python3.5` or similar.

http://stackoverflow.com/q/47473629
has comment: http://stackoverflow.com/comment/81903211
has comment: http://stackoverflow.com/comment/81901768
tagged with: python
score: -1
has body: I'm trying to check for the quantity of a string in a list, by making a for loop with another list. I'm searching for the index of doubles in list1, but my problem is as soon as the first string is found in the list the index does not go up when the second instance is found. I expect in this case 0,1,2,3 but in reality it's 0,1,1,3. list1 = ['ABBA', 'CBBA', 'CBBA','DBBA'] list2 = ['ABBA','CBBA','DBBA'] for line in list1: for marker in list2: if marker in line: print("Marker found", list1.index(line))
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81917370
upvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47473870
downvote count: 1
favorite count: 0
type: Question
has title: Comparing content and quantity between lists

http://stackoverflow.com/comment/81998586
has text: Thank you - have posted the code above. I'm not sure if I am using the correct method. Should I be using df or an iloc type of code?
type: QuestionComment
comment on: http://stackoverflow.com/q/47520367
type: Comment
score: 0

http://stackoverflow.com/comment/82035256
comment on: http://stackoverflow.com/a/47531946
type: Comment
has text: it gives the error :UnpicklingError: the STRING opcode argument must be quoted
type: AnswerComment
score: 0

http://stackoverflow.com/a/47511103
has comment: http://stackoverflow.com/comment/81978092
accepted answer of: http://stackoverflow.com/q/47511055
type: Answer
has comment: http://stackoverflow.com/comment/81978276
answers question: http://stackoverflow.com/q/47511055
has comment: http://stackoverflow.com/comment/81986149
score: 2
has comment: http://stackoverflow.com/comment/81978137
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81978187
has body: It looks like NaN is a string here. Try doing this: df['Name'].replace('NaN', np.nan).str.count(',') + 1 You should get something along these lines: 0 1.0 1 NaN 2 2.0 Name: Name, dtype: float64 You can then call .fillna('') to fill in the blanks.
has comment: http://stackoverflow.com/comment/82015448
has comment: http://stackoverflow.com/comment/81993379
has comment: http://stackoverflow.com/comment/81978259
has comment: http://stackoverflow.com/comment/81978162
has comment: http://stackoverflow.com/comment/81978072

http://stackoverflow.com/q/47534476
has comment: http://stackoverflow.com/comment/82025687
has answer: http://stackoverflow.com/a/47534625
answer count: 1
downvote count: 1
favorite count: 0
has title: IndexError: list index out of range - python for loop
type: Question
has body: I am trying to fix this error, I dont really understand it as I'm a poorly skilled network engineer. I am reading lines of show commands on a router in to a list - this is all working fine. From that list I want to parse out certain values, which I am doing that with a for loop. I'm getting the result I need at the end of it, but also an error. I only want certain values from the list, which is the "3rd" IP address only, no port number etc (i.e '2.122.62.193', '31.49.158.183') out1 = ['tcp 217.33.162.162:443 172.16.0.1:443 2.122.62.193:49971 2.122.62.193:49971', 'tcp 217.33.162.162:443 172.16.0.1:443 31.49.158.183:49266 31.49.158.183:49266', ''] gnat = [] for x in out1: y = x z = y.split(':')[3] w = z.split()[1] gnat.append(w) &gt;&gt;&gt; for x in out1: ... y = x ... z = y.split(':')[3] ... w = z.split()[1] ... gnat.append(w) ... Traceback (most recent call last): File "&lt;console&gt;", line 3, in &lt;module&gt; IndexError: list index out of range &gt;&gt;&gt; print gnat ['2.122.62.193', '31.49.158.183' It may not be the most efficient code, but this is the correct result. Only that I don't understand the error?
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: python-2.7

http://stackoverflow.com/q/47400396
tagged with: python
has title: How to convert string containing list of dictionaries to python (object) LIST of DICT
type: AnsweredQuestion
score: 0
has body: Using python socket I am receiving value as a string and want to store the value in SQLite DB as dictionary key to column and values as a row. So for that purpose, I am not able to convert the string to dictionary - ReceivedValue = [{'Value1': 'OutPut00', 'Value2': 'OutPut01', 'Value3': '2253.23'},{'Value1': 'NA', 'Value3': 'NA'}] ReceivedValue always returns str type instead list and stopping me to process further to add in SQLite DB. How can I convert this received value to a Dictionary or list of dictionaries? Json Approach EDIT:1 - Attached the required screenshot for Json Error eval Approach EDIT:2 - def process(ReceivedValue): print ReceivedValue finVal = ast.literal_eval(ReceivedValue) print finVal print type(finVal) OutPut - "[{'APACHE_MODJK': '1.2.41', 'PROCESSOR_MODEL': ' Intel(R) Xeon(R) CPU E5-2680 0 @ 2.70GHz', 'APACHE_HOME': '/opt/www/apache/2.4.17', 'OS_KERNEL': '2.6.32-573.26.1.el6.x86_64', 'APACHE_SSO': 'YES', 'TOMCAT_VER': 'NA', 'ENV': 'PROD', 'APACHE': 'RUNNING', 'JBOSS_HOME': '/opt/www/jboss/4.3/jboss-as', 'APACHE_VIP': 'NA', 'CPU': 2, 'OS_VER': 'Red Hat Enterprise Linux Server release 6.7 (Santiago)', 'TOMCAT_DB': 'NA', 'SAN': 'NA', 'JBOSS_DB': 'p377', 'MEMORY': 4, 'JBOSS_VER': '4.3.0.GA_CP02', 'JDK_VER': '1.6.0_18', 'APACHE_VER': '2.4.17', 'MACHINE_TYPE': 'VMware Virtual Platform'}]" [{'APACHE_MODJK': '1.2.41', 'PROCESSOR_MODEL': ' Intel(R) Xeon(R) CPU E5-2680 0 @ 2.70GHz', 'APACHE_HOME': '/opt/www/apache/2.4.17', 'OS_KERNEL': '2.6.32-573.26.1.el6.x86_64', 'APACHE_SSO': 'YES', 'TOMCAT_VER': 'NA', 'ENV': 'PROD', 'APACHE': 'RUNNING', 'JBOSS_HOME': '/opt/www/jboss/4.3/jboss-as', 'APACHE_VIP': 'NA', 'CPU': 2, 'OS_VER': 'Red Hat Enterprise Linux Server release 6.7 (Santiago)', 'TOMCAT_DB': 'NA', 'SAN': 'NA', 'MEMORY': 4, 'JBOSS_VER': '4.3.0.GA_CP02', 'JDK_VER': '1.6.0_18', 'APACHE_VER': '2.4.17', 'MACHINE_TYPE': 'VMware Virtual Platform'}] &lt;type 'str'&gt; WORKING SOLUTION: Just Removed the double quotes from the RecievedValue to evaluate it acros…
has comment: http://stackoverflow.com/comment/81754436
accepted answer: http://stackoverflow.com/a/47415043
answer count: 3
has answer: http://stackoverflow.com/a/47415043
possible better answer: http://stackoverflow.com/a/47406138
has answer: http://stackoverflow.com/a/47400465
has answer: http://stackoverflow.com/a/47406138
type: Question
has comment: http://stackoverflow.com/comment/81754782

http://stackoverflow.com/a/47384337
answers question: http://stackoverflow.com/q/47383772
score: 1
downvote count: 0
upvote count: 1
has body: You don't have to escape characters unless they are part of code you are writing or from an input from a user. If the backslash character or a quote character is generated by a Python program, then it is already stored as that character in memory. There is no need do any additional escaping. Why? Because Python is not interpreting a string literal, it is simply generating characters, which are stored as numbers in memory. When you ask Python to display a string containing one of the characters such as a single quote or a backslash, it will automatically escape them. Here is an example. A double quote is 34, single quote is character 39, and backslash is 92. 'a'+chr(34)+'b'+chr(39)+'c'+chr(92)+'d' # returns: 'a"b\'c\\d' Because I included a double quote and a single quote Python will use a single quote to surround the string, an unescaped double quote within the string, an escaped single quote, and and escaped backslash. So there is no need to escape characters that are generated within a Python program, it does it for you.
type: Answer

http://stackoverflow.com/q/47509168
tagged with: alarm
has body: I want to make a function that executes at specified time interval, lets say at every 30 seconds, when the time is something like this: 12:37:00.000000, 12:37:30.000000, 12:38:00.000000 Now the easy approach would be to create a thread running a function that has a while loop that has a sleep(30) at the end, thus waiting 30 seconds at the end. My application will be running 24/7, and in time, lets say maybe 2-3 hours from the start, the real time at which it will be executing that function would be X:X:00.5 or X:X:33.5(because there is a lot of code above that sleep(30)), thus delaying my work by a small margin every 30 seconds, and in few hours, by a pretty big margin. What I'm searching for is a elegant method to set like an alarm that triggers at every 30 seconds, but always exactly 30 seconds, no more, no less, since precision is a must.
has answer: http://stackoverflow.com/a/47510198
upvote count: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47510118
tagged with: signals
answer count: 2
accepted answer: http://stackoverflow.com/a/47510198
tagged with: multithreading
score: 1
has answer: http://stackoverflow.com/a/47510118
downvote count: 1
has title: Python thread executing at precise time interval
favorite count: 0
type: Question
tagged with: datetime
has comment: http://stackoverflow.com/comment/81974285
tagged with: python
has comment: http://stackoverflow.com/comment/81974095

http://stackoverflow.com/q/47459216
has comment: http://stackoverflow.com/comment/81873558
favorite count: 0
has comment: http://stackoverflow.com/comment/81874754
has comment: http://stackoverflow.com/comment/81878662
has comment: http://stackoverflow.com/comment/81875376
has comment: http://stackoverflow.com/comment/81873441
has title: Page not found error in Django REST framework tutorial
has body: I am doing the Django REST Framework Tutorial, and I got to the part when they add the view for an individual snippet (view snippet_detail, tutorial 2). When I start the server and point the browser to url http://127.0.0.1:8000/snippets, it returns the 3 snippets I have created before (ids:1,2,3), fine. At url http://127.0.0.1:8000/snippets/2, it returns only the snippet 2, perfect. But when I try http://127.0.0.1:8000/snippets/1, it raises a Page not found error: Request URL: http://127.0.0.1:8000/snippets/1/ Using the URLconf defined in tutorial.urls, Django tried these URL patterns, in this order: ^ ^snippets/$ ^ ^snippets/(?P&lt;pk&gt;[0-9]+)$ ^admin/ The current path, snippets/1/, didn't match any of these. I don't understand why snippets/1 doesn't match the second url pattern. Can someone please clarify this error and help me overcome this.
has comment: http://stackoverflow.com/comment/81873047
has comment: http://stackoverflow.com/comment/81873413
tagged with: python
has comment: http://stackoverflow.com/comment/81874954
type: Question
has comment: http://stackoverflow.com/comment/81873036
answer count: 0
has comment: http://stackoverflow.com/comment/81873164
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django
score: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/81873427

http://stackoverflow.com/comment/81918797
type: Comment
type: QuestionComment
has text: perfect! makes sense now. Thank you!
comment on: http://stackoverflow.com/q/47481819
score: 0

http://stackoverflow.com/q/47529266
has title: Is set a param for CharField like upload_to param for FileField possible?
type: AnsweredQuestion
score: 0
has body: I have a WorkOrderUploadFile model like bellow: class WorkOrderUploadFile(models.Model): wo_num = models.CharField(max_length="16") filepath = models.CharField(max_length=128, default="images/qiyun_admin_servicemanage_workorder/") file = models.FileField(upload_to=generate_files_directory) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) You see, for the FileField there is a upload_to param, so I can use the generate_files_directory method to generate the file field value. Is is possible to set a method for CharField param? (because the wo_num CharField is need use a method to generate the number.)
has answer: http://stackoverflow.com/a/47529867
type: Question
accepted answer: http://stackoverflow.com/a/47529867
answer count: 1
tagged with: django
tagged with: python

http://stackoverflow.com/comment/81938329
type: QuestionComment
has text: I updated with another block of code that shows the cpp struct explicitly
comment on: http://stackoverflow.com/q/47491371
score: 0
type: Comment

http://stackoverflow.com/comment/81842523
type: QuestionComment
has text: Is there a particular reason why you use `all()` and then `annotate() `?
score: 0
comment on: http://stackoverflow.com/q/47442937
type: Comment

http://stackoverflow.com/a/47433043
accepted answer of: http://stackoverflow.com/q/47431547
score: 1
has comment: http://stackoverflow.com/comment/81970545
has comment: http://stackoverflow.com/comment/81971876
type: AcceptedAnswer
downvote count: 0
has body: Assuming 'd' is the dataframe you show as your starting point then: d.date = pd.to_datetime(d.date).values.astype('&lt;M8[m]') d = d.set_index('date') d.resample('1Min').ffill().fillna(method='ffill') You have to 'chop off' the seconds and fractions of seconds by calling .values.astype('&lt;M8[m]') because ffill rounds up even for a few seconds. Also the two ffill calls seem weird but if you try with just one you will see that things are filled in only partially until another non-NaN value shows up in any column. And also make sure 'date' is set as the index.
upvote count: 1
answers question: http://stackoverflow.com/q/47431547
type: Answer

http://stackoverflow.com/comment/81917204
comment on: http://stackoverflow.com/q/47481191
score: 1
type: Comment
has text: Why is it ugly? If double underscore names are not your thing, Python might not be the language for you.
type: QuestionComment

http://stackoverflow.com/q/47518835
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has title: Is it okay to create a net.Socket() 'data' event handler once for each Node.js http request/response?
tagged with: node.js
score: 0
has body: I've got a Node.js web server communicating with a locally running Python TCP socket server (communicating via their respective socket modules net.Socket, socket). Clients make HTTP post requests from the browser which get handled by a Node http.createServer function, with some of them sent to the Python server for heavy computations, the results of which are then sent back to Node and back to the browser for rendering. The Python server is necessary instead of a Node child process as there are some large (immutable) objects required for the Python computations that take a while to initialise and are then shared across threads. It would be infeasible to create and destroy these objects for every browser request. So my question is, using the Node callback paradigm, how do I capture the response object for each POST request in the net.Socket data event handler/s? Note 0: Each request has a unique id that is sent to the Python server and returned. This currently works* inside my http.createServer callback: http.createServer((request, response) =&gt; { // route and parse incoming requests etc. // send POST data to Python python_socket.write(parsed_request_post_data); // Python works away diligently then emits a data event handled below python_socket.once('data', (data_from_python) =&gt; { // error and exception handling response.setHeader('Content-Type', 'application/json'); response.end(data_from_python); }); }).listen(HTTPport); *However if I bomb the server with multiple requests, sometimes I get the same data returned in each response (even though Python handles each data separately). I worry that I am trying to assign multiple once('data' callbacks in the same Node event loop and only one of them is persisting, and that is the one repeatedly sending the Python data back to the browser? Though if this were the case the response object would also be getting repeated and I would get an error for trying to end an already closed response right? But each response seems t…
answer count: 0
tagged with: javascript
has comment: http://stackoverflow.com/comment/81995396
has comment: http://stackoverflow.com/comment/81995039
has comment: http://stackoverflow.com/comment/81994524
type: Question
has comment: http://stackoverflow.com/comment/81993950

http://stackoverflow.com/comment/82000035
type: QuestionComment
comment on: http://stackoverflow.com/q/47521630
score: 0
type: Comment
has text: Or: [Convert a column of datetimes to epoch in Python](https://stackoverflow.com/questions/35630098/convert-a-column-of-datetimes-to-epoch-in-python)

http://stackoverflow.com/a/47534625
has body: Look at the list values, you might see your error is at ''.split(':')[3]. What are you splitting there? Try this logic If it's an empty String, do nothing Split the spaces Grab the IP:Port Split off the port Something like this for x in out1: if x.strip() == '': continue ip_port = x.split()[3] ip = ip_port.split(':')[0] gnat.append(ip)
score: 0
answers question: http://stackoverflow.com/q/47534476
type: Answer
has comment: http://stackoverflow.com/comment/82037626

http://stackoverflow.com/q/47458833
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47458902
tagged with: windows-10
has body: I trying to run a program in python 2.7 that uses numpy but it gives me the error ImportError: No module named numpy. I am using Windows 10. I tried running pip install numpy and it says it was installed but I still can't run the program.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81872150
upvote count: 0
has comment: http://stackoverflow.com/comment/81872240
has title: Python 2.7 ImportError: No module named numpy
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81872319
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81872167

http://stackoverflow.com/comment/81956195
score: 1
type: QuestionComment
has text: Welcome at [so]. It is expected that questions meet certain criteria. These are described in the [ask] page that I strongly suggest you read. In addition we expect a certain level of effort to already have been spent on your part. This is typically done by showing us the code that you're working on and providing us with descriptions of the things you've tried and the results you've observed. In case of larger blocks of code, simplifying it to a [mcve] helps to understand the issue much quicker on our part.
type: Comment
comment on: http://stackoverflow.com/q/47500214

http://stackoverflow.com/q/47397800
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has body: I'm getting this error: "ValueError at /5 invalid literal for int() with base 10: '' " I think that I'm passing a string and trying to use it as an int. How do I pass the int I want correctly? This is the code I have, in the html template: {% csrf_token %} Register In urls.py: url(r'^(?P<pk>)', authentication_views.registerAttende, name='register'), In views.py: def registerAttende(request,pk): act = Activity.objects.get(pk=pk) //This is the line that is causing the error act.save() attend = act.attendee.create(student=request.user.id) return render(request, 'dashboard.html') I'm getting that the value of of the variable pk is: u'' https://i.sstatic.net/uSw24.png How do I fix this? What am I doing wrong?
has comment: http://stackoverflow.com/comment/81748841
type: Question
has comment: http://stackoverflow.com/comment/81748859
has answer: http://stackoverflow.com/a/47397907
accepted answer: http://stackoverflow.com/a/47397907
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81748723
has comment: http://stackoverflow.com/comment/81748753
has title: How to pass a pk from template in url to use in view "Django"?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47512508
linked to: http://stackoverflow.com/q/15829782
has body: These are the 2 questions(both can be solved by InputMask?) I want to restrict the user input to 16 characters only In a field like 'Age/ID', I would like the user's input to be integer only, if the user enters a string it must not be accepted or the user must not be able to type in a string in the first place. I'm not sure how I can implement the first part in real-time,i.e., the user types a max of 16, nothing beyond 16 appears. This is my code(not working) for the 2nd part of the question: self.onlyInt = QIntValidator() self.lineEdit_15.setValidator(self.onlyInt) det15=str(self.lineEdit_15.text()) list_val.append(det15)
upvote count: 2
tagged with: pyqt
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/129270686
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: pyqt4
has answer: http://stackoverflow.com/a/47513327
has comment: http://stackoverflow.com/comment/81981855
tagged with: python
has title: PyQt: QLineEdit input mask for only Integer or only String and length restriction
has comment: http://stackoverflow.com/comment/81981904
score: 2
tagged with: python-2.7

http://stackoverflow.com/comment/81945495
has text: Why are you manually doing what `orm.relatuonship` is for?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47494094
type: QuestionComment

http://stackoverflow.com/comment/81958198
has text: No error but **white pixel and total pixel are same **
comment on: http://stackoverflow.com/a/47500956
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47495326
linked to: http://stackoverflow.com/q/5387208
type: Question
score: 0
has answer: http://stackoverflow.com/a/47495642
has body: I have a hex string a = 54776f204f6e65204e696e652054776f And I want it in the form of a matrix like this: s = [[54, 4f, 4e, 20], [77, 6e, 69, 54], [6f, 65, 6e, 77], [20, 20, 65, 6f]] How do I do it? For more clarification: I am writing a program for AES encryption and decryption. And this is the 1st part where the plaintext is converted to hexadecimal and then to a state (4x4 matrix).
tagged with: cryptography
has comment: http://stackoverflow.com/comment/81945918
tagged with: aes
has answer: http://stackoverflow.com/a/47495538
has title: Converting Hex string to matrix form in Python
answer count: 2
has comment: http://stackoverflow.com/comment/81958232
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81946124
has comment: http://stackoverflow.com/comment/81946053

http://stackoverflow.com/q/47492406
tagged with: anaconda
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/56506216
downvote count: 0
has title: Anaconda python pyinstaller Can not find path ./libtbb.dylib
favorite count: 0
type: Question
has body: Mac OS X 10.13 Anaconda python 2.7.12 pyintaller error When compiling a script that includes: from __future__ import division from __future__ import print_function import sys import os import math import matplotlib.pyplot as plt I get the following errors and wwarnings: NameError: name 'FigureManagerWebAgg' is not defined 101543 ERROR: Can not find path ./libtbb.dylib (needed by /Users/barr /anaconda2/lib/libmkl_tbb_thread.dylib) 97784 WARNING: library user32 required via ctypes not found 103993 WARNING: library user32 required via ctypes not found looking in anaconda2/lib the file libtbb.dylib is certainly absent. Where can I find it to put in anaconda1/lib? When the executable is run I get the error output below: Traceback (most recent call last): File "site-packages/PyInstaller/loader/rthooks/pyi_rth_pkgres.py", line 11, in &lt;module&gt; File "lib/python2.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 396, in load_module File "site-packages/pkg_resources/__init__.py", line 1040, in &lt;module&gt; File "site-packages/pkg_resources/__init__.py", line 1043, in Environment File "site-packages/pkg_resources/__init__.py", line 272, in get_supported_platform File "site-packages/pkg_resources/__init__.py", line 478, in get_build_platform File "sysconfig.py", line 617, in get_platform File "sysconfig.py", line 481, in get_config_vars File "sysconfig.py", line 364, in _init_posix ImportError: No module named _sysconfigdata The same script is compiled and executed without errors using Anaconda Python on Windows 10 and Ubuntu Linux 16.04 (the same version of Anaconda in all cases). Suggestions?
upvote count: 2
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: python-2.7

http://stackoverflow.com/a/47500849
has comment: http://stackoverflow.com/comment/81957339
upvote count: 1
type: AcceptedAnswer
downvote count: 1
type: Answer
has body: You appear to be adding instead of multiplying. for i in range(b): x *= a You don't need special cases for 0 and 1; b == 0 is sufficient. def mypow(a, b): answer = 1 # a ** 0 == 1 # The loop is only entered if b &gt; 0 for _ in range(b): answer *= a return answer
accepted answer of: http://stackoverflow.com/q/47500825
score: 0
answers question: http://stackoverflow.com/q/47500825

http://stackoverflow.com/comment/81823789
type: QuestionComment
comment on: http://stackoverflow.com/q/47434658
score: 0
has text: Share the sizes/shapes of xvoxels, yvoxels, zvoxels, striatal_mask_np, values of img_dim? Or better add a sample case?
type: Comment

http://stackoverflow.com/comment/81995213
has text: when on windows I would not even try wasting time on building well-known libraries, why not search internet for "python windows binaries", download a suitable one, pip install that pre-built wheel and be done with it.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47517351
score: 0

http://stackoverflow.com/comment/81854846
type: QuestionComment
score: 0
has text: Where do you get the error? What is the callstack? Show us a [log file](https://docs.python.org/3/library/ftplib.html#ftplib.FTP.set_debuglevel). Can you upload the file using a standalone FTP client running on the same machine as your Python code? Show us its log file.
type: Comment
comment on: http://stackoverflow.com/q/47445814

http://stackoverflow.com/q/47434283
answer count: 0
has comment: http://stackoverflow.com/comment/81824437
tagged with: unicode
favorite count: 0
has body: I am trying to do a redis dump using the python package redis-dump-load. It is in UTF-8, except for apparently one key, which I'm being told is in ascii. No idea why, but I thought, ok, if there is a UnicodeDecodeError for this one key (I am receiving lots of data from the dump stream up to this point), what I will do is get the encoding of the bytes string I have, and decode with that instead. However, I am still getting a UnicodeDecodeError for ASCII as well! It is bytes, it is ascii, I think it might just be corrupt and I plan to just skip it, but curious if anyone had any other ideas. This is my code snippet: value = {} for k in response: try: value[k.decode(encoding)] = response[k].decode(encoding) except UnicodeDecodeError: print("Error for", k) print(type(k)) orig_encoding = chardet.detect(k)['encoding'] print(orig_encoding) value[k.decode(orig_encoding)] = response[k].decode(orig_encoding) return value And here is the ouput I see: Error for b'meta' &lt;class 'bytes'&gt; ascii Traceback (most recent call last): File "redisdl.py", line 243, in handle_response value[k.decode(encoding)] = response[k].decode(encoding) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "redisdl.py", line 635, in &lt;module&gt; main() File "redisdl.py", line 626, in main do_dump(options) File "redisdl.py", line 547, in do_dump dump(output, **kwargs) File "redisdl.py", line 174, in dump for key, type, ttl, value in _reader(r, pretty, encoding, keys): File "redisdl.py", line 293, in _reader type, ttl, value = _read_key(encoded_key, r, pretty, encoding) File "redisdl.py", line 284, in _read_key value = reader.handle_response(results[2], pretty, encoding) File "redisdl.py", line 250, in handle_response response[k].decode(orig_encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128) Am I mis…
has comment: http://stackoverflow.com/comment/81824944
tagged with: encoding
type: Question
has title: A strange python unicode decode error trying to do redis dump (prefer python3, but seeing in both 2 & 3))
tagged with: python
type: UnansweredQuestion
tagged with: utf-8
has comment: http://stackoverflow.com/comment/81824820
tagged with: ascii
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47514605
tagged with: python
has title: Python - Initialzing tkinter inside class,and what happens when need another gui in another class?
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47517003
answer count: 1
favorite count: 0
type: Question
has body: I'm trying to create a 'read from csv file' class. This class should read a csv file and return result as a list.So far- quite simple even for a newbie as me. BUT- I need something a bit more complexed: 1) If filename is not given ( as an argument to class) - a file selection dialog box pops up to select one. 2) Optional: show file's content in a GUI, using a CSVGui class (using method self.out_in_gui). Since ReadCSV is not GUI based class, GUI is initialized only in need to launch a askopenfilename. A use of widtdraw() is made in order not to show additinal blank GUI. The probelm is: When I try to read a file, without spcifing one, a file selection dialog pops up, PLUS calling method self.out_in_gui to execute CSVGui class - file contents does not show in GUI (Entries left empty). TRIES:when I specify as a parameter, the file to be loaded, everything runs OK. My guess- it has something to do with using the GUI in ReadFile to load file selection GUI. Thanks J import csv import tkinter as tk from tkinter import ttk from tkinter.filedialog import askopenfilename class ReadFile: """This class reads CSV w/out header line, and returen it as a list""" def __init__(self, fname='', path='', **kwargs): if fname == '' and path == '': tk.Tk().withdraw() self.filename = askopenfilename(title='Select CSV file', filetypes=[('CommaSeperatedFile', '*.csv')]) else: if path != '': self.filename = path + '/' + fname else: self.filename = fname self.file_content = [] self.read_file(kwargs) self.out_in_gui() def read_file(self, kwargs): with open(self.filename, newline='', **kwargs) as csvfile: file_obj = csv.reader(csvfile) for i in file_obj: self.file_content.append(i) print("file %s was read successfully, containing %d lines" % (self.filename, len(self.file_content))) def out_in_gui(self): print("send data to CSVGui") CSVGui(self, data=self.file_content) def file_contents(self): return self.file_content class CSVGui(ttk.Frame): def __init__(self, master=None, data=[]): ttk.Frame.__in…
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/47517003

http://stackoverflow.com/q/47524054
tagged with: python
linked to: http://stackoverflow.com/q/24863576
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/55464923
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/82004336
has comment: http://stackoverflow.com/comment/82004503
has answer: http://stackoverflow.com/a/55464923
accepted answer: http://stackoverflow.com/a/47525557
has comment: http://stackoverflow.com/comment/82004524
downvote count: 2
has comment: http://stackoverflow.com/comment/82007126
has answer: http://stackoverflow.com/a/47525557
has comment: http://stackoverflow.com/comment/82004305
upvote count: 7
has comment: http://stackoverflow.com/comment/82004423
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/127167951
has body: I have a file named client_simulator.py and it contains a Class named Client_simulator which simulates clients behavior. I have another file named pool_manager.py and it has no class, it has one __main__ and lot of functions and basically, I want to call a method named generator of Client_simulator class from one of the methods of pool_manager.py. the basic structure of client_simulator.py is as follows class Client_simulator(object): def generator(self): if __name__ == '__main__': Client_simulator().generator() the basic structure of file pool manager.py is as follows def start_client_simulator(): client_simulator.Client_simulator().generator() if __name__ == "__main__": start_client_simulator() I am getting the following error 'module' object is not callable P.S: I want to call __main __ instead of `generator()', how to do that? I am recently moving from java to python that's why having these basic doubts. Thanks in advance
score: 5
has title: Calling __main__ from another file in python
has comment: http://stackoverflow.com/comment/82004407

http://stackoverflow.com/a/47536882
answers question: http://stackoverflow.com/q/47536733
upvote count: 1
downvote count: 0
score: 1
type: Answer
has body: When you import a module in Python you are not executing the content of it. if __name__ == "__main__": is there so that your Python files can act as either reusable modules, or as standalone programs. If you want to execute the main() function you'll need to explicitly call it.: from functest import main, get_info main() # calling the main function in your functest file print(get_info()) # calling the get_info function this will return the value you are looking for. Now, main will be called if you execute the functest.py file: $ python functest.py #=&gt; 9

http://stackoverflow.com/q/47444841
has body: I have a file containing a 5 x 7 table: enter image description here I want a validation check that there is either a 5,7, or 9; but none of them is repeated, i.e there must be only one occurrence of these numbers. 5 and 7 are required, 9 is optional, the remaining three columns can be 0. I have written this code but it doesn't work. I also want to store the valid rows in a separate list. My attempt of the program in python is as follows def validation (): numlist = open("scores.txt","r") invalidnum=0 for line in numlist: x = line.count("0") inv1 = line.count("1") inv2 = line.count("2") inv3 = line.count("3") if x &gt; 2 or inv1 &gt; 1 or inv2 &gt; 1 or inv3 &gt; 1 or line not in ("0","5","7","9"): invalidnum=invalidnum+1 print(invalidnum,"Invalid numbers found" else: print("All numbers are valid in the list") I will appreciate if someone can help me on this.
accepted answer: http://stackoverflow.com/a/47444916
has comment: http://stackoverflow.com/comment/81845066
score: -3
has answer: http://stackoverflow.com/a/47445001
tagged with: python
has title: Data check routine isn't working
has comment: http://stackoverflow.com/comment/81845016
type: AnsweredQuestion
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/47444916
downvote count: 3
possible better answer: http://stackoverflow.com/a/47445001
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81845667
has comment: http://stackoverflow.com/comment/81845472
has comment: http://stackoverflow.com/comment/81845723

http://stackoverflow.com/q/47490341
has comment: http://stackoverflow.com/comment/81935992
has answer: http://stackoverflow.com/a/47490988
accepted answer: http://stackoverflow.com/a/47490988
answer count: 1
has title: How to iterate through this text file faster?
has comment: http://stackoverflow.com/comment/81936433
has comment: http://stackoverflow.com/comment/81936162
tagged with: parsing
favorite count: 0
type: Question
has body: I have a file with lots of sections in this format: section_name_1 &lt;attribute_1:value&gt; &lt;attribute_2:value&gt; ... &lt;attribute_n:value&gt; { field_1 finish_num:start_num some_text ; field_2 finish_num:start_num some_text ; ... field_n finish_num:start_num some_text; }; section_name_2 ... ... and so on The file can be hundreds of thousands of lines long. The number of attributes and fields for each section can be different. I'd like to build a few dictionaries to hold some of these values. I have a separate dictionary already which holds all the possible 'attribute' values. import os, re from collections import defaultdict def mapFile(myFile, attributeMap_d): valueMap_d = {} fieldMap_d = defaultdict(dict) for attributeName in attributeMap_d: valueMap_d[attributeName] = {} count = 0 with open(myFile, "rb") as fh: for line in fh: # only look for lines with &lt; if '&lt;' in line: # match all attribute:value pairs inside &lt;&gt; brackets attributeAllMatch = re.findall(r'&lt;(\S+):(\S+)&gt;', line) attributeAllMatchLen = len(attributeAllMatch) count = 0 sectionNameMatch = re.match(r'(\S+)\s+&lt;', line) # store each section name and its associated attribute and value into dict for attributeName in attributeMap_d: for element in attributeAllMatch: if element[0] == attributeName: valueMap_d[attributeName][sectionNameMatch.group(1).rstrip()] = element[1].rstrip() count += 1 # stop searching if all attributes in section already matched if count == attributeAllMatchLen: break nextLine = next(fh) #in between each squiggly bracket, store all the field names and start/stop_nums into dict #this while loop is very slow... while not "};" in nextLine: fieldMatch = re.search(r'(\S+)\s+(\d+):(\d+)', nextLine) if fieldMatch: fieldMap_d[sectionNameMatch.group(1)][fieldMatch.group(1)] = [fieldMatch.group(2), fieldMatch.group(3)] nextLine = next(fh) return valueMap_d My problem is that the while loop that matches all the field values is noticeably slower than the rest of the co…
has comment: http://stackoverflow.com/comment/81936417
upvote count: 6
score: 6
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81936408
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/47506743
type: Answer
answers question: http://stackoverflow.com/q/47505747
score: 2
upvote count: 2
has body: your question is not much clear , but here are few things which is needed while trying to call any APK Appium Appium is needed in order to communicate with apps in phone from your preferred language . You will find many links on net about setting up the appium on your environment Appium Python client This will allow to use appium library in python https://pypi.org/project/Appium-Python-Client/ Desired Capability Desired capability tells the program about the target application and devices details . so if you want to test your application, you need to provide your details here desired_caps[‘platformName’] = ‘Android’ desired_caps[‘platformVersion’] = ‘4.4’ desired_caps[‘deviceName’] = ‘A102’ desired_caps[‘app’] = ‘C:PyEditorAppium_ScrollTestsrcWitStatus.apk’ desired_caps[‘appPackage’] = ‘com.witmergers.getstatus’ desired_caps[‘appActivity’] = ‘.MainActivity’ for further details, you can refer https://github.com/appium/python-client The scope of your question is quite big, but at least this will give u a head start to move ahead
downvote count: 0

routes
type: Tag
tags question: http://stackoverflow.com/q/47459950
tag name: routes

http://stackoverflow.com/q/47509504
has comment: http://stackoverflow.com/comment/83633164
downvote count: 0
has title: How to find a permutation in a tensor ? (Tensorflow)
tagged with: python
tagged with: sorting
linked to: http://stackoverflow.com/q/41985060
has comment: http://stackoverflow.com/comment/81977994
answer count: 0
score: 1
upvote count: 1
tagged with: permutation
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81974695
has comment: http://stackoverflow.com/comment/81974975
type: UnansweredQuestion
has body: I would like to find a permutation s for a 1D tensor x with this property : x[s[i x[s[i-1]] (the permutation is the sort of x) thank you !

http://stackoverflow.com/q/47471658
has comment: http://stackoverflow.com/comment/81898647
has comment: http://stackoverflow.com/comment/81899102
type: Question
has body: I get a problem in Django Rest Framework. class FeedDetailSerializer(ModelSerializer): user = UserFeedSerializer(read_only=True) comment_count = SerializerMethodField(default=0) comment_list = CommentFeedSerializer(many=True, read_only=True) class Meta: model = Feed fields = [ 'id', 'comment_count', 'comment_list', ] def get_comment_count(self, obj): comment_count = Comment.objects.filter(feed=obj.id, parent__isnull=True).count() return comment_count This is the CommentFeedSerializer I've created: class CommentFeedSerializer(ModelSerializer): url = comment_detail_url class Meta: model = Comment fields = [ 'url', 'id', 'comment', 'posted_on', ] With this Serializer I've done, API will render like this: "comment_count": 2, "comment_list": [ { "url": "http://localhost:8000/api/v1/comments/2/", "id": 2, "comment": "haha", "reply_count": 0, "posted_on": "2017-11-24T10:23:28.353000Z" }, { "url": "http://localhost:8000/api/v1/comments/1/", "id": 1, "comment": "Good", "reply_count": 1, "posted_on": "2017-11-24T09:54:48.680000Z" } ] But this is very hard to manage. So I want to put comment_count into comment_list: commentlist like below How can I do that? "comment_list": [ "comment_count": 2, { "url": "http://localhost:8000/api/v1/comments/2/", "id": 2, "comment": "haha", "reply_count": 0, "posted_on": "2017-11-24T10:23:28.353000Z" }, { "url": "http://localhost:8000/api/v1/comments/1/", "id": 1, "comment": "Good", "reply_count": 1, "posted_on": "2017-11-24T09:54:48.680000Z" } ]
type: UnansweredQuestion
has title: Insert count objects fields in Array Django Rest Framework
tagged with: django
tagged with: python
tagged with: django-rest-framework
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81898720

http://stackoverflow.com/a/47407910
score: 1
type: Answer
has body: You don't need to check health constantly. Anytime you call a function reducing health (e.g. attack(character, damage)), you could simply check if health &gt; 0. If not, you should call game_over(). Here's some code from a related question: class Character: def __init__(self, name, hp_max): self.name = name self.xp = 0 self.hp_max = hp_max self.hp = hp_max # TODO: define hp_bar here def is_dead(self): return self.hp &lt;= 0 def attack(self, opponent, damage): opponent.hp -= damage self.xp += damage def __str__(self): return '%s (%d/%d)' % (self.name, self.hp, self.hp_max) hero = Character('Mario', 1000) enemy = Character('Goomba', 100) print(enemy) # Goomba (100/100) hero.attack(enemy, 50) print(enemy) # Goomba (50/100) hero.attack(enemy, 50) print(enemy) # Goomba (0/100) print(enemy.is_dead()) # True print(hero.xp) # 100
answers question: http://stackoverflow.com/q/47407869
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47401432
has comment: http://stackoverflow.com/comment/81756889
upvote count: 0
type: AcceptedAnswer
type: Answer
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/81781597
has comment: http://stackoverflow.com/comment/81811538
answers question: http://stackoverflow.com/q/47400968
has comment: http://stackoverflow.com/comment/81781115
has comment: http://stackoverflow.com/comment/81779644
accepted answer of: http://stackoverflow.com/q/47400968
has body: I don't know what you are exactly aiming, but here is what I made for you: https://gist.github.com/dgsbicak/96517f33e516ca4438c6e252149b8cbc def verifyPassword(password, password2): count = 0 # Rule 1 pas = [password, password2] for p in pas: if len(p)&lt;3: print("Password length is shorter than 3") break elif len(p)&gt;19: print("Password length is longer than 19") break else: pass if password==password2: return "Password is correct" else: return "Password is not correct" print(verifyPassword("le3ather", "leather2")) print(verifyPassword("leather", "leather2")) print(verifyPassword("leather", "leather")) print(verifyPassword("le", "Le")) print(verifyPassword("leatherLeatherleather", "leatherLeatherleather"))

http://stackoverflow.com/q/47413142
has body: We have an application developed in python with spark streaming (version 1.6) that executes a kafka process reading, clears the information and inserts this new information into the elastic Search and HDFS. The process works well for 1 hour, but after this we are experiencing the following exception: self._jwrite.save(path) File "/tmp/hadoop/yarn/local/usercache/u028952/appcache/application_1510909047380_0215/container_e02_1510909047380_0215_01_000002/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__ answer, self.gateway_client, self.target_id, self.name) File "/tmp/hadoop/yarn/local/usercache/u028952/appcache/application_1510909047380_0215/container_e02_1510909047380_0215_01_000002/pyspark.zip/pyspark/sql/utils.py", line 45, in deco return f(*a, **kw) File "/tmp/hadoop/yarn/local/usercache/u028952/appcache/application_1510909047380_0215/container_e02_1510909047380_0215_01_000002/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value format(target_id, ".", name), value) py4j.protocol.Py4JJavaError: An error occurred while calling o25359.save. : java.io.IOException: com.google.protobuf.ServiceException: java.lang.RuntimeException: unexpected checked exception at org.apache.hadoop.ipc.ProtobufHelper.getRemoteException(ProtobufHelper.java:47) at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.delete(ClientNamenodeProtocolTranslatorPB.java:542) at sun.reflect.GeneratedMethodAccessor77.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:252) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:104) at com.sun.proxy.$Proxy10.delete(Unknown Source) at org.apache.hadoop.hdfs.DFSClient.delete(DFSClient.java:2052) at org.apache.hadoop.hdfs.DistributedFileSystem$14.doCall(DistributedFileSystem.jav…
tagged with: hdfs
upvote count: 1
favorite count: 0
has title: outmemoryerror saving hdfs streaming proccess spark python
type: Question
tagged with: out-of-memory
tagged with: spark-streaming
score: 1
tagged with: python
tagged with: hadoop
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47460835
tagged with: numpy
has body: I have a 4 Dimensional array, where the first 3 dimensions are x,y,z locations and the 4th one is Time. I have to make a filter for (each voxel in) this array then substract each filter from each voxel and then fill in the new filtered values in a new array called data_4d_filt! I'm having trouble with figuring out the right indexing inside my nested Forloop, because it's 4D, I've lost track of where I am and what I'm doing! I don't really know if I should index my Filter or the to be filled data_4d_filt array? So in the code below should I do this: Filter[i, ii, iii] = gaussian_filter(data_4d[i, ii, iii], 25) data_4d_filt = data_4d - Filter or this: Filter[i] = gaussian_filter(data_4d[i], 25) data_4d_filt = data_4d - Filter or this: Filter = gaussian_filter(data_4d, 25) data_4d_filt[i, ii, iii] = data_4d[i, ii, iii] - Filter Can anyone help me with this plz??? data_4d = nib.load('unfiltered_data_ds.nii.gz').get_data() print("Shape of the original 4D fMRI scan: %s" % (data_4d.shape,)) # Here, we pre-allocate a matrix of the same shape as data_4d, in which # you need to store the filtered timeseries data_4d_filt = np.zeros(data_4d.shape) # Start loop across X-dimension for i in range(data_4d.shape[0]): # Start loop across Y-dimension for ii in range(data_4d.shape[1]): # Start loop across Z-dimension for iii in range(data_4d.shape[2]): # Filter the timeseries for voxel at location X=i, Y=ii, Z=iii and store it # using an appropriate index in the pre-allocated variable data_4d_filt! # My CODE HERE Filter[i, ii, iii] = gaussian_filter(data_4d[i, ii, iii], 25) data_4d_filt = data_4d - Filter
answer count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: nested
tagged with: python
tagged with: loops
has title: How to fill in a Numpy 4D array using nested For loops in Python?
type: Question

http://stackoverflow.com/q/47522167
has comment: http://stackoverflow.com/comment/82000859
type: Question
tagged with: numpy
tagged with: python-3.x
has title: Python Matrix Output to Excel
has comment: http://stackoverflow.com/comment/82000735
has comment: http://stackoverflow.com/comment/82000750
tagged with: python
has comment: http://stackoverflow.com/comment/82000817
accepted answer: http://stackoverflow.com/a/47522310
has comment: http://stackoverflow.com/comment/82000861
tagged with: excel
has answer: http://stackoverflow.com/a/47522310
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82000796
tagged with: http://stackoverflow.com/tag/csv
score: 0
has body: I'm trying to output a matrix with 4 rows (1st row is header) and over 6000 columns. Each column header is a word from different text documents (rows 1-3). I want to export it to excel so I can easily filter the top 10 words with highest frequency. I get no error, but nothing shows up in the excel file. Where am I going wrong? np.savetxt('file.csv', matrix_TF, delimiter = ',', newline = '\n', encoding='utf8')
answer count: 1

http://stackoverflow.com/comment/81886890
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47466078
has text: Interestingly enough you'd get the same results, but for a different reason, if you used parentheses to force the first comparison to be evaluated. e.g. `(1 == 1) in [1]` is `True` because `1 == 1` is `True` and `True` is in `[1]` (that is, `True == 1`).
score: 1

http://stackoverflow.com/q/47453216
answer count: 2
has title: numpy different data type of multidimensional array
tagged with: pandas
downvote count: 0
has body: I want to insert 2d data into numpy and project as data frame in pandas . Basically it has 10 rows and 5 column . Data type of all 5 columns are order ( int , string , int , string, string) . _MaxRows = 10 _MaxColumns = 5 person = np.zeros([_MaxRows,5]) person def personGen(): for i in range(0,_MaxRows): # add person dynamically # person[i][0] = i # person[i][1] = names[i] # person[i][2] = random.randint(10,50) # person[i][3] = random.choice(['M','F']) # person[i][4] = 'Desc' personGen() OUTPUT REQUIRED AS DATA FRAME Id Name Age Gender Desc 1 Sumeet 12 'M' 'HELLO' 2 Sumeet2 13 'M' 'HELLO2'
possible better answer: http://stackoverflow.com/a/65131909
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
accepted answer: http://stackoverflow.com/a/47453531
tagged with: python
has answer: http://stackoverflow.com/a/47453531
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65131909
score: 2

http://stackoverflow.com/comment/82011384
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47526001
type: Comment
has text: So that was the issue! I was under the impression that the steps_per_epoch was to indicate the number of rows that should be parsed for training

http://stackoverflow.com/comment/82018781
has text: You can use the nested-relationships
type: QuestionComment
comment on: http://stackoverflow.com/q/47531258
score: 0
type: Comment

http://stackoverflow.com/a/64593546
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47533875
downvote count: 0
has body: If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with import camelot tables = camelot.read_pdf('foo.pdf') You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive. tables.export('foo.csv', f='csv', compress=False) Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead. import camelot import cProfile import pstats import tabula cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)" prof_tabula = cProfile.Profile().run(cmd_tabula) time_tabula = pstats.Stats(prof_tabula).total_tt cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')" prof_camelot = cProfile.Profile().run(cmd_camelot) time_camelot = pstats.Stats(prof_camelot).total_tt print(time_tabula, time_camelot, time_camelot/time_tabula) gave 1.8495559890000015 11.057014036000016 5.978199147125147

http://stackoverflow.com/comment/100177051
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47404232
score: 0
has text: What value did you specify for from and to time

http://stackoverflow.com/a/47453061
score: 0
has comment: http://stackoverflow.com/comment/81862030
has comment: http://stackoverflow.com/comment/81871097
has body: I found a solution, but first let me explain the problem The problem is that I have 2 Python installations. - The one I Installed - One that came with anaconda Following other tutorials I was able to confirm that the file cv2.so was in fact in the directory usr/local/lib/python2.7/site-packages (my python installation) file that is used to link python and opnecv But then executing the command which python I realize that the default python being executed was the anaconda one, that one din't have the opencv-python configuration file i.e., cv2.so . Solution: I just copied the cv2.so python-opencv configuration file form the python I installed .i.e., /usr/local/lib/python2.7/site-packages directory to the python installation directory of python-anaconda .i.e., /home/anaconda2/lib/python2.7/site-packages this last directory may variate based in your installation.
type: Answer
answers question: http://stackoverflow.com/q/47451166

http://stackoverflow.com/q/47533291
has comment: http://stackoverflow.com/comment/82039033
duplicate of: http://stackoverflow.com/q/47112642
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82330308
has comment: http://stackoverflow.com/comment/82038775
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82034644
has comment: http://stackoverflow.com/comment/82056826
tagged with: opencv
score: 2
type: AnsweredQuestion
tagged with: webcam
tagged with: opencv3.0
has body: The integrated webcam in OpenCV on Ubuntu 16.04 is throwing back the below error. I checked cheese with a different program and it shows still images and video, therefore it seems not the camera itself to be the problem here. The code I used to test this out : import cv2 import numpy as np import time cam = cv2.VideoCapture(2) if not cam.isOpened(): print('Cannot open camera') while True: ret,frame = cam.read() cv2.imshow('webcam', frame) if cv2.waitKey(1)&amp;0xFF == ord('q'): break cam.release() cv2.destroyAllWindows() The error : Cannot open camera (feedback from script at if not cam.isOpened():). OpenCV Error: Assertion failed (size.width>0 &amp;&amp; size.height>0) in imshow, file /io/opencv/modules/highgui/src/window.cpp, line 325 Traceback (most recent call last): File "Video_test.py", line 13, in cv2.imshow('webcam', frame) cv2.error: /io/opencv/modules/highgui/src/window.cpp:325: error: (-215) size.width>0 &amp;&amp; size.height>0 in function imshow Any help would be appreciated. Thanks!
accepted answer: http://stackoverflow.com/a/47538876
has title: Unable to use integrated webcam in OpenCV on Ubuntu 16.04(host)
has comment: http://stackoverflow.com/comment/82039445
has answer: http://stackoverflow.com/a/47538876
downvote count: 0
linked to: http://stackoverflow.com/q/47112642
answer count: 1

http://stackoverflow.com/comment/81890637
comment on: http://stackoverflow.com/a/47467985
has text: I have update the reason why you need add perms manual,have a look
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/47444586
type: Answer
has comment: http://stackoverflow.com/comment/81844455
score: 0
has body: In python you don't need to loop over strings like for x in range(len(s)). Instead python can be more succinct with for char in message. Furthermore the if clause looks like it should be followed by an elif and an else (for non alphabetical characters). The code below works well for short messages since += recopies the string each time due to it being an immutable type. If this impacts the speed of your program consider using str.join() instead. def swap_case(message): swapped_message = '' for char in message: if char.isupper(): swapped_message += char.lower() elif char.islower(): swapped_message += char.upper() else: swapped_message += char return swapped_message
answers question: http://stackoverflow.com/q/47444473

http://stackoverflow.com/comment/81807383
type: Comment
type: QuestionComment
score: 0
has text: @FrankAK I still got same error after creating blank `__init__.py` in the same directory.
comment on: http://stackoverflow.com/q/47426234

http://stackoverflow.com/a/47430614
type: Answer
has comment: http://stackoverflow.com/comment/81827063
has comment: http://stackoverflow.com/comment/96474390
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81827370
has body: poly_grid = GridSearchCV... will only declare and instantiate the grid search object. You need to supply some data with fit() method to do any training or hyper-parameter search. Something like this: poly_grid.fit(X, y) Where X and y are your training data and labels. Please see the documentation: fit(X, y=None, groups=None, **fit_params)[source] Run fit with all sets of parameters. And then use the cv_results_ and/or best_params_ to analyse the results. Please take a look at the examples given below: http://scikit-learn.org/stable/auto_examples/exercises/plot_cv_diabetes.html http://scikit-learn.org/stable/auto_examples/model_selection/plot_randomized_search.html http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html Responding to comment: @BillyChow Do you call poly_grid.fit() or not? If no, then obviously it wont produce any result. If yes, then depending on your data, it will take a lot of time because you have specified degree from 1 to 10 in params with 10-fold cv. So as the degree increases, the time to fit and cross-validate increases pretty quickly. Still if you want to see the working, you can add verbose param to the gridSearchCV, like this: poly_grid = GridSearchCV(PolynomialRegression(), param_grid, cv=10, scoring='neg_mean_squared_error', verbose=3) And then call poly_grid.fit(X, y)
accepted answer of: http://stackoverflow.com/q/47414819
answers question: http://stackoverflow.com/q/47414819
has comment: http://stackoverflow.com/comment/81830376
upvote count: 2
downvote count: 2

http://stackoverflow.com/a/47529374
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47528793
type: Answer
answers question: http://stackoverflow.com/q/47528793
downvote count: 0
has body: I tracked down my problem to an extraneous argument to the setup() command. Judging by the documentation at https://docs.python.org/2/distutils/setupscript.html, I do not need the packages=['Foo'] argument, and in fact that's what's causing it to create the inner Foo package that's messing everything up.
score: 1

http://stackoverflow.com/a/47487015
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47487014
has body: I've been trying out HJSON (human-readable JSON), but bundling a text file like HJSON into the React build doesn't work AFAIK without ejecting create-react-app and modifying the webpack config to use raw-loader, or using react-app-rewired to do something similar. I wound up using react-app-rewired - First add these libraries to the React project - yarn add react-app-rewired yarn add hjson yarn add hjson-loader Then add a config-overrides.js file to the top level of the React project - this will modify the webpack config on the fly - const { getLoader } = require('react-app-rewired'); function rewireAddHjson(config, env, options = {}) { const hjsonExtension = /\.hjson$/; const excludeRule = getLoader(config.module.rules, rule =&gt; rule.exclude); excludeRule.exclude.push(hjsonExtension); const hjsonRule = { test: hjsonExtension, loader: 'hjson-loader', }; config.module.rules.push(hjsonRule); return config; } module.exports = function override(config, env) { config = rewireAddHjson(config, env); return config; }; and in package.json replace "react-scripts" with "react-app-rewired": "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", + "start": "react-app-rewired start", + "build": "react-app-rewired build", + "test": "react-app-rewired test --env=jsdom" } Then in Python you can say import hjson with open('app/client/src/assets/options.hjson') as f: options = hjson.load(f) and in React can say import options from '../assets/options.hjson'; // a json object
accepted answer of: http://stackoverflow.com/q/47487014
type: Answer

http://stackoverflow.com/a/47493037
has body: It seems like url is not correct. It happens here: tracking_url = json_obj["message"]["body"]["lyrics"]["html_tracking_url"] If you have ability to run that API locally and see what is returned into tracking_url, you can find out what is still wrong with it. UPDATE: I reproduced it, so the urllib.request cannot process empty string URL: "", that is why you need to check if the tracking_url != "" and only if its not empty string or None you need to request for the song.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81948287
accepted answer of: http://stackoverflow.com/q/47492487
score: 2
answers question: http://stackoverflow.com/q/47492487
has comment: http://stackoverflow.com/comment/81948299
type: Answer

http://stackoverflow.com/comment/82007562
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47498553
has text: Thank you. I have fixed the grammar now.

http://stackoverflow.com/comment/81781244
comment on: http://stackoverflow.com/q/47413871
has text: This seems to be a repost of your [last question](https://stackoverflow.com/questions/47410854/mock-datetime-datetime-now) which was already marked as a duplicate, any reason not to edit your previous question and try to get that reopened rather than repost?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81962006
comment on: http://stackoverflow.com/a/47497916
type: Comment
score: 1
type: AnswerComment
has text: @Blckknght. Equivalent or better ? Actually I do so because [Most Python developers do not nest classes, so when you do so you break convention and increase maintenance cost.](https://stackoverflow.com/a/30376236/4194079). That being said I am neither 100% sure to understand what the OP wants :).

http://stackoverflow.com/comment/81992413
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47516234
has text: Please post at least one line of your csv. I can't suggest any parsing otherwise
score: 0

http://stackoverflow.com/comment/81733574
score: 0
has text: But I did manage to setup apache2.2 + mod_wsgi + python2.7 + mod_ssl. I upgraded python and apache, and installed the new mod_wsgi (using pip). So it seems that python2.7 ssl libs and the OS libs were fine. I don't see why it should be a problem with python3.6. And anyway, how is this error (in PIL code, which I actually did not install) relates to the issue?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47387266

http://stackoverflow.com/a/47444089
score: 2
has comment: http://stackoverflow.com/comment/81843684
accepted answer of: http://stackoverflow.com/q/47444039
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47444039
has body: Yes, you could do it that way. Another is to use the stride parameter to specify the stride in each dimension. You can set the other dimension's stride to 0. stride=(1, 0) is the proper syntax, I think.
type: Answer
has comment: http://stackoverflow.com/comment/81843600

http://stackoverflow.com/comment/81993566
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47518679
has text: Perfect, thanks! I was just wondering if there was already something built-in rather than making something for myself.

http://stackoverflow.com/comment/81820554
comment on: http://stackoverflow.com/q/47432965
has text: i think you left self in function as a arguement
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81929213
type: QuestionComment
has text: Technically, there is no distinct object called a decorator; it's really just a function that takes a function as an argument and returns (or is expected to return) another function. What *is* special is decorator *syntax*, which provides a concise way to apply the decorator function. `@foo def bar(): ...` is shorter than `def bar(): ...; bar = foo(bar)`.
score: 1
comment on: http://stackoverflow.com/q/47486953
type: Comment

http://stackoverflow.com/comment/82024319
type: AnswerComment
has text: Thank you for your suggestion. I get the Error: `UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 68: invalid start byte`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47533709

http://stackoverflow.com/q/47487329
answer count: 1
tagged with: mysql
has body: I'm getting a very strange error while using MySQLdb in Bottle on PythonAnywhere.com Whenever the execute contains columns of type int, decimal or datetime, the execute throws a 500 error. For example, from a table Tools, manufacturer and sub_type are both varchars, so this block of code works perfectly: reservation_id = request.forms.get("reservation_id") db = MySQLdb.connect("...") c = db.cursor() c.execute("""SELECT manufacturer, sub_type FROM Tool""") row = c.fetchone() return row But ask for the tool_id from that same table, which is of int type, or any other column of int, decimal or datetime type from that table: reservation_id = request.forms.get("reservation_id") db = MySQLdb.connect("...") c = db.cursor() c.execute("""SELECT tool_id FROM Tool""") row = c.fetchone() return row And Bottle throws a critical error: Error running WSGI application SystemError: returned a result with an error set In MySQL bash, every query works perfectly. Put that same query (only int, decimal or datetime) in execute(), and it fails. Has anyone had any similar experience?
favorite count: 0
has answer: http://stackoverflow.com/a/47493258
type: AnsweredQuestion
tagged with: python
tagged with: bottle
has title: Execution of Int, Decimal or Datetime Types in Bottle and MySQLdb Not Working
tagged with: pythonanywhere
type: Question
upvote count: 2
score: 2
accepted answer: http://stackoverflow.com/a/47493258
downvote count: 0
has comment: http://stackoverflow.com/comment/81941627

http://stackoverflow.com/a/47443343
type: Answer
has comment: http://stackoverflow.com/comment/81843319
has comment: http://stackoverflow.com/comment/81847705
has comment: http://stackoverflow.com/comment/81844284
has comment: http://stackoverflow.com/comment/81845657
has comment: http://stackoverflow.com/comment/81846143
downvote count: 0
answers question: http://stackoverflow.com/q/47443122
has comment: http://stackoverflow.com/comment/81844194
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81847911
has body: Instead of minimizing np.sum(e ** 2), minimize sqrt(np.sum(e ** 2)), or better (in terms of calculation): np.linalg.norm(e)! This modification: does not change your solution in regards to x will need post-processing if the original objective is needed (probably not) is much more robust With this change, all cases work, even using numerical-differentiation (i was too lazy to modify the gradient, which needs to reflect this!). Example output (number of func-evals gives away num-diff): Optimization terminated successfully. (Exit mode 0) Current function value: 3.815547437029837e-06 Iterations: 16 Function evaluations: 88 Gradient evaluations: 16 fun: 3.815547437029837e-06 jac: array([-6.09663382, -2.48862544]) message: 'Optimization terminated successfully.' nfev: 88 nit: 16 njev: 16 status: 0 success: True x: array([ 2.00000037, 0.10000018]) Optimization terminated successfully. (Exit mode 0) Current function value: 0.0002354577991007501 Iterations: 23 Function evaluations: 114 Gradient evaluations: 23 fun: 0.0002354577991007501 jac: array([ 435.97259208, 288.7483819 ]) message: 'Optimization terminated successfully.' nfev: 114 nit: 23 njev: 23 status: 0 success: True x: array([ 1.99999977, 0.10000014]) Optimization terminated successfully. (Exit mode 0) Current function value: 0.0003392807206384532 Iterations: 21 Function evaluations: 112 Gradient evaluations: 21 fun: 0.0003392807206384532 jac: array([ 996.57340243, 51.19298764]) message: 'Optimization terminated successfully.' nfev: 112 nit: 21 njev: 21 status: 0 success: True x: array([ 2.00000008, 0.10000104]) While there are probably some problems with SLSQP, it's still one of the most tested and robust codes given that broad application-spectrum! I would also expect SLSQP to be much better here compared to COBYLA, as the latter is based heavily on linearizations. (but just take it as a guess; it's easy to try given the minimize-interface!) Alternative In general, an Interior-point based solver for Convex Quadrat…
has comment: http://stackoverflow.com/comment/81843255

http://stackoverflow.com/a/47425930
downvote count: 0
answers question: http://stackoverflow.com/q/47425797
score: 2
accepted answer of: http://stackoverflow.com/q/47425797
type: Answer
upvote count: 2
has body: You want Child(self, **kwargs), not just Child(self, kwargs). It is trying to send it as an argument, when you want a keyword.
type: AcceptedAnswer

http://stackoverflow.com/a/47430983
downvote count: 0
type: AcceptedAnswer
has body: Ok it takes some time but I figured it out. All it was about Sharing state between processes now all it works like charm. Code : from multiprocessing import Process, Value import time def child_process(number): number.value = 0 while True: number.value += 1 #print(number) def main(): num = Value('i') process = Process(target=child_process, args=(num,)) process.start() while True: print("should get same number:", num.value) time.sleep(1) if __name__ == "__main__": main()
answers question: http://stackoverflow.com/q/47428768
type: Answer
accepted answer of: http://stackoverflow.com/q/47428768
upvote count: 2
score: 2

http://stackoverflow.com/comment/82017510
score: 0
type: QuestionComment
has text: Yes, @EikePierstorff , it's added
type: Comment
comment on: http://stackoverflow.com/q/47530081

http://stackoverflow.com/comment/81826353
type: QuestionComment
comment on: http://stackoverflow.com/q/47434224
has text: this goes under the name of *System Identification* and as far as I know statsmodels and scikit doesn't deal with this and they are not related. There is an absence of a SysID package in Python and other languages not only because there are limited users but because these methods are not that successful and have very little demand. You can solve manually if you need to have to solve this particular instance.
score: 1
type: Comment

http://stackoverflow.com/comment/81835373
comment on: http://stackoverflow.com/q/47440077
score: 0
type: Comment
type: QuestionComment
has text: @MaxU, well, it answers a part of it. Actually after looking at that question I thouhgt `df.iloc[0,1] is pd.np.nan` would resolve to `True` but it's not. That question doesn't answer my second question. "Is it possible to check for NaN values using ix or iloc?"

http://stackoverflow.com/q/47539253
has answer: http://stackoverflow.com/a/47539335
has answer: http://stackoverflow.com/a/47539367
type: AnsweredQuestion
answer count: 2
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I want to perform the following: &gt;&gt;&gt; [0-2, 4] #case 1 [-2, 4] #I want the output to be [0, 1, 2, 4] I know I can perform the same in this way: &gt;&gt;&gt; list(range(3)) + [4] #case 2 [0, 1, 2, 4] But I am curious is there any way to achieve the same result using the case 1 method (or something similar)? Do I need to override the integer '-' operator or do I need to do anything with the list?
upvote count: 5
accepted answer: http://stackoverflow.com/a/47539335
tagged with: python
possible better answer: http://stackoverflow.com/a/47539367
score: 4
has title: Is there a way to set a list value in a range of integer in python

http://stackoverflow.com/q/47491371
tagged with: python
has comment: http://stackoverflow.com/comment/81938398
tagged with: c++
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81938241
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81938277
has answer: http://stackoverflow.com/a/47491622
tagged with: binaryfiles
has title: Reading a Binary File that was generated with C++ data types Using Numpy
has comment: http://stackoverflow.com/comment/81938329
has comment: http://stackoverflow.com/comment/81938149
has comment: http://stackoverflow.com/comment/81938642
has comment: http://stackoverflow.com/comment/81938358
has comment: http://stackoverflow.com/comment/81938303
type: Question
possible better answer: http://stackoverflow.com/a/47491622
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47491621
has body: I am attempting to read a binary file with a known data type that was generated in C++ with the following structure: uint64_t shot; uint32_t status; double easting, northing, altitude; uint32_t zoneNumber; char zoneLetter; float vNorth, vEast, vDown; float qw, qx, qy, qz; float acel_x, acel_y, acel_z, gyro_x, gyro_y, gyro_z; float rollStdDev, pitchStdDev, yawStdDev; float northingStdDev, eastingStdDev, altitudeStdDev; float vNorthStdDev, vEastStdDev, vDownStdDev; The only strangeness happening here is that the 'zoneletter' is a 1byte character with 3 bytes of padding following. So the character should start on byte 40 and then vNorth should start on byte 44. This is my attempting at reading this binary file with python using numpy. I am unsure about if I converted the c++ doubles correctly, and I am pretty sure my problems are coming from reading the character. The problem being that on the first iteration shot and status are reading correctly, but thereafter everything that is reading doesn't make any sense to what the actual data should look like. So I believe there is a problem with either the character or double reading from bytes 12-44. dt2 = np.dtype([('ShotNum', np.uint64), ('Status', np.uint32), ('easting', np.float_),\ ('northing', np.float_),('alt', np.float_), ('Znum', np.uint32),('letter', np.character),\ ('vnorth', np.float32),('veast', np.float32),('vdown', np.float32),\ ('qw', np.float32),('qx', np.float32),('qy', np.float32),('qz', np.float32),\ ('acX', np.float32),('acY',np.float32),('acZ', np.float32),('gyX', np.float32),\ ('gyY', np.float32),('gyZ', np.float32),('rollSTD', np.float32),('pitSTD', np.float32),\ ('yawSTD', np.float32),('northSTD', np.float32),('eastSTD', np.float32),('altSTD', np.float32),\ ('vnorthSTD', np.float32),('veastSTD', np.float32),('vDownSTD', np.float32)]) Here is the c++ explicit struct [thread: 892] mainwindow.cpp(65): Sizeof NavigationSolution: 136 bytes [thread: 892] mainwindow.cpp(66): shot [thread: 892] mainwindow.cp…
has answer: http://stackoverflow.com/a/47491621
has comment: http://stackoverflow.com/comment/81938327
has comment: http://stackoverflow.com/comment/81938197

frequency-distribution
tag name: frequency-distribution
tags question: http://stackoverflow.com/q/47439715
type: Tag

http://stackoverflow.com/a/47529947
answers question: http://stackoverflow.com/q/47529864
has body: I install it with the cmd (shell): pip install pyqt5 this works for my
has comment: http://stackoverflow.com/comment/82018593
has comment: http://stackoverflow.com/comment/82017285
has comment: http://stackoverflow.com/comment/82017711
score: 0
type: Answer

http://stackoverflow.com/a/58069946
type: Answer
has body: The simplest solution is to install chromedriver like this: conda install -c conda-forge python-chromedriver-binary Then at the top of your code, add the following import statement to update your PATH variable appropriately: import chromedriver_binary
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47405394
score: 1

http://stackoverflow.com/a/47504050
type: Answer
score: 0
has body: The key parts of the output are: Uninstalling pycrypto-2.6: c:\python27\lib\site-packages\pycrypto-2.6-py2.7-win32.egg Proceed (y/n)? y Usually, there's a long list of files here. In your case, it's only an .egg. Which means that you installed the package as a packed .egg (thus most probably, you installed it with easy_install rather than pip: pip always unpacks .eggs). Now, WindowsError: [Error 2] The system cannot find the file specified: 'c:\\python27\\lib\\site-packages\\pycrypto-2.6-py2.7-win32.egg' Means that the .egg was already deleted (probably you deleted it by hand, or a previous uninstallation process was interrupted), but installation metadata wasn't. IIRC it's kept in a file or directory named something like pycrypto-2.6-py2.7-win32.egg-info. So, locate it in site-packages and delete it.
answers question: http://stackoverflow.com/q/47503547

http://stackoverflow.com/comment/82039305
type: AnswerComment
has text: Note for later: for the x coordinate in the first instance, I used (len(ind)/2)-0.5 instead of 400 (and did not set the ylim values).
type: Comment
comment on: http://stackoverflow.com/a/47539690
score: 0

http://stackoverflow.com/q/47393181
answer count: 2
has answer: http://stackoverflow.com/a/47393402
has title: cURL command return the 400 Bad request error
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: flask
downvote count: 1
tagged with: postgresql
has comment: http://stackoverflow.com/comment/81742777
has body: I use the postgres to fetch data from postgres database. So create flask api but when I use curl command it retuns 400 bad request error. Here is my code - from flask import Flask, render_template, request, Response import psycopg2 import csv import json from psycopg2.extras import RealDictCursor import requests conn = psycopg2.connect("host='localhost' dbname='postgres' user='postgres'") app = Flask(__name__) @app.route('/', methods = ['GET','POST']) def index(): cur = conn.cursor(cursor_factory=RealDictCursor) query = request.form['query'] cur.execute(query) return Response(json.dumps(cur.fetchall(),indent=2),mimetype='application/json') if __name__ == "__main__": app.run(host='0.0.0.0') conn.close() I use this curl command - curl -H "Content-Type: application/json" -X GET http://127.0.0.1:5000/ -d '{"query":"SELECT COUNT(*) FROM usage"}' So how to use curl with flask api.
has answer: http://stackoverflow.com/a/77141361
tagged with: flask-sqlalchemy
tagged with: curl
favorite count: 0
type: Question

http://stackoverflow.com/q/47410137
favorite count: 0
tagged with: arcgis
type: Question
has body: When I use arcpy.ListRasters within an IDE (tested for Pyscripter and IDLE), my process stops. In IDLE, the Python Engine simply restarts, while in Pyscripter, an application error is thrown: EOFError: [Errno 10054] An existing connection was forcibly closed by the remote host Example code: import arcpy arcpy.env.workspace = r'C:\scratch' rasterList = arcpy.ListRasters() Notes: This code will work perfectly fine when executed from the command prompt or from the Python interpreter. the code will work when the workspace is set to a gdb. When executed from the Python Window in ArcMap, it also works. So the combination of working with an IDE and listing rasters from a normal folder seems to be the issue. I'm using ArcGIS 10.5.1 on Windows 7 64bit.
tagged with: arcpy
tagged with: pyscripter
type: UnansweredQuestion
tagged with: python
upvote count: 2
answer count: 0
score: 1
downvote count: 1
tagged with: ide
has title: Python IDE crashes with EOFError 10054 when calling arcpy ListRasters()

http://stackoverflow.com/q/47493392
accepted answer: http://stackoverflow.com/a/47493967
has comment: http://stackoverflow.com/comment/81942127
has comment: http://stackoverflow.com/comment/81948138
has title: output label Y train shape keras tensorflow 1.4
tagged with: python
has comment: http://stackoverflow.com/comment/81948542
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81948699
has comment: http://stackoverflow.com/comment/81942043
has comment: http://stackoverflow.com/comment/81948428
has answer: http://stackoverflow.com/a/47493967
answer count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
has body: I am running VGG16 network for image classification on svhn database. I am saving images into shape (None,64,64,3) and labels of shape (None,10).Labels are 1d array of size 10. Below is the part of my code. import pandas as pd import numpy as np import cv2 import tensorflow as tf import os import scipy from skimage import data, io, filters import scipy.io as sio from utils import * import h5py vgg = tf.keras.applications.vgg16.VGG16 (include_top=False, weights='imagenet', input_tensor=None, input_shape=(64,64,3), pooling='avg', classes=10) vgg.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) vgg.fit(train_data, labels_data, epochs=5, batch_size=32) and so I get error: ValueError: Error when checking target: expected block5_pool to have shape (None, 512) but got array with shape (None, 10) What changes should I do?
type: Question
has comment: http://stackoverflow.com/comment/81948199

regression
tags question: http://stackoverflow.com/q/47521872
tags question: http://stackoverflow.com/q/47509303
tag name: regression
type: Tag
tags question: http://stackoverflow.com/q/47413054
tags question: http://stackoverflow.com/q/47467196

http://stackoverflow.com/comment/81882335
score: 1
type: Comment
type: QuestionComment
has text: I am assuming you have some kind of Linux distro running on your Pi. Does your Python file include a shebang line (https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script/2429517)? I think that was a problem that I had some time ago, when a Python file wouldn't run from PHP on some kind of Linux server.
comment on: http://stackoverflow.com/q/47463593

http://stackoverflow.com/a/47528360
answers question: http://stackoverflow.com/q/47512347
score: 0
type: Answer
has body: This should work as well. from collections import defaultdict d = defaultdict(int) b = map(lambda x: (x[0], int(x[1])), [x.split(':') for x in li]) for k, v in b: d[k] += v &gt;&gt;&gt;d defaultdict(&lt;type 'int'&gt;, {'coffee': 23, 'salt': 26, 'sugar': 57})

http://stackoverflow.com/q/47460353
type: Question
accepted answer: http://stackoverflow.com/a/47462730
score: 3
has body: I have my products with extra fields that come from a custom module. I'm trying to rewrite the copy function because otherwise when I try to duplicate the product some values don't duplicate. So, in this copy function I manage to add those fields but if I try to just add the ids from the original product field, that one loses the values after the product is duplicated. I guess that makes sense. Code: class ProductTemplate(models.Model): _inherit= 'product.template' @api.multi def copy(self, default=None): default = dict(default or {}) array_attribute_line_ids = [] for value_id in self.attribute_line_ids.read([]): array_attribute_line_ids += [(4,value_id['id'])] print (array_attribute_line_ids) default.update({ # General Information # 'standard_price': self.standard_price, # Variants &gt; Attributes 'attribute_line_ids': array_attribute_line_ids, # Purchase &gt; Vendors # Inventory 'weight': self.weight, 'volume': self.volume, # Invoicing 'property_account_income_id': self.property_account_income_id, 'supplier_taxes_id': self.supplier_taxes_id, #NOT WORKING 'property_account_expense_id': self.property_account_expense_id, 'property_account_creditor_price_difference': self.property_account_creditor_price_difference, }) return super(ProductTemplate, self).copy(default) View: the field at hand is attribute_line_ids shown in the bottom of the image. Problem: I could create new records based on the original ones but the problem is that one of these values depends on a many2one that needs a value 'product_tmpl_id' which is the id of the product. So, how can I create these value if I don't have the id of the new product yet because it hasn't been duplicated at the moment. Previously in a different feature I created the record and then using it's id I update these values. Now its not possible. Is there a way to solve this? Is there a .copy() function that allows me to duplicate all this records without the need of creating then manually? This is odoo 11 enterprise.
tagged with: odoo-10
tagged with: odoo
tagged with: python
type: AnsweredQuestion
tagged with: odoo-11
has answer: http://stackoverflow.com/a/47462730
upvote count: 3
has title: Duplicate record missing many2one field issue
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/47506988
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81969759
accepted answer of: http://stackoverflow.com/q/47506851
type: Answer
has body: In case of html.find(self.TAG) you're actually only putting a single string as a parameter, namely: html.find('"span",{"data-automation":"jobListingDate"}') Notice the single quote ' around the string, which is the same as "\"span\",{\"data-automation\":\"jobListingDate\"}" in your second example html.find("span",{"data-automation":"jobListingDate"}) we're talking about two parameters. Of course this will behave differently.
answers question: http://stackoverflow.com/q/47506851
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81960994
comment on: http://stackoverflow.com/q/47467914
score: 0
has text: pip list did not give me mon_agent :(
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81810905
comment on: http://stackoverflow.com/a/47428017
type: Comment
has text: I'm not compelling you. Dracula does that. Your question has been answered. Now you are facing a different problem. The question was "why is it giving flower not defined". That has been helped with and a lot more than that.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81913542
has text: @Rogue: My pleasure. Thanks for the feedback and keep learning! Python can be very rewarding.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47459025
type: Comment

http://stackoverflow.com/q/47464814
has comment: http://stackoverflow.com/comment/81884754
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81904152
has title: Sprite not moving in the same direction it is facing
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81885013
has body: I have an issue with my sprite not moving in the same direction as it is facing. It is top view of a beetle, 10 images animating its leg movements. The sprite animation works fine, choosing new 'random' direction by rotating the image and re-centering to previous center is working too. What I can't get to work is the sprite to move 'forward', that is to move in the new direction it chooses/faces every second or so. The new direction is simply a small 10-15 degrees rotation left or right from previous position. Instead it moves in what seem like random movements every time the sprite chooses a new direction. For example it will move southwest while facing east, or move north while facing south etc. I suspect the problem is in the move() method where the movement isn't properly translated via trig values. I am adding to the rect.x values because it is the same as the cartesian coords system while subtracting from rect.y values because it is inverted in pygame compared to cartesian. Going down is increasing positively, up - decreasing y values, increasing negatively. The class for the beetle sprite is below: class Foe(): def __init__(self, location): self.sprites = [] for i in range(1, 11): file = pg.image.load("beetleprac1/000"+str(i)+"a.png").convert() # 10 sprite files named "0001a-10a.png" last 1 is idle stance #file.set_colorkey((0, 255, 255)) self.sprites.append(file) self.move_anim_index = 9 self.image = self.sprites[self.move_anim_index] self.rotated_image = self.image.copy() self.rect = self.image.get_rect(center=location) self.move_rect_coords = [self.rect.x, self.rect.y] self.angle = 90 self.speed = 3 self.time = 0 self.frames_counter = 0 def move_anim(self, rate=2): # rate is in frames if self.frames_counter % rate == 0: self.move_anim_index += 1 if self.move_anim_index &gt;= 9: self.move_anim_index = 0 self.image = self.sprites[self.move_anim_index] #self.rect = self.image.get_rect(center=self.rect.center) self.rotated_image = self.image.copy() self.rotate…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81887342
has answer: http://stackoverflow.com/a/47467644
tagged with: python
tagged with: pygame
score: 2
upvote count: 2

http://stackoverflow.com/q/47484428
tagged with: nerdcommenter
score: 0
has title: how to uncomment/comment python file using NERD Comment
has answer: http://stackoverflow.com/a/47512932
answer count: 1
type: Question
tagged with: python
type: UnansweredQuestion
has body: the example given in the official doc is C and I change into python " Add spaces after comment delimiters by default let g:NERDSpaceDelims = 1 " Use compact syntax for prettified multi-line comments let g:NERDCompactSexyComs = 1 " Align line-wise comment delimiters flush left instead of following code indentation let g:NERDDefaultAlign = 'left' " Add your own custom formats or override the defaults let g:NERDCustomDelimiters = { 'python': { 'left': '#' } } &lt;== " Allow commenting and inverting empty lines (useful when commenting a region) let g:NERDCommentEmptyLines = 1 " Enable trimming of trailing whitespace when uncommenting let g:NERDTrimTrailingWhitespace = 1 " but it didn't work when I hit &lt;leader&gt;cc and also don't work by hitting &lt;leader&gt;cu? besides, how to change the default mapping key for this plugin like change &lt;leader&gt;cc to &lt;leader&gt;c to comment ?
tagged with: vim

http://stackoverflow.com/q/47386405
has comment: http://stackoverflow.com/comment/81729935
score: 42
upvote count: 42
has title: MemoryError when I merge two Pandas data frames
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66756500
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47387088
possible better answer: http://stackoverflow.com/a/61919115
downvote count: 0
has answer: http://stackoverflow.com/a/47387088
has comment: http://stackoverflow.com/comment/81730418
has comment: http://stackoverflow.com/comment/81725887
has comment: http://stackoverflow.com/comment/81729358
has comment: http://stackoverflow.com/comment/81735374
has body: I searched almost all over the internet and somehow none of the approaches seem to work in my case. I have two large csv files (each with a million+ rows and about 300-400MB in size). They are loading fine into data frames using the read_csv function without having to use the chunksize parameter. I even performed certain minor operations on this data like new column generation, filtering, etc. However, when I try to merge these two frames, I get a MemoryError. I have even tried to use SQLite to accomplish the merge, but in vain. The operation takes forever. Mine is a Windows 7 PC with 8GB RAM. The Python version is 2.7 Thank you. Edit: I tried chunking methods too. When I do this, I don't get MemoryError, but the RAM usage explodes and my system crashes.
favorite count: 0
type: Question
tagged with: out-of-memory
answer count: 5
has answer: http://stackoverflow.com/a/61240860
has answer: http://stackoverflow.com/a/78808980
has comment: http://stackoverflow.com/comment/81730183
has comment: http://stackoverflow.com/comment/81725690
tagged with: python
has answer: http://stackoverflow.com/a/61919115
has comment: http://stackoverflow.com/comment/81725764
tagged with: merge
has comment: http://stackoverflow.com/comment/81725816

http://stackoverflow.com/comment/81788776
has text: Can you update the question with full error stack trace?
comment on: http://stackoverflow.com/a/47405823
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81722762
comment on: http://stackoverflow.com/a/47384376
type: Comment
has text: Im thinking it is a scope issue.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47403816
downvote count: 0
has body: json.loads converts a json object to the python equivalent. This means it uses lists and dicts instead of arrays and objects. You are seeing the representation of the former. doctionary["firstname"] will get you the value in first name (ie, "doe") while it's still a python object. If you want to see json again, you'll need to pass it through json.dumps - but of course you won't be able to manipulate it as above when in that format.
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47403801
has comment: http://stackoverflow.com/comment/81761622
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81761475
accepted answer of: http://stackoverflow.com/q/47403801

http://stackoverflow.com/q/47400711
score: 1
downvote count: 0
tagged with: authentication
has comment: http://stackoverflow.com/comment/81755491
has answer: http://stackoverflow.com/a/47400753
possible better answer: http://stackoverflow.com/a/65002062
favorite count: 0
type: Question
has title: I'm trying to create a login system using a text file
has answer: http://stackoverflow.com/a/65002062
has comment: http://stackoverflow.com/comment/81755442
has comment: http://stackoverflow.com/comment/81755043
has body: I'm trying to create a login system using a textfile so i've turned the text file into a list. When printed the textfile looks like this as i've split the rows: [['11Ali15', '@Tyson345', 'Alice', '15', '11'], ['11Ell16', 'Nibbles', 'Ellen', '16', '11'], ['13Ell12', 'Asdan3', 'Ellie', '12', '13']] This list is set out [Username,Password,Name,Age,Yeargroup] and i want to be able to make a log in system where username and password match so program can be continued. The code i'm using at the moment is:(One of my subroutines) print("--Login--") username = input("Please enter your username:") while len(username) == 0: username = input(" Please enter your username:") password = input("Please enter your password:") while len(password) == 0: password = input(" Please enter your password:") studentlist = [] with open ("studentdetails.txt") as textfile: for row in textfile: row = row.strip ("\n") studentlist.append(row.split()) print (studentlist) for everything in studentlist: UserName = everything[0] PassWord = everything[1] if username == UserName and password == PassWord: print("Logged on.") quizmenu() But this doesn't work as it doesn't let u log in and goes round in a loop of asking username and password even when they're entered correctly.
accepted answer: http://stackoverflow.com/a/47400753
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81755149
has comment: http://stackoverflow.com/comment/81755004
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/81755534
has comment: http://stackoverflow.com/comment/81755221

http://stackoverflow.com/comment/81986514
type: Comment
comment on: http://stackoverflow.com/q/47495182
type: QuestionComment
has text: Maybe look at global list of variables and check for type (?).
score: 0

http://stackoverflow.com/comment/81972426
comment on: http://stackoverflow.com/q/47457956
score: 1
type: Comment
type: QuestionComment
has text: you would need to apply some mapping to your categorical data. but AFAIK meanshift can allow you to treat the "categorical" dimension(s) in a different way than the spatial domain. So, if you have three categories, you can map it to a binary 3-vector (ending up with 5D data).

http://stackoverflow.com/comment/81833872
type: Comment
type: QuestionComment
has text: @ Neto A, even after putting the number in the right box, the search button is still grayed out. So, i can't make use of it. See the link https://www.dropbox.com/s/y9zfzpsdao9kup5/Untitled.jpg?dl=0
score: 0
comment on: http://stackoverflow.com/q/47421419

http://stackoverflow.com/comment/82248999
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47628845
has text: You used sgd optimizer and what was training set size?
type: Comment

http://stackoverflow.com/a/47549181
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: You need to specify some algorithm to handle transparency rendering. VTK natively has depth peeling implemented and dual depth peeling since VTK 7.0 (and I think VTK 8.0 introduced something new, but I haven't checked that yet). So the easiest way to "turn on" transparency is to enable depth peeling on the renderer: render.SetUseDepthPeeling(1) render.SetOcclusionRatio(0.1) render.SetMaximumNumberOfPeels(100) render_window.SetMultiSamples(0) render_window.SetAlphaBitPlanes(1) See https://www.vtk.org/Wiki/VTK/Examples/Cxx/Visualization/CorrectlyRenderTranslucentGeometry for some more details about the parameters. Note that it requires support of openGL version at least 3.2. If you are using VTK 7.0 or higher, the "dual depth peeling" will be used automatically if your graphic drivers support it, otherwise the standard depth peeling will be used.
accepted answer of: http://stackoverflow.com/q/47528086
type: Answer
answers question: http://stackoverflow.com/q/47528086

http://stackoverflow.com/comment/82047734
type: Comment
has text: My high level goal is very much to do with business objects that have no place on stackoverflow. There is a pause button on the google cloud console taskqueue gui because some of the nice people at google recognize that it can be useful to temporarily stop processing.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47533400

makefile
tags question: http://stackoverflow.com/q/47512182
type: Tag
tags question: http://stackoverflow.com/q/47436205
tag name: makefile

http://stackoverflow.com/a/47549590
has comment: http://stackoverflow.com/comment/82076930
has comment: http://stackoverflow.com/comment/82068445
has comment: http://stackoverflow.com/comment/82069399
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82080574
downvote count: 0
score: 47
upvote count: 47
accepted answer of: http://stackoverflow.com/q/47538391
has comment: http://stackoverflow.com/comment/82080997
answers question: http://stackoverflow.com/q/47538391
type: Answer
has comment: http://stackoverflow.com/comment/82079471
has comment: http://stackoverflow.com/comment/82109824
has body: The confusion is due to the meaning of axis in np.mean versus in BatchNormalization. When we take the mean along an axis, we collapse that dimension and preserve all other dimensions. In your example data.mean(axis=0) collapses the 0-axis, which is the vertical dimension of data. When we compute a BatchNormalization along an axis, we preserve the dimensions of the array, and we normalize with respect to the mean and standard deviation over every other axis. So in your 2D example BatchNormalization with axis=1 is subtracting the mean for axis=0, just as you expect. This is why bn.moving_mean has shape (4,).
has comment: http://stackoverflow.com/comment/82078976

http://stackoverflow.com/q/47467964
tagged with: boto3
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
has answer: http://stackoverflow.com/a/47471657
type: Question
has body: Good day, Recent AWS release API for know the billing information. It is available in all aws SDK (c#,python,php). I just tried a lambda function to update my database table with current cost of my all linked accounts. but mt lambda function doesn't work. it show the following error "Unknown service: 'ce'. Valid service names are: acm, apigateway, application-autoscaling, appstream, athena, autoscaling,etc " my lambda code is : import boto3 from datetime import datetime, timedelta def lambda_handler(event, context): client1 = boto3.client( 'ce', aws_access_key_id=accesskey, aws_secret_access_key=secretkey) [referral link for client creation][1] response = client1.get_cost_and_usage( TimePeriod={ 'Start': startdate, 'End': enddate }, Granularity='MONTHLY', Metrics=[ 'BlendedCost', ], GroupBy=[ { 'Type': 'DIMENSION', 'Key': 'LINKED_ACCOUNT' }, ], ) print response
has comment: http://stackoverflow.com/comment/81991111
tagged with: python
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/47919883
has answer: http://stackoverflow.com/a/47471362
answer count: 3
downvote count: 0
type: UnansweredQuestion
has title: cost explorer in python-boto3 unknown service 'ce'

http://stackoverflow.com/comment/82089536
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47492982
type: Comment
has text: okay, now it has a new bug. Value Error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

http://stackoverflow.com/comment/81796041
type: Comment
has text: Glad it helped, if you don't mind could you please accept my answer?
comment on: http://stackoverflow.com/a/47397608
score: 0
type: AnswerComment

http://stackoverflow.com/q/47488206
has answer: http://stackoverflow.com/a/47488365
favorite count: 0
type: Question
upvote count: 0
score: -3
answer count: 1
tagged with: python
has body: I'd like to get the name of any attribute while iterating over it. the ts3defines.py looks like this: class VirtualServerProperties(object): VIRTUALSERVER_UNIQUE_IDENTIFIER = 0 VIRTUALSERVER_NAME = 1 VIRTUALSERVER_WELCOMEMESSAGE = 2 VIRTUALSERVER_PLATFORM = 3 VIRTUALSERVER_VERSION = 4 VIRTUALSERVER_MAXCLIENTS = 5 VIRTUALSERVER_PASSWORD = 6 VIRTUALSERVER_CLIENTS_ONLINE = 7 VIRTUALSERVER_CHANNELS_ONLINE = 8 VIRTUALSERVER_CREATED = 9 VIRTUALSERVER_UPTIME = 10 VIRTUALSERVER_CODEC_ENCRYPTION_MODE = 11 VIRTUALSERVER_ENDMARKER = 12 the getItems(object) function looks like this: def getItems(object): return [getattr(object, a) for a in dir(object) if not a.startswith('__') and not callable(getattr(object, a))] the code in question looks like this: for var in getItems(ts3defines.VirtualServerProperties): (err, var) = ts3.getServerVariable(schid, var) if err == ts3defines.ERROR_ok and var != "" and var != 0: i.append('{0}: {1}'.format(var.__name__, var)) My question is about the var.__name__ shouldn't that return the string VIRTUALSERVER_BLA, etc? Why does it cause? 11/25/2017 16:07:44 pyTSon.PluginHost.infoData Error Error calling infoData of python plugin Extended Info: Traceback (most recent call last): File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\pluginhost.py", line 476, in infoData data = p.infoData(schid, aid, atype) File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\info\__init__.py", line 160, in infoData return self.getServerInfo(schid) File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\info\__init__.py", line 148, in getServerInfo i.append('{0}: {1}'.format(var.__name__, var)) AttributeError: 'int' object has no attribute '__name__'
type: AnsweredQuestion
has title: Get name of attributes
accepted answer: http://stackoverflow.com/a/47488365
has comment: http://stackoverflow.com/comment/81931637
downvote count: 3

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

exscript
tags question: http://stackoverflow.com/q/47399913
tag name: exscript
type: Tag

http://stackoverflow.com/q/47482490
score: 0
has body: Say that i have the the following folder structure: -api_server - __init__.py -app.py If i have the following code in __init__.py: app = config_and_create_app() Then in app.py i have: from api_server import app app.run() will the import statement in app.py "activate" the __init__.py file and therefore app.run() will work?
accepted answer: http://stackoverflow.com/a/47482537
answer count: 1
has comment: http://stackoverflow.com/comment/81920258
has answer: http://stackoverflow.com/a/47482537
favorite count: 0
type: Question
upvote count: 2
has title: Python - does __init__ get executed after import?
downvote count: 2
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47437472
has answer: http://stackoverflow.com/a/66446052
tagged with: python
has comment: http://stackoverflow.com/comment/138604685
upvote count: 11
type: AnsweredQuestion
answer count: 3
tagged with: python-click
has body: My program uses Click for command line processing. It has a main command that takes a required argument. This command has subcommands that take optional arguments. Different subcommands take different options, but they all require the same argument from their parent. I'd like to have the command line look like this: python myprogram.py argument-value subcommand1 --option-1=value I can write this using Click like so import click @click.group() @click.argument("argument") @click.pass_context def main(context, argument): """ARGUMENT is required for both subcommands""" context.obj = {"argument": argument} @click.command() @click.option("--option-1", help="option for subcommand 1") @click.pass_context def subcommand1(context, option_1): print("subcommand 1: %s %s" % (context.obj["argument"], option_1)) @click.command() @click.option("--option-2", help="option for subcommand 2") @click.pass_context def subcommand2(context, option_2): print("subcommand 2: %s %s" % (context.obj["argument"], option_2)) main.add_command(subcommand1) main.add_command(subcommand2) if __name__ == "__main__": main() The top-level help message is what I want. python myprogram.py --help Usage: myprogram.py [OPTIONS] ARGUMENT COMMAND [ARGS]... ARGUMENT is required for both subcommands Options: --help Show this message and exit. Commands: subcommand1 subcommand2 I can get help for a subcommand if I pass in the required argument. python myprogram.py dummy-argument subcommand1 --help Usage: myprogram.py subcommand1 [OPTIONS] Options: --option-1 TEXT option for subcommand 1 --help Show this message and exit. However, I'd like to get the subcommand help without requiring the user to pass in a dummy argument. I want to be able to run python myprogram.py subcommand1 --help and see the same output as above, but instead I just get the help text for the top level. python myprogram.py subcommand1 --help Usage: myprogram.py [OPTIONS] ARGUMENT COMMAND [ARGS]... ARGUMENT is required for both subcommands Options: …
possible better answer: http://stackoverflow.com/a/51708880
accepted answer: http://stackoverflow.com/a/47442952
has title: In Python Click how do I see --help for Subcommands whose parents have required arguments?
has answer: http://stackoverflow.com/a/51708880
has answer: http://stackoverflow.com/a/47442952
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81838756
type: Question
has comment: http://stackoverflow.com/comment/81837324
score: 10

dbus
type: Tag
tags question: http://stackoverflow.com/q/47517934
tag name: dbus

http://stackoverflow.com/a/47383747
answers question: http://stackoverflow.com/q/47383691
type: AcceptedAnswer
has body: I didn't need to make my integer a symbol. The code above works.
type: Answer
accepted answer of: http://stackoverflow.com/q/47383691
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47515975
has comment: http://stackoverflow.com/comment/81987902
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47516361
has title: Python float counter
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47516254
score: 0
has comment: http://stackoverflow.com/comment/81988162
answer count: 2
upvote count: 2
tagged with: pandas
downvote count: 2
has body: I have a pandas column which has floats and missing values example 1,2 11,2,34 nan I would like to create another column which will count these numbers so 1,2 2 11,2,34 3 nan 0

http://stackoverflow.com/comment/81735049
has text: You might want to tell the whole requirement/assignment. If you just want a subset of numbers that have the greatest product, you obviously just remove all numbers that are smaller than 1.
comment on: http://stackoverflow.com/q/47390996
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/47446701
has comment: http://stackoverflow.com/comment/81873412
accepted answer of: http://stackoverflow.com/q/47434852
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47434852
upvote count: 1
has body: Your question doesn't specify what you expect to see when your code works as expected, but this may help you: from bottle import get, run, template, response @get('/list/item') def listItems(): r = requests.get('my/url/which/works/') response.content_type = 'text/plain' # added this return r.content ... The only change is that your webserver will now be setting the content type of the response to text/plain, which should make your browser render the page. Longer term, if (as I'm inferring from your question) you intend to return XML responses, then I suggest either installing a browser plugin (here's an example), or, better yet, use curl or wget to see the precise response. This will help you debug your server's responses.
type: Answer

http://stackoverflow.com/comment/91126669
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50728593
has text: They're both valid endpoints, but they serve slightly different purposes. I spoke with Socrata about this a while ago, but I don't remember exactly what their justification was... Sorry I can't clarify further. Did it work?

http://stackoverflow.com/q/47461480
has comment: http://stackoverflow.com/comment/81878240
downvote count: 1
score: -1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81878244
tagged with: python-3.x
has body: I know this won't work, and it'll produce an error, but I'll ask it anyways. exec(chr(8)) doesn't delete a character from the shell... chr(8) is backspace in ascii. So naturally, I'd think it'll delete a character from the shell, like &gt;&gt;&gt; exec(chr(8)) would return &gt;&gt;&gt; exec(chr(8) # Missing a parenthesis.
upvote count: 0
has comment: http://stackoverflow.com/comment/81878009
has comment: http://stackoverflow.com/comment/81877774
has comment: http://stackoverflow.com/comment/81877635
has comment: http://stackoverflow.com/comment/81877960
has comment: http://stackoverflow.com/comment/81878235
tagged with: python
has comment: http://stackoverflow.com/comment/81877669
has comment: http://stackoverflow.com/comment/81877930
has comment: http://stackoverflow.com/comment/81877800
tagged with: ascii
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47462413
has comment: http://stackoverflow.com/comment/81877986
has comment: http://stackoverflow.com/comment/81878186
has title: why doesn't exec(chr(8)) delete a character from the shell?
has answer: http://stackoverflow.com/a/47462413
tagged with: chr
answer count: 1
has comment: http://stackoverflow.com/comment/81877733
tagged with: exec

http://stackoverflow.com/a/47510892
has body: In Python a string is a sequence of characters, but characters are 1-char strings. So if you access 'foobar'[0], you obtain 'f'. Since f is however a string, we can access the first character of that string. Since 'f'[0] is 'f'. As a result if you access a strings s with s[i][0][0][0], you thus keep accessing the first character of the string s. If you write s[i][1] however, this will error, since s[i] is a one-character string, and thus you can not obtain the second character, since there is no such character. The string itself is not multidimensional, you simply obtain a new string and call the index of that new string. You can add as many [0]s as you like.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47510820
score: 1
downvote count: 0

http://stackoverflow.com/comment/82002237
type: Comment
has text: Search for "image alignment in opencv" to find a lot of tutorials for this. [This](https://stackoverflow.com/questions/22086062/align-images-in-opencv) answer has a lot of suggestions for the various ways of accomplishing this. The two general methods are *dense* optical flow, which looks to align each pixel, and *sparse* optical flow, which looks to align features. Feature based methods are faster and more robust to different illumination conditions. If your images are *purely* rotated, then you can simply rotate your image in a loop and do template matching.
type: QuestionComment
comment on: http://stackoverflow.com/q/47522403
score: 1

http://stackoverflow.com/a/47400753
accepted answer of: http://stackoverflow.com/q/47400711
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47400711
type: Answer
has body: Your indentation is off. It should be checking for Username and Password for each user in the text file, which would be like the following: for everything in studentlist: UserName = everything[0] PassWord = everything[1] if username == UserName and password == PassWord: print("Logged on.") quizmenu()

http://stackoverflow.com/a/47571289
downvote count: 0
has comment: http://stackoverflow.com/comment/108707643
has comment: http://stackoverflow.com/comment/123269828
has comment: http://stackoverflow.com/comment/117319455
has comment: http://stackoverflow.com/comment/117293653
has comment: http://stackoverflow.com/comment/123250239
has comment: http://stackoverflow.com/comment/120839144
has comment: http://stackoverflow.com/comment/123168833
accepted answer of: http://stackoverflow.com/q/47396372
has comment: http://stackoverflow.com/comment/123207545
has comment: http://stackoverflow.com/comment/117284566
type: Answer
has comment: http://stackoverflow.com/comment/111008842
has body: I found the solution, lots of stuff was missing. I used the need-data signal like the examples of gst-rtsp-server. I changed some default parameters of appsrc, like the is-live, block and format. The caps on the appsrc element. I was not setting the offset of the buffer correctly. Here's the code for anyone who's facing the same problem or has a somewhat similar one. #!/usr/bin/env python3 import cv2 import gi gi.require_version('Gst', '1.0') gi.require_version('GstRtspServer', '1.0') from gi.repository import Gst, GstRtspServer, GObject class SensorFactory(GstRtspServer.RTSPMediaFactory): def __init__(self, **properties): super(SensorFactory, self).__init__(**properties) self.cap = cv2.VideoCapture(0) self.number_frames = 0 self.fps = 30 self.duration = 1 / self.fps * Gst.SECOND # duration of a frame in nanoseconds self.launch_string = 'appsrc name=source is-live=true block=true format=GST_FORMAT_TIME ' \ 'caps=video/x-raw,format=BGR,width=640,height=480,framerate={}/1 ' \ '! videoconvert ! video/x-raw,format=I420 ' \ '! x264enc speed-preset=ultrafast tune=zerolatency ' \ '! rtph264pay config-interval=1 name=pay0 pt=96'.format(self.fps) def on_need_data(self, src, lenght): if self.cap.isOpened(): ret, frame = self.cap.read() if ret: data = frame.tostring() buf = Gst.Buffer.new_allocate(None, len(data), None) buf.fill(0, data) buf.duration = self.duration timestamp = self.number_frames * self.duration buf.pts = buf.dts = int(timestamp) buf.offset = timestamp self.number_frames += 1 retval = src.emit('push-buffer', buf) print('pushed buffer, frame {}, duration {} ns, durations {} s'.format(self.number_frames, self.duration, self.duration / Gst.SECOND)) if retval != Gst.FlowReturn.OK: print(retval) def do_create_element(self, url): return Gst.parse_launch(self.launch_string) def do_configure(self, rtsp_media): self.number_frames = 0 appsrc = rtsp_media.get_element().get_child_by_name('source') appsrc.connect('need-data', self.on_need_data) class GstServer(GstRtspServe…
score: 15
has comment: http://stackoverflow.com/comment/116349315
has comment: http://stackoverflow.com/comment/117326705
has comment: http://stackoverflow.com/comment/116360009
upvote count: 15
has comment: http://stackoverflow.com/comment/116359944
answers question: http://stackoverflow.com/q/47396372
has comment: http://stackoverflow.com/comment/116359851
has comment: http://stackoverflow.com/comment/116363049
has comment: http://stackoverflow.com/comment/117319221
has comment: http://stackoverflow.com/comment/115224261
has comment: http://stackoverflow.com/comment/91344677
has comment: http://stackoverflow.com/comment/120925780
type: AcceptedAnswer

http://stackoverflow.com/q/47527222
type: AnsweredQuestion
score: 0
has body: Learning scrapy and I'm trying to use it to get some specific topics in a forum. In the forum the infomation I need is stored like: [topic] postname <a something to show the poster and time>** <a something to show the numbers of read and replys>** <a something to show the last replyer and time>** #next thread .... Is there any method to get the postname in the second a tag for a specific topic whose unique topicid is stored in the first a tag. Should I use sibling? For example I get [NEWS] news1 [NEWS] news2 [NEWS] news3 [PIC] picture1 for input. And I want to get an output only include "NEWS" topic like['news1','news2','news3'] Thanks for your help!
answer count: 1
type: Question
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/47529297
has comment: http://stackoverflow.com/comment/82012524
has comment: http://stackoverflow.com/comment/82012407
has comment: http://stackoverflow.com/comment/82012631
has answer: http://stackoverflow.com/a/47529297
has comment: http://stackoverflow.com/comment/82012341
has comment: http://stackoverflow.com/comment/82011849
tagged with: python
has comment: http://stackoverflow.com/comment/82011289
has comment: http://stackoverflow.com/comment/82013789
has title: Python beautifulsoup select CSS issue
has comment: http://stackoverflow.com/comment/82012946

http://stackoverflow.com/comment/82016648
type: Comment
comment on: http://stackoverflow.com/q/47524492
type: QuestionComment
has text: Yes you are right. With a print, it works perfectly. The problem here is that I am sending this data to WordPress via XMLRPC. Scrapy only works with Python 2.
score: 0

http://stackoverflow.com/comment/81993789
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47518068
has text: @alexis You answered your own question with "*I should have read the [docs on super()](https://docs.python.org/3/library/functions.html#super) more carefully.*" RTFM questions seems to get downvoted these days...
type: Comment

http://stackoverflow.com/comment/81728250
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47387056
has text: I get this error `File "/usr/lib/python3.6/csv.py", line 143, in writeheader header = dict(zip(self.fieldnames, self.fieldnames)) TypeError: zip argument #1 must support iteration` From what I could gather with a little bit of searching, a dict writer would only be useful if my "exported_data" is a dictionary, correct? In this case, I'm using a list as you can see here: `exported_data = list(result.get_points())` What would you suggest me to do here?
type: Comment

http://stackoverflow.com/comment/81746641
score: 0
type: AnswerComment
has text: i don't think its good to create another class to keep same information.
comment on: http://stackoverflow.com/a/47395674
type: Comment

http://stackoverflow.com/q/47478083
type: Question
has body: Say I am parsing a listing page and generating a JSON output. At the end when all stuff is parsed, I want to run some operations on final scraped result. How can i do it in Scrapy? I know about process_item but it works for each item in iteration. The closed thing I found was close_spider but I am not sure that if I run scrapy crawl spider whether it will give me JSON I created in closed_spider? If yes then how?
type: UnansweredQuestion
tagged with: python
score: 0
has title: How to process final scrapers result in Scrapy?
answer count: 1
tagged with: scrapy
has answer: http://stackoverflow.com/a/47480292

http://stackoverflow.com/comment/84632170
has text: @DavidDale nice answer, but it would be even better if you clarified which method is assuming predicted probabilities to be normally distributed (delta method), and which method is assuming log-odds to be normally distributed (the "transformation" method, i.e., the last plot you show).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47419474

http://stackoverflow.com/a/54794012
has body: The line data = data.repeat(num_epochs) results in repeating the already for num_epochs repeated dataset (also the epoch counter). Can easily be obtained by replacing for _ in range(num_iters): with for _ in range(num_iters+1):.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47410778

http://stackoverflow.com/comment/81952359
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47498558
has text: So change the condition so it calculates the next one, like the posted answer suggests.
type: QuestionComment

http://stackoverflow.com/comment/81991164
score: 0
type: Comment
has text: No difference. Wrong forum I was told so I moved to a more proper forum.
type: QuestionComment
comment on: http://stackoverflow.com/q/47517442

http://stackoverflow.com/a/47488803
type: Answer
has comment: http://stackoverflow.com/comment/81933320
has body: just type in cmd "pip install jupyter" after the installation type "jupyter notebook" jupyter will run on browser. if it doesn't work just type "python -m pip install jupyter"
answers question: http://stackoverflow.com/q/47488215
score: 0

http://stackoverflow.com/q/47534128
tagged with: python
has answer: http://stackoverflow.com/a/47534957
answer count: 2
score: 1
has body: I have a two file matrices, that look like this File1: {'key1',g,l,i,o,+: [0.0, 0.0, 0.92, 0.02, 0.01],'key2',g,l,i,o,+: [0.1, 0.2, 0.90, 0.26, 0.10].....'key100',g,l,i,o,+: [0.1, 0.1, 0.29, 0.19, 0.20]} File2: {'key1',g,l,i,o,+: [0.0, 0.0, 0.96, 0.06, 0.01],'key2',g,l,i,o,+: [0.0, 0.1, 0.95, 0.26, 0.11].....'key100',g,l,i,o,+: [0.2, 0.0, 0.23, 0.16, 0.21]} Both files have the same 'keys'. I want to average the values between the two files, so the result file looks like this: Desired output file: {'key1',g,l,i,o,+: [0.0, 0.0, 0.94, 0.04, 0.01],'key2',g,l,i,o,+: [0.05, 0.15, 0.925, 0.26, 0.105].....'key100',g,l,i,o,+: [0.15, 0.1, 0.29, 0.175, 0.205]} I have thought about the python script I could write, but since I am quite new to this, any quick ideas would be welcome: import gzip import numpy as np inFile1 = gzip.open('/home/file1') inFile2 = gzip.open('/home/file2') inFile.next() for line in inFile: cols = line.strip().split('\t') data = cols[6:] for line in inFile2: cols = line.strip().split('\t') data2 = cols[6:] newdata = (data + data2)/2
has comment: http://stackoverflow.com/comment/82026073
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82025549
type: Question
has comment: http://stackoverflow.com/comment/82027406
has answer: http://stackoverflow.com/a/47536836
has comment: http://stackoverflow.com/comment/82025658
type: UnansweredQuestion
has title: how to average between values in two files?
has comment: http://stackoverflow.com/comment/82026506

http://stackoverflow.com/a/47423574
has comment: http://stackoverflow.com/comment/81801970
answers question: http://stackoverflow.com/q/47423481
type: Answer
has comment: http://stackoverflow.com/comment/81801958
score: 0
has body: clothing_ids = [] for key, value in file.items(): if key == 'id': clothing_ids.append(value) Go through every key value pair, and where the key is ID, add the value to your ID list.

http://stackoverflow.com/a/47491520
upvote count: 2
downvote count: 0
type: Answer
has body: You could create a class, and instantiate it as many times as you need different input boxes. something like this: # pseudocode # class InputBox(pygame.Rect): def __init__(self, position=(50, 50, 140, 32), font=pygame.font.Font(None, 32), color_inactive=pygame.Color('lightskyblue3'), color_active=pygame.Color('dodgerblue2'), text = '', active=False) super().__init__(position) #&lt;- this may need to be adjusted to pygame Rect specs self.font = font self.color_inactive = color_inactive self.color_active = color_active self.color = color_inactive self.text = text self.active = active
score: 2
answers question: http://stackoverflow.com/q/47491451

http://stackoverflow.com/comment/81813668
type: AnswerComment
has text: Lol love it, Thank you too
score: 0
comment on: http://stackoverflow.com/a/47429343
type: Comment

http://stackoverflow.com/comment/82066291
has text: @ACIE Please upvote if it helped you. You are Welcome!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47524662

http://stackoverflow.com/comment/81926700
has text: Use DateTime instead
comment on: http://stackoverflow.com/q/47485952
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47388013
linked to: http://stackoverflow.com/q/9236926
has title: 1D numpy concatenate: TypeError: only integer scalar arrays can be converted to a scalar index
accepted answer: http://stackoverflow.com/a/47388030
tagged with: numpy
score: 80
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47388030
duplicate of: http://stackoverflow.com/q/9236926
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0
type: Question
upvote count: 80
has body: I want to store numpy array into to another numpy array I am using np.concatenate This is my code x=np.concatenate(x,s_x) These are the type and the shape of x and s_x Type of s_x: &lt;class 'numpy.ndarray'&gt;, Shape of s_x: (173,) Type of x: &lt;class 'numpy.ndarray'&gt; (0,), Shape of x: (0,) This is the error being displayed TypeError: only integer scalar arrays can be converted to a scalar index
tagged with: python

http://stackoverflow.com/comment/81754156
type: Comment
comment on: http://stackoverflow.com/q/47400311
score: 0
type: QuestionComment
has text: zip & sort as tuples.

http://stackoverflow.com/q/47509869
type: Question
has title: What is the type of 'special' operators/instructions in Python?
has comment: http://stackoverflow.com/comment/81975307
has comment: http://stackoverflow.com/comment/81975320
tagged with: python
has answer: http://stackoverflow.com/a/47509935
has comment: http://stackoverflow.com/comment/81975359
possible better answer: http://stackoverflow.com/a/47509938
has comment: http://stackoverflow.com/comment/81975303
has body: In Python, we have things like if, elif, else, break, continue, pass, etc. For want of a better word, I'll call them special instructions. What type are they? If I do something like type(pass) I get a SyntaxError.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47509938
has comment: http://stackoverflow.com/comment/81975319
answer count: 2
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/47509935
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47437582
tagged with: python
accepted answer: http://stackoverflow.com/a/47441268
has comment: http://stackoverflow.com/comment/81830278
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81830078
answer count: 1
tagged with: neural-network
upvote count: 1
tagged with: machine-learning
has body: Here is my project. It consists of: m = 24 where m is the number of training examples; 3 hidden layers and the input layer; 3 sets of weights connecting each layer; the data is 1x38 with a response of y (1x1). import numpy as np x = np.array([ [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, …
has comment: http://stackoverflow.com/comment/81829911
has answer: http://stackoverflow.com/a/47441268
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81829845
score: 0
has title: Neural network not producing results
has comment: http://stackoverflow.com/comment/81830024
tagged with: gradient-descent
has comment: http://stackoverflow.com/comment/81830363

http://stackoverflow.com/comment/81934791
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47488586
has text: glad you solved it. I removed my answer because it wasn't working for you, so it wasn't answering. I don't like leaving generic answers here. Maybe you could answer your own question then.
type: Comment

http://stackoverflow.com/comment/81910508
type: QuestionComment
comment on: http://stackoverflow.com/q/47477868
type: Comment
score: 0
has text: we can't solve it if we don't know the functions' definitions

http://stackoverflow.com/comment/81913746
type: QuestionComment
comment on: http://stackoverflow.com/q/47479225
has text: You may want to read [ask] and [mcve].
type: Comment
score: 0

http://stackoverflow.com/q/47426996
has body: I am trying to deploy my first django app to google app engine but am having a hard time follow docs as many are out of date. I have a project that I started from this (https://github.com/Shopify/shopify_django_app) but cant deploy with the outdated docs in the readme. -I dont know my project name -I am unfamiliar with gunicorn -and I'm unsure where to put my wsgi file as I have multiple django apps Every tutorial seems to only have one app (https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/hello_world_django) # app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT main:app health_check: enable_health_check: True check_interval_sec: 5 timeout_sec: 4 unhealthy_threshold: 2 healthy_threshold: 2 handlers: - url: /static static_dir: static/ expiration: '30d' - url: /.* script: djangoappengine/main/main.py
has comment: http://stackoverflow.com/comment/81808691
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81809255
linked to: http://stackoverflow.com/q/45842772
type: Question
has comment: http://stackoverflow.com/comment/81827907
type: UnansweredQuestion
tagged with: google-app-engine
has title: deploying django with gunicorn (and multiple django apps)
tagged with: django
tagged with: python

http://stackoverflow.com/comment/81855105
has text: This is exactly what I was looking for! Thank you so much!
comment on: http://stackoverflow.com/q/47395061
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47472878
tagged with: pandas
tagged with: datetime
answer count: 1
tagged with: python
has body: I have a dataframe column which looks like this : It reads M:S.MS. How can I convert it into a M:S:MS timeformat so I can plot it as a time series graph? If I plot it as it is, python throws an Invalid literal for float() error. Note : This dataframe contains one hour worth of data. Values between 0:0.0 - 59:59.9
favorite count: 0
type: Question
upvote count: 2
has title: Convert Dataframe column to time format in python
has answer: http://stackoverflow.com/a/47472986
tagged with: datetime-format
accepted answer: http://stackoverflow.com/a/47472986
type: AnsweredQuestion
score: 2
tagged with: python-2.7
downvote count: 0

http://stackoverflow.com/comment/81910010
score: 1
type: AnswerComment
has text: try `import bs4`, and then `doc = bs4.BeautifulSoup(req.content)`
comment on: http://stackoverflow.com/a/47477054
type: Comment

http://stackoverflow.com/a/47490951
has body: All variables within __init__ are instance variables, and so will be saved. Both the list and non-list variables outside __init__ are class variables, so won't be saved. However, when you change object1.b that creates the instance variable b instead of setting the class variable, so it will be saved. However, when you modify object1.a, you are not reassigning it, just an element of it, so it is still an (unsaved) class variable. If you want to save it, make it an instance variable or save the class variables separately.
score: 0
answers question: http://stackoverflow.com/q/47490905
has comment: http://stackoverflow.com/comment/81937676
accepted answer of: http://stackoverflow.com/q/47490905
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/47536248
answers question: http://stackoverflow.com/q/47534817
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47534817
type: AcceptedAnswer
has body: This is a solution, however to maintain order of your dictionary, items should be appended one by one. In such exact order, items will be stored in OrderedDict object. from collections import OrderedDict import random ordered_dict = OrderedDict() ordered_dict['the'] = 2 ordered_dict['quick'] = 1 ordered_dict['brown'] = 1 generated_index = random.randrange(0, 3) new_index = ordered_dict.values()[generated_index] + generated_index resulting_string = ordered_dict.keys()[new_index] print resulting_string There is possibility that your new index will be out of bounds. Please think about how to handle such situation.

http://stackoverflow.com/q/47414022
score: 1
has body: I'm attending an online Python course for beginners. The content of a unit is to teach students to extract all links in the source code of a webpage. The code is as follows, with Block_of_Code unknown: def get_page(url): &lt;Block_of_Code&gt; def get_next_target(page): start_link=page.find('&lt;a href=') if start_link==-1: return None,0 start_quote=page.find('"',start_link) end_quote=page.find('"',start_quote+1) url=page[start_quote+1:end_quote] return url,end_quote def print_all_links(page): while True: url,endpos=(get_next_target(page)) if url: print(url) page=page[endpos:] else: break print_all_links(get_page('https://youtube.com')) If I were not in China, the Block_of_Code should not have been a problem for me. As far as I know, it may have been: import urllib.request return urllib.request.urlopen(url).read().decode('utf-8') But here in China, certain websites (youtube included) are blocked. So the above code doesn't apply to them. My goal for Block_of_Code is to get the source code of any website, whether blocked or not. I have searched on Google and found some codes using socks proxy, but none of them worked. For example, I wrote and tried the following code based on this article (having executed pip install PySocks). import socket import socks import urllib.request socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 2012) socket.socket = socks.socksocket return urllib.request.urlopen(url).read().decode('utf-8') The error message is: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host The reason for my searching for code using socks proxy is that I have always been using socks proxy service to visit blocked websites. By launching an app provided by my service provider, I am able to visit those websites using a web browser like Firefox. (My socks proxy port is 2012) Nevertheless, any kind of solution is welcome, whether it is socks proxy or not, as long as it will enable me to get the source of any page. I'm using…
downvote count: 0
has comment: http://stackoverflow.com/comment/81814633
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81947313
type: UnansweredQuestion
has title: How to access a website using SOCKS proxy in Python
tagged with: python
tagged with: web-crawler
tagged with: proxy
has comment: http://stackoverflow.com/comment/82303118
has comment: http://stackoverflow.com/comment/81946321
answer count: 0

http://stackoverflow.com/a/47467313
answers question: http://stackoverflow.com/q/47466909
type: Answer
score: 0
has body: You should keep that logic out of the template and deserialize those value strings in the view or in the form where they originate from: # forms.py import json class WhateverForm(forms.Form) # form class of document.forms # ... def clean_dict(self) return {k: json.loads(v).get('label') for k, v in self.hdict.items() if 'header' not in k} # template {% for form in document.forms.all %} {% for k, v in form.clean_dict.items %} {"key": {{ k }}, "label": "{{ v }}"}, {% endfor %} {% endfor %}

http://stackoverflow.com/comment/81961256
comment on: http://stackoverflow.com/a/47502690
type: Comment
score: 0
type: AnswerComment
has text: suppose I want to access, the 2nd value of each list, how would I do that?

http://stackoverflow.com/q/47429876
upvote count: 1
has answer: http://stackoverflow.com/a/47430061
accepted answer: http://stackoverflow.com/a/47430061
has body: I have two dictionaries : dict1 = {'key1': [val, val, val], 'key2': [val, val, val]} dict2 = {'key1': [val, val, val], 'key2': [val, val, val]} I need to find in dict1 and dict2 keys with the same values and create a new dict with that keys (dicr3 = {'key1': key1}). Is there better way to do this instead of double for loop? for key, val in first_dict.items(): for key2, val2 in sec_dict.items(): if val == val2: print(str(key) + " : " + str(key2))
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81814324
has answer: http://stackoverflow.com/a/47430000
tagged with: python
has title: Merging python dictionaries based on value comparing
possible better answer: http://stackoverflow.com/a/47430000
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47430047
answer count: 3
downvote count: 0
score: 1

http://stackoverflow.com/q/47383376
tagged with: generator
has answer: http://stackoverflow.com/a/47383446
type: Question
tagged with: python-3.x
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
has body: The itertools.islice() method lets me generate a combination of characters from a charset starting from a given value. Running my method with Generate(1, 7, "abcde", "bdca") will run perfectly fine. However, when the integer is at the 'maximum' value (greater than 2147483647) i get the error: ValueError: Indices for islice() must be None or an integer: 0 &lt;= x &lt;= sys.maxsize. How can i get itertools.isliceto take large start values? I did try setting sys.maxsize to 'a large number' and converting startValue to an integer explicitly; sys.maxsize = (len(charset) ** maxVal), but islice() just ignores that. This is the code I have come up with so far: def checkValue(charset, word): pos = len(charset) value = 0 for i,c in enumerate(reversed(word)): value+= (pos**i) * charset.index(c) return value def Generate(minVal, maxVal, charset, startFrom): startValue = int(checkValue(charset, startFrom)) print(startValue) allCombos = itertools.product(charset, repeat=len(startFrom)) combos = itertools.islice(allCombos, int(startValue), None) # error is here with 'startValue' # generate from combo to end of length for num, attempt in enumerate(combos, start=startValue): generated = "".join(attempt) print(num, generated) # have to make new instance or skips a chunk for each length for length in range(minVal + 1, maxVal + 1): to_attempt = itertools.product(charset, repeat=length) for attempt in to_attempt: generated = "".join(attempt) print(generated) Generate(1, 15, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890", "ADHkjdWCE") Thanks for any help.
has title: itertool.islice value error when stop value is greater than sys.maxsize
type: AnsweredQuestion
score: 0
tagged with: python-itertools
tagged with: long-integer
tagged with: python
accepted answer: http://stackoverflow.com/a/47383446

deep-learning
tags question: http://stackoverflow.com/q/47521393
tags question: http://stackoverflow.com/q/47394572
tags question: http://stackoverflow.com/q/47509074
tags question: http://stackoverflow.com/q/47386862
tags question: http://stackoverflow.com/q/47534197
tags question: http://stackoverflow.com/q/47527735
tags question: http://stackoverflow.com/q/47406821
tags question: http://stackoverflow.com/q/47398769
tags question: http://stackoverflow.com/q/47431649
tags question: http://stackoverflow.com/q/47465640
tags question: http://stackoverflow.com/q/47382952
tags question: http://stackoverflow.com/q/47411492
tags question: http://stackoverflow.com/q/47455914
type: Tag
tags question: http://stackoverflow.com/q/47519554
tags question: http://stackoverflow.com/q/47442792
tags question: http://stackoverflow.com/q/47531419
tags question: http://stackoverflow.com/q/47490393
tags question: http://stackoverflow.com/q/47385781
tags question: http://stackoverflow.com/q/47491098
tags question: http://stackoverflow.com/q/47473297
tags question: http://stackoverflow.com/q/47504501
tags question: http://stackoverflow.com/q/47490834
tags question: http://stackoverflow.com/q/47405091
tags question: http://stackoverflow.com/q/47430467
tags question: http://stackoverflow.com/q/47502126
tags question: http://stackoverflow.com/q/47393251
tags question: http://stackoverflow.com/q/47445732
tags question: http://stackoverflow.com/q/47401556
tags question: http://stackoverflow.com/q/47385700
tags question: http://stackoverflow.com/q/47499284
tags question: http://stackoverflow.com/q/47462114
tags question: http://stackoverflow.com/q/47417159
tags question: http://stackoverflow.com/q/47518131
tags question: http://stackoverflow.com/q/47440955
tags question: http://stackoverflow.com/q/47456848
tags question: http://stackoverflow.com/q/47477871
tags question: http://stackoverflow.com/q/47463652
tags question: http://stackoverflow.com/q/47389536
tags question: http://stackoverflow.com/q/47418871
tags question: http://stackoverflow.com/q/47512355
tag name: deep-learning
tags question: http://stackoverflow.com/q/47474869
tags question: http://stackoverflow.com/q/47449731
tags question: http://stackoverflow.com/q/47495190
tags question: http://stackoverflow.com/q/47418617
tags question: http://stackoverflow.com/q/47538391
tags question: http://stackoverflow.com/q/47490578
tags question: http://stackoverflow.com/q/47485373
tags question: http://stackoverflow.com/q/47477065
tags question: http://stackoverflow.com/q/47416861
tags question: http://stackoverflow.com/q/47458521
tags question: http://stackoverflow.com/q/47488598
tags question: http://stackoverflow.com/q/47403634

http://stackoverflow.com/a/47484408
has comment: http://stackoverflow.com/comment/81925583
type: Answer
has comment: http://stackoverflow.com/comment/81946283
has body: I got exactly the same problem (aggregating by an arbitrary period) and I just end up using pandas. pandas how to use groupby to group columns by date in the label?
score: 0
answers question: http://stackoverflow.com/q/47484336

http://stackoverflow.com/q/47507799
has comment: http://stackoverflow.com/comment/81973976
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/81973684
type: UnansweredQuestion
has body: I would like to select a subset of columns from a DataFrame without copying the data. From this answer it seems that it's impossible, if the columns have different dtypes. Can anybody confirm? For me, it seems that there must be a way as the feature is so essential. For example, df.loc[:, ['a', 'b']] produces a copy.
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81972033
has title: Selecting a subset of columns without copying
linked to: http://stackoverflow.com/q/23296282
has comment: http://stackoverflow.com/comment/81971293
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/81974003
has comment: http://stackoverflow.com/comment/81971395
answer count: 1
has answer: http://stackoverflow.com/a/47508254
has comment: http://stackoverflow.com/comment/84051292
favorite count: 0
has comment: http://stackoverflow.com/comment/81971683
type: Question
tagged with: indexing

http://stackoverflow.com/q/47430891
type: Question
has answer: http://stackoverflow.com/a/47430940
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: pymc3
score: 1
tagged with: pymc
tagged with: bayesian-networks
accepted answer: http://stackoverflow.com/a/47430940
has body: I'm new to pymc3 and tried to import the switch method with from pymc3 import switch, but I get this error: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-3-a48d5328031b&gt; in &lt;module&gt;() ----&gt; 1 from pymc3 import switch ImportError: cannot import name 'switch' Does anybody have an idea how to fix that?
has title: pymc3 import switch does not work

http://stackoverflow.com/a/61046244
score: 6
has comment: http://stackoverflow.com/comment/108077460
has comment: http://stackoverflow.com/comment/108094889
has comment: http://stackoverflow.com/comment/108106911
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/108095892
has body: The issue is caused by AWS Elastic Beanstalk with Python3.6, for some reason, on "eb deploy", pip ignores the restriction setup.py: install_requires = [ 'enum34&gt;1.1.0;python_version&lt;"3.4"', ] and tries to install enum34 regardless. The workaround I used was to create a pre-deployment hook which will delete the enum34 package and distribution info immediately after pip install -r requirements.txt during deployment. To achieve this: Create a file in your eb extensions folder. 00_fix_enum.config Put the following content on the file: files: "/opt/elasticbeanstalk/hooks/appdeploy/pre/uninstall_enum34.sh": mode: "000755" owner: root group: root content: | rm -f -r /opt/python/run/venv/lib/python3.6/site-packages/enum &amp;&amp; rm -f -r /opt/python/run/venv/lib/python3.6/site-packages/enum34-1.1.10.dist-info Commit your changes and run eb-deploy. The file uninstall_enum34.sh will be created in the /opt/elasticbeanstalk/hooks/appdeploy/pre/ folder which will then run during the pre deploymentment.
answers question: http://stackoverflow.com/q/47413574
downvote count: 0

http://stackoverflow.com/comment/82031582
comment on: http://stackoverflow.com/a/47537354
score: 0
type: Comment
type: AnswerComment
has text: but i do dataset = client.dataset(BQDATASET) where BQDATASET is a dataset name. So i expect to get True from my code. Not sure `create` is relevant here?

http://stackoverflow.com/q/47517899
tagged with: string
has title: How to Add/Replace/Delete Escape Characters in strings - Python
favorite count: 0
has answer: http://stackoverflow.com/a/47518301
tagged with: encoding
type: Question
tagged with: byte
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47518159
has comment: http://stackoverflow.com/comment/81991943
score: 2
has body: I have some problems regarding escape characters. Problem I: I have a string in the form of: String = "%C3%85" String is the representation of two bytes in UTF-8 encoding this char: "Å". Except: "\x" is replaced with "%". So I want to alter String to look like this: String = "\xC3\x85" Problem II: I have a String in the form: *String* = "\\x33" Now I want to convert it into the UTF-8 byte representation of that which should look like: String = b"\x33" How do I do that? Approaches I tried: I tried using the replace method: string.replace("%","\") -- wont work since \ escapes " string.replace("%","\\") -- wont work since this produces problem II string.replace("%","\x00").replace("00","") -- wont work since "\x00" is a char by its own. bytes(string.replace("%","\\") ) -- wont work since this basically comes down to problem II One approach that works but is way more work than seems to be needed is to create a dictionary with all characters in the form of: "%00" = "\x00" ... ... But well....this should be automatable since its basically just replacing % with x\ I am out of luck and couldnt find any help anywhere on the internet. lmgtfy wont help me either;) Thanks for any help!
answer count: 2
downvote count: 0
tagged with: utf-8
has comment: http://stackoverflow.com/comment/81992189

http://stackoverflow.com/comment/82009334
comment on: http://stackoverflow.com/a/47504374
score: 0
type: Comment
has text: That other issue was unrelated, and is fixed, so I've given you the answer :)
type: AnswerComment

http://stackoverflow.com/comment/87679693
comment on: http://stackoverflow.com/a/47505881
has text: Can you add an explanation of what as_strided is and how to use it? I read the documentation and I'm intimidated by the warning.
type: Comment
type: AnswerComment
score: 0

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/47499142
tags question: http://stackoverflow.com/q/47452166
tag name: decision-tree

http://stackoverflow.com/q/47428448
has comment: http://stackoverflow.com/comment/81811359
tagged with: python
has title: matplotlib show a expection?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47429712
upvote count: 0
answer count: 1
downvote count: 3
has body: I use matplotlib to plot the result of values in two arrays, but the result shows a point (0, 0) which is not in my array. The other points are correct but only this one. Below is my code. import math import numpy as np import matplotlib.pyplot as plt j=0 x=0.6 resx = np.zeros((100, 100)) rr=np.zeros((1, 100)) for r in np.linspace(2.4, 4, 100): rr[0,j] = r for i in range(0, 100): x = r * x * (1-x) resx[j,i] = x plt.plot(rr[0,:], resx[:,j], '.') j=j+1 plt.show()
has comment: http://stackoverflow.com/comment/81811742
favorite count: 0
type: Question
tagged with: matplotlib
score: -3
has answer: http://stackoverflow.com/a/47429712

http://stackoverflow.com/q/47427481
answer count: 0
has comment: http://stackoverflow.com/comment/81810672
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: I am building an application where I call a python process using child-process module which creates an Excel file and downloads it using req.download method.The process runs well in my local machine but when I move it to the Server,many times the connection gets timed out while downloading the file.Please help me to solve this problem.Here is the code of the process app.get('/RawReport',function(req,res){ console.log('Property........................'+req.param('property')) var result='' var month_picker=req.param('monthSelected') var py1 =spawn('python',[process.cwd()+'/routes/Reporting/Raw_Story_Report_03.py',req.param('property'),month_picker,global_user.name]); py1.stdout.on('data',function(data){ result=data.toString() // res.download(result) }); py1.stderr.on('data',function(data){ console.log('err====',data.toString()) }); py1.on('close',function(code){ var result_path=result.split('\n')[0] res.download(result_path) }) })
favorite count: 0
type: Question
score: 1
has title: Download Large file in nodejs
tagged with: python
tagged with: node.js
has comment: http://stackoverflow.com/comment/81810832

win32gui
type: Tag
tag name: win32gui
tags question: http://stackoverflow.com/q/47468388

http://stackoverflow.com/q/47523319
upvote count: 1
tagged with: grid
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47523393
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47523387
tagged with: python
tagged with: append
has answer: http://stackoverflow.com/a/47523569
has comment: http://stackoverflow.com/comment/82002982
has body: I am trying to write a function that reads a file, and appends the lines of a file into a list. For example a file that reads: hello goodbye should return the list: [["h","e","l","l","o"] ["g","o","o","d","b","y","e"]] I have created a helper function splitLine that takes as input, a string and would return a list of the letters in the string. For example "abc" would become ["a","b","c"] I am having trouble inserting new lines and stripping the "\r" and "\n" from the lists. Here is my code: def createGrid(filename): myFile = open(str(filename),"r") myGrid = [] for line in myFile: myLine = splitLine(line) myGrid.append(myLine) return myGrid
answer count: 3
score: 1
has title: Appending Lines from a File into a List
downvote count: 0
tagged with: file

http://stackoverflow.com/q/47510486
tagged with: matplotlib
tagged with: boxplot
has comment: http://stackoverflow.com/comment/81981905
tagged with: python
type: Question
answer count: 0
has title: 'hue' in seaborn plot and x-axis location
type: UnansweredQuestion
tagged with: seaborn
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81976682
favorite count: 0
has body: I have a dataset with 'Counts' from several 'Items' per animal, for totally 291 animals. The data has been acquired at days 4, 10,21 and 60, an (edited) df.to_dense() looks like this Animal Day Item Counts 0 04A 4 11 11 1 04A 4 12 6 2 04A 4 16 26 3 04A 4 20 28 4 04A 4 21 16 [...] 286 60C 60 18 43 287 60C 60 20 69 288 60C 60 21 93 289 60C 60 23 55 290 60C 60 24 114 I would like to plot the data nicely, with seaborn. For this I do sns.boxplot(data=df, x='Day', y='Counts') which gives me the plot below. Now I'd like to show the boxplots for the single animals and thought to just add the 'hue' parameter, like so: sns.boxplot(data=df, x='Day', y='Counts', hue='Animal'). The values are now nicely grouped, as I would have expected it, but they are not really aligned to the x-label. Maye I understand the hue parameter wrong, but I'd like to split the day-points into the different animals and show them (center-)aligned to the x-label. Any tips on how to achieve this?
score: 1

http://stackoverflow.com/a/47418145
answers question: http://stackoverflow.com/q/47417825
type: Answer
has comment: http://stackoverflow.com/comment/81792246
has comment: http://stackoverflow.com/comment/81790592
has comment: http://stackoverflow.com/comment/81791299
has comment: http://stackoverflow.com/comment/81790406
has comment: http://stackoverflow.com/comment/81790697
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: The substring PATHNAME: is part of the list of strings variable named HEADER. Therefore, you have to iterate through every individual string and match it with your substring, like this if what in s for s in HEADER, the updated code is given below: HEADER = ['ROAD_ID: R1.6', 'ROAD_TYPE: Curve', 'ARC_RADIUS: 1650.000000', 'SPIRAL_LEN1: 300.000000', 'SPIRAL_LEN2: 300.000000', 'SUPERELEVATION: 0.030000', 'CONTROL_POINT: 56551.970145 41423.581706 117.415152', 'VCURVE_LEN: 1298.247591', 'VCURVE_MIN: 20.000000', 'SLOPE1: 0.020632', 'SLOPE2: 0.019981', 'PATHNAME: Default Road', 'SPEED: 45.000000', 'NO_PASSING: FALSE', 'STORE_HPR: FALSE', 'NUM_POINTS: 130'] K_WIDTH = 'WIDTH: ' W_REC = ['PROFILE_POINT: 25.500 0.000', 'PROFILE_POINT: -25.500 0.00', 'WIDTH: 51.000', 'CENTER2LEFT: 25.500'] what = 'PATHNAME:' for n in HEADER: print n, type(n) if what in n: print '////////////////////' print 'Found:', what, type(n) if not K_WIDTH in HEADER: print 'Looking for:', what where = [HEADER.index(i) for i in HEADER if what in i] if (where): HEADER.insert(where[0], w_rec) else: print 'Not found', what
accepted answer of: http://stackoverflow.com/q/47417825

http://stackoverflow.com/q/47496704
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47496749
score: 4
has body: Say that if you had a class, and you defined it as: class A: pass And when you use the function: dir(A) Which returns all the methods and attributes the class contains: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] My question is, what are methods with a double underscore before and after them such as __class__, __delattr__, __dict__, __init__, called? I've assumed they were called constructor, but after doing research - it seems that term only refers to the __init__ function. Does anyone know if there's a specific category to call these methods by?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81948669
tagged with: oop
accepted answer: http://stackoverflow.com/a/47496749
tagged with: python
tagged with: naming
has title: What are the unique methods of a class called?
upvote count: 4
possible better answer: http://stackoverflow.com/a/47496748
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81948684
has answer: http://stackoverflow.com/a/47496748

http://stackoverflow.com/comment/81830539
score: 0
has text: Instead of a List Comprehension, it would have been enough to use a generator expression. Looks nearly the same, but has a possible difference on the running time and memory consumption.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47437476

http://stackoverflow.com/a/47525719
has body: You can find neighbors using scipy.ndimage.morphology.binary_dilation import numpy as np from scipy.ndimage import morphology a = np.array([[0,4,3,9,9,9], [4,4,2,2,2,9], [4,2,2,9,2,6], [4,2,2,2,6,8], [4,4,4,3,4,4]]) k = 2 # make mask eq = a==k # find greater neighbors (as mask) nbs = morphology.binary_dilation(eq) &amp; (a&gt;k) # translate to index minidx = np.argwhere(nbs &amp; (a == np.min(a[nbs]))) # now find neighbors' neighbors # pad original mask m,n = a.shape eqp = np.zeros((m+2, n+2), bool) eqp[1:-1,1:-1] = eq # generate offset vectors for the four major directions (up, down, left, right) # corrected for padding offsp = np.array([(0,1),(2,1),(1,0),(1,2)]) # without padding correction offs = offsp - 1# # for each minimum, find all (1-4) reference neighbors refidx = [i + offs[eqp[tuple((i+offsp).T)]] for i in minidx] print(minidx) print(refidx) # [[0 2] # [4 3]] # [array([[1, 2]]), array([[3, 3]])]
answers question: http://stackoverflow.com/q/47525074
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82009617
accepted answer of: http://stackoverflow.com/q/47525074
has comment: http://stackoverflow.com/comment/82009729
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/47426103
score: 1
downvote count: 0
has body: Just replace . with [\s\S] in your regex as shown below: &lt;div class=\"one\"&gt;[\s\S]*?&lt;\/div&gt; Click for Demo Explanation: &lt;div class=\"one\"&gt; - literally matches &lt;div class="one"&gt; [\s\S]*? - matches 0+ occurrences of any character(include the newline character), as few as possible &lt;\/div&gt; - literally matches &lt;/div&gt;
upvote count: 1
answers question: http://stackoverflow.com/q/47425374
has comment: http://stackoverflow.com/comment/81818885
type: Answer

http://stackoverflow.com/comment/81917987
comment on: http://stackoverflow.com/q/47481462
type: Comment
has text: @user1767754 I tried the various regex shown above in the code along re.iterall. for re.findall(r'\bword\b',review) I am not sure why no value is getting passed to the variable word
type: QuestionComment
score: 0

http://stackoverflow.com/q/47478864
type: AnsweredQuestion
has title: Sending emails with celery in Django project
accepted answer: http://stackoverflow.com/a/47557554
has answer: http://stackoverflow.com/a/47557554
tagged with: python
type: Question
has body: I can't understand how to send emails with Celery to real people. May be some one can help me? I can send mail to console with EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' . But how to configure settings.py file to send email for example to my gmail? If you have djproject with celery on github I want to see it to understand what i have to do. My github https://github.com/Loctarogar/Django-by-Example
score: 1
answer count: 1
tagged with: email
downvote count: 0
upvote count: 1
tagged with: django
favorite count: 0
tagged with: celery

http://stackoverflow.com/comment/81734221
type: Comment
score: 0
has text: No. Probably you should post more information. And your comment adds nothing new. Yes, you wrote that and it does not work. I just mentioned an abstraction-layer which is the core of all sklearn-parallelizations (in terms of this kind of parallelization; ignoring SIMD or OpenMP).
type: QuestionComment
comment on: http://stackoverflow.com/q/47390514

http://stackoverflow.com/q/47496882
answer count: 1
has comment: http://stackoverflow.com/comment/81951724
has answer: http://stackoverflow.com/a/47499624
type: Question
type: UnansweredQuestion
tagged with: database-migration
tagged with: django
has title: Django migrations old database, forgot one model before
tagged with: django-models
tagged with: python
has body: I have existing database/production system pre-migration support for Django. We did start to use Djangos migration 2 years back it turns out I did forget to install migrations for one model that now causes problems. 2 years back I had the following models; Location, Tool and a third Log that points to instances of Location and Tool. The 0001_inital.py for Log model has a dependency to Tool for 0001_inital but for Locations it points to _ first _ Now, today I am trying to get Location to use migration (so I later can add things to it, needed now) for the first time... Running makemigration Location works and generates a new clean migration directory and all, but then when doing migrate --fake I get the following django.db.migrations.exceptions.InconsistentMigrationHistory: Migration log.0001_initial is applied before its dependency locations.0001_initial on database 'default'. Understand this is caused by the mistake earlier by forgetting to get migrations done for Locations when we started to use this in Django - any ideas how to resolve this in a good way?
score: 0

http://stackoverflow.com/q/47401526
upvote count: 9
has body: Trying to use pyramid's auto arima function and getting nowhere. Importing the whole class: import pyramid stepwise_fit = auto_arima(df.Weighted_Price, start_p=0, start_q=0, max_p=10, max_q=10, m=1, start_P=0, seasonal=True, trace=True, error_action='ignore', # don't want to know if an order does not work suppress_warnings=True, # don't want convergence warnings stepwise=True) # set to stepwise I get error message: NameError: name 'auto_arima' is not defined Fine, then let's import that specific package from pyramid. from pyramid.arima import auto_arima --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa --------------------------------------------------------------------------- ImportError Traceback (most recent call last) in () 1 #trying to import pyramid ----> 2 from pyramid.arima import auto_arima /usr/local/lib/python2.7/site-packages/pyramid/arima/init.py in () 3 # Author: Taylor Smith 4 ----> 5 from .approx import * 6 from .arima import * 7 from .auto import * /usr/local/lib/python2.7/site-packages/pyramid/arima/approx.py in () 16 # and since the platform might name the .so file something funky (like 17 # _arima.cpython-35m-darwin.so), import this absolutely and not relatively. ---> 18 from pyramid.arima._arima import C_Approx 19 20 all = [ ImportError: numpy.core.multiarray failed to import After importing numpy, or even after just running the block again, I get this error message when running from pyramid.arima import auto_arima --------------------------------------------------------------------------- ImportError Traceback (most recent call last) in () 1 #trying to import pyramid ----> 2 from pyramid import arima /usr/local/lib/python2.7/site-packages/pyramid/arima/init.py in () 3 # Author: Taylor Smith 4 ----> 5 from .approx import * 6 from .arima import * 7 from .auto import * /usr/local/lib/python…
possible better answer: http://stackoverflow.com/a/54703540
answer count: 5
tagged with: pyramid-analytics
has answer: http://stackoverflow.com/a/47921173
tagged with: python
score: 9
has answer: http://stackoverflow.com/a/61072957
has answer: http://stackoverflow.com/a/51199561
accepted answer: http://stackoverflow.com/a/54408529
has answer: http://stackoverflow.com/a/54408529
has answer: http://stackoverflow.com/a/54703540
downvote count: 0
has title: Error importing auto_arima from pyramid
tagged with: data-science
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/47445137
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Unittest + Selenium - __init__() takes 1 positional argument but 2 were given
has answer: http://stackoverflow.com/a/47460821
tagged with: python
accepted answer: http://stackoverflow.com/a/47445297
has answer: http://stackoverflow.com/a/47445297
answer count: 2
possible better answer: http://stackoverflow.com/a/47460821
tagged with: super
has body: I'm working with unittest and selenium for the first time but thats also my first bigger code in python. I found some answers for this problem but there was no explaination for classes with __ init __ inheritance and method super().__ init __() TL;DR I have classes that inherits one by one. The first class StartInstance that creates chrome instance inherits from unittest.TestCase and the problem is with inheritance and super().init() in other classes, becouse when i remove it test normaly starts All looks like: class StartInstance(unittest.TestCase): @classmethod def setUpClass(cls): pass class A(StartInstance): def __init__(self): super().__init__() adding variables etc to init class B(A): def __init__(self): super().__init__() adding variables etc to init class C(A): def __init__(self): super().__init__() adding variables etc to init class PrepareTests(B, C, D): def all tests(self): self.tests_B self.tests_C self.tests_D class Tests(PrepareTests): def test_click: click() all_tests() #and finally somewhere a test runner suite = loader.loadTestsFromTestCase(Tests) runner.run(suite()) #when i run this i get this error and it only raises when i add classes with their own init #heh TL;DR almost as long as normal text sorry :( ALL: FULL ERROR MESSAGE: Traceback (most recent call last): File "xyz\main_test.py", line 24, in &lt;module&gt; runner.run(suite()) File "xyz\main_test.py", line 11, in suite about_us = loader.loadTestsFromTestCase(AboutUs) File "xyz\Python36\lib\unittest\loader.py", line 92, in loadTestsFromTestCase loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) File "xyz\Python36\lib\unittest\suite.py", line 24, in __init__ self.addTests(tests) File "xyz\Python36\lib\unittest\suite.py", line 57, in addTests for test in tests: TypeError: __init__() takes 1 positional argument but 2 were given Thats my code: I have a settings.py file with variables in dict of dicts accessed by settings.xyz["layer1"]["KEY"] setup.py - setup class for selenium cla…
score: 2
upvote count: 2
downvote count: 0
tagged with: selenium
tagged with: inheritance
tagged with: unit-testing

http://stackoverflow.com/comment/81981808
type: Comment
has text: you can go one step further with numpy. It accepts an array as a 'projection' of another array.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47512795

http://stackoverflow.com/q/47484572
has comment: http://stackoverflow.com/comment/81923990
has body: I have installed cufflinks using pip install however when I try to import it is says No module named 'cufflinks' What can I do? PS python 3.6
has answer: http://stackoverflow.com/a/47484601
has comment: http://stackoverflow.com/comment/81924030
tagged with: python
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has title: Python Error (Importing Module)

http://stackoverflow.com/comment/82033166
comment on: http://stackoverflow.com/a/47536983
has text: You can continue using the numpy functions as long as they are do with any operation to the array. For eg, np.sum(), np.argmax(), np.exp(), np.log() etc. For the backend, you need tensors which can be updated and used in the model. keras.backend lets you do that. keras.backend.reshape() for instance, returns a tensor which is something that the backend (say tensorflow) understands. I strongly suggest you read the documentation and the samples to get a better idea. Hope this helps.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47474582
downvote count: 0
answers question: http://stackoverflow.com/q/47472123
has body: The last method here(1) is suitable for any dimensional sphere: To pick a random point on a sphere: - generate N Gaussian random variables x1,x2..xN - get norm of x[i] L = Sqrt(x1*x1 + x2*x2 + .. + xn*xn) ux1 = x1 / L ux2 = x2 / L ... Then the distribution of the vectors ux[i] is uniform over the surface SN-1 To provide uniform distribution in the ring: - generate uniform random in range R_NPow = RandomUniform(R_InnerN, R_OuterN) and get radius (like this 2D case) R = R_NPow1/N then calculate resulting point coordinates: res_x1 = R * ux1 res_x2 = R * ux2 ... res_xn = R * uxn (1) Muller, M. E. "A Note on a Method for Generating Points Uniformly on -Dimensional Spheres." Comm. Assoc. Comput. Mach. 2, 19-20, Apr. 1959.
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/a/47405846
has comment: http://stackoverflow.com/comment/81812004
answers question: http://stackoverflow.com/q/47405393
has body: Why not like this? text = re.sub(r"&gt;((?:[^&lt;&gt;\d]|\d{2,})*)&lt;", r"\1", text) (?:[^&lt;&gt;\d]|\d{2,})* matches either any character except angle brackets or digits ([^&lt;&gt;\d]) or any digits as long as there are at least two (\d{2,}), repeatedly (*).
type: Answer
has comment: http://stackoverflow.com/comment/81767133
has comment: http://stackoverflow.com/comment/81784102
has comment: http://stackoverflow.com/comment/81823902
score: 0
has comment: http://stackoverflow.com/comment/81792026

http://stackoverflow.com/q/47405659
has answer: http://stackoverflow.com/a/47421828
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81765133
has title: Trouble with datetime
tagged with: datetime-format
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81765267
tagged with: join
has comment: http://stackoverflow.com/comment/81765224
tagged with: strptime
has comment: http://stackoverflow.com/comment/81765526
has comment: http://stackoverflow.com/comment/81764860
has comment: http://stackoverflow.com/comment/81765047
type: Question
has body: Yet another silly programming attempt on my part. This beauty searches through a file (that part was simplified in the example, no issues with that) for a start date and end date of something and tries to convert it to local time for nefarious purposes. Here's what I managed to put together ( remember, newbie coder here): #will need it later# import datetime #this part simulates other code that opens a #file for me. The format of date and time #is preserved mail_body = """ Maintenance Date/Time (Local): Nov 17 2017 00:01 CET - Nov 17 2017 06:00 CET Maintenance Date/Time (GMT): Nov 16 2017 23:30 GMT - Nov 17 2017 05:00 GMT""" #Turning it all into list to be able to get important # bits of text by using index later word_list = mail_body.split() # A dictionary to transform months into numbers months = { "Jan":1,"Feb":2,"Mar":3,"Apr":4, "May":5,"Jun":6,"Jul":7,"Aug":8, "Sep":9,"Oct":10,"Nov":11,"Dec":12 } #Various lists start_date = [] start_date_local = [] # Will need that to convert GMT to my local GMT + 1 add_hour = datetime.timedelta(hours = 1) gmt = word_list.index("(GMT):") #Grabbing parts of the text I need by selecting #index numbers def get_gmt(x): start_date.extend(word_list[gmt + 1:gmt + 5]) end_date.extend(word_list[gmt + 7:gmt + 11]) #print (",".join(start_date)) return (",".join(start_date)) #Attempting to add +1 hour in a safe way, program #needs to know it's working with dates def start_local(x): #Where the pain starts.....must be string, not list #Not really sure how to get around that start_date_local = datetime.datetime.strptime(start_date, "%m-%d-%Y %H:%M") start_date_local = start_date_local + add_hour return start_date_local #Calling functions get_gmt(word_list) start_date start_local(start_date) The issue starts with the .strptime(). I am unable to convert start_date into format that strptime will accept. Yes, I have read many answers on those boards, also read the documentation for strptime (not that I understand it). .join() didn't seem to help,…
has comment: http://stackoverflow.com/comment/81765243
has answer: http://stackoverflow.com/a/47406331
has comment: http://stackoverflow.com/comment/81765205

http://stackoverflow.com/a/59993939
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47414426
has body: It turns out that the NBT library only supports .mcr region files which have been replaced by .mca files about 6 years ago. However, mcedit is written in Python and supports those files. Due the changes in the Minecraft save format, the interpretation of the content needs to be adjusted though, but the files can be successfully read.
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/71224174
score: 2
has body: If you want to save it as None in case when no data provided in the form for that field. You can do it with empty_value parameter to CharField (Django Docs): field_name = forms.CharField(required=False, empty_value=None) Note: You should save null to a char field ONLY if you want to distinguish between null and &quot;&quot; (blank) on that field. Otherwise, a nullable char field is not much recommended.
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47422491
type: Answer

http://stackoverflow.com/comment/81803554
has text: With a `numpy` array, `tolist()` or `item()` (for one element) is the best way of getting either a list or native Python object. `astype` just changes the array `dtype`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47423930
score: 1

http://stackoverflow.com/a/47521166
downvote count: 0
upvote count: 1
has body: I solved the issue by changing the way I was testing and by changing the way I was importing the Celery configuration. Initially, I was setting the configuration by importing a Django settings object: app = Celery('groot') app.config_from_object('django.conf:settings', namespace='CELERY') But this was ignoring the settings with the CELERYD_... prefix. Thus I used the new notation and called the following method: app.conf.update( task_soft_time_limit=30, task_time_limit=120, ) I also changed from testing this in the Django test environment to spinning up an actual Celery worker and sending the task to the worker. If someone would supply a solution for how to test the timeout settings in the unit test it would be much appreciated.
accepted answer of: http://stackoverflow.com/q/47517063
answers question: http://stackoverflow.com/q/47517063
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81998455
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47438839
has text: I have no idea. I never had the chance to work with this notation.
score: 0

http://stackoverflow.com/a/47465589
type: Answer
has body: You can use ast.literal_eval: import ast pObjects = map(ast.literal_eval, pObjects)
answers question: http://stackoverflow.com/q/47465579
downvote count: 0
has comment: http://stackoverflow.com/comment/81886008
upvote count: 1
score: 1

http://stackoverflow.com/comment/81935291
type: AnswerComment
has text: Thanks for this, this is very similar to what I've come up with. However, this solution is still partial, since a call still has to be made after plotting. I think there must be a way to define the way future legend-related artists are to be managed.
type: Comment
comment on: http://stackoverflow.com/a/47489824
score: 0

http://stackoverflow.com/comment/82009049
comment on: http://stackoverflow.com/q/47525074
type: Comment
type: QuestionComment
has text: Yeah, `binary_dilation` will probably be faster as it doesn't require allocating extra memory for the padded array. That's why I asked about the edges - if I didn't have to `pad`, using windowed views would probably be faster.
score: 0

http://stackoverflow.com/comment/81807085
comment on: http://stackoverflow.com/a/47426033
type: Comment
score: 0
type: AnswerComment
has text: Perfect! That did it. Just one more thing, I am running this loop over multiple files, so essentially this for loop gets run multiple times but I think my code only prints the outputs to the for loop once (on the text file), the terminal has as many for loops as there are files in my dir since I am looping over them. What would a reason for this not being reflected in the out.txt? Thanks :)

http://stackoverflow.com/comment/82067769
type: AnswerComment
comment on: http://stackoverflow.com/a/47524055
type: Comment
score: 0
has text: Thanks, I'm giving it a try with Selenium and Chrome webdriver.

http://stackoverflow.com/comment/81916420
has text: Hey! Sorry for the delay. In the end, I want to obtain a single dataframe, with some extra columns that are filled with numbers. The output is too big for this comment I will update the main post.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47480456
type: QuestionComment

http://stackoverflow.com/comment/81779996
type: QuestionComment
comment on: http://stackoverflow.com/q/47413054
score: 1
type: Comment
has text: Have you tried increasing the learning rate ? 0.0001 is rather small. And what kind of loss values do you get ?

http://stackoverflow.com/q/47424245
has body: When using web.whatsapp.de one can see that the link to a recieved image may look like this: blob:https://web.whatsapp.com/3565e574-b363-4aca-85cd-2d84aa715c39 If the link is copied in to an address window it will open up the image, however - if "blob" is left out - it will simply open a new web whatsapp window. I am trying to download the image displayed by this link. But using common techniques such as using request, or urllib.request or even BeautifulSoup always struggle at one point: The "blob" at the beginning of the url will throw an error. These answers Download file from Blob URL with Python will trhow either the Error URLError: &lt;urlopen error unknown url type: blob&gt; or the Error InvalidSchema: No connection adapters were found for 'blob:https://web.whatsapp.com/f50eac63-6a7f-48a4-a2b8-8558a9ffe015' (using BeatufilSoup) Using a native approach like: import requests url = 'https://web.whatsapp.com/f50eac63-6a7f-48a4-a2b8-8558a9ffe015' fileName = 'test.png' req = requests.get(url) file = open(fileName, 'wb') for chunk in req.iter_content(100000): file.write(chunk) file.close() Will simply result in the same error as using BeautifulSoup. I am controlling Chrome using Selenium in Python, however I was unable to download the image correctly using the provided link.
answer count: 3
has answer: http://stackoverflow.com/a/47425305
tagged with: python
type: Question
possible better answer: http://stackoverflow.com/a/47424339
has comment: http://stackoverflow.com/comment/81804587
linked to: http://stackoverflow.com/q/39517522
has comment: http://stackoverflow.com/comment/81804405
has answer: http://stackoverflow.com/a/47424339
downvote count: 0
has title: How to download an image with Python 3/Selenium if the URL begins with "blob:"?
tagged with: selenium
tagged with: url
tagged with: javascript
score: 13
has answer: http://stackoverflow.com/a/49705310
favorite count: 0
tagged with: whatsapp
upvote count: 13
has comment: http://stackoverflow.com/comment/81804477
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47425305

http://stackoverflow.com/q/47494670
tagged with: differential-equations
upvote count: 2
has answer: http://stackoverflow.com/a/47494768
has comment: http://stackoverflow.com/comment/81944635
has title: Adding Results to a List and Setting up a for-loop
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81944616
has comment: http://stackoverflow.com/comment/81944715
possible better answer: http://stackoverflow.com/a/47495089
has comment: http://stackoverflow.com/comment/81944510
has answer: http://stackoverflow.com/a/47495089
has body: For a school assignment, I am coding an algorithm that computes slopes using the Euler method. In part of it, I have a for loop that will repeat a pattern of equations until the end result is met. What I need is a way to add each result to a list and then afterwards plot each item in the list. I also need some help setting up the for-loop if possible. Here's what I have, keeping in mind I am very inexperienced at coding (please bear with me) stpsz = input ("Define "h" Value (step size)") tfinal = input ("Define Final "T" Value (stopping place)") xnow = input ("Define "X0" as a Starting Value") t = 0 while t &gt; tfinal t = t + 1 slopenow = (xnow * (1-xnow)) #Save slopenow (as a number, not variable) to a list of slopes ( I don't understand how to make a list like this) #Save xnow (as a number, not variable) to a list of xs) xnext = (slopenow * stpsz)+(xnow) xnext = x now #repeat while-loop until tfinal is reached) I greatly appreciate whatever help you all can give.
tagged with: python
tagged with: calculus
score: 2
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47494768
tagged with: for-loop

http://stackoverflow.com/comment/81885345
has text: Possible duplicate of [How do I find the formatting for a subset of text in an Excel document cell](https://stackoverflow.com/questions/12371787/how-do-i-find-the-formatting-for-a-subset-of-text-in-an-excel-document-cell)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47465312

http://stackoverflow.com/q/47490033
downvote count: 0
has title: Why I am getting a special character printed after the recursive DFS?
accepted answer: http://stackoverflow.com/a/47490058
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81935391
has body: I have a simple toy code for Depth First Search, But why I am getting a % after the print? # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def dfs(t): if t==None: print("",end="") else: print(t.val,end="") dfs(t.left) dfs(t.right) t=TreeNode(1) t.left=TreeNode(2) t.right=TreeNode(3) t.left.left=TreeNode(4) t.left.right=TreeNode(5) t.right.left=TreeNode(6) t.right.right=TreeNode(7) dfs(t) Output: 1245367%
tagged with: algorithm
tagged with: python
tagged with: depth-first-search
has answer: http://stackoverflow.com/a/47490058
type: AnsweredQuestion
tagged with: recursion
score: 2
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/81935363

http://stackoverflow.com/comment/81868354
score: 14
type: Comment
comment on: http://stackoverflow.com/a/47456679
type: AnswerComment
has text: Also, funny that whenever someone asks "how to do this simple thing in a pythonic way", everything turns into "how to do it in least microseconds per loop"

http://stackoverflow.com/q/47482872
has body: On git bash, I receive a command not found message for python, r and nano. I am on Windows 10. I do not know what I am doing wrong. I type r --version python --version nano --version and they all return command not found. I read something that had me try alias python='winpty python.exe' and it renamed python, but when I tried touch .bashrc it returned touch: command not found I followed the instructions in a Github course, PS239T. I have been fortunate, except for getting these three programs to work. I tried build/console.exe c:/Python36/python.exe and it returned build/console.exe: No such file or directory I tried PATH=$PATH:/c/Python36/ $ export PATH="$PATH:/c/Python36" echo 'export PATH="$PATH:/c/Python36"' &gt; .profile and nothing. I got Python 64-bit via Anaconda. I tried setting up the Python 3.4 environment conda create –n py34 python=3.4 anaconda ./python name_of_your_python_script.py nothing. which python got me a huge directory path: which: no python in (/c/Users/Edward/bin:/mingw64/bin:/usr/local/bin:usr /bin:/bin:/mingw64/bin:/usr/bin:c/user/Edward/bin:/c/Program Files (X86)/Intel/ 1CLS client:/c/Program Files/Intel/1CLS Client:/c/Windows /System32:/C/Windows:/C/Windows/Sytem32/Wbem:/c/Windows/System32 WindowsPowerShell/V1.0:/c/Program Files/Intel/Intel(R) Management Engine Components/Dal:/c/Program Files/Intel/Intel(R) Management Engine Components/IPT:/c/Program Files (x86)/Intel/Intel(R) magament Engine Components/IPT:/c/Program Files (X86)/Intel/Intel(R) Management Engine Components/IPT:/c/WINDOWS/Syste,32/Wbem:/c/WINDOWS/System32 /WindowsPowerShell/v1.0:/c/Program Files (x86)/Rand McNally/RNDDock /GtkSharp/2.12/bin/:/c/Program Files d/AppData/Local/Mircosoft /WindowsApps:/c/Users/Edward/AppData/Local/Pandoc:/usr/bin/vendor_perl: /usr/bincore_perl:/c/python36 I would have just put up the screenshot or copied and pasted it, but I do not know how. I am sure I made an error somewhere. I get the same type of results when I try to figure out what is goi…
tagged with: development-environment
accepted answer: http://stackoverflow.com/a/47483274
tagged with: environment-variables
has answer: http://stackoverflow.com/a/47483274
downvote count: 0
answer count: 1
has title: bash: 'command not found' for python, r and nano
has comment: http://stackoverflow.com/comment/81938413
favorite count: 0
type: Question
tagged with: path
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion

javascript
tags question: http://stackoverflow.com/q/47450002
tags question: http://stackoverflow.com/q/47396494
tags question: http://stackoverflow.com/q/47518835
tags question: http://stackoverflow.com/q/47493369
tags question: http://stackoverflow.com/q/47517922
tags question: http://stackoverflow.com/q/47497809
tags question: http://stackoverflow.com/q/47464406
tags question: http://stackoverflow.com/q/47386118
tags question: http://stackoverflow.com/q/47449241
tags question: http://stackoverflow.com/q/47481819
tags question: http://stackoverflow.com/q/47460759
tags question: http://stackoverflow.com/q/47435918
tags question: http://stackoverflow.com/q/47496470
tags question: http://stackoverflow.com/q/47495643
tags question: http://stackoverflow.com/q/47447236
tags question: http://stackoverflow.com/q/47502496
tags question: http://stackoverflow.com/q/47527454
tags question: http://stackoverflow.com/q/47437760
tags question: http://stackoverflow.com/q/47517016
tags question: http://stackoverflow.com/q/47497930
tags question: http://stackoverflow.com/q/47435230
tags question: http://stackoverflow.com/q/47439310
tags question: http://stackoverflow.com/q/47460593
tags question: http://stackoverflow.com/q/47515137
tag name: javascript
tags question: http://stackoverflow.com/q/47467582
tags question: http://stackoverflow.com/q/47483103
tags question: http://stackoverflow.com/q/47451704
tags question: http://stackoverflow.com/q/47414575
tags question: http://stackoverflow.com/q/47538130
tags question: http://stackoverflow.com/q/47413977
tags question: http://stackoverflow.com/q/47437936
tags question: http://stackoverflow.com/q/47487014
tags question: http://stackoverflow.com/q/47391823
tags question: http://stackoverflow.com/q/47508553
tags question: http://stackoverflow.com/q/47540053
tags question: http://stackoverflow.com/q/47460642
tags question: http://stackoverflow.com/q/47433198
tags question: http://stackoverflow.com/q/47483184
tags question: http://stackoverflow.com/q/47525825
tags question: http://stackoverflow.com/q/47529218
tags question: http://stackoverflow.com/q/47444541
tags question: http://stackoverflow.com/q/47410643
tags question: http://stackoverflow.com/q/47476463
tags question: http://stackoverflow.com/q/47487498
tags question: http://stackoverflow.com/q/47443714
type: Tag
tags question: http://stackoverflow.com/q/47507144
tags question: http://stackoverflow.com/q/47514386
tags question: http://stackoverflow.com/q/47485792
tags question: http://stackoverflow.com/q/47518719
tags question: http://stackoverflow.com/q/47389635
tags question: http://stackoverflow.com/q/47410305
tags question: http://stackoverflow.com/q/47466722
tags question: http://stackoverflow.com/q/47424245
tags question: http://stackoverflow.com/q/47416061
tags question: http://stackoverflow.com/q/47534396

http://stackoverflow.com/q/47412460
accepted answer: http://stackoverflow.com/a/47503081
score: 5
has comment: http://stackoverflow.com/comment/81923151
has answer: http://stackoverflow.com/a/47503081
answer count: 1
downvote count: 0
has title: binding key event in python using ctypes function
has comment: http://stackoverflow.com/comment/81955269
tagged with: keyboard
favorite count: 0
type: Question
tagged with: linux
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/81924918
has body: I have been trying to use python to bind my customize event to keyboard event with specific event code number like below ctypes.windll.user32.keybd_event('0x24',0,2,0) but as you already know windll the library only worked on Windows OS. how can I do something like this in Linux machines? I read about CDLL('libc.so.6') but I can't figure it out if this library is helpful or not? is there another way to set keypress listener in OS level with python using the virtual key code?
type: AnsweredQuestion

http://stackoverflow.com/q/47421305
downvote count: 0
upvote count: 1
tagged with: python
has body: I have a large numpy array, with each row containing a dict of words, in a similar format to below: data = [{'a': 1, 'c': 2}, {'ba': 3, 'a': 4}, ... } Could someone please point me in the right direction for how would I go about computing the sum of all the unique values of the dicts in each row of the numpy array? From the example above, I would hope to obtain something like this: result = {'a': 5, 'c': 2, 'ba': 3, ...} At the moment, the only way I can think to do it is iterating through each row of the data, and then each key of the dict, if a unique key is found then append it to the new dict and set the value, if a key that's already contained in the dict is found then add the value of that key to the key in the 'result'. Although this seems like an inefficient way to do it.
linked to: http://stackoverflow.com/q/11290092
favorite count: 0
possible better answer: http://stackoverflow.com/a/47421403
has comment: http://stackoverflow.com/comment/81797147
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47421403
has comment: http://stackoverflow.com/comment/81797073
has answer: http://stackoverflow.com/a/47421411
score: 1
has title: Computing the sum of all unique values in a numpy array containing rows of dicts
type: Question
accepted answer: http://stackoverflow.com/a/47421411
answer count: 2
linked to: http://stackoverflow.com/q/16458340
has comment: http://stackoverflow.com/comment/81797260

http://stackoverflow.com/comment/81900143
type: QuestionComment
comment on: http://stackoverflow.com/q/47472864
has text: `for i in rows():`. You need parenthesis to call the function, not brackets
score: 1
type: Comment

http://stackoverflow.com/q/47515353
linked to: http://stackoverflow.com/q/16909380
has title: How to get table names from SQL using select_parser.py from pyparsing?
linked to: http://stackoverflow.com/q/39259647
tagged with: python
type: Question
tagged with: pyparsing
accepted answer: http://stackoverflow.com/a/47545802
has answer: http://stackoverflow.com/a/47545802
answer count: 1
linked to: http://stackoverflow.com/q/39212886
type: AnsweredQuestion
score: 0
has body: When I take select_parser.py from pyparsing, and run it with pyparsing 2.2.0 using this code: query="select z.a, b from test_table left join test2_table where 1=1 and b in (select bb from foo)" for key, val in select_stmt.parseString(query, parseAll=True).items(): print "%s: %s" % (key, val) I get $ python select_parser.pyparsing.py where_expr: [['1', '=', '1'], 'AND', ['b', 'IN', ['SELECT', 'bb', 'FROM', 'foo']]] from: [['test_table', ['LEFT', 'JOIN'], 'test2_table', []]] columns: [['z.a'], ['b']] Although there is a named element "table" in the original definition: single_source = ( (Group(database_name("database") + "." + table_name("table*")) | table_name("table*")) + there is no dict key that comes out with the name "table". Perhaps the "from" element consumed things first? I don't understand the exact logic of how the named elements get populated, and I haven't gotten a clear idea from reading the docs (several talks, etc.). How can I use select_parser.py to get all the table names in a SQL query? Note: the right answer here is a list (or set): test_table, test2_table, foo. I could go through "from" and ditch lists, but that seems hacky, I don't know if it would work, and it doesn't seem like how pyparsing is supposed to work. I see this question, this one, and this one, but I don't understand how they help here.

http://stackoverflow.com/a/47510242
has comment: http://stackoverflow.com/comment/81977495
has comment: http://stackoverflow.com/comment/81977491
type: Answer
has comment: http://stackoverflow.com/comment/81976160
has comment: http://stackoverflow.com/comment/81976711
has comment: http://stackoverflow.com/comment/81977511
has comment: http://stackoverflow.com/comment/81977277
answers question: http://stackoverflow.com/q/47510207
has comment: http://stackoverflow.com/comment/81976782
has comment: http://stackoverflow.com/comment/81977413
score: 2
has comment: http://stackoverflow.com/comment/81976653
upvote count: 2
has body: You can use: #if necessary #df = df.set_index('Index') df = df.apply(lambda x: pd.Series(x.dropna().values), axis=1).iloc[:, :4] print (df) 0 1 2 3 Index 1991-12-31 100.000 100.000 100.000 89.123 1992-01-31 98.300 101.530 100.000 92.342 1992-02-29 100.230 98.713 97.602 NaN 1992-03-31 102.060 93.473 98.123 NaN 1992-04-30 102.205 107.755 94.529 94.529 Or for better performance use numpy - working with requirement there are at least 4 non values per row: a = df.values df = pd.DataFrame(a[~np.isnan(a)].reshape(a.shape[0],-1)[:, :4], index=df.index) Timings: Index Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 0 1991-12-31 100.0 100.000 100.000 89.123 NaN NaN NaN NaN 1 1992-01-31 98.3 101.530 100.000 NaN 92.342 NaN NaN NaN 2 1992-02-29 NaN 100.230 98.713 97.602 NaN NaN NaN 1.0 3 1992-03-31 NaN NaN 102.060 93.473 98.123 NaN NaN 1.0 4 1992-04-30 NaN 102.205 107.755 94.529 94.529 NaN NaN NaN df = df.set_index('Index') df = pd.concat([df] * 10000, ignore_index=1) In [260]: %timeit pd.DataFrame(justify(df.values, invalid_val=np.nan, axis=1, side='left')[:,:4]) 100 loops, best of 3: 6.78 ms per loop In [261]: %%timeit a = df.values ...: pd.DataFrame(a[~np.isnan(a)].reshape(a.shape[0],-1)[:, :4], index=df.index) ...: 100 loops, best of 3: 2.11 ms per loop In [262]: %timeit pd.DataFrame(np.sort(df.values, axis=1)[:, :4], columns=np.arange(1, 5)).add_prefix('Col') 100 loops, best of 3: 5.28 ms per loop In [263]: %timeit pd.DataFrame(mask_app(df.values)[:,:4]) 100 loops, best of 3: 8.68 ms per loop
downvote count: 0
has comment: http://stackoverflow.com/comment/81977645
has comment: http://stackoverflow.com/comment/81976768
has comment: http://stackoverflow.com/comment/81977306
has comment: http://stackoverflow.com/comment/81977560

http://stackoverflow.com/q/47497652
favorite count: 0
type: Question
has body: I am trying to install hmmlearn however I am having issues. My version of python, Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) I have checked that my pip is up to date as well. c:\users\xxx\pip install c:\users\xxx\documents\code\python\hmmlearn-0.2.0-cp35-cp35m-win32.whl I get the error message hmmlearn-0.2.0-cp35-cp35m-win32.whl is not a supported wheel on this platform I have also tried the file hmmlearn-0.2.0-cp35-cp35m-win_amd64 and get the same error message. How do I install hmmlearn? Update Last week I downloaded PyCharm on my computer have no idea if this will have created an issue?
has title: trying to install hmmlearn but getting is not a supported wheel on this platform
type: UnansweredQuestion
tagged with: pip
tagged with: python
answer count: 0
tagged with: hmmlearn
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82009151
has text: ehehe you get it ;) I wanted to mix too many things. Your solution, after turning off the piece of code in the other question, is solved. Many many thanks!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47499019
score: 0

http://stackoverflow.com/comment/82324244
has text: ok so it means it is gaussian. i wonder how convoution with guassian kernels help in separating image features ....
comment on: http://stackoverflow.com/a/47628845
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81906527
type: QuestionComment
comment on: http://stackoverflow.com/q/47475354
has text: As a reminder, pandas really doesn't support putting nonscalar entries in cells. Unless this is the very last step in your process, you're likely to encounter some mysterious behaviour.
score: 0
type: Comment

http://stackoverflow.com/a/49956549
answers question: http://stackoverflow.com/q/47479225
has body: Try the below: Portfolio Variance portfolio_variance=np.dot(weights.T,np.dot(log_returns.cov()*252,weights)) Portfolio Volatility portfolio_vol = np.sqrt(np.dot(weights.T,np.dot(log_returns.cov()*252,weights)))
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47512770
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: spyder
has body: I have some questions about spyder 3.2.4 ide for python: The "sidebar" (to the right of the main code-window) which marks all lines with warnings, all lines with todo etc with a small colored marker. Can I set these colors? Can I disable which ones to show? Can I "smart rename" a variable like in other IDEs? I mean not just text replace, but actually make sure i just rename the selected variable (all occurances and nothing but it) and not just text matching a string i type in like i would in "word". Can I list all occurances of a variable like in other IDEs? Lets say I have a list called "combinedAreas" and want to list all the uses of that variable, preferably also being ablo to click a line and jump to that line. Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/47516219
score: 1
downvote count: 0
answer count: 1
tagged with: ide
upvote count: 1
has title: spyder IDE sidebar, rename, find all occurances?

http://stackoverflow.com/comment/81961415
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47502554
has text: @Loïc I'm avoiding using a database as the data is ephemeral and would just lead to an unnecessarily high amount of INSERT and DELETE operations. A message broker sounds useful for a lot of continuous messages between php and python, but overly complex for this particular problem.
score: 0

http://stackoverflow.com/q/47453268
tagged with: mpi
has answer: http://stackoverflow.com/a/47455541
has body: I recently updated all the pip packages I have installed and I can no longer import mpi4py. If I try to load it I get an error ImportError: No module named mpi4py, both in interactive mode and when running a script. (It also happens for both python 2.7 and python 3.) (If it's relevant I'm still using OS X Yosemite.) running $ python -c "import mpi4py; print(mpi4py.__file__)" the output is: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: No module named mpi4py` and the output from pip show -f mpi4py is: Name: mpi4py Version: 3.0.0 Summary: Python bindings for MPI Home-page: https://bitbucket.org/mpi4py/mpi4py/ Author: Lisandro Dalcin Author-email: dalcinl@gmail.com License: BSD Location: /usr/local/lib/python2.7/site-packages Requires: Files: mpi4py-3.0.0.dist-info/DESCRIPTION.rst,mpi4py-3.0.0.dist-info/INSTALLER,mpi4py-3.0.0.dist-info/METADATA,mpi4py-3.0.0.dist-info/RECORD,mpi4py-3.0.0.dist-info/WHEEL,mpi4py-3.0.0.dist-info/metadata.json,mpi4py-3.0.0.dist-info/top_level.txt,mpi4py/MPI.pxd,mpi4py/MPI.so,mpi4py/__init__.pxd,mpi4py/__init__.py,mpi4py/__init__.pyc,mpi4py/__main__.py,mpi4py/__main__.pyc,mpi4py/bench.py,mpi4py/bench.pyc,mpi4py/dl.so,mpi4py/futures/__init__.py,mpi4py/futures/__init__.pyc,mpi4py/futures/__main__.py,mpi4py/futures/__main__.pyc,mpi4py/futures/_base.py,mpi4py/futures/_base.pyc,mpi4py/futures/_lib.py,mpi4py/futures/_lib.pyc,mpi4py/futures/aplus.py,mpi4py/futures/aplus.pyc,mpi4py/futures/pool.py,mpi4py/futures/pool.pyc,mpi4py/futures/server.py,mpi4py/futures/server.pyc,mpi4py/include/mpi4py/mpi.pxi,mpi4py/include/mpi4py/mpi4py.MPI.h,mpi4py/include/mpi4py/mpi4py.MPI_api.h,mpi4py/include/mpi4py/mpi4py.h,mpi4py/include/mpi4py/mpi4py.i,mpi4py/libmpi.pxd,mpi4py/mpi.cfg,mpi4py/run.py,mpi4py/run.pyc If I run python -c "import sys; print(sys.path)" I get: ['', '$HOME', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib…
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/81862780
has comment: http://stackoverflow.com/comment/81862509
score: 2
has comment: http://stackoverflow.com/comment/81861732
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81863421
has comment: http://stackoverflow.com/comment/81861430
accepted answer: http://stackoverflow.com/a/47455541
upvote count: 2
answer count: 1
downvote count: 0
has title: Python package not importing after update on Mac OS X
has comment: http://stackoverflow.com/comment/81862861
favorite count: 0
has comment: http://stackoverflow.com/comment/81863041
has comment: http://stackoverflow.com/comment/81862569
type: Question

http://stackoverflow.com/comment/82048638
score: 2
comment on: http://stackoverflow.com/q/47502650
type: Comment
type: QuestionComment
has text: What @alfasin meant is that you ask about "_prime_" factors but your code doesn't check whether a number _is_ prime or not. Some feedback: while you showed your code (thank you) the (scarce) textual explanations are unclear, as you can see by comments. You got great answers for this question, but in the future try to imagine how things read for strangers who have no idea what you are doing. Writing good questions isn't easy. [Stackoverflow help](https://stackoverflow.com/help) has useful pages (for instance, [how to ask](https://stackoverflow.com/help/how-to-ask)), and links to more.

http://stackoverflow.com/a/47460725
answers question: http://stackoverflow.com/q/47460240
accepted answer of: http://stackoverflow.com/q/47460240
type: Answer
score: 2
has body: Binary file, but please, be careful with the format of data that you are saving. If possible, reduce the width of each variable that you are using. For example, do you need to save decimal or float, or you can have just 16 or 32 bit integer? Further, yes, you may apply some of the compression scheme to compress the data before saving, and decompress it after reading, but that requires much more work, and it is probably an overkill for what you are doing.
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47466917
answer count: 2
has comment: http://stackoverflow.com/comment/81888698
has comment: http://stackoverflow.com/comment/81943486
upvote count: 1
downvote count: 1
has body: I have a sample of a file with sentences and labels. How can it be split into sentences and labels? A very, very, very slow-moving, aimless movie about a distressed, drifting young man. 0 Not sure who was more lost - the flat characters or the audience, nearly half of whom walked out. 0 Attempting artiness with black &amp; white and clever camera angles, the movie disappointed - became even more ridiculous - as the acting was poor and the plot and lines almost non-existent. 0 Very little music or anything to speak of. 0 output list of sentences: ['A very, very, very slow-moving, aimless movie about a distressed, drifting young man','Not sure who was more lost - the flat characters or the audience, nearly half of whom walked out'] corresponding labels: ['0','0']
favorite count: 0
type: Question
tagged with: file-handling
possible better answer: http://stackoverflow.com/a/47467062
has answer: http://stackoverflow.com/a/47467131
accepted answer: http://stackoverflow.com/a/47467131
has answer: http://stackoverflow.com/a/47467062
has comment: http://stackoverflow.com/comment/81888443
tagged with: python
has title: splitting lines in python with sentences and labels
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81888613

http://stackoverflow.com/q/47396866
downvote count: 1
has answer: http://stackoverflow.com/a/47397083
has body: I need to replace the value inside a capture group of a regular expression with some arbitrary value; I've had a look at the re.sub, but it seems to be working in a different way. I have a string like this one : s = 'monthday=1, month=5, year=2018' and I have a regex matching it with captured groups like the following : regex = re.compile('monthday=(?P&lt;d&gt;\d{1,2}), month=(?P&lt;m&gt;\d{1,2}), year=(?P&lt;Y&gt;20\d{2})') now I want to replace the group named d with aaa, the group named m with bbb and group named Y with ccc, like in the following example : 'monthday=aaa, month=bbb, year=ccc' basically I want to keep all the non matching string and substitute the matching group with some arbitrary value. Is there a way to achieve the desired result ? Note This is just an example, I could have other input regexs with different structure, but same name capturing groups ... Update Since it seems like most of the people are focusing on the sample data, I add another sample, let's say that I have this other input data and regex : input = '2018-12-12' regex = '((?P&lt;Y&gt;20\d{2})-(?P&lt;m&gt;[0-1]?\d)-(?P&lt;d&gt;\d{2}))' as you can see I still have the same number of capturing groups(3) and they are named the same way, but the structure is totally different... What I need though is as before replacing the capturing group with some arbitrary text : 'ccc-bbb-aaa' replace capture group named Y with ccc, the capture group named m with bbb and the capture group named d with aaa. In the case, regexes are not the best tool for the job, I'm open to some other proposal that achieve my goal.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81747031
upvote count: 8
answer count: 5
has comment: http://stackoverflow.com/comment/81748044
has comment: http://stackoverflow.com/comment/81747652
has answer: http://stackoverflow.com/a/78710528
has comment: http://stackoverflow.com/comment/81747248
has comment: http://stackoverflow.com/comment/81748199
has title: Replace named captured groups with arbitrary values in Python
tagged with: python
has comment: http://stackoverflow.com/comment/81748146
tagged with: regex
has comment: http://stackoverflow.com/comment/81748246
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81747820
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81747623
has comment: http://stackoverflow.com/comment/81747293
score: 7
accepted answer: http://stackoverflow.com/a/47397954
has answer: http://stackoverflow.com/a/47397140
has comment: http://stackoverflow.com/comment/81747548
has answer: http://stackoverflow.com/a/47397778
possible better answer: http://stackoverflow.com/a/47397083
has comment: http://stackoverflow.com/comment/81746859
has answer: http://stackoverflow.com/a/47397954

http://stackoverflow.com/comment/81724500
type: QuestionComment
score: 0
has text: Im on my phone so code writing is tough. And also, im not sure whether thats _best practice_, only that you can do it and it will work. I haven't seen anything substantially different from that approach though.
comment on: http://stackoverflow.com/q/47385354
type: Comment

http://stackoverflow.com/a/47517003
has comment: http://stackoverflow.com/comment/82010247
type: Answer
accepted answer of: http://stackoverflow.com/q/47514605
has comment: http://stackoverflow.com/comment/81994865
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81994517
has comment: http://stackoverflow.com/comment/82005841
answers question: http://stackoverflow.com/q/47514605
has body: I tried your code and it doesn't work for me because problem is master In ReadFile you run CSVGui(self, ...) and self means ReadFile. In CSVGui you assign this ReadFile to master and use in ttk.Frame.__init__(self, master) - but master has to be any tkinter's widget, not ReadFile. I made changes in two places First: in ReadFile I create Tk() window and after askopenfilename I destroy it. This way if I run ReadFile() or ReadFile(filename.csv) I always will run CSVGui without master in computer memory. if fname == '' and path == '': master = tk.Tk() master.withdraw() self.filename = askopenfilename(title='Select CSV file', filetypes=[('CommaSeperatedFile', '*.csv')]) master.destroy() Second: CSVGui doesn't need master as second argument because I create it inside CSVGui class CSVGui(ttk.Frame): def __init__(self, data=[]): master = tk.Tk() ttk.Frame.__init__(self, master) It also need self.pack() to put class CSVGui(ttk.Frame) inside this master, and master.mainloop() to keep it open. import csv import tkinter as tk from tkinter import ttk from tkinter.filedialog import askopenfilename class ReadFile: """This class reads CSV w/out header line, and returen it as a list""" def __init__(self, fname='', path='', **kwargs): if fname == '' and path == '': # &lt;--- changes master = tk.Tk() master.withdraw() self.filename = askopenfilename(title='Select CSV file', filetypes=[('CommaSeperatedFile', '*.csv')]) master.destroy() else: if path != '': self.filename = path + '/' + fname else: self.filename = fname self.file_content = [] self.read_file(kwargs) self.out_in_gui() def read_file(self, kwargs): with open(self.filename, newline='', **kwargs) as csvfile: file_obj = csv.reader(csvfile) for i in file_obj: self.file_content.append(i) print("file %s was read successfully, containing %d lines" % (self.filename, len(self.file_content))) def out_in_gui(self): print("send data to CSVGui") CSVGui(self.filename, data=self.file_content) # &lt;--- changes def file_contents(self): retu…

http://stackoverflow.com/comment/81983989
has text: There is probably a dir named like something 64. You should follow exactly the instructions in the CuDNN site. https://developer.nvidia.com/rdp/cudnn-download
score: 0
comment on: http://stackoverflow.com/q/47495190
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81903499
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47474385
has text: Do **NOT** use imgur! Copy and paste dataframe in question.

http://stackoverflow.com/comment/94738657
score: 0
type: AnswerComment
has text: the '~' is a not operator. So True turn to False and False turn to True.
comment on: http://stackoverflow.com/a/47490612
type: Comment

http://stackoverflow.com/a/47518174
has body: Method attribute access on a super() proxy object, like ordinary method binding, just passes the object implicitly as the first positional argument. Change this: super().__setitem__(self, key, val) To this: super().__setitem__(key, val) Note that OrderedDict doesn't use cooperative inheritance, i.e. it just calls dict.__setitem__ directly. Ideally, every object in the inheritance chain should be using super. Please proceed with caution if you plan to use OrderedDict with a multiple-inheritance structure.
has comment: http://stackoverflow.com/comment/81992824
has comment: http://stackoverflow.com/comment/81992438
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81992596
has comment: http://stackoverflow.com/comment/81992631
answers question: http://stackoverflow.com/q/47518068
score: 1
type: Answer

http://stackoverflow.com/a/47513478
accepted answer of: http://stackoverflow.com/q/47448587
has body: I made a (trivial) change to the payload from the frontend to the endpoint. I use Django Rest Framework but there was nothing special I can reuse from DRF. I use Django bulk update https://github.com/aykut/django-bulk-update to help with the mass updating (this was actually quite useful) I chose to use patch as the method and not to return any content if successful other than the number of affected rows I removed the unique_together constraint in the Track model. (this is very important) Change to the payload Instead of [{"id":1},{"id":2},{"id":3},{"id":4},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":75},{"id":76},{"id":77},{"id":78}] I did {"children" :[{"id":1},{"id":2},{"id":3},{"id":4},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":75},{"id":76},{"id":77},{"id":78}]} the DRF endpoint in urls.py url(r'^(?i)api/v1.0/album/(?P&lt;pk&gt;[0-9]+)/update_children_order$', views.TracksList.as_view(), name='view-tracks'), in views.py from django_bulk_update.helper import bulk_update from rest_framework.response import Response import json from rest_framework.views import APIView class TracksReorder(APIView): def patch(self, request, pk=None): """ Update the order of the tracks by the parent album id request.data is in the expected structure: track pk is in data.children.{n}.id """ # because the data is expected to be nested dictionary decoded = request.body.decode('utf8') data = json.loads(decoded) sorted_dict = {} for key, value in enumerate(data['children']): sorted_dict[value['id']] = key # sorted dict uses track pk as key and new order as value tracks = Track.objects.filter(album_id=pk) for track in tracks: track.order = sorted_dict[track.id] affected_rows = bulk_update(tracks, update_fields=['order']) if affected_rows: return Response({'affected_rows': affected_rows}) return Response({}, status.HTTP_204_NO_CONTENT)
answers question: http://stackoverflow.com/q/47448587
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81992506
type: QuestionComment
score: 0
has text: you can translate your code to `convolution -> relu -> convolution -> relu -> reshape -> linear -> relu -> linear`, which will make 2 convolutional layers and 2 linear layers
comment on: http://stackoverflow.com/q/47518131
type: Comment

http://stackoverflow.com/a/69762672
upvote count: 1
score: 1
has body: selenium, find elementByName, then use pynput lib to right click and download. used similar for fetching market data works prety well, refer to official selenium docs for spesifics .
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47539225

http://stackoverflow.com/a/47444271
answers question: http://stackoverflow.com/q/47444178
has body: I guess in UNIX based systems it really just comes down to personal preference. I'd use os.getlogin() if I plan to write the code for other platforms such as windows. Moreover, enviroment variables and easier be manipulated. so it's more secure to use it in cases where security is a priority.
type: Answer
score: 0

http://stackoverflow.com/q/47398054
type: AnsweredQuestion
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/25445791
has answer: http://stackoverflow.com/a/47398589
has answer: http://stackoverflow.com/a/47398428
possible better answer: http://stackoverflow.com/a/47398428
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: How to parse and sort JSON with multiple keys in Python
has answer: http://stackoverflow.com/a/47398631
accepted answer: http://stackoverflow.com/a/47398589
has body: Actually training with JSON trying to understand how I can parse a new JSON using two differents keys. I want to sort some logs for data vizualisation purpose. My data JSON { "productTitle": "Product", "apiName": "soapwebservice" "statusCode": "200 OK" }, { "productTitle": "Product", "apiName": "productionservice", "statusCode": "200 OK" }, { "productTitle": "Product", "apiName": "firstapi", "statusCode": "200 OK" }, { "productTitle": "Product", "apiName": "firstapi", "statusCode": "200 OK" }, { "productTitle": "Suitability", "apiName": "suitability-api", "statusCode": "200 OK" } The Output JSON expected : { "Product": 4, "api-activity": { "soapwebservice": 1, "productionservice": 1, "firstapi": 2 } } { "Suitability": 1, "api-activity": { "suitability-api": 1, } } This is my first code to parse and count the first key : import json from collections import Counter with open('events1.json') as json_data: json_obj = json.load(json_data) # Read the JSON file # print(json_obj['calls'][0]['appName']); #Example JSON Extract c = Counter(player['productTitle'] for player in json_obj['calls']) with open('output.json', 'w') as f: f.write(json.dumps(c, indent=4)) # Parse and write the file print("Translation of JSON"); I'm looking for a way to obtain the expected JSON, probably with a loop as explain here : parse JSON values by multilevel keys But I cannot obtain the JSON as expected, do you have any idea ?
score: 2
upvote count: 2

http://stackoverflow.com/comment/81863058
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47454273
has text: is models.py formatted in same way as you have mentioned??? and does table have entries?
score: 0

http://stackoverflow.com/q/47469947
tagged with: python
has comment: http://stackoverflow.com/comment/81895313
has title: as_strided: Linking stepsize (strides of conv2d) with as_strided strides parameter
has comment: http://stackoverflow.com/comment/81894686
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81894599
has comment: http://stackoverflow.com/comment/81895657
upvote count: 1
downvote count: 0
answer count: 1
tagged with: stride
favorite count: 0
has body: I found that for generating (X - x + 1, Y - y + 1) patches of size (x,y) from (X,Y) with stride 1, image requires us to give strides parameter as img.strides * 2 or img.strides + img.strides. I don't know how they quickly compute this knowing the no. of strides in conv2d But what should I do to get ((X-x)/stride)+1, ((Y-y)/stride)+1 patches of same size from same sized image with stride stride? From this SO answer with slight modification, with channels and number of images placed in front def patchify(img, patch_shape): a,b,X, Y = img.shape # a images and b channels x, y = patch_shape shape = (a, b, X - x + 1, Y - y + 1, x, y) a_str, b_str, X_str, Y_str = img.strides strides = (a_str, b_str, X_str, Y_str, X_str, Y_str) return np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides) I can see that it creates a sliding window with size (x,y) and stride 1 (move 1 pixel to the right and move 1 pixel down). I have trouble correlating the strides parameter which as_strided uses and the strides we usually use for conv2d. How do I add a parameter to the above function that computes as_strided strides parameter? def patchify(img, patch_shape, stride): # stride=stepsize in conv2d eg: 1,2,3,... a,b,X,Y = img.shape # a images and b channels x, y = patch_shape shape = (a,b,((X-x)/stride)+1, ((Y-y)/stride)+1, x, y) strides = ??? # strides for as_strided return np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides) img is 4d (a, b, X, Y) a=no.of images, b=no.of channels, (X,Y) = width and height Note: By stride in conv2d I mean stepsize Unfortunately this is also called stride. Note 2: Since stepsize will usually be the same on both axes, in the code I provided, I've provided only one parameter, however used it for both dimensions. Playground: What goes in for strides here. I have it running for stepsize=1 here. I noticed that it might not work from the link but it works when pasted in new playground. This should give a clear idea of what I need: [[ 0.548813…
type: AnsweredQuestion
tagged with: conv-neural-network
linked to: http://stackoverflow.com/q/41849548
score: 1
has comment: http://stackoverflow.com/comment/81894334
has comment: http://stackoverflow.com/comment/81895241
has answer: http://stackoverflow.com/a/47470711
has comment: http://stackoverflow.com/comment/81895439
accepted answer: http://stackoverflow.com/a/47470711

http://stackoverflow.com/q/47454903
linked to: http://stackoverflow.com/q/40466097
has comment: http://stackoverflow.com/comment/81865812
has comment: http://stackoverflow.com/comment/81866017
has title: How apply decorator on a class method in python
type: UnansweredQuestion
answer count: 1
has body: I'm trying to modify a class which has methods based on the csv module. The data is a simple three-column csv file which I wanted to turn into a nested list of dictionaries. I've managed to that with the help of this SO question. However, I'd like to be able to implement a more general 'load_data' method, one which I could use decorators to introduce methods to output to take two columns of a loaded csv and output as a list of dictionaries. My attempt to produce the wrapper function and proposed csv_to_dict_dicts method are commented out. import csv class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value """ def csv_decorator(func): def func_wrapper(self): for row in reader: return dict(self.data[row[0]][row[1]] = row[2] ) return func_wrapper """ class CSV: def __init__(self): self.data = AutoVivification() def load_data(self, path): with open(path, encoding="utf-8") as f: self.path = path reader = csv.reader(f) for row in reader: self.data[row[0]][row[1]] = row[2] #@csv_decorator #def csv_to_dict_dicts(self): # return self.load_data(path) c = CSV() c.load_data(path) UPDATE: I've tried using SO question thus: def csv_decorator(func): def func_wrapper(self): reader = func(self) for row in reader: self.data[row[0]][row[1]] = row[2] return func_wrapper class CSV: def __init__(self): self.data = AutoVivification() @csv_decorator def load_data(self, path): with open(path, encoding="utf-8") as f: self.path = path reader = csv.reader(f) return reader However, I receive the error: TypeError: func_wrapper() takes 1 positional argument but 2 were given
has answer: http://stackoverflow.com/a/47455970
score: 0
linked to: http://stackoverflow.com/q/1263451
has comment: http://stackoverflow.com/comment/81865134
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81866233
tagged with: python-decorators
type: Question

http://stackoverflow.com/q/47479587
has comment: http://stackoverflow.com/comment/81934618
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47905412
accepted answer: http://stackoverflow.com/a/47905412
has comment: http://stackoverflow.com/comment/81943399
has title: How to feed input with changing size in Tensorflow
has comment: http://stackoverflow.com/comment/82743284
has body: I want to train a network with planar curves, which I represent as numpy arrays with shape (L,2). The number 2 stands for x,y coordinates and L is the number of points which is changing in my dataset. I treat x,y as 2 different "channels". I implemented a function, next_batch(batch_size), that provides the next batch as a 1D numpy array with shape (batch_size,), containing elements which are 2D arrays with shape: (L,2). These are my curves, and as mentioned before, L is different between the elements. (I didn't want to confine to fixed number of points in the curve). My question: How can I manipulate the output from next_batch() so I will able to feed the network with the input curves, using a scheme similar to what appears in Tensorflow tutorial: https://www.tensorflow.org/get_started/mnist/pros i.e, using the feed_dict mechanism. In the given turorial the input size was fixed, in the tutorial's code line: train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) batch[0] has a fixed shape: (50,784) (50 = #samples,784 = #pixels) I cannot transform my input into numpy array with shape (batch_size,L,2) since the array should have fixed size in every dimension. So what can I do? I already defined a placeholder (that can have unknown size): #first dimension is the sample dim, second is curve length, third:x,y coordinates x = tf.placeholder(tf.float32, [None, None,2]) but how can I feed it properly?
answer count: 4
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/47963720
type: Question
tagged with: numpy
upvote count: 9
tagged with: python-3.x
score: 9
has answer: http://stackoverflow.com/a/47896185
possible better answer: http://stackoverflow.com/a/47896185
has answer: http://stackoverflow.com/a/47967531
downvote count: 0
tagged with: python

http://stackoverflow.com/a/47496649
has comment: http://stackoverflow.com/comment/128695707
has comment: http://stackoverflow.com/comment/82110949
answers question: http://stackoverflow.com/q/47496415
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/134954722
score: 12
has comment: http://stackoverflow.com/comment/139137972
has comment: http://stackoverflow.com/comment/129427887
has comment: http://stackoverflow.com/comment/82116716
has body: If you don't want to define a dictionary as in @timgeb's answer, then you can call locals(), which gives you a dict of the variables available in the local scope. def get_ext(file_type): text = ['txt', 'doc'] audio = ['mp3', 'wav'] video = ['mp4', 'mkv'] return locals()[file_type] and a test to show it works: >>> get_ext("text") ['txt', 'doc']
has comment: http://stackoverflow.com/comment/82116481
has comment: http://stackoverflow.com/comment/81956436
downvote count: 1

http://stackoverflow.com/q/47538967
type: UnansweredQuestion
tagged with: wsgi
downvote count: 0
tagged with: python
has title: How to catch exception outside of Flask?
tagged with: flask
score: 2
answer count: 0
tagged with: middleware
favorite count: 0
type: Question
has body: I would like to create WSGI middleware to handle an exception. However, Flask always catches the exception before it reaches the middleware. How can I raise an exception and catch it outside of Flask? I don't want to let Flask handle this because I want to be able to use the middleware with other WSGI applications besides Flask.
upvote count: 2

http://stackoverflow.com/q/47521088
tagged with: loops
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82001059
has body: I explain what I have to develop. Let's say I have to perform a function that is responsible for receiving two matrices, which have the same number of columns but can differ in the number of rows. In summary, we will have two matrices of vectors with the same dimension but different number N of elements. I have to calculate the Euclidean distance between each of the vectors that make up my two matrices, and then store it in another matrix that will contain the Euclidean distance between all my vectors. This is the code I have developed: def compute_distances(x, y): # Dimension: N, d = x.shape M, d_ = y.shape # The dimension should be the same if d != d_: print "Dimensiones de x e y no coinciden, no puedo calcular las distancias..." return None # Calculate distance with loops: D = np.zeros((N, M)) i = 0 j = 0 for v1 in x: for v2 in y: if(j != M): D[i,j] = math.sqrt(sum([(xi-yi)**2 for xi,yi in zip(v1,v2)])) #print "[",i,",",j,"]" j = j + 1 else: j = 0 i = i + 1; print D In this method I am receiving the two matrices to later create a matrix that will have the Euclidean distances between the vectors of my matrices x and y. The problem is the following, I do not know how, to each one of the calculated Euclidean distance values ​​I have to assign the correct position of the new matrix D that I have generated. My main function has the following structure: n = 1000 m = 700 d = 10 x = np.random.randn(n, d) y = np.random.randn(m, d) print "x shape =", x.shape print "y shape =", y.shape D_bucle = da.compute_distances(x, y) D_cdist = cdist(x, y) print np.max(np.abs(D_cdist - D_bucle)) B_cdist calculates the Euclidean distance using efficient methods. It has to have the same result as D_bucle that calculates the same as the other but with non efficient code, but I'm not getting what the result should be. I think it's when I create my Euclidean matrix D that is not doing it correctly, then the calculations are incorrect. Updated!!! I just updated my solution, my problem is that…
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/27948363
has answer: http://stackoverflow.com/a/47521809
score: 0
has title: Adding Euclidean distance to a matrix
has comment: http://stackoverflow.com/comment/82000387
answer count: 1
has comment: http://stackoverflow.com/comment/82000428

http://stackoverflow.com/comment/81988555
score: 0
comment on: http://stackoverflow.com/q/47513724
type: Comment
type: QuestionComment
has text: @Ehsan Thanks for your advise. i have an another question. how can i Transform the np.log(dataset) back to the normal value?

http://stackoverflow.com/comment/81783935
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47415132
has text: @bluesummers The answer was in your title :)
type: Comment

http://stackoverflow.com/comment/81945530
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47495263
has text: `itertools.chain.from_iterable` would be the thing to use here...

http://stackoverflow.com/comment/81782760
type: QuestionComment
score: 2
has text: You need to post the error you 're getting.
comment on: http://stackoverflow.com/q/47414618
type: Comment

http://stackoverflow.com/a/47430105
has body: Iterate over the dict, then over the values of the current dict: for d_ in d.values(): for item in d_: print item['name'] Or in comprehension names = [item['name'] for d_ in d.values() for item in d_] print names ['john', 'steve', 'jack', 'anna']
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47429981
type: Answer

http://stackoverflow.com/comment/81865347
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47454047
has text: Have you tried logging the blob url? After you've worked out the url you're requesting in your code, use storage explorer to compare what you are requesting with your code with what's actually in the storage account: this is the blob storage equivalent of "File not found".
score: 0

http://stackoverflow.com/q/47446751
has comment: http://stackoverflow.com/comment/81848889
has title: I want to send data from php to python
has comment: http://stackoverflow.com/comment/81849594
has comment: http://stackoverflow.com/comment/81848893
has comment: http://stackoverflow.com/comment/81848872
score: 0
linked to: http://stackoverflow.com/q/17425426
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81848870
type: UnansweredQuestion
has body: I've tried to send data from php to python, I found a tutorial from here. this is the code. php &lt;?php $data = array('1','4','67','34'); $result = shell_exec('python try.py ' . escapeshellarg(json_encode($data))); $resultData = json_decode($result, true) var_dump($resultData); ?&gt; python #!/Python27/python import sys, json # Load the data that PHP sent us try: data = json.loads(sys.argv[1]) except: print "ERROR" sys.exit(1) # Send it to stdout (to PHP) print json.dumps(data) and output: array(4) { [0]=&gt; int(1) [1]=&gt; int(4) [2]=&gt; int(67) [3]=&gt; int(34) } I try and succeed, but it's just an integer, I want a string. I tried to replace the data $data = array('tiger','dog','cow','lion'); but the result is NULL
tagged with: python
tagged with: php

http://stackoverflow.com/comment/81876907
has text: @ekhumoro I had a try with the tandem multiprocessing.pool / map_async to download 100 objects. It was successful. However, since I'm losing the slot/signal mechanism, I had to add a “busy waiting loop” in order to get on the QPlainTextEdit some information on what was going on. Is there an elegant way to introduce a little more real time into this script (i. e. every time a worker has finished his task, he sends his end message to the console)?
comment on: http://stackoverflow.com/q/47431119
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/116368621
type: Comment
type: AnswerComment
has text: How do you check if two operations run in parallel? Is there a way to profile it?
comment on: http://stackoverflow.com/a/47492027
score: 0

http://stackoverflow.com/comment/81837652
has text: Yeah, sorry, I did screw that one up. Fixed it, to conform with PEP8.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47441272
type: Comment

http://stackoverflow.com/comment/81845645
has text: The purpose of this site is for public QA so that solutions to your problems might help others who come across the same thing. People aren't really here to help with your code for free.
comment on: http://stackoverflow.com/q/47445043
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47501185
has comment: http://stackoverflow.com/comment/81958316
type: Question
tagged with: if-statement
has title: how to check if variables equal each other
accepted answer: http://stackoverflow.com/a/47501252
possible better answer: http://stackoverflow.com/a/47501224
tagged with: python
has answer: http://stackoverflow.com/a/47501252
has body: I am trying to check if two variables are equal to each other. If they are, I want to reset a variable and change another. Here is my sample code: eq = int(input("\nhow many equations do you have? ")) matrix = [[] for _ in range(eq)] solution = [[] for _ in range(eq)] for i in range(eq*eq): q = 0 x = 0 a = int(input("input the coefficients to your variables in your equation: ")) matrix[x].append(a) q += 1 if q == eq: q = 0 print("It's time to move on to the next equation!") x += 1 The problem is the if statement. Everything else works fine.
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81958138
tagged with: variables
has answer: http://stackoverflow.com/a/47501224

http://stackoverflow.com/a/47547972
answers question: http://stackoverflow.com/q/47525920
type: Answer
score: 0
has body: Accessing elements in a parse tree is simple and when you look at your generated classes it should become obvious. A parse tree has a children property or method that allows to access all parse rule contexts that have been created for the found elements during parsing. For convenience there are special accessors that ease getting to specific child contexts. In your example you will see an ID() function on your HiParseContext which gives you a context with details for the matched ID token (e.g. location in the input, token type, token text and more). Just look at the generated and the runtime source code to see what's possible.

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/47538745
tags question: http://stackoverflow.com/q/47540354
tags question: http://stackoverflow.com/q/47390928
tags question: http://stackoverflow.com/q/47399807
tags question: http://stackoverflow.com/q/47460196
tag name: xml
tags question: http://stackoverflow.com/q/47393951
tags question: http://stackoverflow.com/q/47437308
tags question: http://stackoverflow.com/q/47531391
tags question: http://stackoverflow.com/q/47444501
tags question: http://stackoverflow.com/q/47491111
tags question: http://stackoverflow.com/q/47415039
tags question: http://stackoverflow.com/q/47488253
type: Tag
tags question: http://stackoverflow.com/q/47446433
tags question: http://stackoverflow.com/q/47533299
tags question: http://stackoverflow.com/q/47477190
tags question: http://stackoverflow.com/q/47466282
tags question: http://stackoverflow.com/q/47458949
tags question: http://stackoverflow.com/q/47453372
tags question: http://stackoverflow.com/q/47475024
tags question: http://stackoverflow.com/q/47391557
tags question: http://stackoverflow.com/q/47536858
tags question: http://stackoverflow.com/q/47457069
tags question: http://stackoverflow.com/q/47517194
tags question: http://stackoverflow.com/q/47447939
tags question: http://stackoverflow.com/q/47524614
tags question: http://stackoverflow.com/q/47500129
tags question: http://stackoverflow.com/q/47428635
tags question: http://stackoverflow.com/q/47539248
tags question: http://stackoverflow.com/q/47439566
tags question: http://stackoverflow.com/q/47470803
tags question: http://stackoverflow.com/q/47463990
tags question: http://stackoverflow.com/q/47433632
tags question: http://stackoverflow.com/q/47481025
tags question: http://stackoverflow.com/q/47445236
tags question: http://stackoverflow.com/q/47475790
tags question: http://stackoverflow.com/q/47498792

http://stackoverflow.com/comment/138369883
comment on: http://stackoverflow.com/a/47534998
score: 0
has text: I guess a `tuple` of only lengths 1 or 2 would have to be a union: `list[tuple[int] | tuple[int, int]]`.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47423746
score: 0
has comment: http://stackoverflow.com/comment/81803697
answer count: 1
has body: I'm trying to write a python2.7 function that can tell whether or not a specific IP address (host) can be connected to using SSH protocol. The problem is I have to do it without having the login information of the device I'm connecting to. My plan is to attempt to connect with an empty string as the username and password, then use the exception it throws to determine if it could be connected to or not. My reasoning is that if it throws an AuthenticationException for example, it must have attempted to connect but simply determined the login information to be invalid. This is my code so far: def ssh(host): try: s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(host, username=None, password=None) except(paramiko.ssh_exception.AuthenticationException, paramiko.ssh_exception.BadAuthenticationType, paramiko.ssh_exception.BadHostKeyException, paramiko.ssh_exception.PasswordRequiredException, paramiko.ssh_exception.PartialAuthentication): return True except Exception as e: print(e) return False When I run this, it always returns false and outputs: No authentication methods available My questions are: Is this a feasible strategy to accomplish what I want? Which exceptions are caused by bad credentials and which are caused by more serious issues that would prevent a connection even with the right credentials? Which function is printing to the console and how do I stop it? I'd like to handle error messages on my own. Thanks in advance!
type: Question
has title: How can I verify that an SSH connection is possible without login information?
tagged with: exception
has comment: http://stackoverflow.com/comment/81835250
tagged with: ssh
tagged with: python
tagged with: paramiko
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47454268
has answer: http://stackoverflow.com/a/47454268

http://stackoverflow.com/q/47405628
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/47410839
tagged with: bokeh
favorite count: 0
type: Question
score: 3
has body: Im using Bokeh to plot a pandas Dataframe. Following is the code: map_options = GMapOptions(lat=19.075984, lng=72.877656, map_type="roadmap", zoom=11) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options) plot.api_key = "xxxxx" source = ColumnDataSource( data=dict( lat=[float(i) for i in data.lat], lon=[float(i) for i in data.lon], size=[int(i)/1000 for i in data['count']], ID = [i for i in data.merchant_id], Merchant = [str(i) for i in data.merchant_name], count = [float(i) for i in data['count']] ) ) hover = HoverTool(tooltips=[ ("(x,y)", "($lat, $lon)"), ("ID", "$ID"), ("Name", "@Merchant"), ("count","$count") ]) # hover.renderers.append(circle_glyph) plot.tools.append(hover) circle = Circle(x="lon", y="lat", size='size', fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) # plot.add_layout(labels) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file("gmap_plot.html") show(plot) In the Hovertool using the "Name" field throws the following error: UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 6: unexpected end of data Also commenting the "Name" field still gives me the error but there is an output plot. Following is the dataframe I'm using: lat lon merchant_id count merchant_name 0 18.539971 73.893963 757 777 Portobello 1 18.565766 73.910980 745 10193 The Wok Box 2 18.815427 76.775143 1058 2354 Burrito Factory 3 18.914633 72.817916 87 1985 Flamboyante 4 18.915794 72.824370 94 1116 Butterfly Pond 5 18.916473 72.826868 145 1010 Leo's Boulangerie 6 18.918923 72.828325 115 517 Brijwasi Sweets 7 18.928063 72.832888 973 613 Pandora's Box 8 18.928562 72.832353 101 64 La Folie Patisserie 9 18.929516 72.831860 961 6673 Burma Burma From my knowledge, the merchant name has characters that's causing the error, but i've tried encoding the column with 'utf-8', 'ascii', etc. But I get the following error: data['merchant_name'] = data['merchant_name'].str.encode('utf-8') Unicod…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/62747282
has title: Bokeh 'utf8' codec can't decode byte 0xe9 : unexpected end of data
upvote count: 3
answer count: 2
tagged with: encoding

http://stackoverflow.com/a/47429544
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/81813663
upvote count: 6
has comment: http://stackoverflow.com/comment/81816185
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81814580
accepted answer of: http://stackoverflow.com/q/47429525
has body: You need to use a proper URL including protocol: domain = 'http://localhost:8000'
has comment: http://stackoverflow.com/comment/81814628
has comment: http://stackoverflow.com/comment/81816878
answers question: http://stackoverflow.com/q/47429525

http://stackoverflow.com/comment/140128059
comment on: http://stackoverflow.com/a/78047935
type: Comment
score: 0
type: AnswerComment
has text: How to get this email `@someuser` from GitHub Action? Hardcode doesn't work in my context. I hope I can get it like `${{ github.author }}`

http://stackoverflow.com/a/47473129
accepted answer of: http://stackoverflow.com/q/47472959
downvote count: 0
type: AcceptedAnswer
has body: There is problem your dictionary of lists contain duplicate column name ' ' and it is per design not allowed. So is possible create DataFrame by column_stack and define columns names: empty = [np.nan] * len(x) data = pd.DataFrame(np.column_stack([x,empty,z,empty,y]), columns= ['x','','y','','z']) Or a little hack - create all unique columns first in dict and then rename: data = pd.DataFrame({"x":x, "empty1":np.nan, "y":y, "empty2":np.nan, "z":z}, columns=['x','empty1','y','empty2','z']) data = data.rename(columns={'empty1':'', 'empty2':''}) print (data) x y z 0 1.0 NaN 11.0 NaN 6.0 1 2.0 NaN 12.0 NaN 7.0 2 3.0 NaN 12.0 NaN 8.0 3 4.0 NaN 56.0 NaN 9.0 4 5.0 NaN 6.0 NaN 0.0 data.to_excel('test_file.xlsx', index= False)
answers question: http://stackoverflow.com/q/47472959
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/81948699
has text: Also try more connected layers. At this time you just have a single dense layer. You can add some dense layers with relu activation before final layer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47493392
score: 0

http://stackoverflow.com/a/47568897
answers question: http://stackoverflow.com/q/47474294
type: Answer
score: 0
has body: The exactonline help desk says these four functions only allow you to request your own hours. If you want to request all hours use: /manufactering/TimeTransactions instead. (https://start.exactonline.nl/docs/HlpRestAPIResourcesDetails.aspx?name=ManufacturingTimeTransactions)

http://stackoverflow.com/comment/82036383
has text: (That is only possible if you are using threading, not with multiple processes)
type: Comment
comment on: http://stackoverflow.com/a/47539082
type: AnswerComment
score: 0

http://stackoverflow.com/a/47501618
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47499297
score: 2
has body: You would pickle the figure instead the artists in it. import matplotlib.pyplot as plt import numpy as np import pickle ind = np.linspace(1,5,5) y = np.linspace(9,1,5) width = 0.3 fig, ax = plt.subplots() ax.bar(x=ind, height=y, width=width) ax.set_xlabel("x label") pickle.dump(fig, file('oldbar.pkl', 'w')) plt.close("all") ind2 = np.linspace(1,5,5) y2 = np.linspace(8,2,5) width2 = 0.3 fig2 = pickle.load(file('oldbar.pkl')) ax2 = plt.gca() ax2.bar(x=ind2+width, height=y2, width=width2, color="C1") plt.show() However pickling the data itself may make more sense here. import matplotlib.pyplot as plt import numpy as np import pickle ind = np.linspace(1,5,5) y = np.linspace(9,1,5) width = 0.3 dic = {"ind":ind, "y":y, "width":width} pickle.dump(dic, file('olddata.pkl', 'w')) ### new data ind2 = np.linspace(1,5,5) y2 = np.linspace(8,2,5) width2 = 0.3 olddic = pickle.load(file('olddata.pkl')) fig, ax = plt.subplots() ax.bar(x=olddic["ind"], height=olddic["y"], width=olddic["width"]) ax.bar(x=ind2+olddic["width"], height=y2, width=width2) ax.set_xlabel("x label") plt.show()
type: Answer
answers question: http://stackoverflow.com/q/47499297
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/47415918
has comment: http://stackoverflow.com/comment/81840329
type: AnsweredQuestion
has title: Why is it bad to call Join on a daemon thread
tagged with: java
tagged with: thread-safety
has comment: http://stackoverflow.com/comment/81840301
favorite count: 0
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/47443226
linked to: http://stackoverflow.com/q/15085348
has body: I was reading this SO post about daemon threads and the quote at the bottom of the answer is: But joining a demonized thread opens most likely a whole can of trouble! Why exactly is it considered bad practice? I understand .join() blocks regardless if the thread is daemon or not, but I don't understand why it's considered bad practice. Can someone explain?
has answer: http://stackoverflow.com/a/47443226
tagged with: multithreading
downvote count: 0
answer count: 1
tagged with: python
score: 4

http://stackoverflow.com/a/47492043
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47486372
has body: In the else block of the opponent_fun function, you are not returning the result of the recursive call. Changing it to this should fix it. def opponent_fun(board): random.seed() opponent = random.randint(0, 8) if board[opponent] != 'o' and board[opponent] != 'x': board[opponent] = 'o' return board else: return opponent_fun(board) This is happening because a function always returns a value to the direct caller, not all the way up to the first caller. So each time you call a function recursively, you need to return also.
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47486372

http://stackoverflow.com/comment/81924656
type: Comment
has text: @EwuramaMinkaAkuoko yeah, had an off-by-one error in my `range` clause. Edited and fixed.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47484785

http://stackoverflow.com/comment/81808284
type: AnswerComment
has text: in my case, why doesn't x meet the dtype requirement?
comment on: http://stackoverflow.com/a/47426787
type: Comment
score: 0

http://stackoverflow.com/comment/81744969
type: QuestionComment
comment on: http://stackoverflow.com/q/47391487
has text: Excellent. This is also something I was thinking about. Just in case somebody else is not so much interested in programming and just wants to have a practical solution - there are C libraries like http://primesieve.org/ for that.
score: 1
type: Comment

http://stackoverflow.com/q/47407929
tagged with: rest
type: Question
tagged with: django
tagged with: python
type: UnansweredQuestion
tagged with: paypal-sandbox
has comment: http://stackoverflow.com/comment/85254390
has comment: http://stackoverflow.com/comment/81773256
has body: I am using Python 3.6 and Django 1.11 for a project. I am using paypalrestsdk 1.13.1(Paypal REST SDK) package for Paypal Integration. I have been following the steps provided in - https://github.com/paypal/PayPal-Python-SDK and https://developer.paypal.com/docs/api/quickstart/payments/ Following is my view.py def donateThroughPaypal(request): context = locals() approval_url = "" redirect_url = "" if request.method == 'POST': paypalrestsdk.configure({ 'mode': 'sandbox', #sandbox or live 'client_id': '&lt;client_id&gt;', 'client_secret': '&lt;client_secret&gt;' }) payment = Payment({"intent": "sale", # Set payment method "payer": {"payment_method": "paypal"}, # Set redirect urls "redirect_urls": {"return_url": "http://localhost:8000/Return.html", "cancel_url": "http://localhost:8000/Cancel.html"}, # Set transaction object "transactions": [{"amount": {"total": "10.00","currency": "USD"}, "description": "transaction payment description"}]}) if payment.create(): for link in payment.links: if link.rel == "approval_url": approval_url = str(link.href) if link.method == "REDIRECT": redirect_url = str(link.href) return HttpResponseRedirect(approval_url) else: print(payment.error) template = 'donate/donate.html' return render(request,template,context) So the line return HttpResponseRedirect(approval_url) redirects me to Paypal login page. However, when I login into sandbox with buyer account, Paypal responds with - Return to Merchant and this redirects to cancel_url. I am successfully getting the token=EC-XXXXXXXXXXXXXXXXX and payment_id=PAY-XXXXXXXXXXXXXXXXXXXXXXXX. Please assist. Let me know if I am missing any setup. Also, is there any end-to-end (client-to-server), step wise documentation for Python - Paypal REST API integration? Please let me know.
score: 0
answer count: 0
tagged with: paypal
has comment: http://stackoverflow.com/comment/81809739
has title: Python Paypal REST SDK Integration issue
has comment: http://stackoverflow.com/comment/81770701

http://stackoverflow.com/a/47410858
downvote count: 0
answers question: http://stackoverflow.com/q/47410239
type: Answer
has body: The answer is you can't. The Keras Documentation provides the following information for Recurrent Layer: Input shape 3D tensor with shape (batch_size, timesteps, input_dim). In your case you have 64 timesteps where each step is of shape (100, 50). The easiest way to get the model working is to reshape your data to (100*50). Numpy provides an easy function to do so: X = numpy.zeros((6000, 64, 100, 50), dtype=numpy.uint8) X = numpy.reshape(X, (6000, 64, 100*50)) Wheter this is reasonable or not highly depends on your data.
upvote count: 4
score: 4

http://stackoverflow.com/comment/81793749
comment on: http://stackoverflow.com/a/47419512
score: 1
type: Comment
has text: Your answer was the first correct one, thank. However I find the Davy one clearer, hence +1 but not question validation. Thanks !
type: AnswerComment

http://stackoverflow.com/a/47398221
answers question: http://stackoverflow.com/q/47397872
has comment: http://stackoverflow.com/comment/81752042
upvote count: 2
has comment: http://stackoverflow.com/comment/81753287
has comment: http://stackoverflow.com/comment/81751931
downvote count: 0
has comment: http://stackoverflow.com/comment/81752527
has comment: http://stackoverflow.com/comment/81751583
has comment: http://stackoverflow.com/comment/81752901
has comment: http://stackoverflow.com/comment/81776786
score: 2
type: Answer
has body: "Tokenization is the process of splitting a text into tokens". I assume that with tokens you refer to words. This can be done in R using e.g. strsplit on a low level. For example: &gt; example &lt;- "This is an example. This is an example" &gt; unlist(strsplit(example, split = " ")) [1] "This" "is" "an" "example." "This" "is" "an" "example" As you can see the string is automatically transformed into a vector with several character strings. Now splitting by a simple space doesn't handle special cases well. So using a regex for one or more non-alphanumeric character should be considered better: &gt; unlist(strsplit(example, split = "[^[:alnum:]]+")) [1] "This" "is" "an" "example" "This" "is" "an" "example" If you want to preserve the punctuation you can use "\\s+" aka whitespace instead alnum. We can wrap this into a function: &gt; tokenize &lt;- function(x){ + unlist(strsplit(example, split = "\\s+")) + } &gt; tokenize(example) [1] "This" "is" "an" "example." "This" "is" "an" "example" If you want to have tokens different from word (e.g. sentence or character). You could use the tokenizer from quanteda which can handle special cases where e.g. the period does not indicate a new sentence: &gt; example &lt;- "This is an example. This is an example Dr. Knowitall" &gt; quanteda::tokens(example, what = "sentence") tokens from 1 document. text1 : [1] "This is an example." "This is an example Dr. Knowitall" There are several other packages that come with their own tokenizers. The package tokenizers, for example, provides just that.

http://stackoverflow.com/a/47694866
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47435672
answers question: http://stackoverflow.com/q/47435672
has body: Ok, I found out the problem was not with OS. To turn on autocompletion for non-project files it is needed to add libraries you use to External libraries. Instruction how to do this is in https://stackoverflow.com/a/24206781/4601890
score: 0
type: Answer

http://stackoverflow.com/comment/81727418
has text: You can also use collections counter to create a dict first.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47387203

http://stackoverflow.com/q/47411740
tagged with: cmd
tagged with: github
has comment: http://stackoverflow.com/comment/81778044
has comment: http://stackoverflow.com/comment/81778387
has comment: http://stackoverflow.com/comment/81778158
type: Question
has answer: http://stackoverflow.com/a/47413291
has comment: http://stackoverflow.com/comment/81814709
answer count: 2
has comment: http://stackoverflow.com/comment/81778119
has answer: http://stackoverflow.com/a/49197233
possible better answer: http://stackoverflow.com/a/49197233
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/81778511
has comment: http://stackoverflow.com/comment/81777960
has comment: http://stackoverflow.com/comment/81778340
has title: I can't install any github project with Pip
tagged with: git
accepted answer: http://stackoverflow.com/a/47413291
has comment: http://stackoverflow.com/comment/81777829
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81777929
has comment: http://stackoverflow.com/comment/81815409
has body: I've had to reinstall a lot of libraries on Windows. When I want to install pycdc from github Installing pycdc on windows. pip install git+https://github.com/zrax/pycdc.git I get: FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\TT\AppData\Local\Temp\pip-ashu2b4z-build\setup.py C:\Users\TT\unroll&gt;pycdc .py 'pycdc' is not recognized as an internal or external command, operable program or batch file. C:\Users\TT\unroll&gt;pip install git+https://github.com/zrax/pycdc.git Collecting git+https://github.com/zrax/pycdc.git Cloning https://github.com/zrax/pycdc.git to c:\users\TT\appdata\local\temp\pip-ashu2b4z-build Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\TT\Anaconda3\lib\tokenize.py", line 452, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\TT\\AppData\\Local\\Temp\\pip-ashu2b4z-build\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\TT\AppData\Local\Temp\pip-ashu2b4z-build\ C:\Users\TT\unroll&gt;pip install git+https://github.com/zrax/pycdc.git I feel like I'm missing some dependency files Boy do I ever regret doing a re-install. python may be nice to use but a nightmare to setup Also: C:\Users\TT&gt;pip install git+ssh://git@github.com/BlahCo/search/tree/prod_release_branch/ProductName Collecting git+ssh://git@github.com/BlahCo/search/tree/prod_release_branch/ProductName Cloning ssh://git@github.com/BlahCo/search/tree/prod_release_branch/ProductName to c:\users\TT\appdata\local\temp\pip-6x2kywme-build The authenticity of host 'github.com (192.30.255.113)' can't be established. RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8. Are you sure you want to continue connecting (yes/no)? y Please type 'yes' or 'no': yes Warning: Permanently added 'github.com,192.30.255.113' (RSA) t…

http://stackoverflow.com/a/47677680
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47386168
downvote count: 0
has body: You should run gcloud init first Then try df.write.csv('gs://some-test-bucket-delete-me/file_name')
upvote count: 1

http://stackoverflow.com/comment/81805363
type: Comment
has text: Mind you, you can have Python 3.5 and 3.6 both installed at the same time, so "downgrade" isn't necessarily mandatory as such.
score: 1
comment on: http://stackoverflow.com/q/47425171
type: QuestionComment

http://stackoverflow.com/a/47439322
upvote count: 8
has comment: http://stackoverflow.com/comment/81833909
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/81834300
accepted answer of: http://stackoverflow.com/q/47439234
answers question: http://stackoverflow.com/q/47439234
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81833998
has comment: http://stackoverflow.com/comment/81834273
has body: Let us create a new variable g, by cumcount df1['g']=df1.groupby('A').cumcount() df2['g']=df2.groupby('A').cumcount() df1.merge(df2,how='outer').drop('g',1) Out[62]: A B C 0 I 1.0 4.0 1 I 2.0 NaN 2 II 3.0 5.0 3 III NaN 6.0
has comment: http://stackoverflow.com/comment/81834048
has comment: http://stackoverflow.com/comment/81834175
has comment: http://stackoverflow.com/comment/81834149

http://stackoverflow.com/comment/81871097
type: AnswerComment
score: 1
has text: I think I need to investigate a lot more about virtual environments. The whole reason I need to use python-opencv outside the environment is because I plan to use it with ROS ( Robot Operating System) which also uses environments. I think my computer is a mess
comment on: http://stackoverflow.com/a/47453061
type: Comment

http://stackoverflow.com/a/47397437
score: 1
downvote count: 0
upvote count: 1
has body: Relatively more readable and somewhat efficient: def expand_rows(series): """ expand a row by splitting on "/" """ return series.str.split("/", expand=True).stack() d = {'Board': lambda dff: dff['Board'] + '/' + dff['Stops'], 'Off': lambda dff: dff['Stops'] + '/' + dff['Off'] } df.set_index('Pax').assign(**d)'Board', 'Off'.apply(expand_rows).reset_index(level=0) Timed with the dataset from @jezrael's post, it yields the following: 15.8 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
type: Answer
answers question: http://stackoverflow.com/q/47394793

http://stackoverflow.com/comment/82024190
has text: Check all pythons on your machine.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47532858

http://stackoverflow.com/comment/92374643
has text: @InesMontani: it is `sent.text`
type: AnswerComment
comment on: http://stackoverflow.com/a/47502965
score: 2
type: Comment

http://stackoverflow.com/comment/81739339
score: 0
comment on: http://stackoverflow.com/a/47393054
type: Comment
has text: @Travis I defined list `a` here too for completeness.
type: AnswerComment

http://stackoverflow.com/comment/81891066
type: Comment
type: QuestionComment
has text: what does `get_genes()` return specifically? Is it a `numpy` array or any other data type?
comment on: http://stackoverflow.com/q/47468174
score: 0

http://stackoverflow.com/a/47484562
has comment: http://stackoverflow.com/comment/81923968
type: AcceptedAnswer
downvote count: 0
has body: Building upon the solution in the links, you could iterate over each line for each line, extract a list of keys, and its value recurse into a dictionary with each key using setdefault assign the value at the bottom lines = \ ''' foo.bar:10 foo.hello.world:30 xyz.abc:40 pqr:100 '''.splitlines() d = {} for l in lines: k, v = l.split(':') *f, l = k.split('.') t = d for k in f: t = t.setdefault(k, {}) t[l] = int(v) # don't perform a conversion if your values aren't numeric print(d) { "pqr": 100, "foo": { "bar": 10, "hello": { "world": 30 } }, "xyz": { "abc": 40 } } Recursive setdefault traversal learned from here. Breaking down each step - Split on :, extract the key-list string and the value k, v = l.split(':') Split the key-string on . to get a list of keys. I take the opportunity to partition the keys as well, so I have a separate reference to the last key that will be the key to v. *f, l = k.split('.') *f is the catch-all assignment, and f is a list of any number of values (possibly 0 values, if there's only one key in the key-string!) For each key k in the key list f, recurse down into the "tree" using setdefault. This is similar to recursively traversing a linked list. for k in f: t = t.setdefault(k, {}) At the end, the last key value pair comes from l and v. t[l] = v
has comment: http://stackoverflow.com/comment/81923946
has comment: http://stackoverflow.com/comment/81923936
type: Answer
answers question: http://stackoverflow.com/q/47484332
score: 2
accepted answer of: http://stackoverflow.com/q/47484332
upvote count: 2

http://stackoverflow.com/comment/81841021
comment on: http://stackoverflow.com/a/47422889
type: Comment
has text: if I am using back-ticks in the INSERT statement I am able to successfully load the data into the mysql db. But if I try to view the same table through Django admin page its throwing **"string index out of range"** error for the same table. Is it because of the len(header) statement?
type: AnswerComment
score: 0

http://stackoverflow.com/q/47434127
has comment: http://stackoverflow.com/comment/81822626
has comment: http://stackoverflow.com/comment/81826099
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81824666
has title: Getting HTTPError on Ubuntu Server while it works on my Windows PC
tagged with: python
has comment: http://stackoverflow.com/comment/81827175
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/81824261
has comment: http://stackoverflow.com/comment/81863765
has body: I created a Discord Bot in Python which I want to be online 24/7 so I uploaded it to my Server. The Bot is fully working on my Windows PC where Im creating this Bot. I have made a html wrapper to get newest forum link of a forum category. If I start the Bot on Windows it works. I will get the link etc. But If a start it on my Ubuntu Server I will get the following Error: Ignoring exception in command patchnotes Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "launcher.py", line 67, in patchnotes newspage.raise_for_status() File "/usr/lib/python3/dist-packages/requests/models.py", line 840, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: http://board.asharu.com/index.php?board/2-news-game I checked the installed python3 modules with: apt-cache search -n ^python3 and also trying to import all the modules I need via the Python Shell without getting Error so I guess all modules I need are installed. The thing is, that I can't explain, why Im getting this Error only on my Ubuntu Server. Here is the Code I use: # command Patchnotes @client.command(pass_context=True) async def patchnotes(ctx, *arg): """ Get's the newest Topic of the Category "News Game" from board.asharu.com and send the link to the newest Topic to the chat. """ #try: newspage = requests.get('http://board.asharu.com/index.php?board/2-news-game') newspage.raise_for_status() #except requests.exceptions.RequestException as err: #return await client.say(err) tree = html.fromstring(newspage.content) for link_element in tree.xpath('//li[contains(@class, "columnSubject")]//h3//a'): href = link_element.get('href') return await client.say(href) the imports I use are: import discord import logging from lxml import html import requests from discord.ext import commands I also tried to set an UserAgent withou…
score: 0
has comment: http://stackoverflow.com/comment/81822775
answer count: 0
has comment: http://stackoverflow.com/comment/81823372
has comment: http://stackoverflow.com/comment/81823464
has comment: http://stackoverflow.com/comment/81822456
has comment: http://stackoverflow.com/comment/81822448
type: Question
has comment: http://stackoverflow.com/comment/81825708
tagged with: discord.py

http://stackoverflow.com/q/47434779
answer count: 2
has title: Python Selenium can't locate element
tagged with: selenium
has comment: http://stackoverflow.com/comment/81824151
has body: I have some troubles locating a username field on a webpage. Using find_element_by_name/class prompts me with a 'no such element' error. After a lot of fiddling, I still can not get this to work. Have not had this problem on any other webpages where I used the same method. Hope anyone can help me out! &lt;input type="text" class="_ph6vk _o716c" aria-describedby="" aria-label="Telefoonnummer, gebruikersnaam of e-mailadres" aria-required="true" autocapitalize="off" autocorrect="off" autocomplete="username" maxlength="30" name="username" placeholder="Telefoonnummer, gebruikersnaam of e-mailadres" value=""&gt; The HTML above represents the element which I want to locate.
has comment: http://stackoverflow.com/comment/81823747
type: Question
has answer: http://stackoverflow.com/a/47435507
has comment: http://stackoverflow.com/comment/81824363
has comment: http://stackoverflow.com/comment/81824491
has answer: http://stackoverflow.com/a/47435281
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81824224
has comment: http://stackoverflow.com/comment/81859733
has comment: http://stackoverflow.com/comment/81824377
score: 0
has comment: http://stackoverflow.com/comment/81824056

http://stackoverflow.com/q/47385700
accepted answer: http://stackoverflow.com/a/47397608
has title: Getting error "ValueError: could not covert string to float " in integer sequence learning
answer count: 1
tagged with: keras
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: python
has body: I am new to machine learning and I am trying to develop a simple RNN for an integer sequence model (Integer Sequence Learning - Kaggle Competition) My dataset is taken from the Kaggle competition and following is my code: import numpy import matplotlib.pyplot as plt import pandas as pd import math from keras.models import Sequential from keras.layers import Dense from keras.layers import SimpleRNN from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from keras.preprocessing.sequence import pad_sequences # convert an array of values into a dataset matrix def create_dataset(dataset, window_size=1): dataX, dataY = [], [] for i in range(len(dataset)-window_size-1): a = dataset[i:(i+window_size), 0] dataX.append(a) dataY.append(dataset[i + window_size, 0]) return numpy.array(dataX), numpy.array(dataY) # fix random seed for reproducibility numpy.random.seed(7) # loading data dataframe = pd.read_csv('G:/Python/integer_sequencing/train.csv', usecols=[1], engine='python', skipfooter=3) dataset = dataframe.values #dataset = dataset.astype('float32') train_size = int(len(dataset) * 0.67) #67 per cent used for training test_size = len(dataset) - train_size # remaining used for testing train, test = dataset[0:train_size], dataset[train_size:len(dataset)] #print(train_data.head(n=10)) # normalize the datasets scaler_train = MinMaxScaler(feature_range=(0, 1)) scaler_test = MinMaxScaler(feature_range=(0, 1)) train = scaler_train.fit_transform(train) test = scaler_test.fit_transform(test) # reshape input to be [samples, time steps, features] trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1])) print(trainX.shape) print(trainY.shape) I get an error as follows: How do I fix it? Please help... PS - I am using Time series prediction as example
score: -1
tagged with: recurrent-neural-network
type: Question
upvote count: 0
tagged with: deep-learning
has answer: http://stackoverflow.com/a/47397608

http://stackoverflow.com/q/47418938
has title: TypeError: unsupported operand type(s) for -: 'int' and 'tuple'
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81792181
has body: Hello everyone and thanks in advance, I write you on the forum to ask for your help. I have a problem on a program to invert an image with PIL. Voici le code complet: #!/usr/bin/python # -*- coding: utf-8 -*- from PIL import Image import random as r from math import * def ouvrir(nomimage): img=Image.open(nomimage) return img def affiche(img): img.show() def imc2img(imc,n): img=Image.new("F",imc.size) pixc=imc.load() pixg=img.load() width = imc.size[0] height=imc.size[1] for j in range(height): for i in range(width): pixg[i,j]=pixc[i,j][n] return img def imc2r(ims): imr=imc2img(ims,1) return imr def inverse_image(ims): img=Image.new("L",ims.size) pixc=ims.load() pixg=img.load() width=ims.size[0] height=ims.size[1] for j in range(height): for i in range(width): imi=pixg[i,j]=pixc[(255-i),(255-j)] return imi Find the problem and try to solve this? def inverse_image(ims): img=Image.new("L",ims.size) pixc=ims.load() pixg=img.load() width=ims.size[0] height=ims.size[1] for j in range(height): for i in range(width): imi=pixg[i,j]=255-pixc[i,j] return imi the error code was: Traceback (most recent call last): File "&lt;pyshell#18&gt;", line 1, in &lt;module&gt; imi=inverse_image(ims) File "C:\Users\Geoffray\Desktop\TP_note\code.py", line 43, in inverse_image imi=pixg[i,j]=255-pixc[i,j] TypeError: unsupported operand type(s) for -: 'int' and 'tuple' Thanks You! I hope that my explanation is clear enough.
has comment: http://stackoverflow.com/comment/81803846
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81792182
tagged with: python
has comment: http://stackoverflow.com/comment/81791961
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81792521
has comment: http://stackoverflow.com/comment/81792550
has comment: http://stackoverflow.com/comment/81792012
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81792326
favorite count: 0
type: Question

http://stackoverflow.com/comment/81801510
comment on: http://stackoverflow.com/a/47422399
type: Comment
has text: I thought so. But hard to do those lowercase uppercase stuff. thanks for the precisions. As I said, not a `pandas` expert, I almost _never_ answer `pandas` question but that one was hanging low in front of me so...
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82009747
type: AnswerComment
has text: My question is about special characters
type: Comment
comment on: http://stackoverflow.com/a/47526835
score: 0

http://stackoverflow.com/q/47405270
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81764072
tagged with: python
has title: I am not able to install peewee using pycharm terminal. I am using this 'pip install peewee' but can't import the library
score: 0
tagged with: installation
has body: Command "C:\Users\asus\Anaconda2\python.exe -u -c "import setuptools, tokenize;file='c:\users\asus\appdata\local\temp\pip-build-54ytkq\peewee\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\asus\appd ata\local\temp\pip-q5dadg-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\asus\appdata\local\temp\pip- build-54ytkq\peewee\
answer count: 1
has answer: http://stackoverflow.com/a/47406813
type: Question
tagged with: peewee

http://stackoverflow.com/q/47463987
has answer: http://stackoverflow.com/a/47464112
answer count: 2
accepted answer: http://stackoverflow.com/a/47504485
has answer: http://stackoverflow.com/a/47504485
possible better answer: http://stackoverflow.com/a/47464112
type: Question
tagged with: numpy
tagged with: neural-network
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
has body: I have mnist training list in the following form: def load_data(): f = gzip.open('mnist.pkl.gz', 'rb') training_data, validation_data, test_data = cPickle.load(f, encoding='latin1') f.close() def load_data_wrapper(): tr_d, va_d, te_d = load_data() training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]] training_results = [vectorized_result(y) for y in tr_d[1]] training_data = list(zip(training_inputs, training_results)) ........................................ Now I would like to preprocess my training inputs to have zero mean and unit variance. So I used from sklearn import preprocessing in the following: def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): if test_data: n_test = len(test_data) preprocessed_training = preprocessing.scale(training_data) n = len(preprocessed_training) for j in range(epochs): random.shuffle(preprocessed_training) mini_batches = [ training_data[k:k+mini_batch_size]..... .................... However, I'm getting the following error: ValueError: setting an array element with a sequence. I'm modifying code from mnielsen that can be found here. I'm new in python and machine learning in general. I would appreciate if anyone can help me out. Note: If you think there is a better library option then please let me know as well. Update_1: This was my another try which gives the same error. scaler = StandardScaler() scaler.fit(training_data) training_data = scaler.transform(training_data) if test_data: test_data = scaler.transform(test_data) Update_2: I tried the solution provided in the suggested answer using pandas dataframe but I am still getting the same error. Update_3 : So it's object type but I need float type to perform scaler. I did the following: training_data = np.asarray(training_data).astype(np.float64) and I still get the error! Update_4 : General mnist dataset structure: 50k training images, 10k test images. In 50k images, each image is 28 * 28 pixels , which gives 784 data points. For example, a data po…
linked to: http://stackoverflow.com/q/4674473
has title: Preprocessing training list with sklearn
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47499430
has comment: http://stackoverflow.com/comment/81954252
has comment: http://stackoverflow.com/comment/81954237
has comment: http://stackoverflow.com/comment/81954963
answer count: 2
has answer: http://stackoverflow.com/a/47499575
has body: Hi All I have a Dataframe with more than 50000 records. It has a column by name "Country" which has duplicate values. As part of a Machine Learning project I am doing a Label Encoding on this column which will replace this column with 50000 records with integer values. (ok for those who do not know about Label Encoding - it takes the unique values of the column and assign an integer value to it mostly based on alphabetical order but not sure though). Say this Dataframe is DF1 and column is "Country". Now my requirement is that I have to do the same for another dataframe (DF2) manually i.e without using the Label Encoding function. What I have tried so far and where do I get struck is mentioned below I have taken the unique values of DF1.Country column and kept in a new dataframe(temp_df). Tried to do right join of DF2 and temp_df keeping on="Country". But getting "NaN" in few records. Not sure why Tried to do find-and-replace using .isin method but still not getting desired output. So my basic question is how to fill a column in a dataframe with the values of a column in another dataframe by matching the values of two columns in two dataframes ? UPDATED Sample code output is given below for better understanding The Country Column in DF2 has repeatable values like this : 0 us 1 us 2 gb 3 us 4 au 5 fr 6 us 7 us 8 us 9 us 10 us 11 us 12 ca 13 at 14 us 15 us 16 es 17 fi 18 fr 19 us 20 us The temp_df dataframe will have integer value for every unique country name like mentioned below (Note : This dataframe will only have unique values. Not duplicates) : 1 gb 49 2 ca 22 3 au 5 4 de 34 5 fr 48 6 br 17 7 jp 75 8 sv 136 9 no 111 10 se 132 11 es 43 12 nl 110 13 mx 103 14 dk 36 15 ro 127 16 ch 24 17 it 71 18 be 10 19 ru 129 20 kr 78 21 fi 44 22 hk 59 23 ie 65 24 sg 133 25 nz 112 26 ar 3 27 at 4 28 in 68 29 cl 26 30 il 66 Now I have to create a new column in DF2 by taking the integer values from temp_df for each country value in DF2. Hope this helps.
has comment: http://stackoverflow.com/comment/81954182
tagged with: pandas
has comment: http://stackoverflow.com/comment/81954465
type: UnansweredQuestion
has title: Python Pandas - How to substitue a column of DataFrame1 with the values of a column in DataFrame2
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/81955107
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81954467
has answer: http://stackoverflow.com/a/47499499
score: -2
tagged with: python

http://stackoverflow.com/q/47409805
tagged with: numpy-memmap
type: Question
tagged with: numpy
has body: I have a binary file and I am parsing it to a numpy array in Python like the following: bytestream= np.fromfile(path, dtype=np.int16) for a in range(sizeA): for x in range(0, sizeX): for y in range(0, sizeY): for z in range(0, sizeZ): parsed[a, x, y, z] = bytestream[z + (sizeZ * x) + (sizeZ * sizeX * y) + (sizeZ * sizeX * sizeY * a)] However, this is very very slow. Can anyone tell me why and how to speed it up?
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: fromfile
has answer: http://stackoverflow.com/a/47430752
has answer: http://stackoverflow.com/a/47410486
possible better answer: http://stackoverflow.com/a/47430752
accepted answer: http://stackoverflow.com/a/47410486
has title: Reading numpy array from file and parsing very slow

http://stackoverflow.com/comment/81801340
has text: @COLDSPEED thanks, excellent edit. Wouldn't setting `inplace=True,` be better than assigning back to `df['surf']` ? (not the pandas expert, you tell me). Also, raw prefix is not needed here, there are no backslashes in the regex.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47422399
type: AnswerComment

http://stackoverflow.com/q/47440951
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81836934
has comment: http://stackoverflow.com/comment/81837265
has comment: http://stackoverflow.com/comment/81837902
has body: I have a list of starting values which all should go into index 152 of a new list which goes from the starting value (at the 152nd index) to some maximum, and then starting from zero again up to the starting value with some regular spacing. To make this more clear with a simpler example, imagine my starting list looks like this: [3,4,1,2] and these starting values are to be assigned to the second index of a new list of length 8 evenly spaced from a minimum value of 1 to a maximum value of 4. I need to generate four lists that look like the following: [2.5,3,3.5,4,0.5,1,1.5,2] with 3 as the starting value in the second index [3.5,4,0.5,1,1.5,2,2.5,3] with 4 as the starting value in the second index [0.5,1,1.5,2,2.5,3,3.5,4] with 1 as the starting value in the second index [1.5,2,2.5,3,3.5,4,0.5,1] with 2 as the starting value in the second index My actual starting list is 20 entries long so I need to generate 20 new lists with each of those starting values in the 152nd index of a 192 index long list. The minimum value is 0 with a maximum of 24. So going from the starting value, the rest of the list should be filled with even increments to go from start value to max value and then from min value back to start value-increment keeping the starting value in the 152nd index. I hope this makes sense. It is hard to explain, and probably why I am having trouble coding it as well. I have an idea for how to do it, however I am curious if there is an obvious pythonic way I just haven't learned yet. Thanks! Edit: Here is what I have: nlon = 192 lon_idx = 152 lt = [19.6, 19.65, 19.7] spacing = 24/nlon nbefore = lon_idx - 1 nafter = nlon - lon_idx time_dict = {} for i in lt: b = nbefore a = nafter temp = [i] while b &gt; 0: val = temp[0]-spacing if val &lt; 0: temp.insert(0, 24) else: temp.insert(0, val) b -= 1 while a &gt; 0: val = temp[-1]+spacing if val &gt; 24: temp.append(0) else: temp.append(val) a -= 1 time_dict['lst_%s' % i] = temp print (time_dict['lst_19.65'][151]) It wo…
has comment: http://stackoverflow.com/comment/81836921
tagged with: python
has answer: http://stackoverflow.com/a/47442349
has title: Fill a list given a starting value at a specific index
accepted answer: http://stackoverflow.com/a/47442349
type: AnsweredQuestion
score: 0
tagged with: list
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47468605
answer count: 1
downvote count: 0
tagged with: django
has body: I am using django-celery (https://pypi.python.org/pypi/django-celery/) to store celery beat (Periodic Task) schedules in the DB. But it doesn't support celery beyond version 3.1.25. I want to move to celery 4.1.0 and so I was looking at moving to django-celery-beat (https://pypi.python.org/pypi/django_celery_beat) for db based schedules. I was able to successfully migrate the table structures along with data. However, I see that django-celery-beat does not support crontab schedules with multiple minutes and hours which djcelery supported. For example, consider this crontab schedule - 15,30,45 0,1 * * * The task will run everyday at 12:15, 12:30, 12:45, 1:15, 1:30, 1:45. This used to work in django-celery. But in django-celery-beat, it only seems to execute at 12:15 (first instance). Old setup - Django==1.10, celery==3.1.24, django-celery==3.1.17 New setup - Django==1.11.7, celery==4.1.0, django-celery-beat==1.1.0 Can anyone confirm whether or not support for such crontab schedules has been dropped in django-celery-beat? If it is supposed to work, is it an issue with celery or django-celery-beat? Thanks
has answer: http://stackoverflow.com/a/48704337
has comment: http://stackoverflow.com/comment/81891983
has title: Does django_celery_beat support crontab schedules with multiple minutes/hours?
favorite count: 0
tagged with: celery
has comment: http://stackoverflow.com/comment/81891606
has comment: http://stackoverflow.com/comment/81895712
tagged with: django-celery
tagged with: python
has comment: http://stackoverflow.com/comment/81891758
has comment: http://stackoverflow.com/comment/81894739
type: Question
score: 2
has comment: http://stackoverflow.com/comment/81892219
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/47395626
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81751527
has body: You got remarkably far considering that OOXML is such a complex format. Here's some sample Python code showing how to access the comments of a DOCX file via XPath: from lxml import etree import zipfile ooXMLns = {'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'} def get_comments(docxFileName): docxZip = zipfile.ZipFile(docxFileName) commentsXML = docxZip.read('word/comments.xml') et = etree.XML(commentsXML) comments = et.xpath('//w:comment',namespaces=ooXMLns) for c in comments: # attributes: print(c.xpath('@w:author',namespaces=ooXMLns)) print(c.xpath('@w:date',namespaces=ooXMLns)) # string value of the comment: print(c.xpath('string(.)',namespaces=ooXMLns))
accepted answer of: http://stackoverflow.com/q/47390928
has comment: http://stackoverflow.com/comment/102112661
answers question: http://stackoverflow.com/q/47390928
type: Answer
score: 13
upvote count: 13
downvote count: 0

http://stackoverflow.com/q/47392998
tagged with: methods
has comment: http://stackoverflow.com/comment/81739289
type: Question
has comment: http://stackoverflow.com/comment/81739985
has answer: http://stackoverflow.com/a/47393169
answer count: 2
linked to: http://stackoverflow.com/q/1132941
downvote count: 0
has comment: http://stackoverflow.com/comment/81739069
upvote count: 1
possible better answer: http://stackoverflow.com/a/47393105
duplicate of: http://stackoverflow.com/q/1132941
has answer: http://stackoverflow.com/a/47393105
favorite count: 0
tagged with: class
accepted answer: http://stackoverflow.com/a/47393169
type: AnsweredQuestion
tagged with: oop
has title: Default arguments in class method not unique python
score: 1
has body: I am having a problem with default arguments in python classes. It seems that when an argument is not given, the default links to the same object for all instances of a class. Example: class My_class: def __init__(self,options=[]): self.options = options class1 = My_class() class2 = My_class() class2.options.append('something') print(class1.options) This would print: ['something'] How can i make sure each instance of a class will have a unique list for options, instead of a reference to the same object. For example, this is how i could do it: def __init__(self,options=None): if options is None: options = [] self.options = options However, this doesnt feel correct to me. So my questions are if there is a better way to do it, and for someone to explain the initial behaviour to me since i have a clue what is going on, but i don't fully understand why
tagged with: python
has comment: http://stackoverflow.com/comment/81739014

http://stackoverflow.com/q/47400038
type: Question
has title: Python function behaves unexpectedly
linked to: http://stackoverflow.com/q/13419822
tagged with: function
upvote count: 0
has comment: http://stackoverflow.com/comment/81753527
score: -2
accepted answer: http://stackoverflow.com/a/47400063
downvote count: 2
answer count: 1
has body: I am doing a very simple transformation on a pandas dataframe by using a function, but I didn't expect the function will change the input dataframe (but it did). I was wondering why... Here's my code: x = pd.DataFrame({'a': [1,2,3], 'b': [3,4,5]}) def transform(df, increment): new_df = df new_df.a = new_df.a + increment return new_df new_x = transform(x, 1) new_x # output shows new_x.a is [2,3,4], which is expected. x # output shows x.a is also [2,3,4]. I thought it should be [1,2,3] Why is this the case? I think, in the function, all the operations are executed on the new_df, so the input x should stay exactly the same before and after I ran this transform function, isn't it?
tagged with: python
has answer: http://stackoverflow.com/a/47400063
duplicate of: http://stackoverflow.com/q/13419822
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/81753505
has comment: http://stackoverflow.com/comment/81753522

pipeline
type: Tag
tag name: pipeline
tags question: http://stackoverflow.com/q/47525609
tags question: http://stackoverflow.com/q/47404571

http://stackoverflow.com/q/47459225
type: UnansweredQuestion
tagged with: neural-network
downvote count: 0
has answer: http://stackoverflow.com/a/47466512
has answer: http://stackoverflow.com/a/47679004
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/42513613
favorite count: 0
has body: I'm trying to build a seq2seq model in tensorflow (1.4) using the tf.contrib.rnn.ConvLSTMCell API together with the tf.nn.dynamic_rnn API, but I got an error with the dimension of the inputs. My code is: # features is an image sequence with shape [600, 400, 10], # so features is a tensor with shape [batch_size, 600, 400, 10] features = tf.transpose(features, [0,3,1,2]) features = tf.reshape(features, [params['batch_size'],10,600,400]) encoder_cell = tf.contrib.rnn.ConvLSTMCell(conv_ndims=2, input_shape=[600, 400,1], output_channels=5, kernel_shape=[7,7], skip_connection=False) _, encoder_state = tf.nn.dynamic_rnn(cell=encoder_cell, inputs=features, sequence_length=[10]*params['batch_size'], dtype=tf.float32) I get the following error ValueError: Conv Linear expects all args to be of same Dimension: [[2, 600, 400], [2, 600, 400, 5]] Looking at the tf implementation, it seems that the inputs to dynamic_rnn is only 3-dimensional in contrary to the hidden state, which is 4-dimensional. I tried to pass the input as a nested tuple, but it didn't work. The problem is similar to TensorFlow dynamic_rnn regressor: ValueError dimension mismatch, it's slightly different though, as they're using a plain LSTMCell (which worked for me). Can anyone give me a minimal example how to use these 2 APIs together? Thanks!
tagged with: conv-neural-network
score: 1
has comment: http://stackoverflow.com/comment/86030221
tagged with: recurrent-neural-network
tagged with: tensorflow
has title: ValueError: ConvLSTMCell and dynamic_rnn
type: Question
answer count: 2

http://stackoverflow.com/q/47479965
tagged with: python
has comment: http://stackoverflow.com/comment/81914924
tagged with: module
has body: Is there a point to import as both wildcard and non-wildcard manner like: import spam as sp from spam import * in the very same file?
has comment: http://stackoverflow.com/comment/81914876
answer count: 4
tagged with: python-import
linked to: http://stackoverflow.com/q/2386714
score: 2
upvote count: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47480033
accepted answer: http://stackoverflow.com/a/47480030
downvote count: 0
has answer: http://stackoverflow.com/a/47480032
has answer: http://stackoverflow.com/a/47480033
has answer: http://stackoverflow.com/a/47480030
linked to: http://stackoverflow.com/q/2360724
tagged with: import
favorite count: 0
has comment: http://stackoverflow.com/comment/81914748
has answer: http://stackoverflow.com/a/47480037
type: Question
has title: Is there a point to import the same module in two different ways in a program?
tagged with: package

http://stackoverflow.com/a/47491304
has body: Using two loops are not good option for this little task , importing any external module is also not good option: One line solution without any loop: nested_list = [['1','2','3'],['2','4','6']] print(list(map(lambda x:list(map(lambda y:float(y),x)),nested_list))) output: [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]]
score: -1
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/47485633
has comment: http://stackoverflow.com/comment/81971565
has comment: http://stackoverflow.com/comment/81971722
type: Answer

http://stackoverflow.com/q/47396893
has comment: http://stackoverflow.com/comment/81746977
favorite count: 0
has title: Python: 'int' not subscriptable
duplicate of: http://stackoverflow.com/q/8220702
has body: Here is my code to read in a file. I am supposed to sort the numbers in columns[14] in descending order. My code is giving me the error TypeError: 'int' object is not subscriptable. How can I fix this? with open("AT.txt", "r") as f: for line in f: columns = line.split("\t") if (int(columns[14]) &gt; 0): array = [columns[1], int(columns[14])] sorted(array, key=lambda x: x[1], reverse=True) For example when I output print(array) before the sorted line I have: ['Bartenberg', 50] ['Eden', 66] ['Watzing', 23] My desired output would be: ['Watzing', 23] ['Bartenberg', 50] ['Eden', 66] If I change my code to something like: with open("AT.txt", "r") as f: for line in f: columns = line.split("\t") if (int(columns[14]) &gt; 0): c15 = int(columns[14]) array = [columns[1], c15] sorted(array, key=lambda x: x[1], reverse=True) print(array) I still get the same error When I put my data in a dictionary: dictlist =[dict[columns[7], columns[14]]] I get the same error
type: Question
linked to: http://stackoverflow.com/q/8220702
answer count: 0
tagged with: arrays
downvote count: 0
type: UnansweredQuestion
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/81748307
has comment: http://stackoverflow.com/comment/81747224
has comment: http://stackoverflow.com/comment/81748512
tagged with: list
has comment: http://stackoverflow.com/comment/81746931
upvote count: 1
score: 1

http://stackoverflow.com/q/47452359
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/24735311
has title: What does the / sign means in the signature of numpy functions like sqrt?
duplicate of: http://stackoverflow.com/q/24735311
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
has body: What does the / sign means in the signature of numpy functions? The / sign appears between the positional and keword arguments. For example: sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) Online documentation of numpy.sqrt -- and numpy.power functions.

http://stackoverflow.com/q/47490624
has answer: http://stackoverflow.com/a/47490682
tagged with: append
tagged with: enumerate
possible better answer: http://stackoverflow.com/a/47490644
tagged with: list
has body: I am creating a list containing the indices of the lowest three numbers in a separate list (excluding 0 - this is part of a knn function). x = [0, 6, 9, 8, 7, 2, 5, 3, 4, 1] y = [] for index, item in enumerate(x): if 0 &lt; item &lt; 4: y.append(index) print y Out: [5, 7, 9] I would expect y to equal [9, 5, 7], but the list is returned sorted. While this is probably ok for what I'm doing - how can I return the indices in the order they are appended? Update: As lots of people quickly pointed out, I'm an idiot, what I mean to ask is, how can I return y to equal [9,5,7], instead of returning the indices in the order they are appended?
has comment: http://stackoverflow.com/comment/81936672
has comment: http://stackoverflow.com/comment/81936613
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81936748
score: -1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47490644
has title: Behaviour of append and enumerate - when appending to list, can I return values in an order other than they way they are appended?
answer count: 2
accepted answer: http://stackoverflow.com/a/47490682
has comment: http://stackoverflow.com/comment/81936723
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47495885
has comment: http://stackoverflow.com/comment/85112395
tagged with: python
has title: Loading a DLL many times with WinDLL under Python
tagged with: ctypes
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81947630
upvote count: 1
favorite count: 0
type: Question
has body: I am developing a Python application under Windows that drives the Vellemann K8055 card (an I/O card). The manufacturer provided the DLL. Using a Python module, I can drive it with no issues but one. From time to time, because of some electrical interference, the card resets itself, and if I issue a command toward the card I never get an answer. Beside the fact that I need to fix the electrical interference to eliminate the root cause, there is the problem that the card is at a remote site. I can go there only once every 3 or 4 months. Therefore I need a software workaround. I realized that if I reload the DLL, the connection to the card is re-initialized, allowing me to drive it again. What I am not sure of is whether there are other implications in loading the same DLL many times using the ctypes WinDLL function. Does anybody have experience with this?
tagged with: dll
type: UnansweredQuestion
score: 1
tagged with: windows

http://stackoverflow.com/comment/81979584
comment on: http://stackoverflow.com/q/47511885
type: Comment
type: QuestionComment
has text: if you just do `{{ userprofile.photo.url }}` what does it show? Is it the exact same link? Maybe there is a duplication of `/` somewhere. Try this out and compare.
score: 0

http://stackoverflow.com/a/47520129
has comment: http://stackoverflow.com/comment/81997034
type: Answer
has comment: http://stackoverflow.com/comment/81997047
has comment: http://stackoverflow.com/comment/81996762
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47520092
upvote count: 1
has body: you could count the words in your loop, but it's more pythonic to feed sum with a generator comprehension filtered on the word size: &gt;&gt;&gt; l = "Hello world is me" &gt;&gt;&gt; sum(1 for w in l.split() if len(w)==5) 2 another variant is to convert the result of the test to boolean (here the result of the test is already a boolean so no need to bool() it), and sum that: sum(len(w)==5 for w in l.split()) It's ideal for testing one condition, but if you want to count words matching several conditions (len &lt; 5, len == 5) in one go, the classical loop remains the best choice since it iterates on the list only once and you're naturally using short-circuit evaluation with if/elsif, too bad for listcomps but that's life: less_than_5=exactly_5=0 for item in l.split() : if len(item) &lt; 5 : less_than_5 += 1 elif len(item) == 5 : exactly_5 += 1
has comment: http://stackoverflow.com/comment/81996995

http://stackoverflow.com/a/47525474
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47525379
has body: What you need is a Cartesian product of the three sets: import pandas as pd from itertools import product pd.DataFrame(list(product(A,M,F)), columns=['A', 'M', 'F'])

http://stackoverflow.com/comment/81966083
comment on: http://stackoverflow.com/q/47505127
type: Comment
has text: What exactly do you mean by "use"? Do something with the same arguments a particular instance of `A` was constructed with?
score: 0
type: QuestionComment

http://stackoverflow.com/q/47476912
answer count: 2
tagged with: pandas
tagged with: pivot-table
has answer: http://stackoverflow.com/a/47477416
linked to: http://stackoverflow.com/q/43119503
has body: I have a dataframe: index col1 col2 col3 0 X A 123 1 X A 456 2 X B 654 3 X B 321 4 X A 111 I'm trying to use pivot_table to get this df into the following format: index A B 0 123 654 1 456 321 2 111 NaN I'm trying to use... pivot_table(index=df.index, columns=['col2'], values='col3'), however this just ends up in the following state: index A B 0 123 NaN 1 456 NaN 2 111 NaN 3 NaN 654 4 NaN 321 How can I avoid this?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47477094
possible better answer: http://stackoverflow.com/a/47477416
has answer: http://stackoverflow.com/a/47477094
tagged with: python
has title: Ensure adjacent column values using pandas pivot_table
type: Question
score: 0

http://stackoverflow.com/a/47503098
has comment: http://stackoverflow.com/comment/81969768
has comment: http://stackoverflow.com/comment/124546564
has comment: http://stackoverflow.com/comment/124563981
downvote count: 1
has body: Let's start with a list of 4 polygons, three of which overlap other polygons: from shapely.geometry import Polygon import geopandas polygons = [ Polygon([[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]), Polygon([[1, 3], [1, 5], [3, 5], [3, 3], [1, 3]]), Polygon([[2, 2], [2, 3.5], [3.5, 3.5], [3.5, 2], [2, 2]]), Polygon([[3, 1], [3, 2], [4, 2], [4, 1], [3, 1]]), ] gdf = geopandas.GeoDataFrame(data={'A': list('ABCD')}, geometry=polygons) gdf.plot(column='A', alpha=0.75) They look like this: So we can loop through each one, then loop through all of the others and check for overlaps with the shapely API. If there are not any overlaps, we'll append it to our output list: non_overlapping = [] for p in polygons: overlaps = [] for g in filter(lambda g: not g.equals(p), polygons): overlaps.append(g.overlaps(p)) if not any(overlaps): non_overlapping.append(p) Any that gives me: ['POLYGON ((3 1, 3 2, 4 2, 4 1, 3 1))'] Which is what I'd expect. But this is effectively O(N^2), and I don't think it has to be. So let's try to never check the same pair twice: non_overlapping = [] for n, p in enumerate(polygons[:-1], 1): # don't include the last element overlaps = [] for g in polygons[n:]: # loop from the next element to the end overlaps.append(g.overlaps(p)) if not any(overlaps): non_overlapping.append(str(p)) And I get the same result and it's a smidge faster on my machine. We can compress the loop a bit by using generator in the if statement instead of a normal for block: non_overlapping = [] for n, p in enumerate(polygons[:-1], 1): if not any(p.overlaps(g) for g in polygons[n:]): non_overlapping.append(p) Same story.
answers question: http://stackoverflow.com/q/47471872
has comment: http://stackoverflow.com/comment/135903315
upvote count: 5
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/124546716
has comment: http://stackoverflow.com/comment/124557044

http://stackoverflow.com/a/47438028
has comment: http://stackoverflow.com/comment/89734446
has body: First make sure that you have the latest versions of the needed modules(e.g. scipy, numpy etc). When you type random.seed(1234), you use the numpy generator. When you use random_state parameter inside the RandomForestClassifier, there are several options: int, RandomState instance or None. From the docs here : If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. A way to use the same generator in both cases is the following. I use the same (numpy) generator in both cases and I get reproducible results (same results in both cases). from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification from numpy import * X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False) random.seed(1234) clf = RandomForestClassifier(max_depth=2) clf.fit(X, y) clf2 = RandomForestClassifier(max_depth=2, random_state = random.seed(1234)) clf2.fit(X, y) Check if the results are the same: all(clf.predict(X) == clf2.predict(X)) #True Check after running the same code for 5 times: from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification from numpy import * for i in range(5): X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False) random.seed(1234) clf = RandomForestClassifier(max_depth=2) clf.fit(X, y) clf2 = RandomForestClassifier(max_depth=2, random_state = random.seed(1234)) clf2.fit(X, y) print(all(clf.predict(X) == clf2.predict(X))) Results: True True True True True
has comment: http://stackoverflow.com/comment/89724080
answers question: http://stackoverflow.com/q/47433920
has comment: http://stackoverflow.com/comment/132453756
has comment: http://stackoverflow.com/comment/81854219
type: Answer
score: 11
upvote count: 11
accepted answer of: http://stackoverflow.com/q/47433920
has comment: http://stackoverflow.com/comment/89734067
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/127211820
downvote count: 0
has comment: http://stackoverflow.com/comment/127220654

http://stackoverflow.com/comment/81977969
has text: What is `$N`? That isn't set in your script or passed via the environment.
type: QuestionComment
comment on: http://stackoverflow.com/q/47510830
score: 0
type: Comment

http://stackoverflow.com/comment/82037900
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47540395
has text: You should return it from your first function and pass it into the second function.

http://stackoverflow.com/a/47394322
has comment: http://stackoverflow.com/comment/81743297
has body: Assuming each line is transformed in the same way, you could apply your transform functions to each line and use a generator to iterate over all lines, personally I find this more readable. def transform_1(line): return line.replace(' ','') # example of transformation def transform_2(line): return line.strip('#') def process_file(file_location): with open(file_location) as in_f: for line in in_f: yield transform_2(transform_1(line)) Depending on what the transforms do, they could possibly be combined into a single function, but it's hard to know without more context.
has comment: http://stackoverflow.com/comment/81742546
has comment: http://stackoverflow.com/comment/81741859
has comment: http://stackoverflow.com/comment/81742005
type: Answer
has comment: http://stackoverflow.com/comment/81741893
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47394184
downvote count: 0
has comment: http://stackoverflow.com/comment/81741734
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47394184

http://stackoverflow.com/q/47527630
has answer: http://stackoverflow.com/a/47531214
tagged with: python
tagged with: excel
has body: what I was trying to do using Openpyxl is that I copy some cell's values from excel sheet and then open another excel sheet and paste those values. Unexpectedly I got the sheet where the border lines broke, especially combined cells. I'd like to hear your opinion. Also, is there a better way to loop through cells? Currently it is only three cells, but what if it is over 100.... Thank you so much. from openpyxl import load_workbook import os from os.path import exists target_file = input('ex)201711 ') wb = load_workbook(target_file + '.xlsm', data_only=True) sheet = wb['summary'] num_people = len(sheet['A:A']) for i in range(1, num_people): val_1 = sheet.cell(row=i + 1, column=1).value val_2 = sheet.cell(row=i + 1, column=2).value val_3 = sheet.cell(row=i + 1, column=3).value file_name = '2017(' + val_1 + ').xlsx' if not exists(file_name): continue else: wb = load_workbook(file_name, data_only=True) sheet2 = wb['summary2'] sheet2.cell(row=1, column=1).value = val_1 sheet2.cell(row=1, column=2).value = val_2 sheet2.cell(row=1, column=3).value = val_3 wb.save(file_name)
has title: Openpyxl border line breaks when copying data from one sheet and then pasting it to another excel sheet
score: 1
tagged with: openpyxl
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47409308
downvote count: 1
favorite count: 0
type: Question
tagged with: for-loop
answer count: 1
upvote count: 1
tagged with: python
has title: Stop a loop if information is not found
has body: I created a web scraping program that open several URLs, it checks which one of the URLs has information related to "tomorrow"s date and then it prints some specific information that is on that URL. My problem is that sometimes none of the URLs in that list has information concerning "tomorrow". So I would like that in such case, the program prints other innformation like "no data found". How could I accomplish that? Other doubt I have, do I need the while loop at the beginning? Thanks. My code is: from datetime import datetime, timedelta tomorrow = datetime.now() + timedelta(days=1) tomorrow = tomorrow.strftime('%d-%m-%Y') day = "" while day != tomorrow: for url in list_urls: browser.get(url) time.sleep(1) dia_page = browser.find_element_by_xpath("//*[@id='item2']/b").text dia_page = dia_page[-10:] day_uns = datetime.strptime(dia_page, "%d-%m-%Y") day = day_uns.strftime('%d-%m-%Y') if day == tomorrow: meals = browser.find_elements_by_xpath("//*[@id='item2']/span") meal_reg = browser.find_element_by_xpath("//*[@id='item_frm']/span[1]").text sopa2 = (meals[0].text) refeicao2 = (meals[1].text) sobremesa2 = (meals[2].text) print(meal_reg) print(sopa2) print(refeicao2) print(sobremesa2) break
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47409351
tagged with: while-loop
has answer: http://stackoverflow.com/a/47409351
tagged with: break
tagged with: loops

math
tags question: http://stackoverflow.com/q/47445309
tags question: http://stackoverflow.com/q/47417718
tags question: http://stackoverflow.com/q/47383691
tags question: http://stackoverflow.com/q/47463827
tags question: http://stackoverflow.com/q/47445678
type: Tag
tags question: http://stackoverflow.com/q/47492663
tags question: http://stackoverflow.com/q/47493154
tags question: http://stackoverflow.com/q/47466806
tags question: http://stackoverflow.com/q/47488307
tag name: math
tags question: http://stackoverflow.com/q/47463587

http://stackoverflow.com/a/47447206
accepted answer of: http://stackoverflow.com/q/47446929
has comment: http://stackoverflow.com/comment/81849752
type: Answer
answers question: http://stackoverflow.com/q/47446929
score: 1
has comment: http://stackoverflow.com/comment/81849756
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: print(df) Out[35]: user_id a s session b b C b C revenue -1 0 1 2 1 Op1 df.columns=df.columns.map('_'.join) df Out[37]: a_b a_b s_C s_b s_C revenue -1 0 1 2 1 Op2 df.T.reset_index() Out[41]: user_id session revenue 0 a b -1 1 a b 0 2 s C 1 3 s b 2 4 s C 1 Then do the following calculation you need Data Input: df = pd.DataFrame({'user_id':['a','a','s','s','s'], 'session':['b','b','C','b','C'], 'revenue':[-1,0,1,2,1]}) df=df.set_index(['user_id','session']).T

http://stackoverflow.com/q/47410951
tagged with: rest
tagged with: azure
score: 1
has comment: http://stackoverflow.com/comment/81784982
tagged with: python
has comment: http://stackoverflow.com/comment/81775690
has comment: http://stackoverflow.com/comment/81776459
has comment: http://stackoverflow.com/comment/89268025
favorite count: 0
answer count: 0
has body: I'm trying to deploy simple Azure web application. I create it exactly as described here https://learn.microsoft.com/en-us/azure/app-service/app-service-web-get-started-python but replaced code in main.py with following (and update requirements.txt of course): from flask import Flask, request from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) todos = {} class HelloWorld(Resource): def get(self): return {'hello': 'world'} class TodoSimple(Resource): def get(self, todo_id): return {todo_id: todos[todo_id]} def put(self, todo_id): todos[todo_id] = request.form['data'] return {todo_id: todos[todo_id]} api.add_resource(HelloWorld, '/') api.add_resource(TodoSimple, '/&lt;string:todo_id&gt;') if __name__ == '__main__': app.run(debug=True) Everything works fine locally, but there are issues with deployed version: -- http://my-app-name-here.azurewebsites.net is just fine and prints {'hello': 'world'} as expected -- other commands provided by TodoSimple are not accessible. For example following query curl http://my-app-name-here.azurewebsites.net/todo -d "data=Remember the milk" -X PUT would result with "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable." response. Update: it's all fine when ran locally $curl http://localhost:5000/todo -d "data=Remember the milk" -X PUT { "todo": "Remember the milk" } Does anyone know what I'm missing with this app deployment? Update2: approach without flask_restful won't work either: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/data') def get_data(): return 'The data.' if __name__ == '__main__': app.run() Calling http://my-app-name-here.azurewebsites.net/data results in "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable." message again.
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81776024
downvote count: 0
has comment: http://stackoverflow.com/comment/81784680
tagged with: flask
has comment: http://stackoverflow.com/comment/81775766
type: Question
has title: Cannot deploy REST API with Python on Azure
tagged with: azure-web-app-service
has comment: http://stackoverflow.com/comment/81789093

http://stackoverflow.com/q/47518559
upvote count: 0
has title: How can I pass user input in the form of a variable to a lambda function in python?
has answer: http://stackoverflow.com/a/47519169
tagged with: calculator
tagged with: variables
downvote count: 1
favorite count: 0
tagged with: graphing
possible better answer: http://stackoverflow.com/a/47520510
type: Question
has comment: http://stackoverflow.com/comment/81993792
tagged with: python
score: -1
has body: so I'm kind of new to programming and I was looking for some help. I'm making a graphing calculator and would like to have the user enter an equation using x such as (x + 3) or (x^2 + 3x + 4). I recently found out about the lambda function and was wondering if there was a way to pass a variable to it in order to get plot points with the user's equation. I plan on using a for loop to keep passing new values into the equation. If you have any other suggestions on how to go about completing my graphing calculator please do not hesitate to inform me. My code so far is only a way for the user to navigate through my program. Here is my code: def main(): while True: response = menu() if response == "1": print("enter an equation in the form of mx + b") equation = (input()) print(coordinates(equation)) elif response == "2": print("enter a value for x") x = input() print("enter a value for y") y = input() elif response == "0": print("Goodbye") break else: print("please enter '1' '2' or '0'") def menu(): print("Graphing Calculator") print("0) Quit") print("1) Enter an equation") print("2) Plot points") print("Please select an option") response = input() return response """def coordinates(equation): f = lambda x: equation """ if __name__ == "__main__": main()
tagged with: lambda
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81993319
has answer: http://stackoverflow.com/a/47520510
answer count: 2
accepted answer: http://stackoverflow.com/a/47519169

http://stackoverflow.com/a/47421927
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47421681
upvote count: 1
answers question: http://stackoverflow.com/q/47421681
has body: if you have what appears to be your set of tuples: x = {('to', 4648), ('a', 4667), ('and', 6407), ('of', 6703)} format it using \n to join the lines, and str.format to create the lines you want: print("\n".join(["{} : {}".format(*l) for l in x])) result: to : 4648 a : 4667 and : 6407 of : 6703 note that because your input is a set, order isn't guaranteed. It would be if it was a list or a tuple.

http://stackoverflow.com/comment/81963532
type: QuestionComment
comment on: http://stackoverflow.com/q/47503731
has text: A [mcve] is required.
score: 0
type: Comment

http://stackoverflow.com/a/55925583
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47501275
has body: I ended up going with my proposed answer: define those functions in utils.py with the data as explicit parameters, and then use functools.partial before generating the equations to make them implicit and with that codebase having been in production for over a year, it seems reasonable enough to me.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47501275

http://stackoverflow.com/q/47488253
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
has title: Scraping a website xml code daily to update a csv file in python
has comment: http://stackoverflow.com/comment/81933449
accepted answer: http://stackoverflow.com/a/47490464
tagged with: python
has answer: http://stackoverflow.com/a/47490464
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81933058
score: 0
tagged with: http://stackoverflow.com/tag/csv
has body: I know that many versions of this basic question have been asked but I can find nothing that really helps with this particular item. https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Datasets/yield.xml I need to scrape this site for the daily Treasury yields and write them with headers to a CSV file. I need this to repeat each day so the CSV is always current. I am working in python 3.6.3 with beautifulsoup4 So far I have been about to write the headers, and I can parse the xml in python, but I have been unable to write the headers and then the data to a CSV. I tried this solution as a guide, and was able to get the headers to write. https://www.digitalocean.com/community/tutorials/how-to-scrape-web-pages-with-beautiful-soup-and-python-3 Then other posts here on stackexchange have helped me read the xml, but bridging the two, writing the xml headers and data to CSV and then updating it. Here is the current code, such as it is. # Import libraries import csv import requests from bs4 import BeautifulSoup f = csv.writer(open('treasury_yieldsV5.csv', 'w')) f.writerow(['Date', '1 Mo', '3 Mo', '6 Mo', '1 Yr', '2 Yr', '3 Yr', '5 Yr', '7 Yr', '10 Yr' ,'20 Yr' ,'30 Yr']) infile = open("yield.xml","r") contents = infile.read() soup = BeautifulSoup(contents,'xml') titles = soup.find_all('m:properties') for title in titles: print(title.get_text()) print(soup.prettify())
answer count: 1
upvote count: 1

http://stackoverflow.com/q/47523196
linked to: http://stackoverflow.com/q/510357
type: Question
tagged with: python-3.x
has body: So i'm trying to make something that waits for a user to press a key, and it stores whatever key they pressed in a variable without pressing enter. I heard of mscvrt but that only works on Windows, but i'm trying to make this on linux. Any ideas?
tagged with: linux
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/510357
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/82002714
score: 0
answer count: 0
has title: Key input without pressing enter? (LINUX)
has comment: http://stackoverflow.com/comment/82002744

http://stackoverflow.com/comment/81947244
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47482487
has text: Or rather, perhaps the table name should be in singular ,,,
type: Comment

http://stackoverflow.com/q/47510238
has body: I am doing arithmetic on columns of a DataFrame. I get a ValueError exception when the size of the (sub-)DataFrame on which I operate exceeds a threshold. As an example, consider the DataFrame: import numpy as np import pandas as pd random_list = list(np.random.randint(1, 30, 10000)) df = pd.DataFrame({"p": random_list, "q": random_list}) This operation works: df[0:5000] // [2, 10] but this one fails: df[0:5001] // [2, 10] with the exception: ValueError: operands could not be broadcast together with shapes (10002,) (2,) As soon as the slice generates a DataFrame of len greater than 5000, an exception will be thrown. The threshold depends on the number of columns. Considering instead a DataFrame generated from the dictionary: {"p": random_list, "q": random_list, "r": random_list} and a length-3 list for the floor division, the above operation will fail for any slice of length greater than 3334. What is happening?
downvote count: 0
has comment: http://stackoverflow.com/comment/81976041
has comment: http://stackoverflow.com/comment/81976832
has comment: http://stackoverflow.com/comment/81976898
answer count: 1
has comment: http://stackoverflow.com/comment/81976184
has comment: http://stackoverflow.com/comment/81976139
has answer: http://stackoverflow.com/a/47511964
favorite count: 0
accepted answer: http://stackoverflow.com/a/47511964
has title: ValueError exception from a floor-division operation on a DataFrame
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/81978194
has comment: http://stackoverflow.com/comment/81976383
has comment: http://stackoverflow.com/comment/81976665
tagged with: python
has comment: http://stackoverflow.com/comment/81976858
type: Question
upvote count: 2
tagged with: numpy
score: 2
has comment: http://stackoverflow.com/comment/81976587

http://stackoverflow.com/q/47522403
tagged with: opencv
tagged with: rotation
linked to: http://stackoverflow.com/q/46731947
has comment: http://stackoverflow.com/comment/82002145
has comment: http://stackoverflow.com/comment/82002237
has title: Finding the degree of rotation with respect to the original image
tagged with: python
tagged with: image
has comment: http://stackoverflow.com/comment/82001549
linked to: http://stackoverflow.com/q/37877626
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82001320
upvote count: 2
tagged with: angle
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/82001563
has body: I have two versions of an image. One image is not rotated, while the other image is rotated. How can I measure the degree of rotation of the second image with respect to the first image in Python? I looked around, but couldn't find a clear method to do that. For instance, I checked this answer, but when I applied it on my non-rotated image, I got an angle of around -70 returned, while I expected 0. For another rotated image I have it also gave me the wrong angle. Apart from that I would like to compare the rotated image with an some reference image, which I believe the code doesn't include. I also checked this answer, but couldn't grasp the idea of how I can measure the rotation with respect to the original (reference) image. Thanks for your kind support
linked to: http://stackoverflow.com/q/22086062
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82001491

http://stackoverflow.com/q/47518719
has answer: http://stackoverflow.com/a/47813415
tagged with: javascript
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
has title: How can I init brython without onload in
tagged with: python
favorite count: 0
type: Question
has body: It seems that initializing brython requires to be done like so: I tried calling brython() in js in another Your name is : clic !
tagged with: brython
upvote count: 2
score: 2
accepted answer: http://stackoverflow.com/a/47813415
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47522611
has comment: http://stackoverflow.com/comment/82001780
has comment: http://stackoverflow.com/comment/82003921
has comment: http://stackoverflow.com/comment/82004538
type: Question
has comment: http://stackoverflow.com/comment/82003996
has comment: http://stackoverflow.com/comment/82004273
type: UnansweredQuestion
has body: I am trying to use a module mod_a.py to store some app global information (in a webapp environment), but I notice on page reloads, the imported module's global vars aren't re-initialized, i.e. q = [], and so q accumulates items instead of being reset every HTTP request cycle. This behaviour seems odds. I am using my own dead basic framework (for learning) served thru gunicorn as a wsgi app. NOTE: If I modify mod_a.py then q is reset as expected, leading me to a caching issue of some sort. mod_a.py q = [] def add(item): global q q.append(item) mod_b.py import mod_a as a a.add('newitem') print(a.q)
tagged with: python
has comment: http://stackoverflow.com/comment/82001970
has comment: http://stackoverflow.com/comment/82001897
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82004081
has title: Module var behavior

http://stackoverflow.com/q/47525468
has comment: http://stackoverflow.com/comment/82009510
score: 0
has comment: http://stackoverflow.com/comment/82007077
answer count: 3
has comment: http://stackoverflow.com/comment/82007091
has comment: http://stackoverflow.com/comment/82017890
has comment: http://stackoverflow.com/comment/82007188
tagged with: image-processing
has comment: http://stackoverflow.com/comment/82011129
has body: I'm using the method below to get perceived brightness. I'm curious if there are faster ways to do this? def brightness( im_file ): im = Image.open(im_file) stat = ImageStat.Stat(im) r,g,b = stat.rms return math.sqrt(0.241*(r**2) + 0.691*(g**2) + 0.068*(b**2)) Requirements Perfomance is the most important factor Image files are under 30KB Brightness will be similar across the image. There'll be small differences but looking at a fraction of the image should be sufficient.
type: Question
has comment: http://stackoverflow.com/comment/82007053
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47525636
has title: Most efficient way to read in a JPEG image and determine brightness
has comment: http://stackoverflow.com/comment/82007103
has comment: http://stackoverflow.com/comment/82007062
tagged with: python
has answer: http://stackoverflow.com/a/47526370
has answer: http://stackoverflow.com/a/47525812
tagged with: image
linked to: http://stackoverflow.com/q/45890171

http://stackoverflow.com/a/47412567
upvote count: 4
score: 4
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86018361
has comment: http://stackoverflow.com/comment/86016848
has comment: http://stackoverflow.com/comment/86017470
has comment: http://stackoverflow.com/comment/81779042
has comment: http://stackoverflow.com/comment/86018926
accepted answer of: http://stackoverflow.com/q/47412502
has comment: http://stackoverflow.com/comment/86017186
has comment: http://stackoverflow.com/comment/81778416
has comment: http://stackoverflow.com/comment/86022573
has body: Use mul function and multiple DataFrame by Series (column) select by position with iloc: print(df1.mul(df2.iloc[:,0], axis=0)) X Y Z A -0.577748 0.299258 -0.021782 B -0.952604 0.024046 -0.276979 C 0.175287 2.507922 0.597935 D -0.002698 0.043514 -0.012256 E -1.598639 0.635508 1.532068 F 0.196783 -0.234017 -0.111166 Detail: print(df2.iloc[:, 0]) A -2.875274 B 1.881634 C 1.369197 D 1.358094 E -0.024610 F 0.443865 Name: 0, dtype: float64
has comment: http://stackoverflow.com/comment/81778938
answers question: http://stackoverflow.com/q/47412502
type: Answer

http://stackoverflow.com/comment/81799004
type: QuestionComment
comment on: http://stackoverflow.com/q/47422037
score: 0
has text: in `Button` you can assign function with arguments using `lambda` - `comman=lambda:assign_Func(1, 1)`
type: Comment

http://stackoverflow.com/comment/81770458
type: Comment
comment on: http://stackoverflow.com/q/47407887
type: QuestionComment
score: 0
has text: I wouldn't consider this either typical of Python, or a form of encapsulation, and least of all, functional.

http://stackoverflow.com/comment/81894533
score: 1
type: Comment
type: QuestionComment
has text: BTW: `Button1 = Button(...).pack()` will assign None to `Button1` because `pack()` returns `None`, not widget. If you don't need access button later then you can do without `Button1` -> `Button(...).pack()`
comment on: http://stackoverflow.com/q/47469911

http://stackoverflow.com/comment/82036069
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47539457
has text: That is correct @Pat Jones. I am not getting an error.

http://stackoverflow.com/comment/81877368
type: AnswerComment
comment on: http://stackoverflow.com/a/47461325
type: Comment
score: 0
has text: @MohideenibnMohammed Please check the update, I've added the sample execution. This seems to be in order with what the OP wanted.

http://stackoverflow.com/q/47424061
tagged with: opencv
type: AnsweredQuestion
score: 0
tagged with: multidimensional-array
tagged with: image-processing
has comment: http://stackoverflow.com/comment/81992873
has body: I have a grayscale 3D image represented as a numpy array. Dimensions are height x width x depth. Given a square = [p1,p2,p3,p4] I want to call fillConvexPoly(square, 100) on every depth layer of the array. I know I can just loop through the depth and call the function a few hundred times, but I feel like doing so fails to take advantage of the fact that I am working with a numpy array. Is there a faster way to accomplish this?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81805096
has title: OpenCV easy way to call fillConvexPoly() on 3d area?
has comment: http://stackoverflow.com/comment/81980416
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47518498
accepted answer: http://stackoverflow.com/a/47518498

http://stackoverflow.com/comment/81981815
type: Comment
score: 2
has text: your write statement is out of the loop, so why should you expect it to run on each iteration?
comment on: http://stackoverflow.com/q/47513050
type: QuestionComment

http://stackoverflow.com/q/47520668
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81997836
downvote count: 0
score: 1
upvote count: 1
has title: How to print rows from a list (CSV) using the results of xrange?
answer count: 1
accepted answer: http://stackoverflow.com/a/47520726
favorite count: 0
has comment: http://stackoverflow.com/comment/81997797
type: Question
tagged with: http://stackoverflow.com/tag/csv
has body: I'm trying to figure out how to print rows from a list using inputed xrange. I'm trying not to abbreviate my code because I'm still learning and want to follow the logic clearly. So what I want is to print a range of rows from the user provided arguments. I know I have some of the order wrong, but I'm stuck on how to type it out... Here is what I have so far: import csv import sys sourcef = sys.argv[1] # Source file path/name destf = sys.argv[2] # Destination file path/name linestart = int(sys.argv[3]) # Starting row to delete lineend = int(sys.argv[4]) # Ending row to delete with open (sourcef, 'rb') as file1, open (destf, 'wb') as file2: reader = csv.reader(file1) writer = csv.writer(file2) row = list(reader) for i in xrange(linestart, lineend): print i
tagged with: python
has answer: http://stackoverflow.com/a/47520726

http://stackoverflow.com/a/47382950
accepted answer of: http://stackoverflow.com/q/47382887
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47382887
type: Answer
score: 0
has body: You could use isnull + sum and then use the mask to filter df.columns. m = df.isnull().sum(0) / len(df) &lt; 0.6 df = df[df.columns[m]] Demo df A B C 0 29.0 NaN 26.6 1 NaN NaN 23.3 2 23.0 94.0 28.1 3 35.0 168.0 43.1 4 NaN NaN 25.6 5 32.0 88.0 31.0 6 NaN NaN 35.3 7 45.0 543.0 30.5 8 NaN NaN NaN 9 NaN NaN 37.6 10 NaN NaN 38.0 11 NaN NaN 27.1 12 23.0 846.0 30.1 13 19.0 175.0 25.8 14 NaN NaN 30.0 15 47.0 230.0 45.8 16 NaN NaN 29.6 17 38.0 83.0 43.3 18 30.0 96.0 34.6 m = df.isnull().sum(0) / len(df) &lt; 0.3 # 0.3 as an example m A False B False C True dtype: bool df[df.columns[m]] C 0 26.6 1 23.3 2 28.1 3 43.1 4 25.6 5 31.0 6 35.3 7 30.5 8 NaN 9 37.6 10 38.0 11 27.1 12 30.1 13 25.8 14 30.0 15 45.8 16 29.6 17 43.3 18 34.6

http://stackoverflow.com/q/47395258
has comment: http://stackoverflow.com/comment/81744044
has comment: http://stackoverflow.com/comment/81743586
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81745074
has comment: http://stackoverflow.com/comment/81764545
answer count: 1
has comment: http://stackoverflow.com/comment/81743924
score: 0
has title: How can i send password using subprocess while logging in to unix box using ssh from windows using python
has comment: http://stackoverflow.com/comment/81743962
has comment: http://stackoverflow.com/comment/81743678
has comment: http://stackoverflow.com/comment/81745291
has comment: http://stackoverflow.com/comment/81743670
tagged with: ssh
tagged with: python
has answer: http://stackoverflow.com/a/47396692
has comment: http://stackoverflow.com/comment/81743726
has body: I am trying to connect to unix box using subprocess module of python from windows machine.Please Note : Strictly want to use subprocess module(plz dont suggest pexpect,paramiko as i cant run them from windows to connect to unix as per my knowledge also have environment restricitons) Here is my code that i have tried and i always get interactive keyboard authentication message with password prompt: i try to send password to that prompt but unable to do so. import subprocess cmd='plink -ssh username@hostname -pw password' sp=subprocess.Popen(cmd,stdin=subprocess.pipe,stdout=subprocess.pipe,shell=False) sp.stdin.write('password \n') sp.stdin.flush() error,out=sp.communicate print error print out Using -pw in command doesnt work (have used one at a time- either -pw option or stdin.write), also have tried to stdin.write to console but couldn't do that also. I have some limitations on my execution environment too, also pexpect require termios which isnt present in windows
type: Question
has comment: http://stackoverflow.com/comment/81743803
has comment: http://stackoverflow.com/comment/81745215
tagged with: subprocess

http://stackoverflow.com/q/47487529
has answer: http://stackoverflow.com/a/47488301
downvote count: 0
has body: I'm just a beginner in graphics development. Now i'm trying to extend cocos2d python (pyglet) functionality. My target is make class of rectangle object for making platform game. All is okay. But when toggling in wireframe mode - i cant see edges of my rectangle, i need it. Can anyone describe how to support wire-frame mode with my solution? Code example: class ExtRect(cocos.cocosnode.CocosNode): def __init__(self, x, y, width, height): super(ExtRect, self).__init__() self.rect = cocos.rect.Rect(x, y, width, height) def draw(self): gl.glPushMatrix() self.transform() gl.glColor4f(0, 0, 0, 1) #...draw... pyglet.graphics.draw_indexed(4, pyglet.gl.GL_TRIANGLE_STRIP, [0, 1, 2, 1, 2, 3], ('v2i', ( self.rect.x, self.rect.y, self.rect.x + self.rect.width, self.rect.y, self.rect.x, self.rect.y + self.rect.height, self.rect.x + self.rect.width, self.rect.y + self.rect.height )) ) gl.glPopMatrix() Without filling color it works as need: But when i applied color with glColor4f, edge disspears: I also tried to adding colors values to indexed vertex-list data ('c3B', (0, 0, 255, 0) * 4) - result is the same.
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81930059
favorite count: 0
type: Question
tagged with: pyglet
type: UnansweredQuestion
tagged with: opengl
has title: Pyglet, why triangle edges is not showed in wireframe mode?
tagged with: python

http://stackoverflow.com/comment/82039980
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47491321
has text: This is awesome! So we know that z3 = !(z1 XOR z2). What's the difference (1) introducing z3 and the additional constraints to linearize XOR, and (2) just adding the constraint that z1 == z2?
type: Comment

http://stackoverflow.com/q/47386216
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/81725578
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81725846
upvote count: 1
has comment: http://stackoverflow.com/comment/81725400
has comment: http://stackoverflow.com/comment/81725375
favorite count: 0
has comment: http://stackoverflow.com/comment/81725742
type: Question
has comment: http://stackoverflow.com/comment/81725423
has body: I have two dataframes, df1, Values 0 Sri 1 pyd 2 NaN 3 sri, is 4 keyboard 5 kumar,cricketer df2, Values | Names Sri | Sri is a good player NaN | NaN sri, is | Sri is a good player kumar,cricketer | Kumar is a cricketer I am trying to update the df1 by comparing df1 and df2. df1["Values"] will have df2["Values"] and more. if a value present in df1 and df2 then I want to map the corresponding df2["Names"] in df1["Names"] my desired output is df1, Values | Names 0 Sri | Sri is a good player 1 pyd | NaN 2 NaN | NaN 3 sri, is | Sri is a good player 4 keyboard | NaN 5 kumar,cricketer | Kumar is a cricketer Thanks in advance!
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/81725460
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81725473
has comment: http://stackoverflow.com/comment/81725906
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81725774
linked to: http://stackoverflow.com/q/47305897
has title: matching values between two dataframes with a condition in pandas

http://stackoverflow.com/q/47527454
has comment: http://stackoverflow.com/comment/82151573
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82015210
has comment: http://stackoverflow.com/comment/82011210
has comment: http://stackoverflow.com/comment/82130116
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/82012170
has comment: http://stackoverflow.com/comment/82017885
score: 0
answer count: 0
tagged with: render
tagged with: splash-screen
has comment: http://stackoverflow.com/comment/82020996
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82018521
has comment: http://stackoverflow.com/comment/82018239
has body: I'm in a trouble with extracting javascript commentouts. Tools I'm using is a combination of Scrapy and Splash. After rendering javascript to html, commentout still is not available to be extracted. Source code is as follows. I need what's in between after , especially this part lat=42.99461&lng=142.8565 in fill('/Ajax/gasoline.php?lat=42.99461&lng=142.8565','gasolineInfo');. Any idea would save me! Thanks!
type: Question
has title: Scrape Javascript Commentouts with Scrapy+Splash

http://stackoverflow.com/comment/81886729
has text: if it is not a form value to post, you have to pass the parameters to the url.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47465968

http://stackoverflow.com/a/70648620
answers question: http://stackoverflow.com/q/47418760
has body: Open the notebook in a text editor as a text file. You should find a JSON like structure Change "editable": false, to "editable": true, under "metadata"
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/47522697
score: 0
answer count: 2
tagged with: for-loop
type: UnansweredQuestion
tagged with: loops
has title: Creating aligned columns for variables that change
has body: So I've managed to align several variables/text using padding. However, my code involves changing variables inside a list, and therefore this changes the length, and affects the alignment of my columns. product_names = ["hamburger", "cheeseburger", "small fries"] product_costs = [0.99, 1.29, 1.49] product_quantity = [10,5,20] print(format("Product",'&lt;10s'),"Price","Quantity",sep = '\t') for x in range(len(product_names)): print(format(product_names[x],'&lt;16s'),end ='') print(product_costs[x],product_quantity[x],sep = '\t') the output I get is : Product Price Quantity hamburger 0.99 10 cheeseburger 1.29 5 small fries 1.49 20 but if I change cheeseburger to something longer. for instance double cheeseburger. Ill get. Product Price Quantity hamburger 0.99 10 double cheeseburger1.29 5 small fries 1.49 20 how do I keep my columns consistent?
type: Question
has comment: http://stackoverflow.com/comment/82002051
has answer: http://stackoverflow.com/a/47522817
tagged with: text-alignment
tagged with: python
has answer: http://stackoverflow.com/a/47523106

http://stackoverflow.com/a/47415954
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47415891
answers question: http://stackoverflow.com/q/47415891
type: Answer
has body: scrapy checks allowed_domains for only the netloc of a request's url, you need to change http://www.opera.krakow.pl to opera.krakow.pl.
score: 0

http://stackoverflow.com/a/48577942
has body: Use the pysftp.Connection.listdir_attr to get file listing with attributes (including the file timestamp). Then, iterate the list and compare against local files. import os import pysftp import stat remote_path = "/remote/path" local_path = "/local/path" with pysftp.Connection('example.com', username='user', password='pass') as sftp: sftp.cwd(remote_path) for f in sftp.listdir_attr(): if not stat.S_ISDIR(f.st_mode): print("Checking %s..." % f.filename) local_file_path = os.path.join(local_path, f.filename) if ((not os.path.isfile(local_file_path)) or (f.st_mtime > os.path.getmtime(local_file_path))): print("Downloading %s..." % f.filename) sftp.get(f.filename, local_file_path) Though these days, you should not use pysftp, as it is dead. Use Paramiko directly instead. See pysftp vs. Paramiko. The above code will work with Paramiko too with its SFTPClient.listdir_attr.
accepted answer of: http://stackoverflow.com/q/47459065
downvote count: 0
upvote count: 11
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47459065
type: Answer
score: 11

http://stackoverflow.com/a/47420712
answers question: http://stackoverflow.com/q/47420673
type: Answer
score: 4
type: AcceptedAnswer
has body: Use re.findall: import re x = 'aagaaggagatataccATGAATTTGTCGGTTTACCCCAATTTAACCAAAgaaaacctgtacaa' re.findall(r'[a-z]+|[A-Z]+', x) # ['aagaaggagatatacc', 'ATGAATTTGTCGGTTTACCCCAATTTAACCAAA', 'gaaaacctgtacaa']
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47420673
upvote count: 5

http://stackoverflow.com/comment/81827143
type: QuestionComment
comment on: http://stackoverflow.com/q/47435854
score: 0
type: Comment
has text: More exactly Python unicode strings contains unicode characters which can have any code up to U+1FFFFF (or depending on the Python version up to U+FFFF). For example, the unicode string `u'abéè'` can be expressed as `u'\x61\x62\u00e9\u00e8'` and is in utf8 `b'ab\xc3\xa9\xc3\xa8'` or `b'\x61\x62\xc3\xa9\xc3\xa8'`

http://stackoverflow.com/comment/81952919
type: QuestionComment
score: 0
has text: Are you trying to evaluate the function, and then compare the output?
comment on: http://stackoverflow.com/q/47498863
type: Comment

http://stackoverflow.com/comment/81836346
type: QuestionComment
has text: @PhillipMartin: Seems more like a lack of understanding of data types than a typo to me.
comment on: http://stackoverflow.com/q/47440377
score: 1
type: Comment

http://stackoverflow.com/comment/81968783
score: 0
type: Comment
has text: yes! i am doing the changeing of a dict to url params.thanks!
comment on: http://stackoverflow.com/a/47506465
type: AnswerComment

http://stackoverflow.com/q/47460744
accepted answer: http://stackoverflow.com/a/47461467
answer count: 1
type: Question
tagged with: python
has body: In kivy, I try to remove a button in the widget but that doesn't work, I guess it's because my targeting is bad but I don't find on internet the good way to do it. I would like to remove a button when I click on another button class RPS(Widget): user_name_input = ObjectProperty() user_name = '' def save_user_name(self): user_name = self.user_name_input.text print(user_name) self.remove_widget(self.ids.remove) # I guess the problem is here the way I target kivy file user_name_input: user_name TextInput: id: user_name size: 300, 50 pos: 700,400 Button: text: "name" pos: 1070,400 size: 300, 50 on_release: root.save_user_name() Button: id: remove text: "button to remove" pos: 1070,800 size: 300, 50
tagged with: kivy
has answer: http://stackoverflow.com/a/47461467
tagged with: python-3.x
type: AnsweredQuestion
score: 0
has title: Remove a button in the kivy widget

http://stackoverflow.com/q/47398452
downvote count: 0
has answer: http://stackoverflow.com/a/47398503
accepted answer: http://stackoverflow.com/a/47398503
has comment: http://stackoverflow.com/comment/81750766
answer count: 1
tagged with: col
favorite count: 0
type: AnsweredQuestion
has title: How can I get the number of columns and rows from 2D list
tagged with: row
tagged with: multidimensional-array
tagged with: python
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/81751833
type: Question
has body: I create a 2D List with n cols and m rows: 2DList = [[0 for x in range(cols)] for y in range(rows)] How can I get the number of cols and rows with the simple method?
tagged with: list

http://stackoverflow.com/comment/81896327
comment on: http://stackoverflow.com/a/47470790
type: AnswerComment
has text: You are right. But then the issue comes when she tries to add strings to the list a couple of rows above.
score: 0
type: Comment

http://stackoverflow.com/q/47417326
tagged with: web-scraping
tagged with: scrapy
has comment: http://stackoverflow.com/comment/81788581
type: Question
has comment: http://stackoverflow.com/comment/81788696
tagged with: python
has body: I'm scraping a website of supplier. This supplier has products divided into categories and subcategories. The problem is that not all products have subcategories but all products are in categories. So for example: category1 product1 product2 product3 subcategory1 product1 product2 As you can see product3 isn't in subcategory. It's only in category1 and products 2 and 3 are in category but they are in subcategory1 too. I'm working on a spider which will use XMLItemExporter and I want every product to be in XML only once - with it's most specific category. So I want output: product1 - category1&gt;subcategory1 product2 - category1&gt;subcategory1 product3 - category1 I have to traverse through categories because products has no category mentioned in their detail url and I want to have information about their category and subcategory. I can't do this: scrape category - scrape all products - scrape subcategory - scrape all products Because I would have products from subcategory scraped with category only so there will be duplicates in XML. Do you have any idea how to make this work? EDIT: Possible solution? Don't know if I can force scrapy to scrape one type of links before another. I yes, I would get all subcategories urls, scrape products from these subcategories and then scrape all categories. If there were already scraped product, I would skipped it.
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47424355
score: 0
has title: Scrapy: Traverse through subcategories
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81788636

http://stackoverflow.com/q/47466078
has comment: http://stackoverflow.com/comment/81886890
has body: What is happening when I use the following syntax? &gt;&gt;&gt; 1 == 1 in [1] True &gt;&gt;&gt; 1 == 2 in [1] False To make it even more complex: &gt;&gt;&gt; class A: def __init__(self): self.i = 0 def __call__(self): self.i += 1 return self.i &gt;&gt;&gt; a = A() &gt;&gt;&gt; a() 1 &gt;&gt;&gt; 2 == 2 in [a(), a()] # Here a() should only be evaluated once True &gt;&gt;&gt; a() # But in fact it was evaluated twice 4 &gt;&gt;&gt; 5 == 6 in [a(), a()] # Here a() should be evaluated twice because in need to compare with each elements in the list False &gt;&gt;&gt; a() # But in fact it was not evaluated at all 5 I read that in operator is calling the __contains__ method of a list, but &gt;&gt;&gt; [1].__contains__(1 == 1) # 1 is equal to True True &gt;&gt;&gt; [2].__contains__(2 == 2) False To my best knowledge, this question was not asked before. It is really really confusing for me now so any information would be much appreciated!
has comment: http://stackoverflow.com/comment/81886757
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81886768
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18755059
type: Question
has comment: http://stackoverflow.com/comment/81893072
duplicate of: http://stackoverflow.com/q/18755059
has title: Equality check with "in" operator
tagged with: python
has comment: http://stackoverflow.com/comment/81886829
has comment: http://stackoverflow.com/comment/81887644

atom-editor
tags question: http://stackoverflow.com/q/47435205
type: Tag
tag name: atom-editor
tags question: http://stackoverflow.com/q/47539771
tags question: http://stackoverflow.com/q/47398758

http://stackoverflow.com/q/47490511
type: Question
has title: Equivalent of Python's request.session.auth in C# (.NET)
tagged with: c#
tagged with: python
accepted answer: http://stackoverflow.com/a/47490639
has body: In Python I can successfully make a request (with authorization passing) by doing: def send_request(self, url, public_key, secret_key): session = requests.session() session.auth = (public_key, secret_key) return session.get(url) I'm trying to replicate this in C# but it's not authorizing: RestClient client = new RestClient(url); RestRequest request = new RestRequest(url_stuff, Method.GET); request.AddHeader(public_key, secret_key); return client.Execute(request).Content; What am I missing here?
tagged with: restsharp
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47490639
score: 2
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47448412
has comment: http://stackoverflow.com/comment/81851761
downvote count: 1
has comment: http://stackoverflow.com/comment/81852075
has answer: http://stackoverflow.com/a/47448879
has comment: http://stackoverflow.com/comment/81852701
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81851816
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81852199
answer count: 1
tagged with: python
has title: How do I handle methods taking in a variable amount of inputs?
has comment: http://stackoverflow.com/comment/81852052
has body: So basically say I have a class inheriting from a parent. class old_people: def get_age(self, vision, wrinkles, grey_hair): pass class female(old_people): say I have mary = female() and I already have her vision. how would i do: mary.get_age(wrinkles, grey_hair) without changing the placements of the variables?
has comment: http://stackoverflow.com/comment/81851969
score: 0
upvote count: 1

http://stackoverflow.com/comment/81798308
type: QuestionComment
score: 0
has text: Also you only print "Correct" or "Incorrect" after the `for` loop is done, so only for the last question.
comment on: http://stackoverflow.com/q/47421918
type: Comment

http://stackoverflow.com/a/47501040
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47500977
has body: There are two ways to break up long expressions, either use explicit line-continuation character, \: temperature_rate = (temperature_values[-1] - temperature_values[0]) \ / (len(temperature_values) * MONITOR_RATE) Or, the preferred way, use parenthesis: temperature_rate = ((temperature_values[-1] - temperature_values[0]) / (len(temperature_values) * MONITOR_RATE)) Note, this works with any bracketed expression, which is why you could write a list-literal like: my_list = ['a', 'b', 'c']
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47500977

http://stackoverflow.com/q/47383772
tagged with: python
accepted answer: http://stackoverflow.com/a/47384407
possible better answer: http://stackoverflow.com/a/47384337
type: Question
has answer: http://stackoverflow.com/a/47384407
score: 0
has title: python 3: quoting result of random string generation
answer count: 2
has answer: http://stackoverflow.com/a/47384337
has body: I'm new to python and things do not always work as I expect... but I am learning, slowly. Here is a case in point. If I randomly create a string via: thing = ''.join([ random.SystemRandom().choice( "{}{}{}".format( string.ascii_letters, string.digits, string.punctuation ) ) for i in range(63) ]) then I could end up with a string with single quotes as well as backslashes. I assume that I should then go through the string and quote the possibly problematic characters. So, for example: if I generate the (short) string: cs]b77e\IM&gt;&amp;4/,u.s_jr"xmMdHD7a'wrEw( my instinct tells me that I should quote that into: cs]b77e\\IM&gt;&amp;4/,u.s_jr"xmMdHD7a\'wrEw( It looks like the string.replace() method is my friend... thing = ''.join([ random.SystemRandom().choice( "{}{}{}".format( string.ascii_letters, string.digits, string.punctuation ) ) for i in range(63) ]).replace('\\', '\\').replace('\'', '\'') but is there a better way? Also, in the replace() methods the meaning of the single quoted strings seems to change depending on context. Coming from Perl this seems strange to me. My initial attempts had me doing things like replace('\\', '\\\\') thinking that I had to quote the characters going into the replacement string. Is this normal or am I missing something else? Edit My goal here is to end up with 63 characters in a string. I don't really think that I have to quote any generated single quotes but my thought is that if I later use the string and it has generated backslashes then the next character after the backslash would act like it was quoted, right? I mean: len('1234') yields 4 but len('12\4') yields 3 so I need to post-process the generated string to at least quote the backslashes, right? Is there a better way to quote problematic characters than a chain of replaces() methods?
upvote count: 1
has comment: http://stackoverflow.com/comment/81720330
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81720403
tagged with: python-3.x
type: AnsweredQuestion

http://stackoverflow.com/q/47525351
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/47525555
score: 0
tagged with: flask-login
has body: how to make ensure one active session per one user using python flask? Description: if one user logged in two different machines with same credentials I want mechanism to force logout earlier active sessions of that user with flask and python. Please help me out in this. I am currently using flask-login, load_user() and login_manager libraries for login mechanism.
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: how to make ensure one active session per one user using python flask?
tagged with: session

http://stackoverflow.com/a/47459140
has body: Nvm i fixed it! The syntax in this case should be children instead of get_children. which is funny because of that edit above. Anyway, here's an example: This doesn't work: {% for kid in child.get_children %} This does work: {% for kid in child.children%} hopefully this will help anyone else having this little struggle.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47453807
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47453807

http://stackoverflow.com/comment/81732939
comment on: http://stackoverflow.com/a/47387088
type: AnswerComment
has text: 1.Before running the loop have you released all the unnecessary object using del(object)? 2. if so could you try to do it by few rows of df2 and all rows of df1?*just in case for you are joining with the correct row and check the result is as expected.
score: 0
type: Comment

http://stackoverflow.com/comment/81807260
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47426051
has text: I am betting that you have a PKI certificate stored in your browser that is being passed to the server when a request is made. If this is the case, you might be able to export it, decrypt it, and pass it as part of the `get` request.

http://stackoverflow.com/a/47384772
upvote count: 2
answers question: http://stackoverflow.com/q/47384638
has comment: http://stackoverflow.com/comment/81724677
has body: A more elegant solution using list comprehensions ;) [item*M if (index and not (index+1)%N) else item for index, item in enumerate(items)]
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81752987
has comment: http://stackoverflow.com/comment/81750050

http://stackoverflow.com/q/47485952
has comment: http://stackoverflow.com/comment/81926742
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/81926735
has answer: http://stackoverflow.com/a/47486191
downvote count: 2
has comment: http://stackoverflow.com/comment/81926729
has comment: http://stackoverflow.com/comment/81926788
score: 1
has comment: http://stackoverflow.com/comment/81926676
possible better answer: http://stackoverflow.com/a/47486031
favorite count: 0
accepted answer: http://stackoverflow.com/a/47486035
has answer: http://stackoverflow.com/a/47486067
has comment: http://stackoverflow.com/comment/81926700
has answer: http://stackoverflow.com/a/47486035
type: Question
has body: I need convert number to time. For example: I need to convert 1230 to 12:30 or 0730 to 07:30. How to convert a number to time in python?
has answer: http://stackoverflow.com/a/64772833
has title: How to convert number to time in python?
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/47486048
has comment: http://stackoverflow.com/comment/81926752
has answer: http://stackoverflow.com/a/47486031

http://stackoverflow.com/comment/82018050
type: Comment
type: QuestionComment
has text: I personally don't have an idea, but you can check [this](https://stackoverflow.com/questions/12460139/python-urllib2-giving-network-unreachable-error-if-the-url-is-https) and [this](https://stackoverflow.com/questions/10450776/python-always-returning-network-is-unreachable-because-of-old-ipv6-configuration) answers and hopefully you will find some solution. Hope this helps!
comment on: http://stackoverflow.com/q/47530574
score: 1

http://stackoverflow.com/comment/81819282
has text: sorry i'm a complete beginner so i just tried to tag it on both versions
type: Comment
comment on: http://stackoverflow.com/q/47432464
score: 0
type: QuestionComment

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/47437127
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/47493045
tags question: http://stackoverflow.com/q/47390069
tags question: http://stackoverflow.com/q/47431242
tags question: http://stackoverflow.com/q/47516778

http://stackoverflow.com/q/47442088
has body: Does anyone know what is Python's default float precision value? Couldn't find anything via Google!
has answer: http://stackoverflow.com/a/47442224
tagged with: python
has comment: http://stackoverflow.com/comment/81839329
possible better answer: http://stackoverflow.com/a/47442411
linked to: http://stackoverflow.com/q/41975576
has comment: http://stackoverflow.com/comment/81839397
has answer: http://stackoverflow.com/a/47442411
has comment: http://stackoverflow.com/comment/81839431
type: AnsweredQuestion
upvote count: 3
answer count: 2
downvote count: 2
has title: Python2.7 default float precision
duplicate of: http://stackoverflow.com/q/41975576
has comment: http://stackoverflow.com/comment/81839603
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81839330
has comment: http://stackoverflow.com/comment/81839535
has comment: http://stackoverflow.com/comment/81839508
accepted answer: http://stackoverflow.com/a/47442224
type: Question

http://stackoverflow.com/q/47500516
favorite count: 0
linked to: http://stackoverflow.com/q/46308150
tagged with: python-3.x
tagged with: pipenv
tagged with: python
has body: I'm working on Python 3.6.3 on a Windows 10 environment I executed in that order : py -m pip install virtualenv py -m pip install pew py -m pip install pipenv Then : py -m pipenv --three And the result is Creating a virtualenv for this project… Using C:\Users\xxxx\AppData\Local\Programs\Python\Python36-32\python.exe to create virtualenv… Warning: it looks like pew is not in your PATH. We cannot continue until this is resolved. I tried the solution below but it doesn't work : pipenv install gives "pew is not in your PATH"
type: Question
has title: When creating virtualenv on python I have a warning : "it looks like pew is not in your PATH"
has comment: http://stackoverflow.com/comment/81959369
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: virtualenv
tagged with: windows-10

http://stackoverflow.com/q/47427025
has comment: http://stackoverflow.com/comment/81808928
has body: I'm using Python Pyramid with MongoDB. When I selected multiple images, it will save the image name into session. On the confirmation page, I will retrieve the image name from the session and thus get the image pathname from the database. this is what I have right now in Views.py session = request.session greet_array = session['selectgreetings'].split(",") greet = GreetingsImg(request) print("session['selectgreetings']: " , greet_array) for g in greet_array: print('g: ' , g) greetall = greet.get_by_name(g) for ga in greetall: greet_path = ga['path_name'] print('path: ', greet_path) return {'greet_path':greet_path} if I do this, it will print this results (Command Prompt) session['selectgreetings']: ['Pics3', 'Pics2'] g: Pics3 path: static/image/greeting/03.jpg g: Pics2 path: static/image/greeting/02.jpg I was trying to combine the two paths so that I can get this in Command Prompt: static/image/greeting/03.jpg, static/image/greeting/02.jpg When I get the result above, I can use for loop in jinja2 to show the image selected: {% for a in greet_path %} &lt;img src="/{{a}}" class="col-sm-5"/&gt; {% endfor %}
tagged with: python
score: -1
has title: How to combine the two results I got from for loop?
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/81808634
tagged with: for-loop
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47427062
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81754115
type: Comment
comment on: http://stackoverflow.com/q/47398329
type: QuestionComment
score: 0
has text: I added it, but truthfully it is not needed to answer the question, one can assume affine decode is implemented correctly, as the issue not one of code correctness in regards to decode. As the decode I used works just fine. I was more concerned if my cracking approach and math behind the encryption was correct as if it is the string is not actual text it is gibberish. Which again is the nature of my question "8YM8FlYPiiMl.YP[eYWP[P[P." is this string gibberish once decoded?

http://stackoverflow.com/q/47407438
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/81768052
type: UnansweredQuestion
tagged with: hough-transform
has comment: http://stackoverflow.com/comment/81768089
tagged with: python
tagged with: ocr
score: -1
has title: How to compute coordinates of rectange and then do perspective transformation using opencv and python
has comment: http://stackoverflow.com/comment/81768651
has body: Original pic after canny pic pic after perspective tranform Hi, I am doing a small OCR POC.See the original pic, I only care about the content inside the nameplate.Before recognising characters, I need to do perspective transformation for this pictures to increase correctness. See the second picutures, I already did canny to get the contours of the rectangle. I want to get the coordinates of the 4 corners of the rectangle(labled in red),so that I can derived the matrix and do perspective transfromation. The last picture is the output I want. I am new to opencv... can anybody give me some idea regarding how to get the coordinates of 4 corners? I have googled and learn some terms, such as hough transformation? Is it a good way to detect line and then computer the position of the corners? It would be great if somebody can show me some python code to do this, thanks in advance. /* below is my currunt code # coding:utf8 import cv2 import numpy as np import sys if __name__ == '__main__': imagePath = sys.argv[1] img = cv2.imread(imagePath) img = cv2.GaussianBlur(img,(3,3),0) canny = cv2.Canny(img, 50, 150) #element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4)) #dilation = cv2.dilate(canny, element2, iterations = 1) cv2.imwrite("canny.jpg", dilation) cv2.waitKey(0) cv2.destroyAllWindows()
upvote count: 0
tagged with: canny-operator
answer count: 1
has answer: http://stackoverflow.com/a/47408562
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47440965
tagged with: python
score: 3
has title: Dask.delayed doesn't .compute() inside class
upvote count: 3
has answer: http://stackoverflow.com/a/47480462
answer count: 1
has body: I have a folder containing 497 pandas' dataframes stored as .parquet files. The folder total dimension is 7.6GB. I'm trying to develop a simple trading system. So I create 2 different classes, the main one is the Portfolio one, this class then creates an Asset object for every single dataframe in the data folder. import os import pandas as pd from dask.delayed import delayed class Asset(file): def __init__: self.data_path = 'path\\to\\data\\folder\\' self.data = pd.read_parquet(self.data_path + file, engine='auto') class Portfolio: def __init__: self.data_path = 'path\\to\\data\\folder\\' self.files_list = [file for file in os.listdir(self.data_path) if file.endswith('.parquet')] self.assets_list = [] self.results = None self.shared_data = '???' def assets_loading(self): for file in self.files_list: tmp = Asset(file) self.assets_list.append(tmp) def dask_delayed(self): for asset in self.assets_list: backtest = delayed(self.model)(asset) def dask_compute(self): self.results = delayed(dask_delayed) self.results.compute() def model(self, asset): # do shet if __name__ == '__main__': portfolio = Portfolio() portfolio.dask_compute() I'm doing something wrong cause it looks like the results are not processed. If I try to check portfolio.results the console prints: Out[5]: Delayed('NoneType-7512ffcc-3b10-445f-928a-f01c01bae29c') So here are my questions: Can you explain me what's wrong? When I run the function assets_loading() I'm basically loading the entire data folder in memory for faster processing speed, but it saturates my RAM (16GB available). I didn't thought that a 7.6GB folder could saturates 16GB RAM, that's why I want to use Dask. Any solution compatible with my script work flow? There's is another problem and probably the bigger one. With Dask I'm trying to parallelize the model function over multiple assets at the same time, but I need a shared memory (self.shared_data in the script) to store some variables value that resides inside each Dask process to the Po…
tagged with: shared-memory
favorite count: 0
tagged with: python-multiprocessing
type: Question
tagged with: dask
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/81847171
has text: ah I had a feeling I was using x0 for too many things, thanks for your answer that was very helpful!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47445774

http://stackoverflow.com/comment/81864452
has text: After printing from within the functions, you're returning them as well Any reason for that?
score: 3
comment on: http://stackoverflow.com/q/47455016
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81939950
comment on: http://stackoverflow.com/q/47492104
score: 0
has text: Well I do need help but it's an optimization problem first and a string search second, so there's different levels of help I'm trying to get.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81829900
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47437666
has text: Can you provide an example of where the conversion actually fails? There is code actually relevant to your problem here.

http://stackoverflow.com/q/47434701
answer count: 1
tagged with: bokeh
has answer: http://stackoverflow.com/a/58759576
has comment: http://stackoverflow.com/comment/81930120
tagged with: plot
favorite count: 0
type: Question
has body: I am new to using Bokeh. I have data which roughly looks like that date names numbers 2016 var1 62 2012 var2 82 2014 var1 118 2015 var2 69852 2012 var3 167 2016 var1 2266 2011 var1 88282 2015 var3 6307 ... I use a Bokeh script to plot the data and from a dropdown menu I can select for which names (var1, var2, ...) to to plot the data. The script is based on this example: https://github.com/bokeh/bokeh/tree/master/examples/app/weather and looks like this import pandas as pd from bokeh.io import curdoc from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Select from bokeh.plotting import figure def get_dataset(src, name): df = src[src.names == name].copy() del df['names'] df = df.set_index(['date']) df.sort_index(inplace=True) return ColumnDataSource(data=df) def make_plot(source, title): plot = figure(plot_width=800, tools="", toolbar_location=None) plot.title.text = title plot.line(x='date', y='numbers', source=source, legend="Record") return plot def update_plot(attrname, old, new): ver = vselect.value plot.title.text = "xxx" src = get_dataset(df, ver) source.date.update(src.date) df = pd.read_csv('data/test_data.csv', delimiter='\t') ver = 'aps' cc = df['names'].unique() vselect = Select(value=ver, title='VER', options=sorted((cc))) source = get_dataset(df, ver) plot = make_plot(source, "xxx") vselect.on_change('value', update_plot) controls = column(vselect) curdoc().add_root(row(plot, controls)) This works fine, but I would like to allow now to select multiple names (e.g var1 and var2) to be selected to plot them in the same plot for easy comparison. However, I have no idea how to go about this.
type: UnansweredQuestion
has title: Bokeh, select interactivle multiple datasets for plotting
tagged with: python
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/82053409
type: AnswerComment
has text: Works like a charm! Do I need to install it every time I reopen the notebook?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47536742

http://stackoverflow.com/comment/127167951
comment on: http://stackoverflow.com/q/47524054
score: 0
type: Comment
type: QuestionComment
has text: See this answer: https://stackoverflow.com/a/71967141/1364242

http://stackoverflow.com/q/47515625
has comment: http://stackoverflow.com/comment/81987276
answer count: 1
tagged with: selenium
accepted answer: http://stackoverflow.com/a/47515685
has answer: http://stackoverflow.com/a/47515685
type: Question
has comment: http://stackoverflow.com/comment/81987342
has comment: http://stackoverflow.com/comment/81988097
tagged with: python
has body: I am trying to run a script in selenium webdriver python. Where I am trying to click on search field, but its always showing exception of "An element could not be located on the page using the given search parameters." Here is script: from selenium import webdriver from selenium.webdriver.common.by import By class Exercise: def safari(self): class Exercise: def safari(self): driver = webdriver.Safari() driver.maximize_window() url= "https://www.airbnb.com" driver.implicitly_wait(15) Title = driver.title driver.get(url) CurrentURL = driver.current_url print("Current URL is "+CurrentURL) SearchButton =driver.find_element(By.XPATH, "//*[@id='GeocompleteController-via-SearchBarV2-SearchBarV2']") SearchButton.click() note= Exercise() note.safari() Please Tell me, where I am wrong?
has comment: http://stackoverflow.com/comment/81987671
has comment: http://stackoverflow.com/comment/81987934
has title: Unable to select an element via XPath in selenium Webdriver python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/81987897
tagged with: xpath
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81843993
comment on: http://stackoverflow.com/q/47444313
score: 0
has text: Your function returns on the first Char. It doesn't check the whole string.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87904988
type: Comment
comment on: http://stackoverflow.com/a/47471091
has text: @DebanjanB I guess... with get() guy is going to navigate to login page first. So that is fine where get() will return once page is loaded. But on login page, when we hit login button, it is a click operation which will return immediately and we have to wait explicitly for page to be loaded
type: AnswerComment
score: 0

http://stackoverflow.com/q/47383106
upvote count: 1
score: 1
answer count: 1
downvote count: 0
tagged with: web-scraping
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47493763
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/47493763
tagged with: mechanize
has comment: http://stackoverflow.com/comment/81719738
tagged with: python
has title: Script throws error while scraping multiple values
type: AnsweredQuestion
tagged with: python-2.7
has body: My script is trying to scrape a website for 80000 IDs that are stored in a text file. When I run my code with a single o/p, it runs fine, but when I put all the inputs in a loop, I get an error. My code: from bs4 import BeautifulSoup import mechanize br = mechanize.Browser() response = br.open("https://www.matsugov.us/myproperty") for form in br.forms(): if form.attrs.get('name') == 'frmSearch': br.form = form break br.form['ddlType']=["taxid"] with open("names.txt") as ins: tx = ins.read().splitlines() for x in tx: br['txtParm'] = x req = br.submit().read() soup = BeautifulSoup(req, 'html.parser') table = soup.find('td', {'class': 'Grid_5'}) for row in table: print row Error: AttributeError: mechanize._mechanize.Browser instance has no attribute __setitem__ (perhaps you forgot to .select_form()?)

http://stackoverflow.com/q/47531854
tagged with: django
has answer: http://stackoverflow.com/a/47532396
tagged with: python
has comment: http://stackoverflow.com/comment/82020732
score: 1
upvote count: 1
tagged with: django-models
favorite count: 0
has title: how to create a field in django that is only enabled after filling in the previous one?
type: Question
tagged with: python-3.x
downvote count: 0
has body: I want to enable in django admin the "registration" field only if "bond" is filled in as "outsourced". class Contato(models.Model): BOND_CHOICES = ( ('server', 'Servidor'), ('outsourced', 'Terceirizado'), ('trainee', 'Estagiário'), ) name = models.CharField(verbose_name='Nome', max_length=100) date = models.DateField(verbose_name='Data de Nascimento') email = models.CharField(verbose_name='Email', max_length=100) branchLine = models.DecimalField(verbose_name='Ramal', max_digits=4, decimal_places=0) bond = models.CharField(verbose_name='Vínculo', max_length=10, choices=BOND_CHOICES) registration = models.CharField(verbose_name='Matrícula', max_length=20)
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/47476258
has body: A function with no return statement is essentially a function with return None. Your function login.default_login() has no return statement, thus returning a None. And then self.driver is assigned to None: self.driver = login.default_login(self.driver) Just add return driver to login.default_login() and login.log_out() functions to fix both errors.
type: Answer
accepted answer of: http://stackoverflow.com/q/47475299
has comment: http://stackoverflow.com/comment/81968754
answers question: http://stackoverflow.com/q/47475299
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81964882
comment on: http://stackoverflow.com/q/47504564
type: Comment
score: 0
type: QuestionComment
has text: What is the error, you are getting ?

http://stackoverflow.com/q/47449516
favorite count: 0
type: Question
tagged with: numpy
has title: How do `ndarray.flags['OWNDATA']`, `ndarray.base`, `id(ndarray)` and `ndarray.__array_interface__['data']` differ?
tagged with: arrays
has comment: http://stackoverflow.com/comment/81854418
tagged with: python
has body: I seem to have had an XY problem in this question regarding how to tell if arrays share the same memory. The ways I was checking were wrong and I'm not sure why. Let's take a few examples test = np.ones((3,3)) test2 = np.array(test, ndmin = 2, copy = False) test3 = np.array(test, ndmin = 3, copy = False) First, let's check if they're sharing memory using .base test2.base is test False test3.base is test True So it seems like test3 is sharing data with test but test2 isn't. In fact test2.base is None =&gt; True, which I thought meant that it is seperate memory (i.e. a copy). This impression is reinforced when I check with .flags test2.flags['OWNDATA'] True test3.flags['OWNDATA'] False It seems again like only test3 is sharing data, and test2 is a copy. But if I check with the python builtin id(...) id(test) 248896912 id(test2) 248896912 id(test3) 248897352 Now the id (which is supposedly the adress of the object in memory) of test and test2 match but test3 does not, which gives the exact opposite impression from the above methods. And of course, both of those impressions are wrong because: test.__array_interface__['data'] (209580688, False) test2.__array_interface__['data'] (209580688, False) test3.__array_interface__['data'] (209580688, False) The actual buffer addresses all match. Indeed: test[0,0] = 2 test, test2, test3 (array([[ 2., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]), array([[ 2., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]), array([[[ 2., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]])) So if ndarray.base, ndarray.flags['OWNDATA'], and id(ndarray) don't actually tell me if memory is shared, what are they telling me?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47449923
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/47449923
answer count: 1
linked to: http://stackoverflow.com/q/47429254
downvote count: 1

http://stackoverflow.com/q/47471817
tagged with: python
has title: Django - How to run a function inside a constructor?
score: 0
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81898077
tagged with: python-3.x
tagged with: constructor
has body: As far as I've read, overriding the init function is not recommended in Django. Then how can I assign value to "hashed" and "salt"? They will not have the value of the original text, there are functions named def createSalt(self): and def createHash(self, salt, password): that will take the original text and convert it to something different. I tried this in model class but it didn't work: (it probably looks stupid ) salt = models.TextField(createSalt()) or salt = models.TextField(createSalt(self)) Another suggestion was to define a new function named create and use it like a constructor. But then it's not really a constructor, is it? Here is my model: class User(models.Model): username = models.CharField(db.String(100), primary_key=True) hashed = models.TextField() salt = models.TextField()
has answer: http://stackoverflow.com/a/47471905
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81899046
tagged with: django
tagged with: django-models

http://stackoverflow.com/comment/81921311
comment on: http://stackoverflow.com/q/47482620
score: 0
has text: Can you share with us your code trials?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82014963
score: 0
has text: Ok, thanks for the brainstorm. This led me to named tuples. Will dig deeper into it. Thx for help.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47528415

http://stackoverflow.com/q/47539881
has body: I am trying to re-create the column 'sig', below, but in a faster, more efficient way. My attempt is 'sig2' but that, too, runs into its own errors. import numpy as np import pandas as pd a = np.random.standard_normal(500) A = pd.DataFrame(np.cumsum(a)) A['Max'] = pd.rolling_max(A[0],10) A['Min'] = pd.rolling_min(A[0],10) A['Mean'] = pd.rolling_mean(A[0],3) A['sig'] = 0 for t in range(1,A.shape[0]): if (A['Max'][t] &gt; A['Max'][t-1]) &amp; (A['sig'][t-1]==0): A['sig'][t] = 1 elif (A['Min'][t] &lt; A['Min'][t-1]) &amp; (A['sig'][t-1]==0): A['sig'][t] = -1 elif ((A[0][t] &gt; A['Mean'][t]) &amp; (A['sig'][t-1]==-1)) | ((A[0][t] &lt; A['Mean'][t]) &amp; (A['sig'][t-1]==1)): A['sig'][t] = 0 else: A['sig'][t] = A['sig'][t-1] state = 0 B = A.shift() def get_val(A,B,prev_state): global state if (A['Max'] &gt; B['Max']) &amp; (prev_state==0): state = 1 return state elif (A['Min'] &lt; B['Min']) &amp; (prev_state==0): state = -1 return state elif ((A[0] &gt; A['Mean']) &amp; (prev_state==-1)) | ((A[0] &lt; A['Mean']) &amp; (prev_state==1)): state = 0 return state else: return state A['sig2'] = A.apply(lambda x: get_val(x,B,state)) Thank you
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/82065767
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82042891
favorite count: 0
type: Question
has title: pandas time series column conditional on other columns
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47481967
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/81925379
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47486126
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47485560
has comment: http://stackoverflow.com/comment/81925502
tagged with: mouse
tagged with: line
has title: Drawing line with infinity length in the direction of cursor in Pygame
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45389563
has body: I'm searching for some help with pygame. I'm developing simple game in Python to learn Pygame. I want to make spaceship which we can rotate and we can shooting with laser line. I have done controlling by arrow keys, we can also rotating spaceship with mouse position, but I've got a problem with shooting. I want to make a line with infinity length from spaceship position to mouse direction. How I can do that? Here is my code: def draw_objects(self): SCREEN.fill(BLACK) self.target = pygame.mouse.get_pos() self.x = self.player.position[0] #player x position self.y = self.player.position[1] #player y position self.mx = self.target[0] #mouse x position self.my = self.target[1] #mouse y position self.slope=float(float(self.y-self.my)/float(self.x-self.mx+0.1)) #slope self.x_new = DISPLAY_WIDTH #ray length self.y_new = self.y + self.slope * (self.x_new - self.x) self.player.draw() self.draw_columns() for agent in self.all_agents: agent.draw() agent.draw_vectors() if self.player.shoot == True: pygame.draw.line(SCREEN, GREEN, self.player.position,(self.x_new, self.y_new), 2) pygame.display.update() It's not working properly, because it's work only to the right of spaceship. In other cases it draws a line in reflection to cursor. I will be grateful for your help.
score: 1

http://stackoverflow.com/comment/81794541
score: 0
type: Comment
has text: `out, err = ffmpeg.communicate()` perhaps ffmpeg communicates "back to you" via stderr so it is exiting too soon...
type: QuestionComment
comment on: http://stackoverflow.com/q/47414122

http://stackoverflow.com/comment/82021839
type: Comment
has text: Is `url` supposed to be a variable? In your code it is passed as the string `'url'`.
comment on: http://stackoverflow.com/q/47532529
score: 0
type: QuestionComment

http://stackoverflow.com/a/77026442
type: Answer
has body: Thanks @Paul H for the great answer and @alphabetasoup for the thoughtful comment. My solution builds upon this answer for my use case, which is finding the overlapping polygons. # Find polygons in a geopandas dataframe that overlap with another polygon # in the same dataframe as well as non-overlapping polygons overlapping = [] non_overlapping = [] for n, p in enumerate(list(gdf.geometry), 0): overlaps = [] for g in list(gdf.geometry): overlaps.append(g.overlaps(p)) if any(overlaps): overlapping.append(p) if not any(overlaps): non_overlapping.append(p) My use case also required retaining other columns from the original geopandas geodataframe. Here's how I did that: overlapping = [] non_overlapping = [] for n, p in enumerate(list(gdf.geometry), 0): if any(p.overlaps(g) for g in list(gdf.geometry)): # Store the index from the original dataframe overlapping.append(n) if not any(p.overlaps(g) for g in list(gdf.geometry)): non_overlapping.append(n) # Create a new dataframes and reset their indexes gdf_overlapping = gdf.iloc[overlapping] gdf_overlapping.reset_index(drop=True, inplace=True) gdf_non_overlapping = gdf.iloc[non_overlapping] gdf_non_overlapping.reset_index(drop=True, inplace=True) For this I made a few code modifications from the original answer: I found that I needed to include the last element so that I didn't lose one of the overlapping polygons: for n, p in enumerate(polygons[:-1], 1): -&gt; polygons[:] = polygons I used my geopandas geodataframe list(gdf.geometry) instead of a list of polygons I used Python's zero-based indexing to retain the index location of each polygon in my original geopandas geodataframe for n, p in enumerate(polygons[:-1], 1): -&gt; for n, p in enumerate(polygons[:-1], 0): I changed checking polygons from the next indexed element to the end to all the polygons for g in polygons[n:]: -&gt; for g in polygons: since the former method missed some overlapping polygons because it would not check the current polygon against all of the po…
answers question: http://stackoverflow.com/q/47471872
score: 0

http://stackoverflow.com/q/47438663
answer count: 0
has comment: http://stackoverflow.com/comment/81833391
type: UnansweredQuestion
tagged with: pyqt5
tagged with: python
linked to: http://stackoverflow.com/q/22528418
has title: PyQt5: how to inherit a widget with its layout or geometry?
score: 0
has body: I put a QLineEdit in form.ui, and I want to use CustomLabel to inheriance it. But there are both 2 QLineEdit(lines in form.ui and CustomLabel) in my mainwindow. How should I deal with this situation? Here is the image of my programme Here is my code: import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QLabel from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot import PyQt5.uic as uic form_ui,_ =uic.loadUiType('form.ui') print(type(form_ui)) class Mainwindow(QWidget,form_ui): """docstring for App""" def __init__(self): super(Mainwindow, self).__init__() self.setupUi(self) path_lineEdit = CustomLabel(self.lines) class CustomLabel(QLineEdit): def __init__(self,parent=None): super(CustomLabel,self).__init__(parent) # self.resize(parent.size()) def dragEnterEvent(self, e): if e.mimeData().hasFormat('text/plain'): e.accept() else: e.ignore() def dropEvent(self, e): self.setText('212'+e.mimeData().text()) if __name__ == '__main__': app = QApplication(sys.argv) ex = Mainwindow() ex.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/81847723
type: Question

http://stackoverflow.com/q/47500345
linked to: http://stackoverflow.com/q/40105986
type: Question
tagged with: rest
accepted answer: http://stackoverflow.com/a/47500795
upvote count: 2
has answer: http://stackoverflow.com/a/47500795
tagged with: django
tagged with: python
tagged with: django-rest-framework
has body: I am using Django Rest Framework as a backend for an app. I have a User that has one Wallet. Then I have Item. If a User wants an Item it creates an instance in his/her Wallet called WalletItem. All works well. Now I want to limit the number of items for the User using an attribute limit_usage. First, I added a check to post method adding new instance that checks the number of item instances in User's Wallet. So the user gets 403 when trying to add third WalletItem if limit_usage == 2 for this Item. I would like to override a get_queryset() method or queryset in list()/retrieve() methods so that if anonymous user calls /items/ there are unfiltered items in response. However if the user is authenticated I would like to filter only those Items that s/he is allowed to put in the Wallet, i.e. those that have not exceeded limit_usage for current user. class Wallet(models.Model): user = models.OneToOneField('auth.User', related_name='wallet') class Item(models.Model): valid_from = models.DateTimeField() valid_to = models.DateTimeField() limit_usage = models.PositiveSmallIntegerField(default=0) class WalletItem(models.Model): wallet = models.ForeignKey('Wallet', related_name='%(class)ss') offer = models.ForeignKey('Item', related_name='offer') class ItemViewSet(viewsets.ReadOnlyModelViewSet): queryset = Item.objects.all().order_by('-created_at') serializer_class = ItemSerializer def list(self, request, *args, **kwargs): time_now = now() self.queryset = self.queryset.filter( valid_from__lte=time_now, valid_to__gte=time_now, ) serializer = self.get_serializer(self.queryset, many=True) return Response(serializer.data) I created a method of Item class that should have helped me but I realized I cannot use it in the queryset: def is_visible_for_user(self, user=None): if not self.limit_usage or not user: return True ct = WalletItem.objects.filter(item=self, wallet=user.wallet).count() return self.limit_usage &gt; ct So I can iterate through the queryset to see if each item can b…
score: 2
type: AnsweredQuestion
tagged with: django-queryset
has title: Django Rest Framework: advanced queryset filtering based on another model
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/82011356
comment on: http://stackoverflow.com/q/47525536
type: Comment
has text: @SandeepKadapa, I solve this issue thank you, Can you help me for extracting every type of phone number from text file using python
score: 0
type: QuestionComment

loops
tags question: http://stackoverflow.com/q/47429954
tags question: http://stackoverflow.com/q/47423582
tags question: http://stackoverflow.com/q/47517779
tags question: http://stackoverflow.com/q/47527122
tags question: http://stackoverflow.com/q/47492347
tags question: http://stackoverflow.com/q/47405018
tags question: http://stackoverflow.com/q/47443291
tags question: http://stackoverflow.com/q/47448931
tags question: http://stackoverflow.com/q/47460835
tags question: http://stackoverflow.com/q/47522697
tags question: http://stackoverflow.com/q/47436641
tags question: http://stackoverflow.com/q/47409940
tags question: http://stackoverflow.com/q/47456368
tags question: http://stackoverflow.com/q/47403273
tags question: http://stackoverflow.com/q/47475476
tags question: http://stackoverflow.com/q/47410196
tag name: loops
tags question: http://stackoverflow.com/q/47424637
tags question: http://stackoverflow.com/q/47523475
tags question: http://stackoverflow.com/q/47490230
tags question: http://stackoverflow.com/q/47422307
tags question: http://stackoverflow.com/q/47447375
tags question: http://stackoverflow.com/q/47452993
tags question: http://stackoverflow.com/q/47518631
tags question: http://stackoverflow.com/q/47383980
tags question: http://stackoverflow.com/q/47494778
tags question: http://stackoverflow.com/q/47517983
tags question: http://stackoverflow.com/q/47435163
tags question: http://stackoverflow.com/q/47387351
tags question: http://stackoverflow.com/q/47499876
tags question: http://stackoverflow.com/q/47420298
tags question: http://stackoverflow.com/q/47409308
tags question: http://stackoverflow.com/q/47451233
tags question: http://stackoverflow.com/q/47518405
type: Tag
tags question: http://stackoverflow.com/q/47465392
tags question: http://stackoverflow.com/q/47479248
tags question: http://stackoverflow.com/q/47528188
tags question: http://stackoverflow.com/q/47500953
tags question: http://stackoverflow.com/q/47398615
tags question: http://stackoverflow.com/q/47475585
tags question: http://stackoverflow.com/q/47523123
tags question: http://stackoverflow.com/q/47525379
tags question: http://stackoverflow.com/q/47438901
tags question: http://stackoverflow.com/q/47513950
tags question: http://stackoverflow.com/q/47420439
tags question: http://stackoverflow.com/q/47521088
tags question: http://stackoverflow.com/q/47446804
tags question: http://stackoverflow.com/q/47461653
tags question: http://stackoverflow.com/q/47521063

http://stackoverflow.com/q/47441877
answer count: 1
has title: Python subprocesses - passing multiple commands in a loop
type: Question
tagged with: std
has answer: http://stackoverflow.com/a/47445183
tagged with: python
tagged with: c++
score: 0
has body: I am trying to run a c++ implementation of a model (sent2Vec) from a pythonp program using the subprocess module. The c++ program runs a loop like the following: while(raw_input): print(perform_action(input)) This is because it loads a huge model into memory and then uses it as and when a query is passed to it. So, the c++ output looks like this: Pre-computing vectors... done. Query sentence? query 0.603723 1 a1 0.306778 2 a2 0.262201 4 a3 0.198674 0 a4 0.131687 3 a5 0.121209 5 a6 0 6 Query sentence? I would like to run the program and then when required send an input and read the output. I know the number of lines of generated per query so it's fine if I have to read the entire output every time. I tried the following: process = Popen(cmd, stdin=PIPE, stdout=PIPE) process.stdin.write(query) process.stdout.readlines() However, this seems to get stuck in a loop. I looked at multiple stackoverflow threads and most of them suggest what I tried. I would really appreciate any help. Thanks in advance!
tagged with: subprocess
type: UnansweredQuestion

http://stackoverflow.com/comment/81842133
score: 1
type: Comment
type: AnswerComment
has text: @ElisByberi So if I want to calculate an aggregated sum I should just go ahead and modify the original DataFrame? That would definitely mess up my workflow. Half of my code would contain `copy()`s.
comment on: http://stackoverflow.com/a/47435389

http://stackoverflow.com/q/47464418
has comment: http://stackoverflow.com/comment/81883560
has title: DFS algorithm: 'list' object has no attribute 'depth'
has comment: http://stackoverflow.com/comment/81883585
score: 0
answer count: 0
has body: I use python to realize the DFS search algorithm but when I ran the code it said" 'list' object has no attribute 'depth' ".Actually, the object 'node' in my code is an instance of the class Nodes, which will have the attribute 'depth' as I definite before. Here is my code: import numpy as np class Nodes(): # definite a nodes class. It contains state/parent/depth/action properties 'action' means it is generated by which action, which includes 'UP, DOWN, RIGHT, LEFT' def __init__(self, state, parent=None, depth=0, action=None): self.state = state self.parent = parent self.depth = depth self.action = action # .... def DFS(self, goal, limit): opentable = [] opentable.append(self) while True: if len(opentable) &gt; 0: node = opentable.pop(0) if node.depth &lt; limit: # the problem is here if (node.state == goal).all(): moves = [] temp = node i = 0 while True: moves.insert(i, temp.action) if temp.depth == 1: break temp = temp.parent i += 1 return moves opentable.append(node.generatenodes()) opentable.reverse() if __name__ == '__main__': initial = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],['A', 'B', 'C', 'G']]) start = Nodes(initial) goal = np.array([[0, 0, 0, 0], [0, 'A', 0, 0], [0, 'B', 0, 0],[0, 'C', 0, 'G']]) start.DFS(goal, 8)
type: Question
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81925803

http://stackoverflow.com/q/47437752
has answer: http://stackoverflow.com/a/47439169
type: Question
has comment: http://stackoverflow.com/comment/81830746
has title: Django UpdateView extend the Form field choices
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81832491
downvote count: 0
tagged with: django
tagged with: python
has body: I have a Django form with a field called ipts which by default has the content choices=(('', '-'*20),). In the UpdateView I extend this list with more options. Thus, in the get_context_data I get the form and extend that list. choices = form.fields['ipts'].choices choices = choices.extend( [('IPTS-123', 'IPTS-454545'),] ) To make sure the choices was well populated, in the render_to_response method I print the form.fields['ipts'].choices and I have what I was expecting: [('', '--------------------'), ('IPTS-123', 'IPTS-454545')] However the template is not populated with these choices! Just the initial value is available for selection: ('', '--------------------') Any ideas how to extend the choices field in a Class Based View? Suggestions are welcome. Thanks. Edit: Here the view code: class ProfileReductionUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView): ''' ''' model = UserProfile form_class = UserProfileReductionForm template_name = 'users/profile_reduction_form.html' # fields = '__all__' success_url = reverse_lazy('index') success_message = "Your Profile for the Reduction was updated successfully." def get(self, request, *args, **kwargs): print("*** get") return super(ProfileReductionUpdate, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): print("*** get_context_data") context = super(ProfileReductionUpdate, self).get_context_data(**kwargs) from pprint import pprint # pprint(context) import copy form = context['form'] print("Form:") pprint(form) choices = form.fields['ipts'].choices choices = choices.extend( [('IPTS-123', 'IPTS-454545'),] ) pprint(form.fields['ipts'].choices) # form.fields['ipts'].choices = choices context['form'] = form pprint(context['form'].fields['ipts'].choices) return context def render_to_response(self, context, **response_kwargs): print("*** render_to_response") from pprint import pprint pprint(context) pprint(response_kwargs) form = context['form'] print("Form:") pprint(form) print("Form ipts choices…
has comment: http://stackoverflow.com/comment/81830707
has comment: http://stackoverflow.com/comment/81832349
has comment: http://stackoverflow.com/comment/81831186
has comment: http://stackoverflow.com/comment/81830956
score: 1
has comment: http://stackoverflow.com/comment/81832598
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81777108
comment on: http://stackoverflow.com/a/47411187
type: Comment
has text: This one Works Great! I'm just looking how to take out the empty lines in regex documentation. Thank you very Much @Serge Ballesta
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81916807
score: 1
type: Comment
has text: This isn't how Python dictionaries work.
type: QuestionComment
comment on: http://stackoverflow.com/q/47480955

http://stackoverflow.com/a/47465501
has comment: http://stackoverflow.com/comment/81886021
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: getattr should do this for you. It allows you to build a string, and fetch the attribute off the object with that name. attribute_name = level_int(player_level) + "_skill" print(getattr(Character, attribute_name)) If attribute_name is not the name of an attribute on your class, then it will raise AttributeError just like it would if you called Character.not_an_attribute, so behaviorally it's identical. You can also override the default behaviour of rasining an exception by giving getattr a third argument; getattr(Character, attribute_name, "No skill this level")
answers question: http://stackoverflow.com/q/47465488

http://stackoverflow.com/comment/81939549
type: Comment
type: QuestionComment
has text: @hoefling This is not a duplicate of that, they are only removing one of the values and I wish to remove both.
comment on: http://stackoverflow.com/q/47492064
score: 0

http://stackoverflow.com/a/47527622
has comment: http://stackoverflow.com/comment/82020802
has comment: http://stackoverflow.com/comment/82013165
answers question: http://stackoverflow.com/q/47527443
has comment: http://stackoverflow.com/comment/82018979
upvote count: 2
has comment: http://stackoverflow.com/comment/82020809
has comment: http://stackoverflow.com/comment/82020549
has comment: http://stackoverflow.com/comment/82020673
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82019183
has comment: http://stackoverflow.com/comment/82020709
has comment: http://stackoverflow.com/comment/82013635
has comment: http://stackoverflow.com/comment/82020363
score: 2
downvote count: 0
has body: You're not initializing your form with the instance that you want to update: form = HomeForm() instead when you want to have a form filled with the data from an object: form = HomeForm(instance=my_object_to_update) Since you want to do this for every post you display in your HomeView, you need to initialize a different form for every post. In HomeView.get() and in HomeView.post() method, in addition to creating the empty HomeForm() that's used for creating a new serverlist: for post in posts: forms[post.id] = HomeForm(instance=post) And in your template render (assuming your loop {% for server in posts %}) {% with server.id as id %} {% with forms|get_by_key:id as edit_form %} &lt;form action="{% url 'edit_post' server.id %}" method="post"&gt; ... display the form: your current code {% for field in edit_form %} etc... &lt;/form&gt; {% endwith %} {% endwith %} I'm using a custom template filter |get_by_key:variable to get the dict value by key when using a variable: @register.filter(name='get_by_key') def get_by_key(dictionnary, key): """Return element in dictionnary corresponding to `key`.""" return dictionnary[key] if isinstance(dictionnary, dict) else '' Since you have one template to create a new serverlist but also to show all the existing serverlist objects and uptdate them, you need both kinds of forms. So creating the forms dict above is in addition to having the creation form HomeForm(). Your context should have: args = { 'form': form, # this is the serverlist creation form (empty) 'forms': forms, # these are all the forms for existing instances 'posts': posts} Also I don't see where in your PostEdit you specify your form_class, this is needed for an UpdateView to work.
accepted answer of: http://stackoverflow.com/q/47527443
type: Answer

http://stackoverflow.com/comment/82041606
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47533274
has text: You only want to change this server, `await client.send_message(server)` ... replace that server with discord.Object('id').

http://stackoverflow.com/comment/138040184
comment on: http://stackoverflow.com/a/78047935
type: Comment
score: 0
type: AnswerComment
has text: @AlejandroBarone There was a misunderstanding on my part, you dont use the slack handle you would type but the member ID. For me this was more about understanding how to get that.

http://stackoverflow.com/comment/82002145
score: 0
comment on: http://stackoverflow.com/q/47522403
type: QuestionComment
has text: Add the non rotated one as well.... and make sure those are real data. One method would be using `SIFT` algorithm to track features and see how far they went apart.
type: Comment

http://stackoverflow.com/comment/81737031
score: 0
comment on: http://stackoverflow.com/q/47391242
type: Comment
type: QuestionComment
has text: @KenSyme: The service is running after I start it. And when I add the line of code which you suggested, I get the following error when I run flask code in debug mode- 'Error 0xC0000003 - The instance's SvcRun() method failed <Error getting traceback - traceback.print_exception() failed (null): (null)'

http://stackoverflow.com/a/73762332
type: Answer
upvote count: 1
has body: I tried this answer, but it is too slow for big graphs. I discovered that converting the Networkx graph to DataFrame and combining the nodes on DataFrame is faster than the existing Networkx function. import time import networkx as nx #create node replacement dictionary def createRepDict(G1): node2supernode={} for supernode in nx.connected_components(G1): nodes = sorted(list(supernode)) for node in nodes: node2supernode[node]=nodes[0] #fill the missing nodes with itself (if you have different task) for node in G1.nodes: if node not in node2supernode: node2supernode[node]=node return node2supernode start_time=time.time() for _ in range(10): G1=G.copy() df=nx.to_pandas_edgelist(G1) #create node replacement dictionary node2supernode=createRepDict(G1) df['source']=df.apply(lambda row: node2supernode[row['source']],axis=1) df['target']=df.apply(lambda row: node2supernode[row['target']],axis=1) # you can drop the self loop created after combining the nodes self_loop=df[df['source']==df['target']].index df=df.drop(self_loop) # edge_attr field can change based on your edge datas G1=nx.from_pandas_edgelist(df,'source','target', edge_attr='edgeData',create_using=nx.MultiDiGraph()) print(time.time()-start_time) While this code takes only a total of 4 seconds for 10 random runs on a graph with around 5k nodes and 5k edges, it takes a total of 1455 seconds for 10 random runs with the existing methods.
downvote count: 0
answers question: http://stackoverflow.com/q/47501336
score: 1

http://stackoverflow.com/comment/81873047
score: 1
type: Comment
type: QuestionComment
has text: @patrick please add ```^ ^snippets/(?P<pk>[0-9]+)/$``` if you want acheive http://127.0.0.1:8000/snippets/1/
comment on: http://stackoverflow.com/q/47459216

http://stackoverflow.com/a/48000098
upvote count: 4
answers question: http://stackoverflow.com/q/47502241
has body: Hi, after a little research, I found a way to get DeepSpeech run on Windows, but using a Ubuntu back-end. Here is the link of the blog where you'll find all the detailed steps about how to make DeepSpeech work on Windows, enjoy : https://fotidim.com/deepspeech-on-windows-wsl-287cb27557d4
downvote count: 0
score: 4
type: Answer

http://stackoverflow.com/comment/81821673
type: QuestionComment
has text: I guess this is a strong indication that you have in incomplete or broken matplotlib install or that versions are not matching.
score: 1
comment on: http://stackoverflow.com/q/47430603
type: Comment

http://stackoverflow.com/q/47425797
tagged with: pygame
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47425930
has title: python interpreter throwing a type error where there is none
tagged with: class
has answer: http://stackoverflow.com/a/47425930
type: AnsweredQuestion
tagged with: typeerror
has body: i am trying to create a drop down like feature in pygame. The program consists of the "Drop" class which has texts on it and describes the general purpose of the drop down menu. Then there is the wrapper class which contains all the different labels on the drop down menu. The Child class is the label and can be added on to the wrapper class via the "add_child" function which is where the error is occurring. import pygame as pg doc = "c:/users/user/documents/code/py/pg/project/" vec = pg.math.Vector2 class Drop(Sprite): def __init__(self, parent, **kwargs): self.parent = parent default = { "size":[100, 25], "pos":vec(0, 0), "bg":pg.Color("#ff0000"), } for key, value in default.items(): if key not in kwargs: kwargs[key] = value self.size = kwargs["size"] self.pos = vec(kwargs["pos"]) self.bg = kwargs["bg"] super().__init__() class Child(Sprite): def __init__(self, parent, **kwargs): self.parent = parent default = { "size":[100, 25], "pos":vec(0, 0), "bg":pg.Color("#00ff00") } for key, value in default.items(): if key not in kwargs and key != "name": kwargs[key] = value self.size = kwargs["size"] self.pos = vec(kwargs["pos"]) self.bg = kwargs["bg"] self.name = kwargs["name"] super().__init__() def render(self): self.parent.image.blit(self.image, self.rect) class Wraper(Sprite): def __init__(self, parent, index=1): self.index = index self.children = [] # childs which are labels with texts on it self.parent = { "0":parent.parent, "1":parent.parent.parent }[str(self.index)] self.y = { "0":parent.pos.y + parent.size[1], "1":parent.parent.pos.y + parent.parent.size[1] }[str(self.index)] self.size = [100, 100] self.bg = pg.Color("#000000") self.x = self.parent.pos.x self.pos = vec(self.x, self.y) super().__init__() # this is a custom sprite initialization class i'ts not the problem def add_child(self, **kwargs): self.children.append(Child(self, kwargs)) # this is where the interpreter throws the error # aperantly the child class takes 2 positional arguments # but i gave 3. b…
answer count: 1

http://stackoverflow.com/comment/81955242
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47499876
score: 0
has text: @schwobaseggl This line throws a type error: "TypeError: unsupported operand type(s) for +: 'range' and 'list'"

http://stackoverflow.com/a/47541902
answers question: http://stackoverflow.com/q/47520885
has body: looks like adding dayfirst=True to the read_csv statement did the trick. csv=pd.read_csv(f,engine='c',header=0,index_col='date', parse_dates=True, dayfirst=True,infer_datetime_format=True,names=['date','id','settle_price','settle_price_acc','pos','trade'])
type: Answer
score: 0

http://stackoverflow.com/comment/81796087
comment on: http://stackoverflow.com/q/47420901
type: Comment
type: QuestionComment
has text: I bet `zip` would be useful here.
score: 2

http://stackoverflow.com/a/47498206
score: 3
has comment: http://stackoverflow.com/comment/81951673
type: Answer
accepted answer of: http://stackoverflow.com/q/47498189
upvote count: 3
has comment: http://stackoverflow.com/comment/81951597
has body: Remove the line: line=file1.readline() which reads the first line and thus moves the file pointer past the first line before you start your actual line-by-line iteration. Generally, a file handle as returned by open(...) is an iterator that produces each line only once. You can, however, move it back to beginning by: file1.seek(0)
has comment: http://stackoverflow.com/comment/81951644
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81951726
answers question: http://stackoverflow.com/q/47498189

http://stackoverflow.com/a/47499970
has comment: http://stackoverflow.com/comment/81955455
upvote count: 2
has body: Default for .to_csv is to write a new file. You need to append - mode='a'. See: Panda's Write CSV - Append vs. Write
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47499824
score: 2

http://stackoverflow.com/a/58111077
type: Answer
score: 0
upvote count: 1
downvote count: 1
has body: I suppose that explonation will help you. It's said that with bad configuration tensorflow with intel optimizations may have worse performance then clear build https://github.com/tensorflow/serving/issues/1272#issuecomment-477878180 You may try to configure parameters of batching (with config file and --enable_batching parameter) https://github.com/tensorflow/serving/tree/master/tensorflow_serving/batching And set (inter/intra)_op_parallelism_threads. Additionaly, MKL has it's own flags for improving performance https://www.tensorflow.org/guide/performance/overview#tuning_mkl_for_the_best_performance
answers question: http://stackoverflow.com/q/47512355

http://stackoverflow.com/comment/82051527
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47502107
score: 0
has text: Thanks for the workaround. I typically like my statics / class methods first, but I'd rather have a clean mypy bill of health.

http://stackoverflow.com/q/47491175
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81940096
tagged with: python
has comment: http://stackoverflow.com/comment/81940281
has body: In bash printf "\x00\x00\xFF\x00" | dd bs=4 seek=$(($y*$width+$x)) of=/dev/fb0, where width is the width in pixel of your monitor, allow you to write a red pixel at the x, y coordinates on your screen. I'm using python to retrieve color values of an image and I want to call the previous bash command and put the values I found with python. When I call the subprocess with: command = 'printf "\x00\x00\xFF\x00" | dd bs=4 seek=276200 of=/dev/fb' subprocess.call(command, shell=True) I get this error: Traceback (most recent call last): File "./sub.py", line 30, in &lt;module&gt; subprocess.call(command, shell=True) File "/usr/lib/python2.7/subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception TypeError: execv() arg 2 must contain only strings Without the \x characters the subprocess works. command = 'printf "test" | dd bs=4 seek=2 of=test.txt' subprocess.call(command, shell=True) I found some interesting links like this one : Formatting a command in python subprocess popen but I don't really get it. Is it possible to put \x characters to a subprocess ? How ? Is there an other way ? Thank you very much EDIT: First of all thank you all for your help. I found something that do the trick. I don't think that this is the best way to do it but it works. printf "\x00\x00\xFF\x00" in the terminal works normally and print a weird character �. But when called in a python subprocess subprocess.call('printf "\x00\x00\xFF\x00"', shell=True) it gives an error TypeError: execv() arg 2 must contain only strings. When you escape backslash like this subprocess.call('printf "\\x00\\x00\\xFF\\x00"', shell=True) it prints \x00\x00\xFF\x00 and not the weird � so this is not exactly the same as the printf directly from the terminal. I tried to escape in a lot of different ways but I didn't get the �. I d…
score: 0
tagged with: bash
tagged with: subprocess
linked to: http://stackoverflow.com/q/27985888
answer count: 1
has answer: http://stackoverflow.com/a/47491267
has comment: http://stackoverflow.com/comment/81937744
tagged with: hex
type: Question
tagged with: dd
has title: Hex to python subprocess
has comment: http://stackoverflow.com/comment/81940398
has comment: http://stackoverflow.com/comment/81940337

http://stackoverflow.com/comment/81770285
has text: @immortal you probably should just use the `__dict__` attribute, and use `vars` to access it in that case instead of `dir`
comment on: http://stackoverflow.com/q/47408447
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47708478
type: Answer
has body: To read a line-separated JSON file line by line read each line of the file in as a string using the loads() method in python (load String). I then wrote the following code to get at the keys I was looking for: with open(input_file) as tweets_file: for line in tweets_file: tweet = json.loads(line) # try catch handles for possibly_sensitive not being in the tweet metadata.. try: sensitive = tweet['possibly_sensitive'] except KeyError: sensitive = None This worked wonderfully.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47522258
accepted answer of: http://stackoverflow.com/q/47522258
score: 0

http://stackoverflow.com/q/47428530
has body: I have a json which I am converting to a dictionary and then I am creating a dataframe using certain key-value pairs present in the dictionary # json a = """{ "cluster_id": 3, "cluster_observation_data": [[1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 1]], "cluster_observation_label": [0, 1], "cluster_centroid": [1, 2, 3, 4, 5, 6, 7, 10], "observation_id":["id_xyz_999","id_abc_000"] }""" # convert to dictionary data = json.loads(a) sub_dict = dict((k, data[k]) for k in ('cluster_observation_data', 'cluster_observation_label')) train = pd.DataFrame.from_dict(sub_dict, orient='columns') After converting it to a ddataframe, I an trying to calculate its euclidean distance from the cluster_centroid present in the data dictionary. The function works fine, but in the final train dataframe I am getting NaNs def distance_from_center(row): centre = data['cluster_centroid'] obs_data = row[0] print('obs_data', obs_data) print('\n\n\n\n') print('center', centre) # print(type(obs_data)) # print(type(centre)) dist = sum([(a - b)**2 for a, b in zip(centre, obs_data)]) print(dist) return dist train.loc[:, 'center_dist'] = train.loc[:, ['cluster_observation_data']].apply(distance_from_center) I'm not able to figure where it is that I am going wrong. even a small hint will do.
accepted answer: http://stackoverflow.com/a/47428607
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/47428820
has answer: http://stackoverflow.com/a/47428607
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/47428820
favorite count: 0
type: Question
answer count: 2
has title: pandas apply returning NaN
downvote count: 0
tagged with: python

http://stackoverflow.com/q/47493423
tagged with: pytorch
has answer: http://stackoverflow.com/a/47493519
has comment: http://stackoverflow.com/comment/81942092
has title: Implementing a tutorial for Tensorflow and SaaK Transform: Handwritten Digits Recognition
answer count: 1
tagged with: tensorflow
type: Question
has body: I am learning to work with Tensorflow. I have installed most of the libraries. # load libs import torch import argparse from torchvision import datasets, transforms import matplotlib.pyplot as plt import numpy as np from data.datasets import MNIST import torch.utils.data as data_utils from sklearn.decomposition import PCA import torch.nn.functional as F from torch.autograd import Variable But I am facing an error like this: ImportError Traceback (most recent call last) &lt;ipython-input-8-257b7af364e1&gt; in &lt;module&gt;() 5 import matplotlib.pyplot as plt 6 import numpy as np ----&gt; 7 from data.datasets import MNIST 8 import torch.utils.data as data_utils 9 from sklearn.decomposition import PCA ImportError: No module named data.datasets I have installed the "dataset" library using the following command: sudo -H pip install dataset But I am still seeing this error. I am using python 2.7. I am pretty new to python. Can anyone help me in identifying the missing thing. Thanks in advance.
has comment: http://stackoverflow.com/comment/81948549
tagged with: mnist
tagged with: python
has comment: http://stackoverflow.com/comment/81941995
has comment: http://stackoverflow.com/comment/81942365
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47493519
linked to: http://stackoverflow.com/q/19917492

matching
tags question: http://stackoverflow.com/q/47523960
type: Tag
tag name: matching

http://stackoverflow.com/comment/82020363
type: AnswerComment
has text: I added the short code of the posts I loop in the html in the table in the main question in the end... Can you edit in your answer exactly where I should add the html code to pass the form id? and also what is "do something? " do what? I just need to pass the form id no?
score: 0
comment on: http://stackoverflow.com/a/47527622
type: Comment

http://stackoverflow.com/comment/81912904
has text: Edit: I tacked on list of lists `teams1` in the answer. But that is a silly representation, much better to stick with `teams`. The `data1` assignment in the answer appears to be what is relevant to you. You may have been having trouble sending a bare `team` string to the DB, when it requires a list or tuple of strings, as described in the answer. The notation `(s,)` converts string `s` into a 1-element tuple, which is suitable for sending through the database API.
type: Comment
comment on: http://stackoverflow.com/a/47478831
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81800131
score: 0
type: AnswerComment
has text: @depperm no, answer.sort() return is None, you don't need to assign back
comment on: http://stackoverflow.com/a/47422789
type: Comment

http://stackoverflow.com/q/47465171
answer count: 1
downvote count: 1
has body: We were planning to play colored Jenga with my kids and realized that we lost a dice with three colors (yellow, blue, red). I decided to write a program to generate random three colors. My program does not open a new window. from tkinter import * import random def get_color(): a = ['blue', 'red', 'yellow'] print(random.choice(a)) Button(text='Select Color', command=get_color).pack() mainloop()
has comment: http://stackoverflow.com/comment/81886129
has comment: http://stackoverflow.com/comment/81885089
favorite count: 0
has answer: http://stackoverflow.com/a/47465327
has comment: http://stackoverflow.com/comment/81885098
has title: Click button to pop up new window with random color on python 3
tagged with: python
type: Question
score: 0
tagged with: tkinter
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/81803349
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47424151
has text: ^hey coldspeed, thanks for the tip! it did indeed work. also cool username
score: 0

ctypes
tags question: http://stackoverflow.com/q/47466589
tags question: http://stackoverflow.com/q/47478773
tags question: http://stackoverflow.com/q/47520712
tags question: http://stackoverflow.com/q/47519605
tags question: http://stackoverflow.com/q/47437481
tags question: http://stackoverflow.com/q/47519836
tags question: http://stackoverflow.com/q/47470452
tags question: http://stackoverflow.com/q/47490929
tags question: http://stackoverflow.com/q/47509438
tags question: http://stackoverflow.com/q/47524320
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/47482674
tags question: http://stackoverflow.com/q/47495885

neural-network
tags question: http://stackoverflow.com/q/47536066
tags question: http://stackoverflow.com/q/47477942
type: Tag
tags question: http://stackoverflow.com/q/47508874
tags question: http://stackoverflow.com/q/47417060
tags question: http://stackoverflow.com/q/47513599
tags question: http://stackoverflow.com/q/47459225
tags question: http://stackoverflow.com/q/47493559
tags question: http://stackoverflow.com/q/47502648
tags question: http://stackoverflow.com/q/47408424
tags question: http://stackoverflow.com/q/47463987
tags question: http://stackoverflow.com/q/47476036
tags question: http://stackoverflow.com/q/47421951
tags question: http://stackoverflow.com/q/47488598
tags question: http://stackoverflow.com/q/47500817
tags question: http://stackoverflow.com/q/47472833
tags question: http://stackoverflow.com/q/47390661
tags question: http://stackoverflow.com/q/47441250
tags question: http://stackoverflow.com/q/47445732
tags question: http://stackoverflow.com/q/47509074
tags question: http://stackoverflow.com/q/47464999
tags question: http://stackoverflow.com/q/47531026
tags question: http://stackoverflow.com/q/47389536
tags question: http://stackoverflow.com/q/47394958
tags question: http://stackoverflow.com/q/47442792
tags question: http://stackoverflow.com/q/47400126
tags question: http://stackoverflow.com/q/47490834
tags question: http://stackoverflow.com/q/47520820
tag name: neural-network
tags question: http://stackoverflow.com/q/47432168
tags question: http://stackoverflow.com/q/47437582
tags question: http://stackoverflow.com/q/47426002
tags question: http://stackoverflow.com/q/47525790

http://stackoverflow.com/comment/119724687
type: AnswerComment
score: 0
has text: He specifically asked for help with pyupset not upsetplot?
comment on: http://stackoverflow.com/a/53686100
type: Comment

http://stackoverflow.com/a/47526432
score: 7
has comment: http://stackoverflow.com/comment/82357613
has comment: http://stackoverflow.com/comment/82366782
type: Answer
accepted answer of: http://stackoverflow.com/q/47494142
has body: For those who encounter this problem in future, you can save yourself some time and let npm install all necessary programs by running: npm install --global --production windows-build-tools Note: you need to run this command as administrator
answers question: http://stackoverflow.com/q/47494142
has comment: http://stackoverflow.com/comment/103831936
upvote count: 7
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47409630
has comment: http://stackoverflow.com/comment/81797349
accepted answer of: http://stackoverflow.com/q/47409573
type: Answer
has comment: http://stackoverflow.com/comment/81811598
has comment: http://stackoverflow.com/comment/81772934
has comment: http://stackoverflow.com/comment/81773138
has body: This is due to Python GIL (Global Interpreter Lock). It blocks Python threads to work on a single CPU. You can read more about it at https://wiki.python.org/moin/GlobalInterpreterLock Python GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe. There are multiple questions on the subject, check out the list here on SO If you want your code to work on multiple CPUs, check out the multiprocessing module.
has comment: http://stackoverflow.com/comment/81773418
upvote count: 2
has comment: http://stackoverflow.com/comment/81773453
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47409573
score: 2
has comment: http://stackoverflow.com/comment/81772528

http://stackoverflow.com/q/47416793
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Using regular expressions or pattern matching inside method calls?
has body: So I am using the testing the mechanical soup package to get into some webscraping stuff and I came across an interesting problem. I want to get a list of all the links in a page that have a period in the displayed text, indicating a file. I can check for that using an if statement inside a for loop: for link in browser.links(): if '.' in str(link.string): But the links method has a way to search the string of a link by using link_text="whatever", but it needs to match exactly. Is there any way I can do: for link in browser.links(link_text=something_with_a_period_in_it): I have a feeling this won't save any computation time but I can see it being useful in the future.
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47419354
has answer: http://stackoverflow.com/a/47419354
has comment: http://stackoverflow.com/comment/81788271

http://stackoverflow.com/q/47426203
upvote count: 1
has body: I am creating a Python package whose features include logging certain actions in a database. Thus I would like to store the database in a location such as ~/.package-name/database.sqlite. Additionally, ~/.package-name could be a directory to hold configuration files. What is the best practice for doing this? I am using setuptools to handle package installation. I imagine that within one of my modules, I would have code that checks for the existence of the database file and config file(s), creating them if necessary. Reading the documentation, it states you can’t actually install data files to some arbitrary location on a user’s machine; this is a feature, not a bug. You can always include a script in your distribution that extracts and copies your the documentation or data files to a user-specified location, at their discretion. It seems that I cannot create the location ~/.package-name using setuptools. So should I create this directory the first time the user runs the program by checking for the directory and invoking a script or function? Is there a standard sort of example I might look at? I had some trouble searching for my problem.
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81807682
tagged with: python
has title: Python packaging: create directory in homedir during installation
has comment: http://stackoverflow.com/comment/81808075
answer count: 0
tagged with: python-packaging
score: 1

http://stackoverflow.com/q/47433414
tagged with: python
has title: boto3 iam client: get policy by name
tagged with: boto3
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/54830110
answer count: 2
has body: I am trying to get a policy from boto3 client but there is no method to do so using policy name. By wrapping the create_policy method in a try-except block i can check whether a policy exists or not. Is there any way to get a policy-arn by name using boto3 except for listing all policies and iterating over it.
has answer: http://stackoverflow.com/a/47442387
favorite count: 0
score: 8
type: Question
upvote count: 8
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47437704
score: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81830874
has body: I'm new to SF, Python and Flask, which are the tools I'm using to build up a little web UI for registering (creating a new contact on SF). I found Simple-Salesforce and it works pretty well for me. So, right now I have this code that is working perfectly so far: # User Registration @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): FirstName = request.form['FirstName'] LastName = request.form['LastName'] AccountId = request.form['AccountId'] Birthdate = request.form['Birthdate'] # password = sha256_crypt.encrypt(str(form.password.data)) Home_Endpoint__c = request.form['Home_Endpoint__c'] # Execute query sf.Contact.create({'LastName':LastName,'FirstName':FirstName,'AccountId':AccountId, 'Birthdate':Birthdate, 'Home_Endpoint__c':Home_Endpoint__c, 'Test_User__c':1 }) flash('You are now registered', 'success') return render_template('register.html', form=form) What I need is to catch/read the SF dictionary JSON response with the new created id as shown in the Record Management section: Record Management To create a new ‘Contact’ in Salesforce: sf.Contact.create({'LastName':'Smith','Email':'example@example.com'}) This will return a dictionary such as {u'errors': [], u'id': u'003e0000003GuNXAA0', u'success': True} So that I can keep working with the new registered member on other processes. I will appreciate if someone gives me a hand on this.
has answer: http://stackoverflow.com/a/47604744
favorite count: 0
has comment: http://stackoverflow.com/comment/82162160
type: Question
tagged with: simple-salesforce
upvote count: 1
has title: Simple-Salesforce sf.Contact.create JSON response
tagged with: salesforce
tagged with: python
tagged with: flask
accepted answer: http://stackoverflow.com/a/47604744
type: AnsweredQuestion

http://stackoverflow.com/comment/82012864
comment on: http://stackoverflow.com/q/47528262
type: Comment
type: QuestionComment
score: 2
has text: They do entirely different things. the first loop always breaks after the first iteration.

http://stackoverflow.com/comment/81934364
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47489369
type: QuestionComment
has text: BTW: there will be other problem - `accept()` waits for user connections so first client will to have to wait for all other user before it can't start game. So it is easier to run user in thread.

http://stackoverflow.com/a/47493466
accepted answer of: http://stackoverflow.com/q/47489554
upvote count: 4
answers question: http://stackoverflow.com/q/47489554
has body: Interestingly Plotly seems to ignore categoryorder for integers but disabling of sorting can be achieved by passing type='category in xaxis in layout. type ( enumerated : "-" | "linear" | "log" | "date" | "category" ) default: "-" Sets the axis type. By default, plotly attempts to determined the axis type by looking into the data of the traces that referenced the axis in question. import plotly import plotly.graph_objs as go import numpy as np plotly.offline.init_notebook_mode() consultants = [1, 3, 2, 5, 4] info = np.random.randint(100, size=(5,5)) data = [] for i in range(len(info)): data.append(go.Bar(x=consultants, y=info[i,:])) layout = go.Layout(barmode='stack', xaxis=dict(type='category'), yaxis=dict(title='Number of customers')) fig = go.Figure(data=data, layout=layout) plotly.offline.iplot(fig, filename='stacked-bar')
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/109231977

http://stackoverflow.com/comment/84989236
type: QuestionComment
comment on: http://stackoverflow.com/q/47419305
has text: Bir daha bunu çözmeyi denemeyeceğim.
score: 0
type: Comment

http://stackoverflow.com/comment/81944529
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47494803
score: 0
has text: It is not easy to understand for a beginner.

http://stackoverflow.com/comment/82013727
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47528689
type: QuestionComment
has text: In Python 3, division always returns a float. If you want int division, like in Python 2, use ``//`` instead of ``/``

http://stackoverflow.com/comment/81809948
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47427386
type: Comment
has text: Dear, I am not getting expected output though this code. I think my logic or something is wrong. Please suggest .. I want to allow two mismatch with special character. `N = "TAG", K = "LQ", D = "E"`

http://stackoverflow.com/comment/82002772
score: 0
comment on: http://stackoverflow.com/q/47523179
type: Comment
type: QuestionComment
has text: Your function `data` does not return any value so `running` gets set to `none`. And your while input... loop logic looks strange, I suggest you read through it carefully.

http://stackoverflow.com/comment/81828989
score: 1
type: Comment
type: QuestionComment
has text: `Popen.terminate()` *is*, in general, the right thing. By the way, for requesting feedback on working code (as opposed to questions about specific problems, with code built into a [mcve] that isolates a single problem), consider [codereview.se] instead of StackOverflow (though *do* read the Help Center there before posting).
comment on: http://stackoverflow.com/q/47437300

http://stackoverflow.com/comment/81955099
type: QuestionComment
has text: Can you give one Jason example?
comment on: http://stackoverflow.com/q/47499824
type: Comment
score: 0

http://stackoverflow.com/q/47414080
has body: I need to use AWS IoT MQTT service. I am doing some experimenting with https://github.com/aws/aws-iot-device-sdk-python currently. My application will be using websockets to communicate with another service, and then publish / subscribe to MQTT topics to forward / receive messages. Is it likely that this library will be blocking code execution? I still try to get my head around asyncio, and not sure what things I should be looking out for. How do I know if it will cause problems? I believe I will only need to use AWSIoTMQTTClient from above library . This is an extract from the working code I have: class AWSIoTClient: def __init__(): ... self.client = AWSIoTMQTTClient(...) def subscribe(self, callback): self.client.subscribe(f'{self.TOPIC}/subscribe/', 0, callback) def publish(self, message): self.client.publish(self.TOPIC, message, 0) class MyWSProtocol(WebSocketClientProtocol): def set_aws_client(self, client: AWSIoTClient): client.subscribe(self.customCallback) self.client = client def customCallback(self, client, userdata, message): # This will be called when we send message from AWS if message.payload: message = json.loads(message.payload.decode('utf-8').replace("'", '"')) message['id'] = self.next_id() self.sendMessage(json.dumps(message).encode('utf-8')) def onMessage(self, payload, isBinary): message = json.loads(payload) # This will forward message to AWS self.client.publish(str(payload))
tagged with: aws-iot
linked to: http://stackoverflow.com/q/33357233
has title: AWS IoT Python SDK and asyncio
tagged with: python-asyncio
tagged with: mqtt
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47415716
accepted answer: http://stackoverflow.com/a/47415716
tagged with: amazon-web-services
favorite count: 0
type: Question

http://stackoverflow.com/comment/81915731
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47480366
type: Comment
has text: please check out my UPDATE in question

pre-trained-model
tag name: pre-trained-model
tags question: http://stackoverflow.com/q/47451919
type: Tag

http://stackoverflow.com/a/47432059
downvote count: 0
has body: There are a few problems in the code above: stop() does not need a parameter The program ends before the coroutine is executed (stop() was called before it). Here is the fixed code (without exceptions and the exception handler): import asyncio from threading import Thread async def coro(): print("in coro") return 42 loop = asyncio.get_event_loop() thread = Thread(target=loop.run_forever) thread.start() fut = asyncio.run_coroutine_threadsafe(coro(), loop) print(fut.result()) loop.call_soon_threadsafe(loop.stop) thread.join() call_soon_threadsafe() returns a future object which holds the exception (it does not get to the default exception handler): import asyncio from pprint import pprint from threading import Thread def exception_handler(loop, context): print('Exception handler called') pprint(context) loop = asyncio.get_event_loop() loop.set_exception_handler(exception_handler) thread = Thread(target=loop.run_forever) thread.start() async def coro(): print("coro") raise RuntimeError("BOOM!") fut = asyncio.run_coroutine_threadsafe(coro(), loop) try: print("success:", fut.result()) except: print("exception:", fut.exception()) loop.call_soon_threadsafe(loop.stop) thread.join() However, coroutines that are called using create_task() or ensure_future() will call the exception_handler: async def coro2(): print("coro2") raise RuntimeError("BOOM2!") async def coro(): loop.create_task(coro2()) print("coro") raise RuntimeError("BOOM!") You can use this to create a small wrapper: async def boom(x): print("boom", x) raise RuntimeError("BOOM!") async def call_later(coro, *args, **kwargs): loop.create_task(coro(*args, **kwargs)) return "ok" fut = asyncio.run_coroutine_threadsafe(call_later(boom, 7), loop) However, you should probably consider using a Queue to communicate with your thread instead.
answers question: http://stackoverflow.com/q/47413359
score: 8
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/81822913
accepted answer of: http://stackoverflow.com/q/47413359
type: AcceptedAnswer

http://stackoverflow.com/q/47439103
has title: How to execute tests in a test suite in parallel
answer count: 1
tagged with: selenium
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81868636
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/81844185
type: UnansweredQuestion
has body: I have managed to run tests in parallel by using webdriver against a selenium hub and node. This code called before the tests is run. cls.driver = webdriver.Remote( command_executor="http://localhost:4444/wd/hub", desired_capabilities={ "browserName": "chrome", }) cls.driver.maximize_window() cls.driver.get(cls.serverUrl) p = multiprocessing.Process(target=cls.driver.get(cls.serverUrl), args=()) p.start() p.join() In that way I can start multiple browsers by executing them manually from Eclipse. However I would like to do that automatically in a testsuite. But in a test suite all tests are started in a sequence. If anyone has an idea how to proceed it would be great.
tagged with: python
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/47459254
downvote count: 0

http://stackoverflow.com/q/47403218
has answer: http://stackoverflow.com/a/47414600
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47424112
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/81760254
score: 0
has body: -I am successfully logged into my Virtual Machine and I have uploaded my files to the AWS as well (Amazon EC2). What I wish to do is execute my python code on the server but it says that the dependencies are not installed. When I run a pip install command, it returns the following error: PermissionError: [Errno 13] Permission denied: '/usr/local/lib64/python3.4/site-packages/apiclient How do I fix this? Is it even possible to install packages using pip? If yes, how?
answer count: 2
has title: How to add dependencies for my python code on Amazon EC2?
tagged with: amazon-ec2
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47388981
has answer: http://stackoverflow.com/a/47389077
downvote count: 2
favorite count: 0
type: Question
has body: I need to make function which returns rounded pi to n decimal places as string. For example pi_digits(3) should return '3.142', pi_digits(0) returns '3'. Here is my code: from math import pi def pi_digits(n): if n &gt; 0: return str(round(pi, n)) else: return str(round(pi)) But pi_digits(12) returns '3.14159265359' instead of '3.141592653590'. How to consider 0 while rounding?
has answer: http://stackoverflow.com/a/47389101
tagged with: rounding
upvote count: 0
has title: How to round float to n decimal places including 0 in the end in Python
tagged with: python
score: -2
accepted answer: http://stackoverflow.com/a/47389101
has comment: http://stackoverflow.com/comment/81731013
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47389077
answer count: 2

http://stackoverflow.com/q/47501511
has body: When running the following code there is a syntax error. I have researched and the syntax error happens for no reason that I know. The syntax error is: File "src/cloudspeech_demo.py", line 49 elif 'repeat after me' in text: TabError: inconsistent use of tabs and spaces in indentation ^ Here is my code: #!/usr/bin/env python3 # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A demo of the Google CloudSpeech recognizer.""" import aiy.audio import aiy.cloudspeech import aiy.voicehat def main(): recognizer = aiy.cloudspeech.get_recognizer() recognizer.expect_phrase('turn off the light') recognizer.expect_phrase('turn on the light') recognizer.expect_phrase('blink') recognizer.expect_phrase('repeat after me') button = aiy.voicehat.get_button() led = aiy.voicehat.get_led() aiy.audio.get_recorder().start() while True: print('Press the button and speak') button.wait_for_press() print('Listening...') text = recognizer.recognize() if text is None: print('Sorry, I did not hear you.') else: print('You said "', text, '"') if 'turn on the light' in text: led.set_state(aiy.voicehat.LED.ON) elif 'turn off the light' in text: led.set_state(aiy.voicehat.LED.OFF) elif 'blink' in text: led.set_state(aiy.voicehat.LED.BLINK) elif 'repeat after me' in text: to_repeat = text.replace('repeat after me', '', 1) aiy.audio.say(to_repeat) elif 'goodbye' in text: break if __name__ == '__main__': main() Please tell me what I need to do to fix this error.
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/81958913
has title: Unknown Syntax Error in google aiy voice kit code
has answer: http://stackoverflow.com/a/47501588
linked to: http://stackoverflow.com/q/45621722
upvote count: 1
has comment: http://stackoverflow.com/comment/81958905
answer count: 1
has comment: http://stackoverflow.com/comment/81960775
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/91857154
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81960900
tagged with: google-aiy
has comment: http://stackoverflow.com/comment/81960833
type: UnansweredQuestion
score: -3

http://stackoverflow.com/a/72530731
score: 2
answers question: http://stackoverflow.com/q/47446480
downvote count: 0
has body: I know this is old, but there is another alternative - ie to "split" the json file and store each important field as its own environment variable. Something like: PRIVATE_KEY_ID=qsd PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n" CLIENT_EMAIL=blabla@lalala.iam.gserviceaccount.com CLIENT_ID=7777 CLIENT_X509_CERT_URL=https://www.googleapis.com/robot/v1/metadata/x509/whatever.iam.gserviceaccount.com This can be in a .env file locally, and put on heroku using the UI or heroku config:set commands Then in the python file, you can initialize the ServiceAccount using a dict instead of a JSON CREDENTIALS = { "type": "service_account", "project_id": "iospress", "private_key_id": os.environ["PRIVATE_KEY_ID"], "private_key": os.environ["PRIVATE_KEY"], "client_email": os.environ["CLIENT_EMAIL"], "client_id": os.environ["CLIENT_ID"], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": os.environ["CLIENT_X509_CERT_URL"] } credentials = ServiceAccountCredentials.from_json_keyfile_dict(CREDENTIALS, SCOPES) It's a bit more verbose than some of the options presented here, but it works without any buildback or other
upvote count: 2
type: Answer

http://stackoverflow.com/comment/81780667
comment on: http://stackoverflow.com/a/47411798
type: Comment
has text: I was wrong regarding the transformation. Longitudes in [-180, 180] are just fine
score: 0
type: AnswerComment

http://stackoverflow.com/q/47478050
upvote count: 1
tagged with: file
has title: Accessing global file in the user defined function
favorite count: 0
has body: I am trying to access file which is opened globally as below: with open("number.txt") as num: val=int(num.read()) consider number.txt will be having some number After the above lines of code if I use the above file pointer inside a method as below: def updateval(): global num num.write(numb) I am getting error as :ValueError: I/O operation on closed file If I open file inside function then there wont be any issue.But I want to open file only once so in many opther function I can perform file operation without opening again and again Please help me in resolving this!! Many thanks in advance..
type: Question
has answer: http://stackoverflow.com/a/47478075
possible better answer: http://stackoverflow.com/a/47478075
answer count: 2
tagged with: function
has answer: http://stackoverflow.com/a/47478218
accepted answer: http://stackoverflow.com/a/47478218
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
score: 1

http://stackoverflow.com/a/47458192
has comment: http://stackoverflow.com/comment/81870973
has comment: http://stackoverflow.com/comment/81871065
answers question: http://stackoverflow.com/q/47458136
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81871252
has comment: http://stackoverflow.com/comment/81871022
score: 1
type: Answer
has body: We can using pd.concat and drop_duplicates,(sorry seems like SO, hide their format...., it will make the answer ugly...) pd.concat([df1,df2]).drop_duplicates('subject_id',keep='first') Out[95]: subject_id first_name last_name 0 1 Alex Anderson 1 2 Amy Ackerman 2 3 Allen Ali 3 4 Alice Aoni 4 5 Ayoung Atiches 2 6 Bran Balwner 3 7 Bryce Brice 4 8 Betty Btisan pd.concat([df1,df2]).drop_duplicates('subject_id',keep='last') Out[96]: subject_id first_name last_name 0 1 Alex Anderson 1 2 Amy Ackerman 2 3 Allen Ali 0 4 Billy Bonder 1 5 Brian Black 2 6 Bran Balwner 3 7 Bryce Brice 4 8 Betty Btisan

http://stackoverflow.com/a/47500882
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81967312
accepted answer of: http://stackoverflow.com/q/47500793
answers question: http://stackoverflow.com/q/47500793
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81970444
has body: You read the list from the file after you filled it with data. So if we analyze the main (I removed the add function, and annotated the program), we get: # the standard value of the list my_list = ["a", "b", "c", "d", "e"] # adding data to the list while True: # we write the new list to the file item = input("Add to the list: \n").upper() if item == "Q": break else: item = add(item) # loading the list we overrided in this program session with open("my_list.pickle", "rb") as file1: my_items = pickle.load(file1) # print the loaded list print(my_items) So since you start with a default list, and each time you add elements to the file you rewrite the file, if you at the end of the program load the list, guess what? you obtain the list you just saved. The solution is thus to move the loading to the top of the program: import pickle import os.path # the standard value of the list my_list = ["a", "b", "c", "d", "e"] # in case the file already exists, we use that list if os.path.isfile("my_list.pickle"): with open("my_list.pickle", "rb") as file1: my_items = pickle.load(file1) # adding data to the list while True: # we write the new list to the file item = input("Add to the list: \n").upper() if item == "Q": break else: item = add(item) # print the final list print(my_items) Note that is rather inefficient to each time store the new list. You better give the user the opportunity to alter the list, and store it at the end of the program.
type: AcceptedAnswer

http://stackoverflow.com/comment/81831349
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47438306
has text: There also seems to be some code missing at the end.
score: 0

http://stackoverflow.com/comment/82038114
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47537837
has text: btw I think you should change .content to .text
score: 0

utf-8
tags question: http://stackoverflow.com/q/47405236
tags question: http://stackoverflow.com/q/47525872
tags question: http://stackoverflow.com/q/47534573
tags question: http://stackoverflow.com/q/47435854
tag name: utf-8
tags question: http://stackoverflow.com/q/47517899
tags question: http://stackoverflow.com/q/47409514
tags question: http://stackoverflow.com/q/47469201
tags question: http://stackoverflow.com/q/47425695
type: Tag
tags question: http://stackoverflow.com/q/47434283
tags question: http://stackoverflow.com/q/47535373
tags question: http://stackoverflow.com/q/47393869
tags question: http://stackoverflow.com/q/47433181
tags question: http://stackoverflow.com/q/47419943
tags question: http://stackoverflow.com/q/47493880

http://stackoverflow.com/comment/82002151
has text: Yea, I know about read the whole file to overwrite, but i don't know how can I overwrite just one file row.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47521340
type: QuestionComment

http://stackoverflow.com/comment/81898048
comment on: http://stackoverflow.com/q/47471516
type: QuestionComment
has text: If you really kill a process it can't do any cleanup. You must terminate it in a "nicer" way. You could e.g. open an additional control socket on which you send a command to terminate or, depending on OS, handle a SIGTERM (Un*x-like) or handle the request to stop the service on Windows.
type: Comment
score: 0

http://stackoverflow.com/q/47433769
tagged with: dictionary
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/47433894
accepted answer: http://stackoverflow.com/a/47433894
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81822292
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Add element to JSON in Python
has body: There are few topics regarding this, however, neither of them helped me in a way I need. I would need to parse json by (some) fields that user enters, meaning the user can fill 3 out of 7 fields, leaving 4 empty. I cannot put attribute with an empty value to json, thus I need join only the entered ones. This is where my issue comes, can't figure out the correct way to glue together, for example, nw_src with IP address (appearing as one variable) together with nw_proto, dl_type and potentially others, in the match attribute. In this code, Python expects comma instead of the colon between nw_proto and 1. data2 = {} data2['nw_src'] = '10.0.0.5' #or variable json_data = json.dumps(data2) data = {"dpid": "1", "priority": "65500", "table_id": "0", "match": {data2, 'nw_proto': '1', 'dl_type': '2048'}} r = requests.post('http://localhost:8080/stats/flowentry/add', data=json.dumps(data)) I tried this way, also with json_data and something like this: data[0]['f'] = var no one did the trick and resulted in error. Any ideas?
tagged with: http://stackoverflow.com/tag/json
tagged with: python

http://stackoverflow.com/q/47399041
has title: How to find an email address from the below elements?
linked to: http://stackoverflow.com/q/31416858
tagged with: python
has answer: http://stackoverflow.com/a/47399153
score: -1
tagged with: regex
has answer: http://stackoverflow.com/a/47399131
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81751327
answer count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/47399153
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/81751516
favorite count: 0
has answer: http://stackoverflow.com/a/47399155
accepted answer: http://stackoverflow.com/a/47399155
type: Question
has comment: http://stackoverflow.com/comment/81751256
has comment: http://stackoverflow.com/comment/81751334
has body: How to find an email address using regex and considering mailto: as a flag. I tried with an expression but it only parses a small portion. import re html_content=''' info@mohindraroto.com ''' row = re.findall(r'mailto:(\w*.)',html_content)[0] print(row) It gives me: info@ Any help to modify my existing expression or create a new one for the sake of finding email will be highly appreciated.

http://stackoverflow.com/comment/81801707
score: 0
type: Comment
has text: it completes only if you're commenting. Otherwise (edit, dupehammer to close) it doesn't. thanks for the UV.
type: AnswerComment
comment on: http://stackoverflow.com/a/47422399

http://stackoverflow.com/q/47479080
type: Question
has title: Problems with cache queryset django rest framework
has body: Good day to all, I have been trying to make this query be consulted every time the REST service is used in the API, but only the first time it obtains the data from the DB and when the data changes the service only brings the cache stored data My Code: urls.py router.register(r'cron-log',views.CronLogViewSet, base_name='cron-log') Views.py - my viewset class class CronLogViewSet(viewsets.ModelViewSet): queryset = Cron_log.objects.all().order_by('-id').values()[:5:1] serializer_class = CronLogSerializer Models.py my model class from Cron_log class Cron_log(models.Model): log = models.CharField(max_length=40) time = models.CharField(max_length=40) def as_dict(self): return {'log':self.log,'time':self.time} Serializer.py serializer class class CronLogSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Cron_log fields = ('log','time') I tried with a for before the queryset, with list(query_set) but the issue still there thanks! for your help
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/47480618
tagged with: rest
score: 1
favorite count: 0

http://stackoverflow.com/a/47538565
answers question: http://stackoverflow.com/q/47537849
downvote count: 0
type: AcceptedAnswer
score: 3
upvote count: 3
has body: Use the re module to define your pattern and then use the sub() function to substitute occurrence of that pattern with your own string. import re ... pat = re.compile(r"D133330593\d{6}") re.sub(pat, "D133330593abcdef", filedata) The above defines a pattern as -- your string ("D133330593") followed by six decimal digits. Then the next line replaces ALL occurrences of this pattern with your replacement string ("abcdef" in this case), if that is what you want. If you want a unique replacement string for each occurrence of pattern, then you could use the count keyword argument in the sub() function, which allows you to specify the number of times the replacement must be done. Check out this library for more info - https://docs.python.org/3.6/library/re.html
accepted answer of: http://stackoverflow.com/q/47537849
type: Answer

http://stackoverflow.com/comment/81738712
score: 0
comment on: http://stackoverflow.com/q/47390035
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159390/discussion-between-masterwizard-and-gphilo).
type: Comment

http://stackoverflow.com/comment/81808871
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47427053
type: Comment
has text: C:\Anaconda3\python.exe C:/Users/hsingh/PycharmProjects/untitled/Multiprocessing_example.py end the time is Wed Nov 22 10:37:18 2017 the time is Wed Nov 22 10:37:20 2017 the time is Wed Nov 22 10:37:22 2017 the time is Wed Nov 22 10:37:24 2017 the time is Wed Nov 22 10:37:26 2017 Process finished with exit code 0

http://stackoverflow.com/a/47515196
has comment: http://stackoverflow.com/comment/81986163
has comment: http://stackoverflow.com/comment/81986221
type: Answer
answers question: http://stackoverflow.com/q/47514913
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81986249
downvote count: 0
has body: This code: lst = ['a-doa-a-h2t','a-rne','a-ece','a-ece','a-tnt-c-doa-d-nvc-a-nnm-a-h5t','a-tps'] for item in lst: words = item.split('-') print([word for word in words if len(word) == 3]) produces output something like your requirement: ['doa', 'h2t'] ['rne'] ['ece'] ['ece'] ['tnt', 'doa', 'nvc', 'nnm', 'h5t'] ['tps']

http://stackoverflow.com/q/47529156
has comment: http://stackoverflow.com/comment/98140497
favorite count: 0
has title: Creating table over written parquet file in Athena
tagged with: amazon-athena
score: 1
answer count: 1
tagged with: python
has body: I am creating a parquet file from a CSV file using the following python script: import pandas as pd import pyarrow as pa import pyarrow.parquet as pq csv_file = '~/Desktop/SWA_UK_Pickup_Forecast_HOURLY_M1_at_2017-11-28-04_20_21-UTC_from_28-Nov-2017_to_28-Nov-2017.csv' chunksize = 10 csv_stream = pd.read_csv(csv_file, sep=',', chunksize=chunksize, low_memory=False) for i, chunk in enumerate(csv_stream): if i == 0: parquet_schema = pa.Table.from_pandas(df=chunk).schema parquet_writer = pq.ParquetWriter('/Users/kohujwal/Desktop/parquet_forecast_file.parquet', parquet_schema, compression='snappy') table = pa.Table.from_pandas(chunk, schema=parquet_schema); parquet_writer.write_table(table) parquet_writer.close(); Then I am manually uploading it to some s3 location, and creating a table over it in Athena. The query used to create the table: CREATE EXTERNAL TABLE IF NOT EXISTS forecast_report_lom_parquet ( `forecast_week` int, `for_date` string, `forecast_day_of_week` string, `merchant_id` string, `shipper_account_id` string, `shipper_name` string, `node_id` string, `routing_preference` string, `forecast_shipment_count` int, `forecast_pallet_count` int, `forecast_volume` double ) STORED AS PARQUET LOCATION 's3://prevoir-athena-input-prod/spike-computation/forecast-reports/parquet/live-order-model/' tblproperties ("parquet.compress"="SNAPPY") The table is created successfully, however when I try to query the table, it doesn't display the contents. It just shows the indexes of the rows and the column names. Here is the CSV and the parquet file. The query on the parquet table : SELECT * FROM prevoir_prod.forecast_report_lom_parquet Results that I am seeing on the console. Can anyone point out what's going wrong here?
tagged with: apache-arrow
type: Question
tagged with: parquet
tagged with: pyarrow
has comment: http://stackoverflow.com/comment/82820197
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52118387
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/115812154
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47533671
has text: The link to the twitter post is gone. Is there anywhere else I can find that? It is exactly what I need (check for non-existence of a field).
score: 0

url-parameters
tags question: http://stackoverflow.com/q/47397323
type: Tag
tag name: url-parameters

http://stackoverflow.com/q/47403336
tagged with: tflearn
tagged with: python
type: UnansweredQuestion
has title: tflearn creating multiple models
tagged with: openai-gym
score: 0
tagged with: machine-learning
answer count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/47407037
has body: I am working on a machine-learning script with tflearn and gym. I am able to get one network working in my python-script but whenever I try to call my functions to build up a 2nd or 3rd network and train it with model.fit, I get a tensorflow.python.framework.errors_impl.InvalidArgumentError edit; The goal should be to build up several different networks in order to compare them. First this should be only focused on the input_data and number of training epochs, but in the end, I'd like to compare different networksizes. Additionally I'd like to run it in a loop, building up more than two networks. The following code reproduces my error: initial_population(pop_size) creates an array of random actions, size of pop_size neural_network_model(input_size): creates a neural network train_model(training_data) creates a new model, if none is passed, and trains the model on the provided training data import gym import random import numpy as np import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression LR = 1e-3 env = gym.make('CartPole-v0') env.reset() goal_steps = 500 score_requirement = 1 def initial_population(pop_size): training_data = [] scores = [] accepted_scores = [] for _ in range(pop_size): score = 0 game_memory = [] prev_observation = [] for _ in range(goal_steps): action = random.randrange(0,2) observation, reward, done, info = env.step(action) if len(prev_observation) &gt; 0: game_memory.append([prev_observation, action]) prev_observation = observation score += reward if done: break if score &gt;= score_requirement: accepted_scores.append(score) for data in game_memory: if data[1] == 1: output = [0,1] elif data[1] == 0: output = [1,0] training_data.append([data[0], output]) env.reset() scores.append(score) return np.array(training_data) def neural_network_model(input_size): network = input_data(shape=[None, input_size, 1], name='input') network = fully_connected(network, 128, activation='relu…

http://stackoverflow.com/q/47500683
has comment: http://stackoverflow.com/comment/81957184
tagged with: hdfs
has body: I need to write a csv to hdfs. Currently i am using hdfs module for doing that. df = pd.DataFrame(data, columns = ['FirstName','LastName','City']) d = InsecureClient('http://localhost:50070') with d.write(path, encoding = 'utf-8', overwrite=True) as writer: df.to_csv(writer) file is succesfully generated, but it adds and extra index column as starting to the csv. I need to have the file with the columns i have specified. how i can remove this index? i could not find any parameter for that. #current output: ,"FirstName","LastName","City" 0,"John","Doo","New York" 1,"Jane","Doo","San Francisco" #expected: "FirstName","LastName","City" "John","Doo","New York" "Jane","Doo","San Francisco" thanks in advance, clairvoyant update: using pandas package to create my csv
has title: python hdfs writer adds an extra index column to output csv
has comment: http://stackoverflow.com/comment/81957213
type: Question
linked to: http://stackoverflow.com/q/20845213
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47500840
accepted answer: http://stackoverflow.com/a/47500840
score: 0
answer count: 1

http://stackoverflow.com/comment/82000967
type: QuestionComment
has text: `my_list.sort(key=lambda animal: animal.name)`
comment on: http://stackoverflow.com/q/47522199
score: 0
type: Comment

http://stackoverflow.com/comment/82025521
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47534430
has text: https://docs.python.org/3/library/json.html

http://stackoverflow.com/q/47395119
tagged with: python
score: 11
upvote count: 11
tagged with: pandas
has body: When I resample a Pandas time series to reduce the number of data points, the timestamp of each resulting datapoint is at the start of each resampling bin. When overplotting graphs with different resampling rates, this causes an apparent shift of the data. How can I "center" the timestamp of the resampled data in its bin, whatever the resample rate? What I get now is (when resampling to one hour): In [12]: d_r.head() Out[12]: 2017-01-01 00:00:00 0.330567 2017-01-01 01:00:00 0.846968 2017-01-01 02:00:00 0.965027 2017-01-01 03:00:00 0.629218 2017-01-01 04:00:00 -0.002522 Freq: H, dtype: float64 what I want is: In [12]: d_r.head() Out[12]: 2017-01-01 00:30:00 0.330567 2017-01-01 01:30:00 0.846968 2017-01-01 02:30:00 0.965027 2017-01-01 03:30:00 0.629218 2017-01-01 04:30:00 -0.002522 Freq: H, dtype: float64 MWE showing apprarent shift: #!/usr/bin/env python3 Minimal working example: import pandas as pd from matplotlib import pyplot as plt import numpy as np import seaborn seaborn.set() plt.ion() # sample data t = pd.date_range('2017-01-01 00:00', '2017-01-01 10:00', freq='1min') d = pd.Series(np.sin(np.linspace(0, 7, len(t))), index=t) d_r = d.resample('1h').mean() d.plot() d_r.plot()
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/69945592
type: Question
has answer: http://stackoverflow.com/a/47395358
has answer: http://stackoverflow.com/a/47395671
type: UnansweredQuestion
has title: Center datetimes of resampled time series
downvote count: 0
has answer: http://stackoverflow.com/a/70987536

http://stackoverflow.com/comment/81780964
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47413756
has text: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.histogram.html may help

http://stackoverflow.com/comment/115377673
comment on: http://stackoverflow.com/a/47419857
score: 2
type: AnswerComment
has text: I found I had to modify the pde_cdf line slightly: `pde_cdf = ndtr(np.subtract.outer(x, n)/stdev).mean(axis=1)`. You'll see the division by the standard deviation in the source code you point to. Mathematically, I think this is required anyway. And if you are lucky enough to look at things like a normal distribution, this sort-of does ok. But without the `stdev` it really breaks if you are looking at anything not "normal". It is working here because the width of your gaussian is 1.0.
type: Comment

http://stackoverflow.com/comment/81907902
score: 0
has text: I'm going to try some stuff.
comment on: http://stackoverflow.com/q/47476388
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81999931
type: Comment
has text: :D I will be looking more into this, thank you for the great advice
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47520510

http://stackoverflow.com/comment/81740254
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47393459
has text: Nothing is wrong but...at the end of this code I am assigning the transformed labels. Then I would have again to do an if/else as above. So I was just wondering if there was a parametrized way of referring to index or columns to avoid this repetitions.
type: Comment

http://stackoverflow.com/q/47429591
has answer: http://stackoverflow.com/a/47432108
favorite count: 0
type: Question
score: 3
tagged with: cypher
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47444437
has title: neo4j cypher performance with parameter as a list
has body: We are running neo4j version 3.3. we have 2 types of nodes (total of 10k nodes) which have a total of 650k relationships. We heap size of the memory is 8GB. The Nodes have a UNIQUE CONSTRAINT on the node ID. We are using the official neo4j-python official driver (we also tried to use the py2neo driver but the performance was even worse). While running the following query, the performance is VERY problematic. For a 1 hop distance it takes a few minutes (even for a list of several nodes). For a 2 hop distance (like the query below) with a list of 1 node it takes over 40 mintues. Any ideas how to improve the performance? query = '''MATCH (n1:label1) WHERE n1.ID IN {list} MATCH paths=((n1)-[:relType*..2]-&gt;(n2)) WHERE n1.ID &lt;&gt; n2.ID AND (n2:label1 OR n2:label2) RETURN DISTINCT paths UNION MATCH (n1:label2) WHERE n1.ID IN {list} MATCH paths=((n1)-[:relType*..2]-&gt;(n2)) WHERE n1.ID &lt;&gt; n2.ID AND (n2:label1 OR n2:label2) RETURN DISTINCT paths''' with driver.session() as session: results = list(session.run(query, parameters={'list':list_nodes})) if results: df = neo4j_graph_to_df(results) The function to process the result is below: def neo4j_graph_to_df(paths): paths_dict=OrderedDict() print(paths) for (pathID, e) in enumerate(paths): paths_dict[pathID]=OrderedDict() nodes_list = [n for n in e['paths'].nodes] rels_list = [r for r in e['paths'].relationships] pathl = [x for x in itertools.chain.from_iterable(itertools.zip_longest(nodes_list, rels_list)) if x ] for i, p in enumerate(pathl): if isinstance(p, neo4j.v1.types.Node): paths_dict[pathID]['Node'+str(i)+'Label']= str(next(iter(p.labels))) dicti = dict(zip(['Node'+str(i)+str(np) for np in p.properties.keys()], p.properties.values())) paths_dict[pathID] = OrderedDict( {**paths_dict[pathID], **dicti} ) if isinstance(p, neo4j.v1.types.Relationship): paths_dict[pathID]['Rel'+str(i-1)]=p.type dicti = dict(zip(['Rel'+str(i)+str(rp) for rp in p.properties.keys()], p.properties.values())) paths_dict[pathID] =Or…
upvote count: 3
answer count: 2
downvote count: 0
tagged with: neo4j

http://stackoverflow.com/a/47404215
answers question: http://stackoverflow.com/q/47404166
accepted answer of: http://stackoverflow.com/q/47404166
score: 0
has comment: http://stackoverflow.com/comment/81763016
has comment: http://stackoverflow.com/comment/81762511
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81762495
has body: Assuming you're using the rewrite branch (which, iirc, you should be), it's as simple as taking a ctx parameter to your command's function and accessing ctx.channel (note that the docs example seems to contradict what it says before it, but in fact it's just shorthand). If you are not using the rewrite branch, I believe it should be pretty much the same process, but your decorator should look like this instead: @client.command(pass_context=True)
has comment: http://stackoverflow.com/comment/81762405
type: Answer
has comment: http://stackoverflow.com/comment/81763857

http://stackoverflow.com/q/47473550
possible better answer: http://stackoverflow.com/a/47473584
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47473584
tagged with: pandas
has body: I'm now processing tweet data using python pandas module, and I stuck with the problem. I want to make a frequency table(pandas dataframe) from this dictionary: d = {"Nigeria": 9, "India": 18, "Saudi Arabia": 9, "Japan": 60, "Brazil": 3, "United States": 38, "Spain": 5, "Russia": 3, "Ukraine": 3, "Azerbaijan": 5, "China": 1, "Germany": 3, "France": 12, "Philippines": 8, "Thailand": 5, "Argentina": 9, "Indonesia": 3, "Netherlands": 8, "Turkey": 2, "Mexico": 9, "Italy": 2} desired output is: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(?????) &gt;&gt;&gt; df Country Count Nigeria 9 India 18 Saudi Arabia 9 . . . (no matter if there's index from 0 to n at the leftmost column) Can anyone help me to deal with this problem? Thank you in advance!
favorite count: 0
type: Question
upvote count: 4
has title: How can I change this form of dictionary to pandas dataframe?
accepted answer: http://stackoverflow.com/a/47473595
downvote count: 0
has answer: http://stackoverflow.com/a/47473597
tagged with: dataframe
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47473595
score: 4

http://stackoverflow.com/q/47453807
has comment: http://stackoverflow.com/comment/81902961
downvote count: 0
upvote count: 1
has title: get_children not working. get_descendants does. But i can't use that
answer count: 1
tagged with: django
tagged with: drop-down-menu
has answer: http://stackoverflow.com/a/47459140
type: Question
type: AnsweredQuestion
score: 1
tagged with: nodechildren
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47459140
has body: I am currently working on the navbar of a project with Django-cms. I am fairly new to this framework and language, so sorry if this is a stupid question. This has double dropdowns, which respond to user changes in the Django-cms admin interface. Which works. Sort of. The problem is that get_children doesn't work (no errors or something, just not detecting children, and showing the 'should be dropdown button' as a non dropdown version), but get_descendants does. But if i use that the content of the second dropdown will be shown again in the first dropdown. So get_children will be perfect, as it will only show the direct descendants, instead of all. {% load cms_tags menu_tags sekizai_tags staticfiles%} {% load menu_tags %} {% for child in children %} {% if child.is_leaf_node %} {{child.get_menu_title }} {% endif %} {% if not child.is_leaf_node or child.ancestor %} {{child.get_menu_title }} {% if child.get_descendants %} {% for kid in child.get_descendants %} {% if kid.is_leaf_node %} {{kid.get_menu_title }} {% endif %} {% if not child.is_leaf_node or child.ancestor %} {{kid.get_menu_title }} {% for baby in kid.get_descendants %} {{baby.get_menu_title }} {% endfor %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} So my question is: Why can't i use children EDIT: *Why can't i use get_children. As in the function. No child labour here.
has comment: http://stackoverflow.com/comment/81902753
tagged with: django-cms

http://stackoverflow.com/comment/82013498
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47528572
has text: `[^>]*` matches empty locations in front of non-matching chars because `*` matches **0** or more occurrences.

http://stackoverflow.com/comment/87597857
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50272113
has text: yep, sorry, missed your comment to the OP

http://stackoverflow.com/a/47415023
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82288516
has comment: http://stackoverflow.com/comment/82266753
has body: Exploiting that the ranges are integer we can give an O(nm) solution, nxm being the shape of arr. The algo works as follows: discard all non-int elements and all that are outside their range use np.add.at to efficiently (O(mn)) generate bincounts for in-range numbers count the above threshold bins in each row and compare to the range . import numpy as np parameterRanges2 = np.array([(1,5),(1,5),(1,7),(1,7),(0,10),(1,20),(1,3),(0,1)]) arr = np.array([[2.0,4.0,3.0,5.0,1.0,3.0,2.0,4.0,2.0,4.0,3.0,5.0,1.0,3.0,2.0,4.0,2.0,4.0,3.0,5.0], [4.0,2.0,3.0,4.0,2.0,4.0,5.0,1.0,2.0,4.0,1.0,3.0,4.0,2.0,3.0,5.0,1.0,3.0,4.0,2.0], [2.0,3.0,4.0,6.0,7.0,1.0,2.0,3.0,5.0,6.0,1.0,2.0,4.0,5.0,6.0,2.0,3.0,4.0,5.0,6.0], [6.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,2.0,2.0,3.0,4.0,5.0], [8.0,9.0,0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,7.0,8.0,9.0,0.0,1.0,2.0,3.0,4.0,5.0,6.0], [11.0,13.0,14.0,16.0,17.0,19.0,1.0,3.0,4.0,6.0,7.0,9.0,10.0,11.0,13.0,14.0,16.0,17.0,19.0,1.0], [1.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,3.0,3.0,3.0,3.0,1.0,1.0,1.0,1.0,1.0,2.0], [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0]]) min_occ = 2 dp = np.diff(parameterRanges2, axis=-1) m = np.zeros((parameterRanges2.shape[0], np.max(dp) + 2), dtype=int) arr = arr - parameterRanges2[:, :1] ia = arr.astype(int) idx = np.where((arr==ia) &amp; (ia&gt;=0) &amp; (ia&lt;=dp), ia, -1) np.add.at(m, (np.arange(parameterRanges2.shape[0])[:, None], idx), 1) res = (m[:, :-1] &gt;= min_occ).sum(axis=-1) == dp.ravel() + 1 print(res) Output: [ True True False True False False True True]
has comment: http://stackoverflow.com/comment/81784569
has comment: http://stackoverflow.com/comment/81783659
type: Answer
accepted answer of: http://stackoverflow.com/q/47413756
score: 2
has comment: http://stackoverflow.com/comment/81783951
upvote count: 2
answers question: http://stackoverflow.com/q/47413756
downvote count: 0

http://stackoverflow.com/q/47415234
type: UnansweredQuestion
score: -3
tagged with: django
upvote count: 1
tagged with: python
favorite count: 0
has title: If I don't know, what is in array or object, how I can show it in Django in console or page like php var_dump?
has body: Suppose I want to know what the array contains, like JS concole.log() or php var_dump def showArticle(request): articles = Article.objects.all() return render(request, 'article.html', {'articles': articles}) My template: &lt;pre&gt; {{ articles }} &lt;/pre&gt; It shows: &lt;QuerySet [&lt;Article: Article object&gt;]&gt; If I use {% for article in articles %} {{ article }} {% endfor %} It will show the same Article object Article object Article object and if I want show request. def printRequest(request): req = str(request) print(request) it prints only: &lt;WSGIRequest: GET '/'&gt;
has comment: http://stackoverflow.com/comment/81784653
linked to: http://stackoverflow.com/q/10150305
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81785196
has comment: http://stackoverflow.com/comment/81795662
downvote count: 4
has comment: http://stackoverflow.com/comment/81784713
has answer: http://stackoverflow.com/a/47415406

http://stackoverflow.com/q/47463064
has body: I am attempting to replace occurrences of '2' with a '1' that appear in a specific column in the text file, for every line in the text file. A line from the text file could look like "2,4,5,3,1". Here's my code for replacing any '1' in column 4: with open("test.txt","r+") as file1: position = 3 text1 = csv.reader(file1) for line in file1: index = line.find("1") // 2 data = list(line) if index == position: for i in range(5): if data[i] == "1": data[i] = 2 elif data[i] == "2": data[i] = 1 print(data) file1.write(str(data)) When I print data it leaves all the commas and empty space in. It also doesn't replace the correct values in the text file. I really don't have much of an idea to how I would replace specific numbers - my code is probably very bad. Any help will be appreciated.
duplicate of: http://stackoverflow.com/q/11033590
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81881118
tagged with: python
has comment: http://stackoverflow.com/comment/81881099
has comment: http://stackoverflow.com/comment/81881102
score: 0
has title: Replacing specific values in a text file in python
answer count: 0
linked to: http://stackoverflow.com/q/11033590
type: Question

http://stackoverflow.com/comment/81948145
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47496445
type: AnswerComment
has text: wats cache man?

http://stackoverflow.com/q/47489595
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/81934554
has answer: http://stackoverflow.com/a/47489813
has answer: http://stackoverflow.com/a/47489655
accepted answer: http://stackoverflow.com/a/47489655
tagged with: python
has comment: http://stackoverflow.com/comment/81934674
has comment: http://stackoverflow.com/comment/81934736
possible better answer: http://stackoverflow.com/a/47489813
has comment: http://stackoverflow.com/comment/81934707
type: AnsweredQuestion
upvote count: 3
answer count: 2
downvote count: 0
tagged with: pandas
has title: Reshaping the result of a pd.DataFrame.aggregate
has body: I have a df with 2 numeric columns DATA_ROWS = 5 df = pd.DataFrame({"id":[1]*DATA_ROWS,"x":[1,2,3,4,5], "z":[1,1,1,5,6]}) df.set_index("id", drop=True, append=True, inplace=True) x z id 0 1 1 1 1 1 2 1 2 1 3 1 3 1 4 5 4 1 5 6 (id is an index) Also, I have a list of functions funcs = [np.max, np.min, np.std, func1, func2] So, when I aggregate, I got df.aggregate(funcs) x z amax 5.000000 6.000000 amin 1.000000 1.000000 std 1.581139 2.489980 func1 7.000000 1.000000 func2 23.500000 6.200000 I will like to get instead of this the following x_amax, x_amin x_std x_func1 x_func2 z_amax z_amin z_std z_func1 z_func2 1 5.000 1.000 1.5811 7.000 23.500 6.000 1.000 2.4899 1.000 6.2000 I read the documentaion about pivot, melt etc and I can't get how to do this, Any ideas?

http://stackoverflow.com/comment/81840629
comment on: http://stackoverflow.com/q/47442733
type: Comment
type: QuestionComment
score: 0
has text: What are you reading from? Are you familiar with `usecols`?

http://stackoverflow.com/q/47449222
linked to: http://stackoverflow.com/q/24644656
downvote count: 0
upvote count: 1
tagged with: dataframe
tagged with: python
has body: I have a pandas dataframe that look like this It is a large dataset with 1500 rows and 200 columns I was wondering how can I remove the number before each value in row and column. example The values look like this: 1: 0.345 2: -0.467 I want only the value to be like this: 0.345 -0.467 How can I do that?
has title: Remove values from all columns and rows of pandas dataframe
type: AnsweredQuestion
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/81853413
has comment: http://stackoverflow.com/comment/81853383
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47449275
linked to: http://stackoverflow.com/q/47449545
has answer: http://stackoverflow.com/a/47449275

http://stackoverflow.com/a/47394479
answers question: http://stackoverflow.com/q/47393869
type: Answer
score: 4
upvote count: 4
has body: Your file is not in utf-8 encoding. Most likely in ASCII with Hebrew codepage. 0xf9 in Hebrew codepage matches the first (last) character you show in your header example. You'll have to use the encoding: parameter with the correct codepage.
downvote count: 0

http://stackoverflow.com/comment/81859973
has text: In that case I do not understand what you mean by "line next to it". Is it the lines that come after it you mean, or the line number?
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47451857

http://stackoverflow.com/comment/81768434
score: 0
comment on: http://stackoverflow.com/q/47394839
type: Comment
type: QuestionComment
has text: Seems odd that the 2-meter temperature is an integer. But anyhow, please add the full trace, at least the part which mentions which line results in the `TypeError`. So far I don't see anything wrong with your code, usually, Numpy/NetCDF4 is quite flexible in casting things to the correct data type.

http://stackoverflow.com/comment/81959629
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47498920
has text: I have another dataframe that I am using as an adjacency matrix with NetworkX (let's call it df1), and I want to "divide" df1 element-wise by sums_df to obtain say df2 . df1 contains counts of common elements between the IDs, but I also have the number of elements in each ID (here Size, and IDs actually are IDs of groups). That way the weights I use with df2 are the shares of common elements rather than the counts of common elements using df1 as an adjacency matrix. I hope that's clear enough!
score: 0

http://stackoverflow.com/q/47452143
type: UnansweredQuestion
tagged with: paramiko
has comment: http://stackoverflow.com/comment/81859410
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47696692
has title: Installing paramiko
has body: I am trying to install paramiko with python 2.7 but pip install fails because cryptography requires python 3 and above: error in cryptography setup command: Invalid environment marker: python_version &lt; '3' Complete output from command python setup.py egg_info: error in cryptography setup command: Invalid environment marker: python_version &lt; '3' i manually installed cryptography for 2.7 and still can't install paramiko using both pip and a downloaded .tar file like "paramiko-2.0.2.tar" giving me the same error any idea how can i install this module? thank you
type: Question
tagged with: python

qt-designer
tags question: http://stackoverflow.com/q/47482998
tags question: http://stackoverflow.com/q/47497383
type: Tag
tag name: qt-designer

http://stackoverflow.com/comment/81861782
has text: Hey! I forgot to mention, that I have an "outer" input which defines A and R. I'm programming in Grasshopper for Rhino3D, where you can use external inputs. I inserted the two missing variables in the code.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47415746
type: Comment

http://stackoverflow.com/q/47495719
answer count: 1
has comment: http://stackoverflow.com/comment/81946890
accepted answer: http://stackoverflow.com/a/47495742
tagged with: pandas
has answer: http://stackoverflow.com/a/47495742
type: AnsweredQuestion
upvote count: 3
has body: I have a pandas data frame. eg: df= paper id year 0 3 1997 1 3 1999 2 3 1999 3 3 1999 4 6 1997 so on I want the maximum year corresponding to a paper id given as input. For example, if the paper id given is 3, I want 1999 as the answer. How can I do this?
downvote count: 1
favorite count: 0
has title: Get the max value of 2nd column where the value in column 1 = specified, from dataframe in pandas
type: Question
score: 2
tagged with: python
linked to: http://stackoverflow.com/q/43070814

http://stackoverflow.com/comment/81992708
comment on: http://stackoverflow.com/a/47517552
score: 1
type: Comment
has text: @MarkokraM simplification see edit, less total loops and less control structs
type: AnswerComment

http://stackoverflow.com/comment/81769577
type: AnswerComment
has text: @llja@ thanks a tonne again for your super detailed answer and the explanation. Accepted your answer.
score: 0
comment on: http://stackoverflow.com/a/47407612
type: Comment

http://stackoverflow.com/comment/81896636
type: Comment
comment on: http://stackoverflow.com/a/47466493
type: AnswerComment
has text: First of all thanks for your comment. I corrected my code according to your suggestions. 1) I was referencing a slightly different paper with a different definiton of k... 2) This was probbably the main mistake, so thanks for that! 3) after changing the mass and hbar to one (asked the TA) I get at least something that looks like a wavefunction... I'll probbably try out some more Potentials and see what happens, if more questions arise I'll poste them here as well
score: 0

http://stackoverflow.com/comment/81882853
comment on: http://stackoverflow.com/a/47463751
type: Comment
has text: @Jake123 your dictionary itself contains invalid Python syntax. The final bracket (`]`), in the example you posted above, is not necessary.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81851448
type: Comment
comment on: http://stackoverflow.com/q/47448013
type: QuestionComment
score: 0
has text: Are you able to launch any other browser? Also is the server running on the same machine or a external machine? Because if server runs on same machine then port blocking may not matter

http://stackoverflow.com/comment/81853248
has text: the server was setup before I started working, and I do not have much information about its installation
comment on: http://stackoverflow.com/q/47449099
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47508956
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47508650
has body: So I'm not entirely certain what resources you were using to create write_File, but there were a few errors. I've fixed them in the below code, with comments to explain what I've changed and why. import tkinter def write_File (text_File): file = open("users.txt", "a") #The object text_File is a tkinter.Entry object, so we will get # the user input by calling the get method on that object. user_Input = text_File.get() #Here we now directly write the user input to the file that has been # opened, I'm not sure you were previously doing with writing the # string version of the file, but this appears to achieve what you # desire. file.write(user_Input) file.close() screen = tkinter.Tk() the_input = tkinter.Entry(screen) the_input.grid(row=1, column=1) button_Write = tkinter.Button(screen, text = "Send to file:", command = lambda: write_File(the_input)).grid(row=10, column=1) screen.mainloop() Another thing is that depending on the version of Python you're using, instead of using file = open(...) and then file.close() at the end of the method, you could instead use the with open(...) as file: construct which will automatically close the file at the end of the scope.
type: Answer
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47508650

http://stackoverflow.com/q/47470501
favorite count: 0
type: Question
has title: Creating large sparse matrix from existing data
has comment: http://stackoverflow.com/comment/81908896
tagged with: pandas
linked to: http://stackoverflow.com/q/47475611
tagged with: python
has body: Main part of my issue was answered here. However, my problem lies in fact that I have a large amount of data - two vectors of 265k (265 000) entries. I tried converting these arrays into sparse scipy matrices but the subtraction doesn't work that way because scipy cannot use numpy's broadcasting. array_one = sparse.csr_matrix(df.id.values) array_two = sparse.csr_matrix(df.id.values[:, None]) array_one - array_two throws MemoryError Currently, I am looping over a 265k2 entries and while it's working it's magic I'd like to ask for a more efficient solution to this for the future. I'm doing this: for j in range(265180): for i in range(265180): if arr1.data[j] == arr2.data[i]: rows.append(j) cols.append(i) data_items.append(1) mat = sparse.coo_matrix(rows, cols, data_items) Is there any way to convert Nx1 - 1xN numpy calculated matrix into NxN sparse matrix when N is large enough so that calculated matrix doesn't fit into the memory?
has comment: http://stackoverflow.com/comment/81936472
tagged with: array-broadcasting
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81936089
linked to: http://stackoverflow.com/q/32505207
tagged with: scipy
tagged with: sparse-matrix
downvote count: 1

http://stackoverflow.com/q/47496129
type: Question
has comment: http://stackoverflow.com/comment/81947433
upvote count: 2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/81947346
has comment: http://stackoverflow.com/comment/81947315
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81947462
has body: I made a (sad) game in where you click a chicken, and you get eggs. I had tested it and it was fully functioning, but I then add a main_loop(), and the console window opens, and it just has a flashing bold underscore, as it does when it is loading, but it does not load. Here is the code: from tkinter import * from PIL import Image, ImageTk import time root = Tk() root.title("Chicken Clicker") eggz = 0 eggvalue = 0.2 eggzps = 0 chookz = 0 def main_loop(): while 1: eggz = eggz + eggzps time.sleep(1) def moar_eggz(): global eggz, eggvalue, eggzps, chookz chookz = chookz + 1 eggzps = round(chookz) / 0.1 print round(chookz) if eggzps &gt;= 10: print round(eggzps) elif eggzps &lt; 10: print eggzps while 1: eggzLabel = "Eggs: " + str(eggz) eggzpsLabel = "Eggs per second: " + str(eggzps) eggvalueLabel = "Egg Value: " + str(eggvalue) chookzLabel = " Chickens: " + str(chookz) label4 = Label(root, text=eggzLabel) label3 = Label(root, text=eggzLabel) label2 = Label(root, text=eggzLabel) label1 = Label(root, text=eggzLabel) label4.pack() label3.pack() label2.pack() label1.pack() imagecnv = Image.open("img/1.png") photo = ImageTk.PhotoImage(imagecnv) main_loop() openbutton = Button(root, image=photo, width = 500, height=500, command = moar_eggz) openbutton.pack() root.mainloop()
accepted answer: http://stackoverflow.com/a/47499303
has title: Python Tkinter Application won't load. No Error. (python)
answer count: 1
has comment: http://stackoverflow.com/comment/81947382
has answer: http://stackoverflow.com/a/47499303
favorite count: 0

http://stackoverflow.com/a/47506365
has body: Have you tried forcing utf-8 encoding in python as follow : import sys reload(sys) sys.setdefaultencoding('utf-8')
score: -1
upvote count: 1
has comment: http://stackoverflow.com/comment/81968549
answers question: http://stackoverflow.com/q/47425695
has comment: http://stackoverflow.com/comment/81978589
downvote count: 2
type: Answer

http://stackoverflow.com/comment/103276846
type: AnswerComment
comment on: http://stackoverflow.com/a/47387088
has text: Did you forget the `df3` assignment?
type: Comment
score: 0

http://stackoverflow.com/a/47429294
type: Answer
has comment: http://stackoverflow.com/comment/81841820
has comment: http://stackoverflow.com/comment/81813949
upvote count: 1
downvote count: 1
has body: model.pop() takes care of all the underlying settings, including setting the model.output to the output of the new last layer. Therefore, you don't need to handle anything regarding the outputs. Please also note that you are assigning to the model variable; thus, model.outputs is already referring to the extended model's output. Here is a sample code that works fine on keras 2.0.6 with TensorFlow backend (1.4.0): import keras from keras.models import Sequential, Model from keras.layers import * import numpy as np model = keras.applications.resnet50.ResNet50(include_top=False, weights='imagenet', classes=10, input_shape=(224, 224, 3)) top_model = Sequential() top_model.add(keras.layers.Flatten(input_shape=model.output_shape[1:])) top_model.add(keras.layers.Dense(256, activation='relu')) top_model.add(keras.layers.Dropout(0.5)) top_model.add(keras.layers.Dense(2, activation='softmax')) model_extended = Model(input=model.input, output=top_model(model.output)) model_extended.layers[-1].pop() model_extended.layers[-1].pop() model_extended.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) model_extended.predict(np.zeros((1, 224, 224, 3)))
answers question: http://stackoverflow.com/q/47417897
score: 0

http://stackoverflow.com/a/47505176
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47504998
upvote count: 2
has body: Answer to your question. number_post is string. Why for loop to display the str ? Please remove the for loop from your template and just add this... {{ number_post }} Or Another solution to your question I believe you want to show all the deaths. Please consider below approach? death_nums = DeathNum.objects.all() return render(request, 'deaths.html', {'death_nums': death_nums}) And in HTML {% for death_num in death_nums %} {{ death_num.deaths }} {% endfor %}
has comment: http://stackoverflow.com/comment/81981524
type: Answer
has comment: http://stackoverflow.com/comment/81980217
accepted answer of: http://stackoverflow.com/q/47504998
score: 2
has comment: http://stackoverflow.com/comment/81980967

http://stackoverflow.com/a/47459440
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Probably the easiest way to do this without re-computing for every new number you're looking for is to make a dictionary: X = [[0, 1, 6], [2, 4], [3, 5]] X_map = {element: group for group, elts in enumerate(X) for element in elts} # {0: 0, 1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 0} Now for any given number, just look it up: X_map.get(5, None) # 2 X_map.get(7, None) # None
type: Answer
accepted answer of: http://stackoverflow.com/q/47459303
answers question: http://stackoverflow.com/q/47459303
score: 3

http://stackoverflow.com/comment/82031765
score: 0
has text: Using postman how are you passing AWS access keys ? Have you set credentials correctly to access AWS resources?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47535861

http://stackoverflow.com/comment/81837110
type: QuestionComment
has text: Or in `/home/birac/SCRIPTS/__pycache__`
comment on: http://stackoverflow.com/q/47440308
score: 0
type: Comment

http://stackoverflow.com/comment/81807457
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47426234
has text: Anything in the `if __name__ == "__main__"` guard won't run when the file is imported as a module. That's the whole point of `if __name__ == "__main__"`.
score: 2

http://stackoverflow.com/a/47431058
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47430994
answers question: http://stackoverflow.com/q/47430994
type: Answer
has body: You need to pass a dictionary to the data keyword argument, not a JSON string: data = {'grant_type': 'client_credentials', 'access_lifetime': '7200'} response_result = requests.post( 'https://www.example.com/oauth/token', data=data, auth=('client_id', 'client_secret) ) See the documentation for details.

http://stackoverflow.com/comment/81823046
has text: already istalled
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47434333
score: 0

http://stackoverflow.com/q/47422570
downvote count: 0
has title: Saving a highscore - Python 3
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47422872
has comment: http://stackoverflow.com/comment/81800342
type: Question
has comment: http://stackoverflow.com/comment/81799819
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47422675
has comment: http://stackoverflow.com/comment/81799648
has answer: http://stackoverflow.com/a/47422975
tagged with: python
has body: I'm trying to save a score for my game. I've got a piece of example code, why isn't it saving, if so, how would I go about fixing it? hisc = open("highscore.txt","w+") hi = hisc.read() if hi == '': hisc.write('0') hi = '0' if score &gt; int(hi): hisc.write(str(score)) print("NEW HIGHSCORE!") else: print("HIGHSCORE =",hi)
possible better answer: http://stackoverflow.com/a/47422788
answer count: 4
has answer: http://stackoverflow.com/a/47422788
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47422975
score: 1

http://stackoverflow.com/a/47426130
has comment: http://stackoverflow.com/comment/81811091
score: 0
has body: Though question is not clear. First question: Make the first column be yyyy-mm-dd as a floating point number, how this could be possible. say 2017.11.22, is this float you mean? Are you looking for something like this? for line in open("my_file.csv"): line_read_as_list = line.split(',') What's you delimiter of csv file? Concept: read as line split in list. if your first column is in "yyyy-mm-dd" format, split line_read_as_list[0] in line_read_as_list with '-' and capture year, month and day in separate list. You should give a try yourself. There are many way to do this. If you want to put back in the format: yyyy.mm.dd simply replace '-' by '.'. It should be string.
type: Answer
answers question: http://stackoverflow.com/q/47425945
has comment: http://stackoverflow.com/comment/81848158

http://stackoverflow.com/comment/81836968
score: 0
has text: Still throws `11:49:47.607 NotFound: 404 GET https://www.googleapis.com/bigquery/v2/projects/liu-laureateid-api-qa/datasets/Backup/tables/Prod_UserUserMetadata: Not found: Table liu-laureateid-api-qa:Backup.Prod_UserUserMetadata`
comment on: http://stackoverflow.com/a/47440934
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81853939
type: AnswerComment
has text: can you pls check this https://stackoverflow.com/questions/47449545/how-to-split-values-in-a-datacolumn-and-adding-it-to-a-new-column-with-a-conditi
type: Comment
comment on: http://stackoverflow.com/a/47449275
score: 0

http://stackoverflow.com/comment/82034025
score: 0
comment on: http://stackoverflow.com/q/47538456
type: Comment
type: QuestionComment
has text: @Aaron it's alright, I see what you mean. OP needs to show exactly what they are using...

http://stackoverflow.com/q/47466909
has title: Trouble parsing orderddict in django template
type: Question
has answer: http://stackoverflow.com/a/47466936
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47467313
has comment: http://stackoverflow.com/comment/81888548
score: 0
has body: I'm having trouble trying to parse an orderddict in my django template. This is an example dict: OrderedDict([ (u'header-1510123912515', '"{u\'label\': u\'label\'}"'), (u'input-1510215273074', '"{u\'label\': u\'Preferred Assignment Area\'}"'), (u'input-1510215283971', '"{u\'label\': u\'Expected Salary\'}"'), (u'input-1510215288135', '"{u\'label\': u\'Last Drawn Salary\'}"'), ]) From the above, I would want to get the content of label. This is how I'm currently going through the dict in the template: {% for form in document.forms.all %} {% for k,v in form.hdict.items %} {% if 'header' not in k %} {"key": {{k}}, "label": "{{v.label}}"}, {% endif %} {% endfor %} {% endfor %} I'm able to successfully get the key, but not the values part (label). I hope you can help me with this as I'm quite new to django. Thanks
answer count: 2

http://stackoverflow.com/comment/81955905
type: QuestionComment
has text: Hello, I have added the grammar to the post.
score: 0
comment on: http://stackoverflow.com/q/47498553
type: Comment

http://stackoverflow.com/comment/81730631
has text: Try `url = "http://www.google.com"`
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47388779
type: QuestionComment

http://stackoverflow.com/comment/81932739
has text: `centroids=df.nlargest(k, 'val')'x','y' plt.scatter(df['x'], df['y'], color='blue') plt.scatter(centroids.x, centroids.y, color='red', marker='^') plt.show()` the red marker will superimpose on the blue
type: AnswerComment
comment on: http://stackoverflow.com/a/47486597
score: 1
type: Comment

http://stackoverflow.com/q/47384490
has answer: http://stackoverflow.com/a/47391711
upvote count: 1
tagged with: python
tagged with: tuples
has body: You are given information about users of your website. The information includes username, a phone number and/or an email. Write a program that takes in a list of tuples where each tuple represents information for a particular user and returns a list of lists where each sublist contains the indices of tuples containing information about the same person. For example: Input: [("MLGuy42", "andrew@example.com", "123-4567"), ("CS229DungeonMaster", "123-4567", "ml@example.net"), ("Doomguy", "john@example.org", "carmack@example.com"), ("andrew26", "andrew@example.com", "mlguy@example.com")] Output: [[0, 1, 3], [2]] Since "MLGuy42", "CS229DungeonMaster" and "andrew26" are all the same person. Each sublist in the output should be sorted and the outer list should be sorted by the first element in the sublist. Below is the code snippet that I did for this problem. It seems to work fine, but I'm wondering if there is a better/optimized solution. Any help would be appreciated. Thanks! def find_duplicates(user_info): results = list() seen = dict() for i, user in enumerate(user_info): first_seen = True key_info = None for info in user: if info in seen: first_seen = False key_info = info break if first_seen: results.append([i]) pos = len(results) - 1 else: index = seen[key_info] results[index].append(i) pos = index for info in user: seen[info] = pos return results
tagged with: list
possible better answer: http://stackoverflow.com/a/47385890
has comment: http://stackoverflow.com/comment/81725648
has comment: http://stackoverflow.com/comment/81725109
type: AnsweredQuestion
score: 0
tagged with: duplicates
downvote count: 1
favorite count: 0
has title: Find duplicates in a list of tuples
type: Question
tagged with: algorithm
has answer: http://stackoverflow.com/a/47385890
accepted answer: http://stackoverflow.com/a/47391711
answer count: 2
has comment: http://stackoverflow.com/comment/81736946

http://stackoverflow.com/a/48024863
answers question: http://stackoverflow.com/q/47452383
type: Answer
score: 0
has body: I think it should look like this + your login creds. import csv import urllib2 url = 'http://winterolympicsmedals.com/medals.csv' response = urllib2.urlopen(url) cr = csv.reader(response) for row in cr: print row Else... url = 'http://winterolympicsmedals.com/medals.csv' r = requests.get(url) text = r.iter_lines() reader = csv.reader(text, delimiter=',') Else... import requests from contextlib import closing import csv url = "http://download-and-process-csv-efficiently/python.csv" with closing(requests.get(url, stream=True)) as r: reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"') for row in reader: # Handle each row here... print row How to read a CSV file from a URL with Python?

http://stackoverflow.com/comment/81883725
has text: So, how can you have number of rows not a multiple of 2 given that way of partitioning?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47462568
score: 0

http://stackoverflow.com/comment/81739743
comment on: http://stackoverflow.com/a/47393406
type: AnswerComment
has text: Does this work if the columns are vectors and not scalars ?
type: Comment
score: 0

http://stackoverflow.com/q/47510667
has answer: http://stackoverflow.com/a/47510856
upvote count: 1
score: 1
answer count: 1
downvote count: 0
has body: These are randomly placed bricks which move along the x-axis, to the left and right from wall to wall. I'd like to have all bricks collide with themselves, for example if one of them hit another brick, the speed must be -speed. brick = [] for in range(50): block = Brick() brick.append(block) My code is below: if block.rect.colliderect(block.rect.colliderect): block.speed *= -1
favorite count: 0
has title: Pygame - How to implement blocks that can collide with each other?
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47510856
tagged with: python
tagged with: pygame

http://stackoverflow.com/q/47386309
has title: Operations on sub-lists in list
answer count: 1
has comment: http://stackoverflow.com/comment/81725550
has body: I have a list of lists: a = [[1, 2], [2, 3], [4, 3]] How to get the following effect in two steps ?: b = [[1, 2, 2, 3], [1, 2, 4, 3], [2, 3, 4, 3]] b = [[1, 2, 3], [1, 2, 4, 3]], it means: 1.1. If the same values occur in the sub-list b[i] next to each other, then one of these values must be deleted. 2.2. If the same values appear in a given sub-list b[i] but not next to each other, then the entire sub-list b[i] must be deleted.
type: Question
accepted answer: http://stackoverflow.com/a/47386616
has comment: http://stackoverflow.com/comment/81725697
has answer: http://stackoverflow.com/a/47386616
has comment: http://stackoverflow.com/comment/81725659
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81725548
tagged with: list

http://stackoverflow.com/comment/81985256
type: Comment
has text: are we talking about the function *returning something or not* **or** *throwing an error* **or** *both*? These are two very different things!
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47514666

http://stackoverflow.com/comment/81887386
type: AnswerComment
has text: That makes sense! Thanks
type: Comment
comment on: http://stackoverflow.com/a/47466438
score: 0

http://stackoverflow.com/q/47539028
has comment: http://stackoverflow.com/comment/82042832
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82043384
has answer: http://stackoverflow.com/a/47543574
linked to: http://stackoverflow.com/q/6836831
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/57049562
has body: I am facing a problem writing a program to send contents of a folder over the network by using Python. There are a lot of examples out there, all the examples I found are assuming the receiver side knew name of the file he want to receive. The program I am trying to do assuming that the receiver side agree to receive a files and there is no need to request a file by its name from the server. Once the connection established between the server and the client, the server start send all files inside particular folder to the client. Here is a image to show more explanation:example here Here are some programs that do client server but they send one file and assume the receiver side knew files names, so the client should request a file by its name in order to receive it. Note: I apologies for English grammar mistakes. https://www.youtube.com/watch?v=LJTaPaFGmM4 http://www.bogotobogo.com/python/python_network_programming_server_client_file_transfer.php python socket file transfer Here is best example I found: Server side: import sys import socket import os workingdir = "/home/SomeFilesFolder" host = '' skServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) skServer.bind((host, 1000)) skServer.listen(10) print "Server Active" bFileFound = 0 while True: Content, Address = skServer.accept() print Address sFileName = Content.recv(1024) for file in os.listdir(workingdir): if file == sFileName: bFileFound = 1 break if bFileFound == 0: print sFileName + " Not Found On Server" else: print sFileName + " File Found" fUploadFile = open("files/" + sFileName, "rb") sRead = fUploadFile.read(1024) while sRead: Content.send(sRead) sRead = fUploadFile.read(1024) print "Sending Completed" break Content.close() skServer.close() Client side: import sys import socket skClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) skClient.connect(("ip address", 1000)) sFileName = raw_input("Enter Filename to download from server : ") sData = "Temp" while True: skClient.send(sFileName) sData …
has title: Transfer contents of a folder over network by python
upvote count: 1
has comment: http://stackoverflow.com/comment/82043319
has comment: http://stackoverflow.com/comment/82042306
favorite count: 0
type: Question
tagged with: file-transfer
tagged with: network-programming
has answer: http://stackoverflow.com/a/57052974
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/comment/81744441
score: 0
comment on: http://stackoverflow.com/q/47395284
has text: did you login ? Did you run it in background ? did you try to put it in `/home/pi/.bashrc` or `/home/pi/.profile` ? Maybe in script add code which save in file some information and exceptions - you will see which part is executed.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47559435
answers question: http://stackoverflow.com/q/47507379
score: 1
downvote count: 0
upvote count: 1
has body: Entities have a 1MB size limit. If what you are trying to store in an entity/property may be bigger than that then you need to use CloudStorage. I suggest storing that text as a file in Cloud Storage and keeping a link in a property of your object. It may look like this: class History(ndb.Model): user_mail = ndb.StringProperty() url = ndb.StringProperty() #https://storage.googleapis.com/{app_id}/{file_name} updated_date = ndb.DateTimeProperty() Then when you need that text you just have to read the file stored in that url.
type: Answer

http://stackoverflow.com/a/47514033
answers question: http://stackoverflow.com/q/47513956
has body: find is not the same as find_all In the for loop you call the method find_all on each element inside results_user, not on results_user directly. It's the same as the difference between ['a', 'b', 'c'].upper() (which doesn't work, 'list' object has no attribute 'upper') and 'a'.upper() ; 'b'.upper() ; 'c'.upper().
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81983876
accepted answer of: http://stackoverflow.com/q/47513956
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82048785
score: 0
type: AnswerComment
has text: Speed. I want to parallelize it. Please take a look at this question if you want to take a crack at it: https://stackoverflow.com/questions/47422677
type: Comment
comment on: http://stackoverflow.com/a/47426525

http://stackoverflow.com/comment/81897179
type: Comment
comment on: http://stackoverflow.com/q/47471261
type: QuestionComment
score: 0
has text: `f"h{('i','ello')[b]}"`

http://stackoverflow.com/comment/82081833
type: AnswerComment
comment on: http://stackoverflow.com/a/47550375
type: Comment
score: 0
has text: Thank you!! TBH I always never thought it made a difference since `str` and binary work together fine in most cases.

http://stackoverflow.com/a/47440783
has comment: http://stackoverflow.com/comment/81836941
has comment: http://stackoverflow.com/comment/81838377
has body: In most cases, there is an implicit expectation that any function or class designed to be used as a decorator should return an object that behaves in the same way as the provided object. However, nothing in Python enforces this "contract." If your decorator is given a class and returns a string (as in your example), people might be confused because a string most likely does not behave in the same way as a class. When decorating a class, you may want to avoid removing instance/class/static methods or class variables. You might want to alter them or add new ones, but it would be strange to strip functionality defined in the class body through the use of a decorator. An example of this is shown below: def bad_decorator(cls): del cls.method return cls @bad_decorator class Test(object): def method(self): return 'test method' print(Test().method()) # AttributeError: 'Test' object has no attribute 'method' In essence, your class -&gt; string example violates this implicit expectation because we can no longer use the class as defined in its body. Borrowing from the duck typing nomenclature, there is some expectation that your returned object will still quack like a duck. Likewise, it is generally encouraged to follow the Principle of Least Astonishment when writing Python.
type: Answer
has comment: http://stackoverflow.com/comment/81836718
has comment: http://stackoverflow.com/comment/81836759
has comment: http://stackoverflow.com/comment/81838393
upvote count: 2
answers question: http://stackoverflow.com/q/47439924
score: 2
has comment: http://stackoverflow.com/comment/81838503
downvote count: 0
has comment: http://stackoverflow.com/comment/81836600

http://stackoverflow.com/comment/81835260
type: QuestionComment
type: Comment
has text: dup of: https://stackoverflow.com/questions/11055303/python-multiprocessing-global-variable-updates-not-returned-to-parent
comment on: http://stackoverflow.com/q/47428768
score: 0

http://stackoverflow.com/q/47500101
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47500409
tagged with: python
has answer: http://stackoverflow.com/a/47500409
has comment: http://stackoverflow.com/comment/81955721
has title: Add a user selected method to a meta base class in python
tagged with: user-input
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81962143
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/47503326
tagged with: metaclass
answer count: 2
has answer: http://stackoverflow.com/a/47503326
has comment: http://stackoverflow.com/comment/81955789
has body: I have base class that cannot be instanciated (BaseFruit in my simplified example) and a few derived classes (for instance Apple in my example) that should all share a same method (printfuture). However, they are many possible variants, and I would like to let the user choose what variant should be used (for instance sadfuture and saddestfuture). As my printfuture method is common to all my derived class, I thought that it would be appropriated to catch the user argument for the variant with the __new__ method of my base class and assign the method to the base class itself. As written in the example below: # my custom methods def sadfuture(self): """A sad future""" print 'It looks {}!'.format(self.aspect) print 'Mmm yummy !' def saddestfuture(self): """A saddest future""" print 'It looks {}'.format(self.aspect) print 'Garbage !' # my base class class BaseFruit(object): """Fruit base class""" def __new__(cls, *args, **kwargs): setattr(cls, 'printfuture', kwargs['usermethod']) return object.__new__(cls) # My class class Apple(BaseFruit): """An apple class""" def __init__(self, aspect, usermethod=sadfuture): self.aspect = aspect if __name__ == '__main__': goodapple = Apple(aspect='delicious', usermethod=sadfuture) goodapple.printfuture() # ==&gt; ok badapple = Apple(aspect='rotten', usermethod=saddestfuture) goodapple.printfuture() # ==&gt; not ok anymore badapple.printfuture() # ==&gt; ok Which prints: It looks delicious! Mmm yummy ! It looks delicious Garbage ! It looks rotten Garbage ! instead of the expected behavior: It looks delicious! Mmm yummy ! It looks delicious! Mmm yummy ! It looks rotten Garbage ! I do understand that I have overwritten my base class and my first object has changed its behavior. So, my main question is: how can I achieve the expected behavior while keeping my custom methods out of the base class? Comments on best practices and on proper designs for such problems are also welcome.
downvote count: 0
has comment: http://stackoverflow.com/comment/81955672
score: 1
upvote count: 1
tagged with: methods
has comment: http://stackoverflow.com/comment/81955810

http://stackoverflow.com/a/47577549
answers question: http://stackoverflow.com/q/47514103
type: Answer
accepted answer of: http://stackoverflow.com/q/47514103
score: 0
type: AcceptedAnswer
has body: Seems to be a limitation of pylint, I disabled the error locally with the below comment/command and everything works fine: # pylint: disable=E1101

http://stackoverflow.com/q/47384632
type: UnansweredQuestion
downvote count: 0
has body: I used the tf.estimator.Estimator class to train a neural network feeding it images and labels using the TFRecordDataset. All this is working fine. Now I'm trying to do predictions from live frames from a webcam. I did another input function for it and it works fine but it's really slow. During the training stage, I'm going through about 100 images/s. The inference code below takes multiple seconds per frame. I'm thinking, maybe I should rework my input function so it's somehow returning a never ending dataset that returns frame after frame from the live feed. Any input on this would be appreciated. Here's what I have now: def live_input_fn(): ret, frame = video_capture.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = tf.image.convert_image_dtype(frame, dtype=tf.float32) frame = tf.image.per_image_standardization(frame) frame = tf.reshape(frame, [1, 120, 160, 3]) dataset = tf.contrib.data.Dataset.from_tensor_slices(frame) iterator = dataset.make_one_shot_iterator() features = iterator.get_next() return features, None toy_classifier = tf.estimator.Estimator( model_fn=model_fn, model_dir=script_dir + "/cnn_tflayers") while True: predictions = toy_classifier.predict( input_fn=live_input_fn ) for p in predictions: print(label_names[p["classes"]]) print(p["probabilities"])
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81757422
has comment: http://stackoverflow.com/comment/81756004
tagged with: python
has title: Tensorflow Estimator input function for live video inference
answer count: 0

http://stackoverflow.com/comment/81983527
has text: Already understand @CoLdSpeed, Thank you very much!
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47480020
type: Comment

http://stackoverflow.com/a/47527265
upvote count: 1
has body: year = ["2014", "2015"] # yellow red orange pink color= ['yellow', 'red', 'orange', 'pink'] for each_year in year: for each_color in color: in_folder = r"E:/test/" + each_year + "/03_lines/" + each_color [rest of the script] Yes you can use for loop for iteration like for i in color:
has comment: http://stackoverflow.com/comment/82010920
type: Answer
has comment: http://stackoverflow.com/comment/82011185
answers question: http://stackoverflow.com/q/47527122
has comment: http://stackoverflow.com/comment/82011374
score: 1
downvote count: 0

http://stackoverflow.com/comment/82017898
comment on: http://stackoverflow.com/q/47529906
has text: I think you need to pass some encoding paramenters to you `connect` function. Like `charset='utf8'` or something like that. I think it needs to match whatever the encoding of your database is, because aparently it is not 'utf-8'.
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/47535672
favorite count: 0
type: Question
score: 3
has body: I apologize if there is a duplicate, but I searched and could not find any topics that address my current issue. I want to know if there is some pythonic way to iterate through two (or more) sublists in parallel. I'm already well aware of the zip function, so I will use it in a short example to explain what I want to do. Let's say I have the following two lists: list1 = [1,2,3] list2 = [4,5,6] I know that I can iterate through them simultaneously like this: &gt;&gt;&gt; newlist = [i+j for i,j in zip(list1, list2)] &gt;&gt;&gt; newlist [5,7,9] However, with the way my data is being handled, I would like to do something slightly different. Instead of two independent lists, my data storage looks more like this: biglist = [[1,2,3], [4,5,6]] I know I could extract each sublist to be it's own variable, but I was moreso hoping I could do something more like this: newbiglist = [i+j for i,j in zip(biglist)] Where python would be able to recognize that there are two sublists in biglist. Does anyone know of any function that could do something like this?
has title: How to iterate through two SUBlists in parallel?
tagged with: python
has answer: http://stackoverflow.com/a/47535781
possible better answer: http://stackoverflow.com/a/47535718
has answer: http://stackoverflow.com/a/47535718
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
accepted answer: http://stackoverflow.com/a/47535781
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/47487281
downvote count: 0
upvote count: 1
score: 1
has body: What about making it easily customizable? width = 5 # Width of grid height = 5 square_w = 2 # Width of square you want found square_h = 2 square_coords = [] avoid = [0] # This number doesn't count as a square grid_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0] # Grid # ONLY EDIT ABOVE /\ /\ /\ conv_list = [] for rep_h in range(height): # Convert grid conv_list += [[0] * width] for rep_w in range(width): conv_list[rep_h][rep_w] = grid_list[rep_h*width+rep_w] for rep_h in range(height-square_h+1): # Find squares for rep_w in range(width-square_w+1): square_vis = True if not conv_list[rep_h][rep_w] in avoid: square_val = conv_list[rep_h][rep_w] for h in range(square_h): for w in range(square_w): if conv_list[rep_h+h][rep_w+w] != square_val: square_vis = False if square_vis: square_coords += rep_h, rep_w print(square_coords) # Print result (Starting coordinates, AKA top left of box found)
type: Answer
answers question: http://stackoverflow.com/q/47486930

http://stackoverflow.com/comment/81884787
type: QuestionComment
has text: @Blorgbeard That's essentially what I want to do yes. Thanks for clarifying it's the whole process I'll need to shut down.
comment on: http://stackoverflow.com/q/47465019
score: 0
type: Comment

http://stackoverflow.com/a/47419366
has comment: http://stackoverflow.com/comment/81795240
answers question: http://stackoverflow.com/q/47417913
has comment: http://stackoverflow.com/comment/81795315
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
has body: If you need to fix the width of the text when saving, you can use the textwrap module from the stdlib: import textwrap def saveText(self, width=100): text = self.textEdit.toPlainText() with open('somefile.txt', 'w') as stream: for line in textwrap.wrap(text, width=width): stream.write(line) The format of the text can be modified in various other ways by using the keyword arguments specified for the TextWrapper class.
accepted answer of: http://stackoverflow.com/q/47417913
type: Answer

http://stackoverflow.com/q/47514435
has comment: http://stackoverflow.com/comment/81984857
type: Question
has answer: http://stackoverflow.com/a/47514533
answer count: 2
tagged with: python
tagged with: twitter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47515022
has body: I have a json file that contains twitter data and looks like this: { "text": "ABC } For some tweets, there is additional information: { "text": "ABC, "extended_text": { "full_text": "ABCDEFG } } Now I want to preprocess the text for tokenization. So far I defined the preprocess and now I want to run it. with open('test.json', 'r') as f: for line in f: tweet = json.loads(line) tokens = preprocess(tweet['text']) How do I create an if-else statement that targets the 'full_text' if available and if not just proceeds with the available 'text'? I'm very new to coding. Any help is appreciated.
tagged with: http://stackoverflow.com/tag/json
score: 0
has title: (If else) targeting specific objects in json file with python

http://stackoverflow.com/a/47515160
score: 1
has comment: http://stackoverflow.com/comment/82076792
has body: Your question is just a combination of python getting a list of value from list of dict and Filter dict to contain only certain keys? By using solutions of both questions, you could achieve it: Let's say s is the dict converted from your json data. keys = ['@id', 'name', 'clientCount', 'clientCount_2_4GHz', 'clientCount_5GHz'] new_dict = {'entity': [{key: d['accessPointDetailsDTO'][key] for key in keys} for d in s['queryResponse']['entity']]} Then convert new_dict by using json.dumps: your_json_object = json.dumps(new_dict)
type: Answer
answers question: http://stackoverflow.com/q/47514710
accepted answer of: http://stackoverflow.com/q/47514710
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47444030
type: Answer
has comment: http://stackoverflow.com/comment/81918314
has comment: http://stackoverflow.com/comment/81928722
score: 10
upvote count: 11
has comment: http://stackoverflow.com/comment/81843301
type: AcceptedAnswer
has body: To execute a Python script in this way, you need three things: The file needs to have the executable bit set for you. To do this, try using: chmod u+x validate_mapping_file.py The file needs to begin with a shebang, for example #!/usr/bin/env python3 which will tell the system to run the script using the python3 executable according to your environment The file needs to be in one of the directories in your PATH environment variable. You can add the current directory using export PATH=$PWD:$PATH or use ./validate_mapping_file.py instead of just validate_mapping_file.py (thanks @Grisha) Afterwards you should be able to execute the script the way you tried before.
downvote count: 1
has comment: http://stackoverflow.com/comment/128952064
answers question: http://stackoverflow.com/q/47443988
has comment: http://stackoverflow.com/comment/81920923
accepted answer of: http://stackoverflow.com/q/47443988

http://stackoverflow.com/a/47405619
downvote count: 0
answers question: http://stackoverflow.com/q/47405395
score: 1
has comment: http://stackoverflow.com/comment/81764774
has body: If you want to convert the date-time stored in the QDateTimeEdit, the first thing to do is get it through dateTime() and then convert it to string with toString() indicating the appropriate format, if you want to obtain with the current format you can use displayFormat() dt = self.StartTime.dateTime() # dt.toString("dd.MM.yyyy hh:mm:ss.zzz")) dt_string = dt.toString(self.StartTime.displayFormat()) print(dt_string)
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47405395

http://stackoverflow.com/comment/81800856
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47422969
has text: Do you get inconsistent results when repeating the same input?

http://stackoverflow.com/q/47482708
has comment: http://stackoverflow.com/comment/81920321
has comment: http://stackoverflow.com/comment/81920330
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81920279
has comment: http://stackoverflow.com/comment/81920291
score: 1
tagged with: setuptools
has comment: http://stackoverflow.com/comment/81920425
tagged with: python
has title: Local Pip install not able to import any classes within the package
accepted answer: http://stackoverflow.com/a/47719855
tagged with: deployment
tagged with: pypi
has comment: http://stackoverflow.com/comment/81920270
type: Question
has answer: http://stackoverflow.com/a/47719855
has comment: http://stackoverflow.com/comment/81920290
has body: I have a python package which I built from python setup.py sdist The package name is : Yify I installed this using pip3 install . After this when I open the python3 interpreter and import Yify , it imports successfully but it doesn't seem to include the main python file inside the dist_packages/Yify directory . Here is the folder structure :- ├── dist │ └── Yify-1.0.tar.gz ├── get-pip.py ├── LICENSE ├── README.rst ├── requirements.txt ├── setup.cfg ├── setup.py ├── Yify │ ├── __init__.py │ ├── venv | ├── Yify.py The Yify.py contains yify class . When i do import Yify Yify.yify() It gives me 'yify' not found error ! . hOW TO fix it ? Here is the setup.py contents:- import platform from setuptools import setup install_requires = ['bs4' , 'urllib3' ] setup( name='Yify', packages = ['Yify'] , version = 'v1.0', description = ''' This Module is used to get the Top seeded torrents at any given time and get the entire movie details and ratings . Its also useful to search for any movie using different parameters and obtain their magnet link or torrent file of any prefered quality. ''' , author = 'Natesh M Bhat' , url = 'https://github.com/nateshmbhat/Yify-Python', author_email = 'nateshmbhatofficial@gmail.com' , # download_url = 'https://github.com/nateshmbhat/pyttsx3/archive/v2.6.tar.gz', keywords=['yify','torrent-python' , 'movie-torrent' , 'torrent' , 'pyyify' , 'Yify' , 'yify torrent' , 'yify download' , 'download yify' , 'yifyer' , 'yifypy' , 'torrent download' , 'movie torrent' , 'movie downloader', 'movie finder'], classifiers = [] , install_requires=install_requires ) Also When I directly go into the python3.6 distpackages/Yify folder and execute python3 from there. Everything works fine . Also dir(Yify) return only the below fields dir(Yify) ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
answer count: 1
downvote count: 0
upvote count: 1
tagged with: pip

http://stackoverflow.com/q/47483496
upvote count: 2
has answer: http://stackoverflow.com/a/47483632
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/7231204
score: -4
favorite count: 0
has answer: http://stackoverflow.com/a/47483522
downvote count: 6
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47483680
has comment: http://stackoverflow.com/comment/81921912
has comment: http://stackoverflow.com/comment/81921797
tagged with: python
linked to: http://stackoverflow.com/q/7231204
has body: list = ['_ ','_ ','_ ','_ ','_ '] index = [1,4] letter = 'm' So is there any away to change lists 1 and 4 to be 'm' using index and letter? Thanks for help!
has title: Is it possible to change multible items in list to same?
type: Question
answer count: 3

http://stackoverflow.com/comment/82029166
score: 0
type: Comment
has text: What is the error message or other problem you encounter with your current approach?
comment on: http://stackoverflow.com/q/47535911
type: QuestionComment

http://stackoverflow.com/comment/81731976
score: 0
comment on: http://stackoverflow.com/q/47388642
has text: No, there is no data lost. If you remove `width=0.001` you will get the expected plot with 20 bars. See [picture](https://i.sstatic.net/Q5PXJ.png)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47419459
downvote count: 0
has body: Create an array of Scalar instances. If you have different obs_dim for each dataset, you can do [Scalar(obs_dim) for obs_dim in obs_dims]. If you have one obs_dim, use [Scalar(obs_dim) for i in range(N)] where N is the number of datasets. You can then refer to each of these by index in the array.
score: 2
answers question: http://stackoverflow.com/q/47418871
type: Answer
accepted answer of: http://stackoverflow.com/q/47418871
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/81820449
has text: To clarify, are you asking why `super(MyInt, one).__repr__()` and `repr(super(MyInt, one))` are different?
type: Comment
comment on: http://stackoverflow.com/q/47433067
type: QuestionComment
score: 0

http://stackoverflow.com/q/47508174
has title: Convert Google Sheet date serial value into human readable date
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47508307
possible better answer: http://stackoverflow.com/a/66738817
upvote count: 3
has answer: http://stackoverflow.com/a/47508307
linked to: http://stackoverflow.com/q/42216491
downvote count: 0
has body: Set-up I'm reading a Google Sheet in Python through Google Drive API. I've got a value for a date – a date serial value, which I need to convert into a human readable date. I have: date = 42747 I know that this implies that the date is 12-1-2017. Question Is there an easy way to convert 42747 to 12-1-2017? I've seen this question, but it's not answering mine.
favorite count: 0
type: Question
answer count: 2
tagged with: google-sheets
has answer: http://stackoverflow.com/a/66738817
tagged with: python
tagged with: date
tagged with: date-conversion

http://stackoverflow.com/q/47466806
tagged with: wolfram-mathematica
has comment: http://stackoverflow.com/comment/81953368
has answer: http://stackoverflow.com/a/47470198
has title: Find all partitions of a plane created by a set of lines
has answer: http://stackoverflow.com/a/47470808
has answer: http://stackoverflow.com/a/47467372
has comment: http://stackoverflow.com/comment/81905797
has comment: http://stackoverflow.com/comment/81888629
has comment: http://stackoverflow.com/comment/81888415
has comment: http://stackoverflow.com/comment/81908753
has answer: http://stackoverflow.com/a/47476829
has answer: http://stackoverflow.com/a/47528663
linked to: http://stackoverflow.com/q/7022082
tagged with: computational-geometry
has comment: http://stackoverflow.com/comment/81888151
has body: I have a set of lines (linear functions of the form y = mx + b) (120 of them!) and if I graph them all, then they partition the R^2 plane. The lines do not necessarily go through the origin. What is the most efficient way to find all partitions created by a set of such lines? Personally, I'm having a hard time coming up with any way at all, let alone an efficient one. To be more clear, I include the following image of just 4 lines: An example of a partition would be the set {(x,y)| -30x+28&lt;= y &amp;&amp; 60x+2 &lt;= y &lt;= 90x+7} , which is the partition created by the red, yellow and green lines in the first quadrant. Another example would be {(x,y)|y &lt;= -30x+28 &amp;&amp; 5x+3 &lt;= y &lt;= 60x+2}, which is the triangle in the first quadrant that is bounded by the blue, red and green lines. An example of a non partition would be {(x,y)|5x+3 &lt;= y &lt;= -30x+28}, which is the set bounded by the green line above and the blue line below. This is not a partition because there are several partitions contained within it (like the second set above, for instance), or overlapping it. The set {(x,y)|5x+3 &lt;= y &lt;= -30x+28 &amp;&amp; 90x+7 &lt;= y}, however, would be a partition. The desired output would be a complete list of such sets: {(x,y)|y &lt;= -30x+28 &amp;&amp; 5x+3 &lt;= y &lt;= 60x+2},{(x,y)| -30x+28&lt;= y &amp;&amp; 60x+2 &lt;= y &lt;= 90x+7}... etc. They don't have to be given in this notation, of course. I'm not sure how to approach this problem, and so, unfortunately, can't provide much in the way of what I have tried. Ideally, I would like to do this in R, Python, Mathematica or MATLAB, but I'm open to any option at this point. EDIT: Since there seems to be an issue with notation, I'll clarify a bit. It is sufficient to simply get a list of conditions on points, such that all points meeting that condition would exactly define a partition. For example, a long list of intersections, would be fine: y &lt;= 5x+3 &amp;&amp; y &gt;= 90x+7 &amp;&amp; y…
downvote count: 1
favorite count: 0
tagged with: matlab
type: Question
type: AnsweredQuestion
upvote count: 8
answer count: 5
has comment: http://stackoverflow.com/comment/81888244
score: 7
tagged with: math
tagged with: python
accepted answer: http://stackoverflow.com/a/47470198
possible better answer: http://stackoverflow.com/a/47467372

http://stackoverflow.com/q/47434557
type: Question
has title: How to select rows in pandas dataframe based on values in other columns and How to select one row for each distinct value in particular column
tagged with: dataframe
tagged with: python
has body: I'm newbie to pandas and I'm having problems while selecting values from a DF based on values in other columns. Following is my dataframe: C1 C2 C3 C4 0 1234 1002 Operational ABC 1 5678 2001 Closed ABC 2 7896 1002 Operational DEF 3 4321 4005 Closed CDE 4 7781 4005 Operational ABC Q1. I want to select duplicate values in C2 whose C3 value is 'Operational'. Output dataframe should be C1 C2 C3 C4 1234 1002 Operational ABC 7896 1002 Operational ABC I've tried df[(df.duplicated(['C2'], keep=False)) &amp; df['C3'] == 'Operational'] but it is selecting rows with index 0,2,4. But I want only rows with index 0 and 2 as a output. Q2. How to select one row for each distinct value in C4. Output dataframe should be C1 C2 C3 C4 7896 1002 Operational DEF 4321 4005 Closed CDE 7781 4005 Operational ABC Can I get any suggestions for these two custom selections.
accepted answer: http://stackoverflow.com/a/47434695
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47434695
tagged with: pandas
score: 2
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/47494809
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81973181
answers question: http://stackoverflow.com/q/47494557
has body: The resulting bars will not neighbour each other as in your first figure, but outside of that, pandas lets you do what you want as follows: df_g = df.groupby(['Pclass', 'Sex'])['Survived'].agg([np.mean, lambda x: 1-np.mean(x)]) df_g.columns = ['Survived', 'Died'] df_g.plot.bar(stacked=True) Here, the horizontal grouping of patches is complicated by the requirement of stacking. If, for instance, we only cared about the value of "Survived", pandas could take care of it out-of-the-box. df.groupby(['Pclass', 'Sex'])['Survived'].mean().unstack().plot.bar() If an ad hoc solution suffices for post-processing the plot, doing so is also not terribly complicated: import numpy as np from matplotlib import ticker df_g = df.groupby(['Pclass', 'Sex'])['Survived'].agg([np.mean, lambda x: 1-np.mean(x)]) df_g.columns = ['Survived', 'Died'] ax = df_g.plot.bar(stacked=True) # Move back every second patch for i in range(6): new_x = ax.patches[i].get_x() - (i%2)/2 ax.patches[i].set_x(new_x) ax.patches[i+6].set_x(new_x) # Update tick locations correspondingly minor_tick_locs = [x.get_x()+1/4 for x in ax.patches[:6]] major_tick_locs = np.array([x.get_x()+1/4 for x in ax.patches[:6]]).reshape(3, 2).mean(axis=1) ax.set_xticks(minor_tick_locs, minor=True) ax.set_xticks(major_tick_locs) # Use indices from dataframe as tick labels minor_tick_labels = df_g.index.levels[1][df_g.index.labels[1]].values major_tick_labels = df_g.index.levels[0].values ax.xaxis.set_ticklabels(minor_tick_labels, minor=True) ax.xaxis.set_ticklabels(major_tick_labels) # Remove ticks and organize tick labels to avoid overlap ax.tick_params(axis='x', which='both', bottom='off') ax.tick_params(axis='x', which='minor', rotation=45) ax.tick_params(axis='x', which='major', pad=35, rotation=0)
upvote count: 14
score: 14
type: Answer
accepted answer of: http://stackoverflow.com/q/47494557

http://stackoverflow.com/comment/81858825
has text: You also have indentation problems with the code. Python is very sensitive to indentation errors.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47451877
type: Comment

http://stackoverflow.com/q/47505051
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/81972267
score: 0
has title: Reading binary file hanging using tensorflow
tagged with: tensorflow
type: Question
has body: I am attempting to Save a numpy n-dimensional array to a *.bin file as a string of bits. Read said *.bin file using tf.FixedLengthRecordReader Extract information using tf.decode_raw This is a fairly standard operation, perfomed countless times, with countless examples online. I have tried copying line for line the example done in the tensorflow example mode. (Found here) Below you see my attempt. The moment I try to evaluate record_bytes, the entire process hangs. I have rewritten the code multiple times, so I am not sure where I am messing up. In terms of trying to debug it. I am sure that the binary file is being made properly, as I can properly open and read the contents of the file using the python method open() Not sure how to debug the tensorflow part of the code. import numpy as np import scipy.io from array import array import tensorflow as tf # Generate File array = np.array([[[1, 2, 3, 3], [4, 5, 6, 6]], [[10, 20, 30, 30], [40, 50, 60, 60]],[[2, 4, 8, 8],[16, 32, 64, 64]]]) output_file = open('temp_file.bin', 'wb') array.astype('uint8').tofile(output_file) print(array.shape) output_file.close() # Attempt to read file with tf.Session(): num_bytes = 3*2*4 reader = tf.FixedLengthRecordReader(record_bytes=num_bytes) filenames = ['temp_file.bin'] for f in filenames: if not tf.gfile.Exists(f): raise ValueError('Failed to find file: ' + f) filename_queue = tf.train.string_input_producer(filenames) key, value = reader.read(filename_queue) record_bytes = tf.decode_raw(value, tf.uint8) print(record_bytes.eval())
has comment: http://stackoverflow.com/comment/81970475
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81966376
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81970013
downvote count: 1

http://stackoverflow.com/comment/81973736
has text: Yes, they are pairs of data. In each `.xlsx` and `.csv` I have 10 variables and its N values (in this particular case, N=11), each variable in each `.xlsx` has her sister in the `.csv` file. What I am trying to do is print the 10 graphs that would result from each pair of files by just using a `for` loop with the keys and values of the dictionary (which are the variables of the `.csv` and the `.xlsx` respectively)
type: Comment
comment on: http://stackoverflow.com/a/47508234
score: 0
type: AnswerComment

http://stackoverflow.com/a/57037519
score: -2
type: Answer
has body: you can use pdf.multi_cell(ln=0, h=5.0, align='L', w=0, txt=text, border=0) method instead of pdf.cell(ln=0, h=5.0, align='L', w=0, txt=text, border=0)
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/47526775

http://stackoverflow.com/comment/82029677
comment on: http://stackoverflow.com/q/47536287
has text: are you calling read() somewhere? also, don't call this thing read :)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81828844
type: QuestionComment
score: 0
has text: Yes the urls all have the same beginning i.e. "http://www.football-data.co.uk/mmz4281/1718/" and I just want to change the bit at the end
comment on: http://stackoverflow.com/q/47436883
type: Comment

http://stackoverflow.com/comment/82135787
type: AnswerComment
comment on: http://stackoverflow.com/a/47545394
has text: Thank you very much! Works perfectly!
score: 0
type: Comment

http://stackoverflow.com/a/47537820
has body: Others have already pointed out your usage error. Even easier, just take the slice of list that you want: a = sorted(a)[:-2] This sorts the list, strips off the last two entries, and assigns the result back to a. &gt;&gt;&gt; a = [5, 8, 3, 2] &gt;&gt;&gt; a = sorted(a)[:-2] &gt;&gt;&gt; a [2, 3]
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47537671
downvote count: 0

http://stackoverflow.com/q/47508763
has body: How do I download a file from Google Drive? I am using pydrive using the link. #https://drive.google.com/open?id=DWADADDSASWADSCDAW from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() drive = GoogleDrive(gauth) gdrive_file = drive.CreateFile({'id': 'id=DWADADDSASWADSCDAW'}) gdrive_file.GetContentFile('DWADSDCXZCDWA.zip') # Download content file. Error: raceback (most recent call last): File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\oauth2client\clientsecrets.py", line 121, in _loadfile with open(filename, 'r') as fp: FileNotFoundError: [Errno 2] No such file or directory: 'client_secrets.json' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\auth.py", line 386, in LoadClientConfigFile client_type, client_info = clientsecrets.loadfile(client_config_file) File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\oauth2client\clientsecrets.py", line 165, in loadfile return _loadfile(filename) File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\oauth2client\clientsecrets.py", line 125, in _loadfile exc.strerror, exc.errno) oauth2client.clientsecrets.InvalidClientSecretsError: ('Error opening file', 'client_secrets.json', 'No such file or directory', 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Hoxton/123/pyu_test.py", line 8, in <module> gdrive_file.GetContentFile('PyUpdater+App-win-1.0.zip') # Download content file. File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\files.py", line 210, in GetContentFile self.FetchContent(mimetype, remove_bom) File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\files.py", line 42, in _decorated self.FetchMetadata() File "C:\Users\Hoxton\AppData\Local\Conti…
has answer: http://stackoverflow.com/a/67399730
accepted answer: http://stackoverflow.com/a/47530516
type: Question
has answer: http://stackoverflow.com/a/47530516
has comment: http://stackoverflow.com/comment/115408824
has comment: http://stackoverflow.com/comment/81973348
tagged with: python
tagged with: google-drive-api
has answer: http://stackoverflow.com/a/72076945
linked to: http://stackoverflow.com/q/25010369
score: 2
upvote count: 2
tagged with: pydrive
type: AnsweredQuestion
answer count: 3
downvote count: 0
has title: Download a file from google drive using python
possible better answer: http://stackoverflow.com/a/72076945
favorite count: 0

http://stackoverflow.com/comment/99679590
score: 3
has text: please add an explanation to your answer.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/56543418

http://stackoverflow.com/comment/81834291
comment on: http://stackoverflow.com/q/47421419
type: Comment
type: QuestionComment
has text: @Shahin I've noticed that the button works with a POST on every keypress, so copy-paste doesn't work. Try to delete the last 2 digits and then type them yourself one by one.
score: 0

http://stackoverflow.com/q/47463730
answer count: 2
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/47463791
has comment: http://stackoverflow.com/comment/81882348
possible better answer: http://stackoverflow.com/a/47463751
favorite count: 0
has answer: http://stackoverflow.com/a/47463751
has comment: http://stackoverflow.com/comment/81882322
tagged with: data-analysis
accepted answer: http://stackoverflow.com/a/47463791
type: Question
has body: {'asin': '0756029929', 'description': 'Spanish Third-year Pin, 1 inch in diameter. Set of 10.', 'title': 'Spanish Third-year Pin Set of 10', 'price': 11.45, 'imUrl': 'http://ecx.images-amazon.com/images/I/51AqSOl7qLL._SY300_.jpg', 'salesRank': {'Toys &amp; Games': 918374}, 'categories': 'Clothing, Shoes &amp; Jewelry', 'Novelty, Costumes &amp; More', 'Novelty', 'Clothing'} {'asin': '0756029104', 'description': 'Viva Espaol pin, 1 x 1 inch. Set of 10.', 'title': 'Viva Espanol Pins Set of 10', 'price': 11.45, 'imUrl': 'http://ecx.images-amazon.com/images/I/51By%2BZpF9DL._SY300_.jpg', 'salesRank': {'Home &amp;amp; Kitchen': 2651070}, 'categories': 'Clothing, Shoes &amp; Jewelry', 'Novelty, Costumes &amp; More', 'Novelty', 'Clothing'} {'asin': '0839933363', 'description': 'This necklace from the popular manga and anime series, Death Note. The necklace\'s charm is black and silver with the text, "Death Note" upon it. The approx. length of the necklace is 12"Dimension &amp; Measurement:Length: Approx. 12"', 'title': 'Death Note Anime Manga: Cross Logo necklace', 'imUrl': 'http://ecx.images-amazon.com/images/I/51f0HkHssyL._SY300_.jpg', 'salesRank': {'Toys &amp; Games': 1350779}, 'categories': 'Clothing, Shoes &amp; Jewelry', 'Novelty, Costumes &amp; More', 'Costumes &amp; Accessories'} {'asin': '1304567583', 'description': 'pink bikini swimwear glow in the dark fashion', 'title': 'Pink Bikini Swimwear Glow in the Dark Fashion', 'price': 19.99, 'imUrl': 'http://ecx.images-amazon.com/images/I/41pS%2B98jhlL._SY300_.jpg', 'categories': 'Clothing, Shoes &amp; Jewelry', 'Novelty, Costumes &amp; More', 'Costumes &amp; Accessories', 'Costumes'} {'asin': '1304567613', 'description': 'Bikini Swimwear glow in the dark fashion blue', 'title': 'Bikini Swimwear Blue Glow in the Dark Fashion', 'price': 29.99, 'imUrl': 'http://ecx.images-amazon.com/images/I/41ZNIUvYkyL._SY300_.jpg', 'categories': [['Clothing, Shoes &amp; Jewelry', 'Novelty, Costumes &amp; More', 'Costumes …
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: How to iterate over a file and put the all the id values into an list [Python]
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/a/47466730
answers question: http://stackoverflow.com/q/47466466
type: Answer
score: 0
has body: enumerate has a start keyword argument, you can count from whatever number you want. Here you can use it to solve your issue without importing any heavy external module or many loops: dict1 = {1:'a',2:'b',3:'c'} dict2 = {1:'d',2:'e'} for index,values in enumerate(dict2.items(),start=len(dict1)+1): dict1[index] = values[1] print(dict1) output: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

http://stackoverflow.com/q/47468388
tagged with: python
tagged with: win32gui
has answer: http://stackoverflow.com/a/47468488
type: AnsweredQuestion
downvote count: 0
score: 1
has body: i want to set my window on the top: SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE) but, it fails: NameError: global name ‘HWND_TOP‘ is not defined is HWND_TOP need define? i can’t find HWND_TOP value from help doc PyWin32.chm
upvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: pywin32
has title: python win32gui HWD_TOPMOST is not defined
accepted answer: http://stackoverflow.com/a/47468488

http://stackoverflow.com/q/47494142
has answer: http://stackoverflow.com/a/47513927
possible better answer: http://stackoverflow.com/a/47513927
tagged with: node.js
has body: I am getting the following error when I attempt to install gulp-converter-tjs using npm install -g gulp-converter-tjs It looks like I am missing python but the path is correct for python.exe . I can even run python command from my cmd and also enviroment variables are set. Any suggestions? C:\Users\themhz\AppData\Roaming\npm\node_modules\gulp-converter-tjs\node_modules\iconv>if not defined npm_config_node_gy p (node "C:\Users\themhz\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin....\node_modules\node-gyp\bin\node-gyp .js" rebuild ) else (node "" rebuild ) gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "C:\Users\themhz\AppData\Local\Programs\Python\Python36-32\python.exe ", you can set the PYTHON env variable. gyp ERR! stack at PythonFinder.failNoPython (C:\Users\themhz\AppData\Roaming\npm\node_modules\npm\node_modules\node- gyp\lib\configure.js:483:19) gyp ERR! stack at PythonFinder. (C:\Users\themhz\AppData\Roaming\npm\node_modules\npm\node_modules\node-g yp\lib\configure.js:509:16) gyp ERR! stack at C:\Users\themhz\AppData\Roaming\npm\node_modules\npm\node_modules\graceful-fs\polyfills.js:284:29 gyp ERR! stack at FSReqWrap.oncomplete (fs.js:152:21) gyp ERR! System Windows_NT 10.0.15063 gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\themhz\AppData\Roaming\npm\node_modules\npm\nod e_modules\node-gyp\bin\node-gyp.js" "rebuild" gyp ERR! cwd C:\Users\themhz\AppData\Roaming\npm\node_modules\gulp-converter-tjs\node_modules\iconv gyp ERR! node -v v8.9.1 gyp ERR! node-gyp -v v3.6.2 gyp ERR! not ok npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! iconv@2.3.0 install: node-gyp rebuild npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the iconv@2.3.0 install script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\themhz\AppData\Roaming\npm-cache_logs\2017-11-25T15_20_09_146Z-debug.log My machine is runn…
type: AnsweredQuestion
score: 1
has title: Can't find Python executable when installing gulp-converter-tjs
tagged with: gulp
has answer: http://stackoverflow.com/a/47526432
accepted answer: http://stackoverflow.com/a/47526432
favorite count: 0
type: Question
answer count: 2
tagged with: npm
upvote count: 2
tagged with: python
downvote count: 1

http://stackoverflow.com/a/47385799
type: Answer
has body: You can use sys.maxsize and 0 to intilize variables for tracking the minimum and maximum rainfall values that realistically the user will never enter above above or below respectively. However for the second case just to make sure you can also add a simple check to ensure the user does not enter a negative rainfall amount: def calculationAlgorithm(userYearsTracking): totalMonths = 0 totalRainfall = 0 maxRainfall = 0 minRainfall = sys.maxsize for currentYear in range (1, userYearsTracking +1): for currentMonth in range (1, 13): monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " + format(currentYear, "d",)+": ")) if monthlyRainfall &lt; 0: print("Error invalid rainfall entered") sys.exit() if monthlyRainfall &gt; maxRainfall: maxRainfall = monthlyRainfall if monthlyRainfall &lt; minRainfall: minRainfall = monthlyRainfall totalMonths += 1 totalRainfall += monthlyRainfall averageRainfall = totalRainfall / totalMonths print("Total months: " + str(totalMonths)) print("Total rain:", format(totalRainfall), "(inch)") print("Total average rainfall:", round(averageRainfall,2), "(inch)") print("Largest input rainfall: " + str(maxRainfall)) print("Smallest input rainfall: " + str(minRainfall)) Try out the full program with above changes here. Example Usage: How many years do you want to track: 1 Inches of rainfall for month 1 | year 1: 2 Inches of rainfall for month 2 | year 1: 2 Inches of rainfall for month 3 | year 1: 2 Inches of rainfall for month 4 | year 1: 2 Inches of rainfall for month 5 | year 1: 4 Inches of rainfall for month 6 | year 1: 1 Inches of rainfall for month 7 | year 1: 2 Inches of rainfall for month 8 | year 1: 2 Inches of rainfall for month 9 | year 1: 2 Inches of rainfall for month 10 | year 1: 2 Inches of rainfall for month 11 | year 1: 2 Inches of rainfall for month 12 | year 1: 2 Total months: 12 Total rain: 25 (inch) Total average rainfall: 2.08 (inch) Largest input rainfall: 4 Smallest input rainfall: …
score: 0
answers question: http://stackoverflow.com/q/47385617

http://stackoverflow.com/a/72176480
answers question: http://stackoverflow.com/q/47494350
has body: One has to have a clear understanding of cv2.countNonZero() before using it. It can be used only with an image of single channel. In other words, an image with only two dimensions (width and height). When used with a 3-channel image you would face an assertion error: (-215:Assertion failed) cn == 1 As the name suggests, it counts number of pixels within an image having pixel value greater than 0, i.e. pixel values within the range [1 - 255] Example 1: The following is a binary image: spot_img = cv2.imread('spots.jpg', 0) binary_img = cv2.threshold(spot_img, 127, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] cv2.countNonZero(binary_img) 5 There are 5 non zero pixels in the image. And given that the image is binary we can conclude there are 5 white pixels (pixel value = 255) Example 2: code_img = cv2.imread(r'C:\Users\524316\Desktop\Stack\m1.png', 0) cv2.countNonZero(code_img) 5937 In the above gray scale image there are 5937 non zero pixels in the image. And that includes pixel values between [1 - 255] To get only the count of white pixels [255], use np.sum() as mentioned above: np.sum(code_img == 255) 5792 To get the count of a particular pixel value, use the same as above
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81754951
comment on: http://stackoverflow.com/q/47400285
type: Comment
has text: Yes this is error Warning: copy(http://telegra.ph/upload/): failed to open stream: HTTP wrapper does not support writeable connections @Don'tPanic
score: 0
type: QuestionComment

http://stackoverflow.com/a/47538788
downvote count: 0
has body: Figured out the Answer: df = pd.read_excel('OriginalSpreadsheet.xlsx', sheet_name='Sheet1') list(set(df.COSIGNER)) list(df['COSIGNER'].unique()) x = list(df['COSIGNER'].unique()) # ORIGINAL CODE THAT DIDN'T WORK: #df1 = pd.DataFrame() #df1['Unique'] = [x] df1 = pd.DataFrame(x, columns=['unique']) # ORIGINAL CODE THAT DIDN'T WORK: #twodf = pd.concat([df, df1], ignore_index=True) twodf = pd.concat([df, df1], axis=1)
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47538163

http://stackoverflow.com/comment/82043716
comment on: http://stackoverflow.com/a/47481743
score: 0
type: Comment
type: AnswerComment
has text: @LarryZ: I think that's a fine solution (using a Series with the separator).

http://stackoverflow.com/comment/81958626
has text: `sys.stdout.write` ?
comment on: http://stackoverflow.com/q/47501453
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81796690
has text: @sparrow there must be a wider application to this because if you only ever want to extract `"Austin"` from `mysting` and assign this to `city`, why not just replace everything with: `city = "Austin"`?
type: Comment
comment on: http://stackoverflow.com/q/47420926
score: 1
type: QuestionComment

http://stackoverflow.com/a/47464860
type: Answer
score: 2
upvote count: 2
has body: If you replace your function by this: def export_png(*parms): for p in parms: print type(p),p it becomes clear that you get your parameters twice. I think this happens because you are using the deprecated form of registration: "/Image/Export as png" The current form of registration would be just "Export as png", and a named parameter at the end: menu="&lt;Image&gt;/Image" (though IMHO this would be better put in &lt;Image&gt;/File/Export/). When you use the current form, the first two parameters are filled implicitly with the current image and layer (if they have the right type), so there is no duplication. And in that case, they don't appear in the dialog, so if they are the only parms, the script is called directly without showing a dialog. self serves no purpose. It used in object methods to obtain a reference to the current object (and must be the first parameter). But this is not the case here, export_png() is a plain function, not an object method.
downvote count: 0
answers question: http://stackoverflow.com/q/47463859

http://stackoverflow.com/comment/81914377
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47479637
has text: That's returned the number 2 - what does this mean?
type: Comment

http://stackoverflow.com/comment/81755830
score: 0
comment on: http://stackoverflow.com/q/47400620
has text: I still get "IndexError: list index out of range". I'm gonna move on to next lessons. Thank you guys. I appreciate it very much. Btw, the book is "Python the hard way".
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81921446
has text: It doesnt matter. Just join the two bag of words. The number of rows should be same. Only the features will increase. And then pass the new 2-d array of shape [number of records, features1 + features2] to the classifier
comment on: http://stackoverflow.com/q/47483215
score: 0
type: Comment
type: QuestionComment

ide
tags question: http://stackoverflow.com/q/47534405
tags question: http://stackoverflow.com/q/47512770
tag name: ide
tags question: http://stackoverflow.com/q/47410137
type: Tag

http://stackoverflow.com/comment/82326344
has text: I think there should be: while running: ... if not data: break it works very well and doesn't have those issues in the code from the link: http://www.binarytides.com/python-socket-server-code-example/ So, my problem is solved
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47409170

http://stackoverflow.com/a/47414085
type: Answer
score: 0
has body: words = ["Apple","Boat","Carrot","Dragonfly","Education"] # 1 # for _ in range(11): print(words[random.randrange(0, len(words))]) # 2 # print("Before shuffle: ",words);random.shuffle(words);print("After shuffle: ",words) # 3 # print("Choose 1 random sample",random.sample(words, 1)) I dont know what is your aim, but here is what I come up with. Also you don't need to store them as str in 'order' list. You can have a list of integers, and you can use it without needing to convert. Such as: order=[1,2,3,4,5] I hope my answer was helpful.Cheers!
answers question: http://stackoverflow.com/q/47413170

http://stackoverflow.com/q/47440203
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47440280
has comment: http://stackoverflow.com/comment/81986557
has comment: http://stackoverflow.com/comment/81835302
tagged with: time
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81835360
has body: I am trying to run two while loops based on an input condition. In this example, that is taken out and replaced by a 1 == 0 so that 0 can be changed back and forth for testing. Once selected, each while loop should run for 10 seconds and then the input condition checked (replaced by 1 == 0) again. The problem appears to be in the time comparison, since it never evaluates correctly. What am I missing? #!/usr/bin/env python3 import time import os import bellmod while True: starttime = time.time() print("Start time " + str(starttime)) #Time check elapsedtime = 0 #Reset elasped time to 0 for each loop iteration. if 1 == 0: #Change this to run either loop. See if remote or local has precidence. while(elapsedtime &lt; 10): print("Inside remote while " + time.strftime("%H:%M:%S")) #Time check elapsedtime = time.time() - starttime #Calculate elasped time. else: elapsedtime = 0 while(elapsedtime &lt; 10): print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check elapsedtime = time.time() - starttime #Calculate elasped time.
has comment: http://stackoverflow.com/comment/81835369
has answer: http://stackoverflow.com/a/47440275
tagged with: while-loop
type: Question
has comment: http://stackoverflow.com/comment/81835279
tagged with: nested
tagged with: python
has title: Python 3: Nested while loops based time

http://stackoverflow.com/a/47448037
has comment: http://stackoverflow.com/comment/81878435
upvote count: 1
has comment: http://stackoverflow.com/comment/81851186
has comment: http://stackoverflow.com/comment/81851427
has comment: http://stackoverflow.com/comment/81853136
accepted answer of: http://stackoverflow.com/q/47447906
type: Answer
answers question: http://stackoverflow.com/q/47447906
has body: The main issue with your code is the JSON read line in your python script. It is not indented properly inside the read block. Since the first program is just a snippet, it did not break the program. But with the original program, due to indentation issue you are getting a huge error. The corrected script follows. Python (Basic Script) import sys, json, random data = {'form_type':'default'} with open('data.json', 'w') as outfile: json.dump(data, outfile) Python (Main Script) import dill import random import sys import os import json restart = 'yes' user_action = 'inventory' pickle = 'rpg.pickle' restart = sys.argv[1] user_action = sys.argv[2] pickle = sys.argv[3] + ".pickle" if restart == "no" and os.path.isfile(pickle) == False: restart = "yes" data = {'form_type':'potato'} with open('data.json', 'w') as outfile: json.dump(data, outfile) # Lots of more code afterward
has comment: http://stackoverflow.com/comment/81888116
has comment: http://stackoverflow.com/comment/81852940
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81851258
has comment: http://stackoverflow.com/comment/81888064

http://stackoverflow.com/comment/81960142
has text: https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
score: 0
comment on: http://stackoverflow.com/q/47502008
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47485278
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81925968
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47495245
has comment: http://stackoverflow.com/comment/81925597
has title: how to add a file contents to a variable in python 3.5
tagged with: python-3.5
tagged with: python
has answer: http://stackoverflow.com/a/47485411
has comment: http://stackoverflow.com/comment/81925892
has comment: http://stackoverflow.com/comment/81925552
type: AnsweredQuestion
has body: I'm not very experienced so please know I'm trying as hard as I can. How do I add the file's first contents (eg. 65) to a new entered number, then overwrite the file to save it? Any advice is greatly appreciated. Here is my programming: henry = 0 emily = 0 george = 0 points = 0 file = open('nfc.txt','r+') for line in file: print(line) if input("Who would you like to give points to? ") == "henry": points = int(input("How many points would you like to give to Henry? ")) henry = henry + points print("Henry now has",henry, "points") points = 0 file.write(str(henry)+" ") file.write(str(emily)+" ") file.write(str(george)+" ") file.close() else: print("That name is not valid")
possible better answer: http://stackoverflow.com/a/47485868
answer count: 3
has answer: http://stackoverflow.com/a/47485868
accepted answer: http://stackoverflow.com/a/47485411
downvote count: 0

http://stackoverflow.com/comment/81978945
comment on: http://stackoverflow.com/q/47511048
type: QuestionComment
type: Comment
has text: Okay, try this - `df.pivot_table(index='user_id', columns='video_id', values=operation_times')`
score: 0

http://stackoverflow.com/comment/81793946
type: QuestionComment
has text: Looks like I got scooped. Anyway, glad to have been of help.
type: Comment
comment on: http://stackoverflow.com/q/47417986
score: 1

http://stackoverflow.com/comment/82003313
type: Comment
comment on: http://stackoverflow.com/q/47523547
type: QuestionComment
has text: Depending on the version of python have a look at [this](https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions)
score: 1

http://stackoverflow.com/comment/81851780
comment on: http://stackoverflow.com/a/47435625
type: Comment
has text: Please help me !...sir
score: 0
type: AnswerComment

http://stackoverflow.com/q/47502584
has answer: http://stackoverflow.com/a/47502641
type: Question
accepted answer: http://stackoverflow.com/a/47502641
has title: Shifting a Pandas time series without frequency
downvote count: 0
answer count: 1
has body: I have a time series whose indices looks like this: In [671]: indices Out[671]: DatetimeIndex(['2000-12-29', '2001-02-20', '2001-03-26', '2001-04-12', '2001-04-24', '2001-07-05', '2001-08-15', '2001-09-10', '2001-09-18', '2001-10-02', '2001-10-11', '2001-10-30', '2001-12-13', '2002-03-07', '2002-06-13', '2002-09-12', '2002-12-12', '2003-03-13', '2003-06-12', '2013-02-19', '2013-05-28', '2013-09-03', '2014-01-21', '2014-02-18', '2014-05-27', '2014-07-07', '2014-09-02', '2015-01-20', '2015-02-17', '2015-05-26', '2015-07-06', '2016-05-31', '2016-07-05', '2016-09-06', '2016-10-04', '2017-01-17', '2017-02-21', '2017-05-30', '2017-09-05'], dtype='datetime64[ns]', name='date', freq=None) I cannot assign a frequency since frequency is irregular. My goal is to get a new set of indices that are shifted by 2 rows (not 2 calendar dates later but two dates later in the data). I try: indices2 = indices.shift(2) But it says: ValueError: Cannot shift with no freq My desired output looks like: In [671]: indices2 Out[671]: DatetimeIndex(['2000-02-20', '2001-03-26', '2001-04-12', ...., '2017-09-05'],
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 7
upvote count: 7
tagged with: date

http://stackoverflow.com/comment/119686245
score: 0
comment on: http://stackoverflow.com/a/47540675
type: Comment
has text: Another nuance: for `UPDATE`, some databases will only report _affected_ row counts, not the number matched. This can occur when the condition for an update matches _n_ rows, but of those rows, only _n - x_ actually would be changed (the current row content differs from the update), and so _n - x_ is the count which will be returned by `rowcount`.
type: AnswerComment

http://stackoverflow.com/q/47466282
tagged with: python-2.7
type: AnsweredQuestion
has title: How to update object information in XML?
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has body: I have a XML file (gt.xml) as follows: class1 Unspecified 805 140 975 300 class2 Unspecified 816 386 1000 575 And I have an object that contains new information as: objects=[{'name': 'class1', 'bbox': [813, 141, 964, 296]}, {'name': 'class2', 'bbox': [824, 389, 989, 568]}] I want to update the values of bbox corresponding to name to the XML file. So the expected new information in the gt.xml XML file will be: class1 Unspecified 813 141 964 296 class2 Unspecified 824 389 989 568 This is my update function: def update_xml(filename, object): """ Parse a PASCAL VOC xml file """ xml_file = os.path.join(dst_xml_dir, filename) tree = ET.parse(xml_file) print (len(object)) for obj in tree.findall('object'): for obj_rotate in range(len(object)): print (object[obj_rotate]['bbox']) if(obj.find('name').text == object[obj_rotate]['name']): bbox=object[obj_rotate]['bbox'] obj.find('bndbox').find('xmin').text= str(bbox[0]) obj.find('bndbox').find('ymin').text = str(bbox[1]) obj.find('bndbox').find('xmax').text= str(bbox[2]) obj.find('bndbox').find('ymax').text = str(bbox[3]) tree.write(xml_file) It can update the XML but it has issues that I must use two loops to insert the class name in the condition if. I guess we can have a better way to use a single loop from objects information. Could we do it in Python?
has answer: http://stackoverflow.com/a/47466588
favorite count: 0
possible better answer: http://stackoverflow.com/a/47466628
type: Question
has answer: http://stackoverflow.com/a/47466628
accepted answer: http://stackoverflow.com/a/47466588
tagged with: python
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/q/47402828
has comment: http://stackoverflow.com/comment/81759400
has body: I generated a list of numbers through the creation of permutations. I'm now trying to remove the non-prime numbers from this list. import itertools from sympy import isprime values = list(itertools.permutations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)) def removeNonPrimes(items): return [p for p in items if isprime(p)] primes = removeNonPrimes(values) print primes However, when I try to create a new list with only the prime numbers, I get the following error: TypeError: int() argument must be a string or a number, not 'tuple' Why is this a tuple and not a list? Still, why can I not remove items from a tuple like I can a list?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81759809
has title: Why can I not remove items from a tuple like I can from a list?
has comment: http://stackoverflow.com/comment/81760993
tagged with: python-itertools
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81759458
has answer: http://stackoverflow.com/a/47402839
upvote count: 0
has comment: http://stackoverflow.com/comment/81759396
answer count: 1
downvote count: 1

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/47395772
tags question: http://stackoverflow.com/q/47448384
tags question: http://stackoverflow.com/q/47539028
tags question: http://stackoverflow.com/q/47496309
type: Tag
tags question: http://stackoverflow.com/q/47396466
tags question: http://stackoverflow.com/q/47385352

http://stackoverflow.com/comment/81905239
score: 0
comment on: http://stackoverflow.com/q/47475225
type: QuestionComment
type: Comment
has text: shouldn't `while not is_window_found` work ?

http://stackoverflow.com/comment/81849193
type: Comment
has text: It has nothing to do with the line being filled with zeroes, you are simply throwing away every other line (due to alternately calling `readline()` in two different places, and only using the return value from one).
type: QuestionComment
comment on: http://stackoverflow.com/q/47446834
score: 1

http://stackoverflow.com/comment/82013423
type: AnswerComment
comment on: http://stackoverflow.com/a/47527669
has text: `if data[last][-1] == 0` checks if you have `0` before `3` (first positive value). If there is ie. `-4` then there is no need to move. Or maybe you have to move even when there is `-4` ? Then you can remove this `if`.
type: Comment
score: 0

http://stackoverflow.com/comment/81965824
comment on: http://stackoverflow.com/q/47504879
type: Comment
has text: the purpose is kind of mapping the calculated values of main query to fuzzy thresholds that have been determined by experts. @RajKris
type: QuestionComment
score: 0

http://stackoverflow.com/a/47517341
has comment: http://stackoverflow.com/comment/82001573
score: 3
has comment: http://stackoverflow.com/comment/81997071
type: Answer
has comment: http://stackoverflow.com/comment/81995995
accepted answer of: http://stackoverflow.com/q/47507831
upvote count: 3
answers question: http://stackoverflow.com/q/47507831
type: AcceptedAnswer
has body: EDIT: Use the query operators listed here, in particular .contains(substr) ORIGINAL: Use fn.substr, fn documentation is here. A similar question and more thorough answer is here.
downvote count: 0

http://stackoverflow.com/comment/81991555
type: QuestionComment
comment on: http://stackoverflow.com/q/47517696
score: 0
has text: Can you clarify your question? What is the expected outcome? Do you want to remove the last number and `.fa` from all of the file names?
type: Comment

http://stackoverflow.com/a/47423145
accepted answer of: http://stackoverflow.com/q/47423045
has body: By using Bday from pandas.tseries.offsets import BDay df.index.max()-BDay(260) Timestamp('2015-01-05 00:00:00')
type: Answer
answers question: http://stackoverflow.com/q/47423045
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/q/47531430
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47531763
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82019315
has body: import time import threading class Check(threading.Thread): def __init__(self): self.stopped = False threading.Thread.__init__(self) def run(self): i = 0 while not self.stopped: time.sleep(1) i = i + 1 print(i) if(i==5): self.stopped = True inst = Check() inst.start()
has comment: http://stackoverflow.com/comment/82020428
upvote count: 0
type: UnansweredQuestion
has title: how can stop only thread but program should keep running in python
tagged with: multithreading
answer count: 1

http://stackoverflow.com/a/47440315
has comment: http://stackoverflow.com/comment/81835769
has comment: http://stackoverflow.com/comment/81835758
has comment: http://stackoverflow.com/comment/118761637
accepted answer of: http://stackoverflow.com/q/47440077
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/106563649
upvote count: 175
has body: Try pd.isna(): In [7]: pd.isna(df.iloc[1,0]) Out[7]: True AKA pd.isnull
has comment: http://stackoverflow.com/comment/104250827
answers question: http://stackoverflow.com/q/47440077
score: 175
type: Answer
has comment: http://stackoverflow.com/comment/81835685

http://stackoverflow.com/a/47516567
answers question: http://stackoverflow.com/q/47516197
downvote count: 0
has comment: http://stackoverflow.com/comment/81989751
has comment: http://stackoverflow.com/comment/81989910
type: Answer
score: 2
has body: Or we can using .iloc and enumerate l=[3, 4, 1] pd.DataFrame(data=[df.iloc[x:x+1,y:y+4].values[0] for x,y in enumerate(l)]) Out[107]: 0 1 2 3 0 1.224124 -0.938459 -1.114081 -1.128225 1 -0.445288 0.445390 -0.154295 -1.871210 2 0.784677 0.997053 2.144286 -0.179895
upvote count: 2

http://stackoverflow.com/a/47458235
has body: Not really. The coin outlines are not continuous so that any kind of filling will leak. You can repair the edges by some form of morphological processing (erosion), but this will bring the coins in contact and create unreachable regions between them. As a fallback solution, you can try a Hough circle detector and mask inside the disks.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47410554

http://stackoverflow.com/q/47425692
accepted answer: http://stackoverflow.com/a/47432138
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/81817122
type: AnsweredQuestion
downvote count: 0
has title: Matplotlib: How to assign increasing shade of colors according to the size of text in a plot?
upvote count: 1
score: 1
tagged with: matplotlib
answer count: 1
has body: I have a bunch of words frequencies: words = ['an', 'apple', 'in', 'a', 'tree'] counts = [23, 12, 45, 20, 9] How can I plot the words in matplotlib according to their values and also color changing smoothly (for example cm.Blues) ? My attempt is this: import numpy as np import matplotlib.pyplot as plt plt.rc('font',**{'size':20, 'family':'fantasy'}) from collections import Counter from matplotlib import colors as mcolors words = ['an', 'apple', 'in', 'a', 'tree'] counts = [23, 12, 45, 20, 9] plt.figure(figsize=(8,8)) c = list(mcolors.CSS4_COLORS.values()) for i in range(len(words)): x = np.random.uniform(low=0, high=1) y = np.random.uniform(low=0, high=1) plt.text(x, y, words[i], size=counts[i]*2, rotation=np.random.choice([-90, 0.0, 90]), color=c[np.random.randint(0,len(c))]) plt.setp(plt.gca(), frame_on=False, xticks=(), yticks=()) plt.show() There are random colors. How can we assign increasing shade of color to make this picture more intuitive?
has answer: http://stackoverflow.com/a/47432138
favorite count: 0
type: Question
tagged with: python-ggplot

http://stackoverflow.com/comment/82035207
type: QuestionComment
comment on: http://stackoverflow.com/q/47539087
score: 0
has text: @monamona there aren't 30 ints. there are `10000000030 - 1000000000 == 9000000030` ints.
type: Comment

http://stackoverflow.com/q/47494094
has answer: http://stackoverflow.com/a/47495064
has comment: http://stackoverflow.com/comment/81946101
tagged with: python
has comment: http://stackoverflow.com/comment/81945495
tagged with: sqlalchemy
has title: SQLAlchemy class have a class variable not instance variable?
has comment: http://stackoverflow.com/comment/81943221
linked to: http://stackoverflow.com/q/16156650
has body: I write some domain class like : class Klient(Base): __tablename__ = 'klient' __table_args__ = ( Index('pg_klient_index', 'nums', 'sals', 'k_id'), ) def __init__(self): self.dogovors=list() adrrab = Column(String(200)) c1uid = Column(String(45)) cods = Column(String(10)) d_first = Column(Date) d_vidan = Column(Date) docum = Column(String(40)) doljn = Column(String(160)) id = Column(BigInteger, primary_key=True, server_default=text("nextval('klient_id_seq'::regclass)")) inn = Column(String(15)) izm = Column(Date) k_id = Column(BigInteger, nullable=False) ..... vidan = Column(String(300)) xmldat = Column(Date) xmlnum = Column(String(15)) zak = Column(Numeric(1, 0)) dogovors = [] I select all records with code: klients = ss.query(Klient).all() for k in klients: q = ss.query(Dogovor).filter(Dogovor.sals == k.sals, Dogovor.kl_id == k.k_id).all() if len(q): k.dogovors.extend(q) And I see unexpected behavior: Every object have a same instance of dogovors how it possibly? UPD: I tried write: class Klient(Base): __tablename__ = 'klient' __table_args__ = ( Index('pg_klient_index', 'nums', 'sals', 'k_id'), ) def __init__(self): self.dogovors=list() adrrab = Column(String(200)) c1uid = Column(String(45)) But I have the error AttributeError: 'Klient' object has no attribute 'dogovors'
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/16156650
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/47404589
has title: PHP - how to terminate python script from php page?
upvote count: 1
tagged with: python
tagged with: php
score: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81763010
has answer: http://stackoverflow.com/a/71444031
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81762994
tagged with: raspberry-pi
has body: I am currently working on my final year project which is IoT based. I have a website written in php and I have sensors which are controlled by the raspberry pi board using python script. One of the functions I want to develop is that the user can control the sensors by turn them on/off via the web page. what I mean by turning on/off is to run or terminate python script from running. I could execute the python file from the web page and it works fine using shell_execute(python fileName.py). however for the termination, I could not, even I tried different ways to do so. The problem I have faced is the script keeps running in the background. Please help if anyone has an idea of how to stop python script from web page(php page - pressing a button for example). Thank you
type: UnansweredQuestion

http://stackoverflow.com/q/47453968
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81863918
tagged with: python
has comment: http://stackoverflow.com/comment/81862981
has body: I am constructing IGMP packet by using SCAPY Lib in Python 2.7. And using hexdump logic in my code. But getting error while executing below code. constructing scapy IGMP packet ipPacket=inet.Ether(dst="01:00:5E:00:00:02",src="30:01:02:03:04:05") /inet.IP(src="0.0.0.0",dst="224.0.0.2")/IGMP(gaddr="225.0.0.1",type=0x17) hexdump logic length = 16 FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)]) lines = [] for c in xrange(0, len(ipPacket), length): chars = ipPacket[c:c+length] hex = ' '.join(["%02x" % ord(x) for x in chars]) printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars]) lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable)) payload = ''.join(lines) Error while compilation: hex = ' '.join(["%02x" % ord(x) for x in chars]) TypeError: ord() expected string of length 1, but Ether found Please let me know if anybody faced this issue before.
score: 0
has title: Python 2.7: TypeError: ord() expected string of length 1, but Ether found
has comment: http://stackoverflow.com/comment/81863603
answer count: 0
has comment: http://stackoverflow.com/comment/81863137
tagged with: scapy
linked to: http://stackoverflow.com/q/28147515
type: Question
has comment: http://stackoverflow.com/comment/81863654
has comment: http://stackoverflow.com/comment/81890598

http://stackoverflow.com/q/47500535
favorite count: 0
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/81956484
has answer: http://stackoverflow.com/a/47500709
has comment: http://stackoverflow.com/comment/81956798
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81956498
has comment: http://stackoverflow.com/comment/81956668
has comment: http://stackoverflow.com/comment/81956643
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
answer count: 1
has body: I am using Python 3.5 to edit a list, which in this case is predictions_dict['D'], included in the dictionary predictions_dict. This is the code that I use: import multiprocessing as multip predictions_dict = {'A': [], 'B': [], 'C': [], 'D': [], 'E': [], 'F': [], 'Def': []} data = [{'index': 1, 'rank': 'A'}, {'index': 2, 'rank': 'D'}, {'index': 3, 'rank': 'E'}] prediction = [(1, 'C'), (2, 'D'), (3, 'D')] def create_predictions_dict(index, rank): for j in data: if j['index'] == index: predictions_dict[rank].append((index, j['rank'], rank)) break np = multip.cpu_count() p = multip.Pool(processes=np) _ = p.starmap(create_predictions_dict, prediction) p.close() p.join() print('final list:', predictions_dict['D']) when I execute this code, the output I get is: final list: [] And I don't understand why, as I would expect to get: final list: [(2, 'D', 'D'), (3, 'E', 'D')]
upvote count: 1
accepted answer: http://stackoverflow.com/a/47500709
has title: Getting an empty list when appending values with multiprocessing

http://stackoverflow.com/q/47527880
answer count: 1
has answer: http://stackoverflow.com/a/47682043
type: Question
tagged with: button
tagged with: python
accepted answer: http://stackoverflow.com/a/47682043
has title: How to remove hover/clicked effect in pygtk?
has body: I want to remove or turn off this hover and clicked effect on button in pygtk. Do you have any ideas? I couldn't find anything useful here gtk.Button I am talking about this: Normal Hover Clicked
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: pygtk

http://stackoverflow.com/a/47385373
downvote count: 0
has body: Try with this #QTextEdit.setTextInteractionFlags (self, Qt.TextInteractionFlags flags) #QTextEdit.setText (self, QString text) textEdit.setTextInteractionFlags (QtCore.Qt.NoTextInteraction) textEdit.setText ('How to make Qtextedit text and non-selectable?')
upvote count: 9
answers question: http://stackoverflow.com/q/47384578
type: Answer
accepted answer of: http://stackoverflow.com/q/47384578
score: 9
type: AcceptedAnswer

http://stackoverflow.com/q/47512072
has comment: http://stackoverflow.com/comment/81981125
has comment: http://stackoverflow.com/comment/81980072
has comment: http://stackoverflow.com/comment/81979868
answer count: 1
has comment: http://stackoverflow.com/comment/81980164
tagged with: latitude-longitude
has body: was looking for a bit of help for my computing coursework, need to make a module to work out the distance between 2 Latlong positions using the Haversine equilibrium. Have this code so far: from math import sin, cos, sqrt, atan2, radians #Radius_Earth is the radius of the planet, I have taken this as 6373.0 approximately. Radius_Earth = 6373.0 #These are the current positions of the boat. Latitude_Boat = radians(input("Please input the latitude of the boat")) Longitude_Boat = radians(input("Please input the longitude of the boat")) Latitude_Destination = radians(input("Please input the latitude of the destination")) Longitude_Destination = radians(input("Please input the longitude of the destination")) #This is for working out the distance between the given points Longitudinal_Distance = Longitude_Destination - Longitude_Boat Latitudinal_Distance = Latitude_Destination - Latitude_Boat #This is for working out the Haversine formula. Haversine_Base = sin(Latitudinal_Distance / 2)**2 + cos(Latitude_Boat) * cos(Longitude_Destination) * sin(Longitudinal_Distance / 2)**2 Haversine_Secondary = 2 * atan2(sqrt(Haversine_Base), sqrt(1 - Haversine_Base)) Distance_Between = Radius_Earth * Haversine_Secondary print("Result:", distance) According to the thread I found it on this should work, can't find it anymore unfortunately and I can't make it work. I receive the traceback error below. Traceback (most recent call last): File "N:\LatLongTest.py", line 6, in &lt;module&gt; Latitude_Boat = radians(input("Please input the latitude of the boat")) TypeError: a float is required Can anyone offer any ideas on how to make this work? (Python 3.4.1)
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47512215
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81980037
upvote count: 0
type: UnansweredQuestion
has title: Latitude and Longitude distance calculations - Python 3.4.1
tagged with: python
score: -1

http://stackoverflow.com/a/47422313
has comment: http://stackoverflow.com/comment/81804397
score: 5
upvote count: 5
has body: You are first adding R0Cx and then R1Cxy. You need to add RxCy. So try: newlist = [] row = A col = B for x in range (0, row): newlist.append([]) for y in range(0, col): newlist[x].append('R' + str(x) + 'C' + str(y)) print(newlist)
answers question: http://stackoverflow.com/q/47422148
type: Answer
has comment: http://stackoverflow.com/comment/81800718
accepted answer of: http://stackoverflow.com/q/47422148
has comment: http://stackoverflow.com/comment/81800283
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81787295
comment on: http://stackoverflow.com/q/47416523
has text: maybe related? https://github.com/skvark/opencv-python/issues/14 at least in these bindings there is no FFmpeg support for Linux and MacOS yet.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81745574
type: QuestionComment
comment on: http://stackoverflow.com/q/47395944
score: 0
has text: provide some data to work with: X.head(20)
type: Comment

http://stackoverflow.com/q/47397872
tagged with: vector
type: UnansweredQuestion
answer count: 1
tagged with: machine-learning
tagged with: data-science
tagged with: http://stackoverflow.com/tag/r
score: 0
has answer: http://stackoverflow.com/a/47398221
has title: Using custom tokenizer in R converting text to vector?
tagged with: python
type: Question
has body: Is there any way in R so that I can convert text to vector using my own tokenizer? vectorizer = TfidfVectorizer(tokenizer=getTokens) X = vectorizer.fit_transform(corpus) Above code is written in python and getTokens is my custom tokenizer is there anyway so that I can do the same thing in R. There are some Things I want to mention like there is a library in R library(text2vec) also but I am not getting How to apply my custom Tokenizer in R Tokens=words

http://stackoverflow.com/q/47444501
has title: Parsing XML files with repeated tags that have differing data using BeautifulSoup in Python
tagged with: bigdata
answer count: 1
has body: I have been stuck on this problem for a while now but no solution. I have a snippet of my Python script that looks like so: pub_ref = soup.findAll("publication-reference") with open('./output.csv', 'ab+') as f: writer = csv.writer(f, dialect = 'excel') for info in pub_ref: pat_cite = soup.findAll("patcit") for item in pat_cite: if item.find("name"): name = item.find("name").text writer.writerow([name]) This part of the script I want to parse children of a citation child root "pacit" of the parent "publication-reference" that crops up multiple times in the XML file and looks like this: . . . <us-references-cited> US 1589850 A Haskell 19260600 cited by applicant US D134414 S Orme, Jr. 19421100 cited by applicant . . . The dots indicate that the file is larger than this and isn't showing the parent root "publication-reference". The problem is that my script only parses one of the many children of pacit, the "name" root, once through as you can tell. And this works fine for those roots that have only one entry per invention, but not multiples. I also want to store these in an CSV file, as you can see with the writer, whereby the output shows these multiple patcit citations down a column like so: invention name country city .... patcit name1 patcit date1.... white space patcit name2 patcit date2.... white space patcit name2 patcit date3.... The XML files I'm using can be found here at https://bulkdata.uspto.gov/data/patent/grant/redbook/fulltext/2017/ Any help would be appreciated as I've tried multiple ways and I feel this is a beginner's problem.
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47446167
tagged with: python
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
accepted answer: http://stackoverflow.com/a/47446167

http://stackoverflow.com/a/47475544
upvote count: 1
has comment: http://stackoverflow.com/comment/81927748
has comment: http://stackoverflow.com/comment/81959525
has comment: http://stackoverflow.com/comment/81968133
has comment: http://stackoverflow.com/comment/81926485
has body: Depending on how you've configures your apps.py from django.apps import apps for name, app in apps.app_configs.items(): if name in ['OPTIONS-N']: utils = app.module.utils
type: Answer
accepted answer of: http://stackoverflow.com/q/47475385
score: 1
answers question: http://stackoverflow.com/q/47475385
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83698620
comment on: http://stackoverflow.com/a/47483966
has text: Did I understand you correctly that this color map is calculated only for this image ? Which tool did you use to get HSV color map from image ?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47489641
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47485692
score: 2
has body: Your second-to-last line is mydata = sd.rec(int(result + result2 + result3 + result4),sampling_frequency,channels=2, blocking=True) Where you try to cast the sum of the result1 etc variables to an integer. However, they are actually numpy arrays, since time is an array. You cannot convert an array into a single integer, since it has multiple values. I'm not sure why you are trying to do that, you probably just want to remove the int(), and change it to mydata = sd.rec(result + result2 + result3 + result4, sampling_frequency, channels=2, blocking=True)
upvote count: 2

http://stackoverflow.com/q/47418227
score: 3
has comment: http://stackoverflow.com/comment/81790865
downvote count: 0
has comment: http://stackoverflow.com/comment/81790460
tagged with: pep8
answer count: 1
favorite count: 0
has title: Declaring class object with PEP 8 standard in Python (pylint error)
type: Question
has comment: http://stackoverflow.com/comment/81790446
has comment: http://stackoverflow.com/comment/81790991
has comment: http://stackoverflow.com/comment/81790687
has comment: http://stackoverflow.com/comment/81790504
type: UnansweredQuestion
tagged with: pylint
tagged with: python
has comment: http://stackoverflow.com/comment/81790521
has body: I am trying to declare an object in Python. I am using Visual Studio Code with the basic pylint setup in it. Here is a snip of some code I have. class MyLogging: """A class to initialize and run the logging commands using built in logging functions.""" def __init__(self): etc... my_can_logger = MyLogging() Pylint keeps giving me an error that my_can_logger is named incorrectly. [pylint] C0103:Invalid constant name "my_can_logger" But I don't want it to be a constant! I want it to be an object. Is there some rule that I am missing? I looked at the PEP-8 styling guide, and I seem to be following their convention pretty well. Thanks in advance
has comment: http://stackoverflow.com/comment/81790596
duplicate of: http://stackoverflow.com/q/41204932
has answer: http://stackoverflow.com/a/47418294
upvote count: 3

http://stackoverflow.com/a/47473873
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47441547
has body: Like jasonharper suggested in the comment, one way to execute traduire 1s after the user stopped writing text is to use after to schedule the execution of traduire in 1s and cancel this execution if another key is pressed, using after_cancel. This way, traduire will actually be executed only if the user has not pressed any key for 1s. My suggestion is to bind &lt;KeyRelease&gt; to the following stop_writing function: stop_writing_id = '' # store id of the scheduled call to traduire def stop_writing(event): global stop_writing_id main.after_cancel(stop_writing_id) # cancel previous scheduling of traduire stop_writing_id = main.after(1000, traduire) # wait 1s and execute traduire
score: 1

http://stackoverflow.com/q/47429981
tagged with: list
has answer: http://stackoverflow.com/a/47430105
possible better answer: http://stackoverflow.com/a/47430105
answer count: 5
score: 1
has comment: http://stackoverflow.com/comment/81864659
has answer: http://stackoverflow.com/a/47430124
tagged with: python
has comment: http://stackoverflow.com/comment/81814648
tagged with: dictionary
has title: extract specific value from dictionary of list of dictionary
has answer: http://stackoverflow.com/a/47430146
tagged with: sublist
type: Question
tagged with: extract
has body: I have dataset like this: {'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}], 'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]} what I want to extract is the name of all people: ['john','steve','jack','anna'] How to get these list using python?
downvote count: 0
has answer: http://stackoverflow.com/a/47430750
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47430083
accepted answer: http://stackoverflow.com/a/47430083
type: AnsweredQuestion

http://stackoverflow.com/q/47517199
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81990487
has body: I want to make program to calculate gas prices, but my code gets an error. from tkinter import * root = Tk() ment = StringVar() root.geometry('450x450+500+300') root.title('ბენზმთვლელი') mlabel2 = Label(root, text='რეგულარი &gt;&gt; '+2.23+ 'GEL').pack() mlabel3 = Label(root , text = 'ევრო რეგულარი &gt;&gt; '+2.29+' GEL').pack() mlabel4 = Label(root, text="პრემიუმი &gt;&gt; " + 3.35 + " GEL").pack() mlabel5 = Label(root, text='დიზელი &gt;&gt; ' + 2.25 + ' GEL').pack() mlabel6 = Label(root, text='ევრო დიზელი &gt;&gt; '+2.33+' GEL').pack() mlabel1 = Label(root, text="მიუთითეთ ბენზინის რაოდენობა(ლიტრებში)").pack() mentry1 = Entry().pack() mlabel7 = Label(root, text="მიუთითეთ ბენზინის დასახელება(ზემოთ ჩამოთვლილთაგან)").pack() mentry2 = Entry().pack() def gamotvla(): if mlabel7 == mlabel3 or mlabel2 or mlabel4 or mlabel5 or mlabel6: print(mlabel1*mlabel7) else: print('რაღაც შეიყვანე შეცდომით!!') mbutton = Button(root, text='გამოთვლა',fg="red",bg='black', command=gamotvla).pack() root.mainloop() Error: Traceback (most recent call last): File "/home/zura12337/Desktop/Python/Atom/tk.py", line 11, in &lt;module&gt; mlabel2 = Label(root, text='რეგულარი &gt;&gt; '+2.23+ 'GEL').pack() TypeError: cannot concatenate 'str' and 'float' objects Can you help me?
linked to: http://stackoverflow.com/q/2960772
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/20002503
has comment: http://stackoverflow.com/comment/81991237
tagged with: python
has comment: http://stackoverflow.com/comment/82017239
has answer: http://stackoverflow.com/a/47517336
score: -14
answer count: 2
upvote count: 0
downvote count: 14
duplicate of: http://stackoverflow.com/q/2960772
has comment: http://stackoverflow.com/comment/81991607
has title: tkinter: cannot concatenate 'str' and 'float' objects
has answer: http://stackoverflow.com/a/47520759
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81999739
has comment: http://stackoverflow.com/comment/81991102

http://stackoverflow.com/comment/81826753
score: 0
comment on: http://stackoverflow.com/q/47436008
has text: For each row with the same id_client shows the final amount of the product_a for each month so...for the client_id = 1 following the sample in the original post, for the first month he bought 1 product, in the next month he bought another one, in the 3rd month he sold 1 product and in the last month he sold another one. So client_id = 1 bought 2 times and sold 2 times and the same logic for client_id = 2. I hope I have clarified the problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47472123
has comment: http://stackoverflow.com/comment/81899744
tagged with: python
has answer: http://stackoverflow.com/a/47492146
has answer: http://stackoverflow.com/a/47474582
tagged with: matlab
linked to: http://stackoverflow.com/q/41912170
has comment: http://stackoverflow.com/comment/81900508
score: 2
upvote count: 3
has body: The algorithm in this question tells us how to efficiently sample from a multidimensional ball. Is there a way to similarly efficiently sample from a multidimensional ring , i.e. have r1&lt;r&lt;r2 I hope that a not too complex modification of that scaling function r*(gammainc(s2/2,n/2).^(1/n))./sqrt(s2) is possible. (Mediocrity disclaimer: haven't even figured the algebra/geometry for the original scaling function yet). Original matlab code copypasted: function X = randsphere(m,n,r) % This function returns an m by n array, X, in which % each of the m rows has the n Cartesian coordinates % of a random point uniformly-distributed over the % interior of an n-dimensional hypersphere with % radius r and center at the origin. The function % 'randn' is initially used to generate m sets of n % random variables with independent multivariate % normal distribution, with mean 0 and variance 1. % Then the incomplete gamma function, 'gammainc', % is used to map these points radially to fit in the % hypersphere of finite radius r with a uniform % spatial distribution. % Roger Stafford - 12/23/05 X = randn(m,n); s2 = sum(X.^2,2); X = X.*repmat(r*(gammainc(s2/2,n/2).^(1/n))./sqrt(s2),1,n); Equivalent python code with demo from Daniel's answer: import numpy as np from scipy.special import gammainc from matplotlib import pyplot as plt def sample(center,radius,n_per_sphere): r = radius ndim = center.size x = np.random.normal(size=(n_per_sphere, ndim)) ssq = np.sum(x**2,axis=1) fr = r*gammainc(ndim/2,ssq/2)**(1/ndim)/np.sqrt(ssq) frtiled = np.tile(fr.reshape(n_per_sphere,1),(1,ndim)) p = center + np.multiply(x,frtiled) return p fig1 = plt.figure(1) ax1 = fig1.gca() center = np.array([0,0]) radius = 1 p = sample(center,radius,10000) ax1.scatter(p[:,0],p[:,1],s=0.5) ax1.add_artist(plt.Circle(center,radius,fill=False,color='0.5')) ax1.set_xlim(-1.5,1.5) ax1.set_ylim(-1.5,1.5) ax1.set_aspect('equal')
linked to: http://stackoverflow.com/q/5408276
tagged with: random
answer count: 3
has comment: http://stackoverflow.com/comment/81899549
has comment: http://stackoverflow.com/comment/81899928
downvote count: 1
has answer: http://stackoverflow.com/a/47475257
favorite count: 0
has title: Sample uniformly in a multidimensional ring without rejection
type: Question
tagged with: geometry
tagged with: uniform-distribution
type: UnansweredQuestion

http://stackoverflow.com/q/47464697
has comment: http://stackoverflow.com/comment/81884217
has comment: http://stackoverflow.com/comment/81884145
has comment: http://stackoverflow.com/comment/81884362
has comment: http://stackoverflow.com/comment/81884304
tagged with: object
score: 0
has comment: http://stackoverflow.com/comment/81884151
has comment: http://stackoverflow.com/comment/81884274
has comment: http://stackoverflow.com/comment/81884327
has comment: http://stackoverflow.com/comment/81884160
has comment: http://stackoverflow.com/comment/81884419
has comment: http://stackoverflow.com/comment/81884174
has comment: http://stackoverflow.com/comment/81884142
has title: Python Method not in object error
tagged with: methods
has comment: http://stackoverflow.com/comment/81884209
downvote count: 1
has comment: http://stackoverflow.com/comment/81884190
favorite count: 0
has body: Im working on writing a method for an object and I keep getting the following error:'MagicCardSet' object has no attribute 'get_uncommon_colors'. All of my other methods work except this one so im kind of confused! Thanks! Object that creates the Magic Card Set: from collections import Counter class MagicCardSet(object): def __init__(self, DeckDict): self.cardlist = [MagicCard(eachCard) for eachCard in DeckDict["cards"]] def get_card_list(self): Card_name_list=[] for newCard in self.cardlist: Card_name_list.append(newCard.get_name()) return(Card_name_list) def get_card_color(self): color_list=[] for newCard in self.cardlist: color_list.append(newCard.get_colors()) return(color_list) def get_card_rarity(self): rarity_list=[] for newCard in self.cardlist: rarity_list.append(newCard.get_rarity()) return(rarity_list) def get_rarest_card(self): card_rarities = Counter(card.rarity for card in self.cardlist if card.rarity !="Basic Land") rarity = min(card_rarities, key=lambda card: card_rarities[card]) # Effectively an argmin card_names=[card.get_name() for card in self.cardlist if card.rarity == rarity] card_colors=[card.get_colors() for card in self.cardlist if card.rarity == rarity] return (list(zip(card_names,card_colors))) def get_uncommon_colors(self): uncommon_list=[] for newCard in self.cardlist: if newCard.get_rarity()=="Uncommon": uncommon_list.append(newCard.get_colors()) return(uncommon_list) call: DTK_Set=MagicCardSet(DTK_information) DTK_Set.get_uncommon_colors() Opening and storing JSON file import json with open('DTK.json',encoding="utf-8") as data_file: DTK_information = json.loads(data_file.read()) Whats in the JSON file: { "name" : "Sen Triplets", "manaCost" : "{2}{W}{U}{B}", "cmc" : 5, "colors" : ["White", "Blue", "Black"], "type" : "Legendary Artifact Creature — Human Wizard", "supertypes" : ["Legendary"], "types" : ["Artifact", "Creature"], "subtypes" : ["Human", "Wizard"], "rarity" : "Mythic Rare", } Trace Error (Hopefully this helps a little more): …
type: Question
has comment: http://stackoverflow.com/comment/81884214
has comment: http://stackoverflow.com/comment/81884286
answer count: 0
has comment: http://stackoverflow.com/comment/81884361
has comment: http://stackoverflow.com/comment/81884276
has comment: http://stackoverflow.com/comment/81884262
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81884288
has comment: http://stackoverflow.com/comment/81884210
has comment: http://stackoverflow.com/comment/81884205
has comment: http://stackoverflow.com/comment/81884348
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/81888883
type: Comment
type: QuestionComment
has text: yes ur right, it should change from 3 to 1, slight typo sorry about that. And my question is how to fix the swapping algorithm as i am unable to get the final output
comment on: http://stackoverflow.com/q/47467189
score: 0

http://stackoverflow.com/comment/81863848
has text: I have removed np.savetxt outside the loop but remain the same. I guess the mistake must have been somewhere during declaration of rain=[lat,lon,rain] or may be another loop need to be imposed before it..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47452993
score: 0

http://stackoverflow.com/comment/81991237
has text: Why are you adding a number to a string? What do you think that is supposed to do?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47517199

http://stackoverflow.com/q/47406911
answer count: 4
has title: Python: Continue if variable is an 'int' and has length >= 5
has body: I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working: while True: stringset = raw_input("Enter number: ") if len(stringset)&gt;=5 and isinstance(stringset, (int, long)): break else: print "Re-enter number: " If anyone has a solution, I'd appreciate it. Thanks
has answer: http://stackoverflow.com/a/47408523
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47407105
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81767067
has answer: http://stackoverflow.com/a/47407158
has comment: http://stackoverflow.com/comment/81767354
favorite count: 0
has comment: http://stackoverflow.com/comment/81767139
type: Question
has answer: http://stackoverflow.com/a/47407083
possible better answer: http://stackoverflow.com/a/47407105
accepted answer: http://stackoverflow.com/a/47407083
has comment: http://stackoverflow.com/comment/81767117
tagged with: python

http://stackoverflow.com/comment/81795692
type: Comment
score: 0
type: AnswerComment
has text: Seemed pretty reasonable to me. Unfortunately, when I tested this out my Raspberry Pi completely stalled, so I had to unplug it. Turned it back on and going to see what happened.
comment on: http://stackoverflow.com/a/47420592

http://stackoverflow.com/q/47454144
has comment: http://stackoverflow.com/comment/81863429
has comment: http://stackoverflow.com/comment/81889746
has body: I want to implement cutting plane method in python using an built in improve lementation of simplex method and then applying cutting plane method on top of it (using scipy.linprog or pulp to implement Simplex method to get the feasible solution) The issue is that simplex solution that displays all equations and tableau is needed so that I can then solve for extra constraints for cutting plane method. However, Linprog only gives me solution for optimal values of x and slack variables and it doesn't give me the whole set of equations (tableau) on which I can select an equation with non-integer and then apply the cut. Is there a way wherein I can use an inbuilt simplex method in Python and then implement cutting plane on it on my own? (I don't want to implement integer constraints in pulp to just get integer soltion, I want to implement cutting plane on top of simplex table on my own). many thanks for your help!
upvote count: 1
has comment: http://stackoverflow.com/comment/81894554
downvote count: 1
has comment: http://stackoverflow.com/comment/81865983
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81873072
type: UnansweredQuestion
tagged with: python
tagged with: linear-programming
tagged with: mixed-integer-programming
score: 0
has comment: http://stackoverflow.com/comment/81916095
has title: Cutting plane method: using python
tagged with: mathematical-optimization
tagged with: simplex
answer count: 0

http://stackoverflow.com/a/47458856
has comment: http://stackoverflow.com/comment/81872416
answers question: http://stackoverflow.com/q/47458099
has comment: http://stackoverflow.com/comment/81872886
has comment: http://stackoverflow.com/comment/81872563
has comment: http://stackoverflow.com/comment/81872689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81872456
downvote count: 0
has body: Code Option 1 See regex in use here (?&lt;=[^\s\d])\d(?:[^a-zA-Z]*\d)? Option 2 Note: This option uses the i flag (case-insensitive) See regex in use here (?&lt;=[a-z)])\d(?:[^a-z]*\d)? This allows number lists in sentences. What I would suggest, if that's the case, however, is to use the following regex and add any additional characters in the list [)] (in the second positive lookbehind) to ensure special characters are preceded by a letter. See regex in use here (?:(?&lt;=[a-z])|(?&lt;=[a-z][)]))\d(?:[^a-z]*\d)? Results Input Although the same genomic DNA is packaged in the nucleus of each cell, different sets of genes are expressed in different cell states1,2. Despite significant progress over the past decade, there are still many unanswered questions about how the genome is organized within the nucleus and how this changes across different cell states3–7. About 20% of these facts are true. In this view, genome organization is largely organized around chromosome territories, such that most DNA interactions occur within an individual chromosome10,20–22. These interactions include chromatin loops that connect specific genomic DNA regions such as enhancers and promoters23–25, local interacting neighborhoods of DNA called topologically associated domains (TADs)26–28, and compartments where DNA regions interact based on their transcriptional activity (A/B compartments)5,9,29,30. However, the extent to which DNA interactions occur between chromosomes has been controversial9,10,20,24, 31,32. The second view is primarily derived from in situ imaging of DNA, RNA, and protein in the nucleus using microscopy. In this view, the genome is also organized around structures such as nuclear bodies that typically concentrate DNA, RNA, and protein molecules that are associated with shared functional or regulatory roles within the nucleus33–37. These include nuclear bodies associated with ribosomal RNA transcription, processing, and biogenesis (nucleolus)16,33,38, .... These observa…
accepted answer of: http://stackoverflow.com/q/47458099
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81872639
has comment: http://stackoverflow.com/comment/81872501

http://stackoverflow.com/comment/81866682
comment on: http://stackoverflow.com/q/47456070
type: Comment
type: QuestionComment
score: 0
has text: @Did you run you code on Python 3.6?

http://stackoverflow.com/comment/81909718
comment on: http://stackoverflow.com/q/47477336
type: QuestionComment
has text: multiply W(7X15) by X(268X7), you will get a matrix 268X15 and then add all the elements along each column, you will get a row vector of length 15.
score: 1
type: Comment

http://stackoverflow.com/comment/81997067
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47518830
has text: @SuperStew that doesn't follow at all. the expression `my_list[<some slice>] = <something else>` **never creates an intermediate list**. Instead, it passes `<some slice>` as an argument to `my_list.__setitem__`. It is simply incorrect to state that a `list` is returned.
type: Comment

http://stackoverflow.com/comment/81868052
type: Comment
comment on: http://stackoverflow.com/a/47456679
type: AnswerComment
score: 1
has text: @Chris_Rands Yes it runs at C-speed, but not entirely since callbacks are made to Python, to repeat the loop until completion. Besides, the repeated assignment is just extra overhead.

http://stackoverflow.com/q/47413977
has comment: http://stackoverflow.com/comment/81782303
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/81782328
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/81781977
answer count: 1
has comment: http://stackoverflow.com/comment/81781801
has title: Django web app that detects a smart-phone user's position
favorite count: 0
has body: I want to build a web app using Django-Python that will be mainly used from smart-phones. I want the app to be able to detect the user's position and showcase it into a google maps front end. Basically, I want the app to be something like google maps GPS and then I will make some calculations with the coordinates and print out to the user some alternatives. I want the user's coordinates to be updated when he walks for example. Do you have any suggestions about what modules, libraries or packages can I use to get this done? I found some packages like djangocms-gmaps but I am not sure if this is the right way to go.
type: Question
has answer: http://stackoverflow.com/a/47414446
type: UnansweredQuestion
upvote count: 1
tagged with: django
tagged with: javascript
tagged with: python

http://stackoverflow.com/comment/81828763
has text: @OptimusPrime - I try edit answer, what do you think?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47436889
score: 0

http://stackoverflow.com/comment/81802162
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47423199
has text: Thanks, but I add this " if(album['name'] == 'Ed+Sheeran'): continue " before "title = album['name']" to test but appears the same issue.

http://stackoverflow.com/comment/81903392
has text: @Ev.Kounis Expressing what I want is easy, but still I have problems to get my head around in python about sorting and grouping and filtering etc. And again I'm stuck right now ... will make a new question here :D
comment on: http://stackoverflow.com/a/47469789
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82038836
has text: edited again above
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47540609
type: Comment

http://stackoverflow.com/q/47432491
score: 9
tagged with: data-visualization
answer count: 0
downvote count: 0
tagged with: python
type: UnansweredQuestion
has body: I am plotting an hourly update of the devices on different maps. To animate and analyze the update I'm displaying a new plot at each iteration by clearing out the output of the cell in jupyter. map_ = [[] for i in range(max(dfByDeviceidHourly['hour'])+1)] for hour in dfByDeviceidHourly['hour'].unique(): df_map = dfByDeviceidHourly[dfByDeviceidHourly['hour'] == hour] map_[hour] = folium.Map(location=list(df_map'geocoordinates_latitude','geocoordinates_longitude'.mean()), zoom_start=13) for i,mark in enumerate(df_map): folium.Marker(list(df_map'geocoordinates_latitude','geocoordinates_longitude'.iloc[i]), popup='The Waterfront').add_to( map_[hour] ) clear_output(wait = True) display(map_[hour]) time.sleep(4) Is there a way in which I can make a video or gif out of the above? I found one method (here: https://github.com/python-visualization/folium/issues/35) which involves saving the images as html, converting them into png, creating a gif out of them and then rendering it on the notebook. Though I'm looking for a more robust alternative for it.
tagged with: animated-gif
tagged with: leaflet
tagged with: folium
has title: python folium: make a gif from maps
favorite count: 0
type: Question
upvote count: 9

http://stackoverflow.com/q/47474155
upvote count: 1
has comment: http://stackoverflow.com/comment/81902879
accepted answer: http://stackoverflow.com/a/47490190
favorite count: 0
has answer: http://stackoverflow.com/a/47490190
type: Question
has comment: http://stackoverflow.com/comment/81919394
has body: I wrote a program to read images using Python's opencv and tried to load 3 GB images, but the program aborted. There is 32 GB of memory on my PC, but when I run this program it will run out of it. What is the cause? The error message is not issued and the PC becomes abnormally heavy. I confirmed it with Ubuntu's System Monitor, and it ran out of memory and swap. I import images into one array to pass to tensorflow deep learning program. The size of the images are 200 x 200 color images. I use 64 bit version of Python. import os import numpy as np import cv2 IMG_SIZE = 200 def read_images(path): dirnames = sorted(os.listdir(path)) files = [sorted(os.listdir(path+dirnames[i]))\ for i in range(len(dirnames))] i = 0 images = [] for fs in files: tmp_images = [] for f in fs: img = cv2.imread(path +dirnames[i] + "/" + f) img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) img = img.flatten().astype(np.float32)/255.0 tmp_images.append(img) i = i + 1 images.append(tmp_images) return np.asarray(images)
tagged with: opencv
has comment: http://stackoverflow.com/comment/81904850
has title: What is causing my Python program to run out of memory using opencv?
has comment: http://stackoverflow.com/comment/81918052
tagged with: python
tagged with: memory
tagged with: image
has comment: http://stackoverflow.com/comment/81918244
has comment: http://stackoverflow.com/comment/81904647
type: AnsweredQuestion
tagged with: numpy
has comment: http://stackoverflow.com/comment/81902831
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82023380
has text: what I am trying to achieve is to see if the code can fetch some URL from one page and then go into each individual URL and fetch more URLs inside the earlier found list of URLs. I will probably achieve this if I have a simple webpage with some HTTP hyperlinks which then will give me further URLs and stop there. I tried with https://xkcd.com/353/.
comment on: http://stackoverflow.com/q/47532722
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47471324
tagged with: geodjango
answer count: 1
has body: I am working on an application, where I have shapefiles (.shp). I have read those shapes into my PostgreSQL database and I can show those shape coordinates over Google Map. Now I'm having a use-case, I need to divide these LGA (Local Governance Area) into sub area (like divide an LGA into 10km2 sub-area). Does anyone have any idea how can I do this using Python/Django/GeoDjango?
has title: Divide multipolygon Area into subarea
type: Question
linked to: http://stackoverflow.com/q/46689979
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/81904436
tagged with: python
tagged with: postgis
tagged with: postgresql
score: 0
has answer: http://stackoverflow.com/a/47474740

http://stackoverflow.com/comment/81993232
score: 0
has text: @juanpa.arrivillaga updated the answer with a new approach.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47518335

http://stackoverflow.com/comment/81839103
score: 0
has text: @mnickey carefully evaluate each solution. Dismissing a solution because it “isn’t simple” may not be the best mindset to have. ;) see my answer for a timings comparison, and if you still want to apply a series after, that’s up to you.
type: Comment
comment on: http://stackoverflow.com/a/47441756
type: AnswerComment

http://stackoverflow.com/a/47416288
type: Answer
accepted answer of: http://stackoverflow.com/q/47415989
has body: You can do something like the following. def query(params): # Make sure it's hardcoded and malicious user can't overwrite it param_whitelist = 'id', 'param1' sql = ''' SELECT * FROM sample WHERE {placeholders} ''' placeholders = ' AND '.join( '`{field}` {op} %s'.format(field=k, op='IS' if params[k] is None else '=') for k in param_whitelist) sql = sql.format(placeholders=placeholders) cursor.execute(sql, params) return cursor data = {'id': 15, 'param1': None} print([r for r in query(data)])
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47415989
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81788750

http://stackoverflow.com/comment/81952369
has text: Oh i see!! What i told you is for the sites in which captcha appears once.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47496680
type: Comment

http://stackoverflow.com/a/47749082
accepted answer of: http://stackoverflow.com/q/47513622
type: AcceptedAnswer
downvote count: 0
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47513622
type: Answer
has body: I realized that I have to remove that output clause and have found the recommended solution to use : __table_args__ = {'implicit_returning':False} when creating the class for the Proposal table.

http://stackoverflow.com/comment/81781645
has text: `' '.join()` will create a string.
comment on: http://stackoverflow.com/q/47414063
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81869890
comment on: http://stackoverflow.com/q/47457279
type: Comment
type: QuestionComment
has text: your static folder called base??
score: 0

http://stackoverflow.com/q/47389447
favorite count: 0
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/47389566
answer count: 4
score: 28
has answer: http://stackoverflow.com/a/66248758
possible better answer: http://stackoverflow.com/a/66248758
type: Question
tagged with: numpy
has title: How convert a list of tuples to a numpy array of tuples?
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/47389566
has answer: http://stackoverflow.com/a/78000075
has body: I have a list like this: l=[(1,2),(3,4)] I want to convert it to a numpy array,and keep array item type as tuple: array([(1,2),(3,4)]) but numpy.array(l) will give: array([[1,2],[3,4)]]) and item type has been changed from tuple to numpy.ndarray,then I specified item types numpy.array(l,numpy.dtype('float,float')) this gives: array([(1,2),(3,4)]) but item type isn't tuple but numpy.void,so question is: how to convert it to a numpy.array of tuple,not of numpy.void?
tagged with: python
has answer: http://stackoverflow.com/a/74827541
upvote count: 28

http://stackoverflow.com/q/47400336
score: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81760363
tagged with: pymongo
downvote count: 0
has body: Currently I have a list of items like so: list_Of_Packages = ['windows', 'python', ...] t = r'.*|.*'.join(list_Of_Packages) r = re.compile(t) From this I am getting the error sre_constant.error: Multiple repeat Why am I getting this error, and what is the best practice approach for querying a large number of values in a Mongo database with Regexes? Thanks for any help.
favorite count: 0
type: Question
has title: Using re.compile with a list of variables to get a value using PyMongo
has comment: http://stackoverflow.com/comment/81754260
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81754336
tagged with: mongodb
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/81998816
has text: It sounds to me like you have a `min_max` value that doesn't have a `/` in it, which is causing it to run into trouble when attempting to reference the values in the `minMax` array from the `.split('/')` call. You will need to check to make sure that `len(minMax) == 2` before attempting to add it to the result - and if it is not, add in code that does what you want to do in that case.
comment on: http://stackoverflow.com/a/47518564
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47460240
tagged with: python
tagged with: http://stackoverflow.com/tag/c
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81875158
has title: Space efficient file type to store double precision floats
upvote count: 2
tagged with: numerical-methods
has comment: http://stackoverflow.com/comment/81875067
downvote count: 0
has body: I am currently running Simulations written in C later analyzing the results using Python scripts. ATM the C Programm is writing the results (lots of double values) in a text file which is slowly but surely eating a lot of disc space. Is there a file format which is more space efficient to store lots of numeric values? At best but not necessarily it should fulfill the following requirements Values can be appended continuously such that not all values have to be in memory at once. The file is more or less easily readable using Python. I feel like this should be a really common question, but looking for an answer I only found descriptions of various data types within C.
accepted answer: http://stackoverflow.com/a/47460725
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/81875230
has answer: http://stackoverflow.com/a/47460725
answer count: 1

http://stackoverflow.com/comment/81909534
type: Comment
has text: @tobias_k looking at the declaration, calling `re.search` simply does `return _compile(pattern, flags).search(string)`. There's no check if the pattern is already compiled.
comment on: http://stackoverflow.com/q/47477347
score: 1
type: QuestionComment

http://stackoverflow.com/q/47515714
upvote count: 1
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: ldap
type: Question
type: UnansweredQuestion
tagged with: python
has body: I'm doing some python work on a flask app that's sitting behind apache. Kerberos is used for authentication so that's relatively simple to set up - just a few apache directives. But there doesn't seem to be an easy way to authorise with apache so we're using LDAP in the python code to authenticate - also relatively simple to set up. The only problem that I'm having is getting the credentials from apache/Kerberos onto the python side of things. Is there any simple way to get this to work that works with python3? Note that the python-krbV module only seems to work with Python2 and there are no plans at the moment for that library to be ported over to Python3.
tagged with: kerberos
has title: How to pass a kerberos username to a flask app from apache
tagged with: apache
answer count: 0
downvote count: 0

http://stackoverflow.com/q/47447906
has comment: http://stackoverflow.com/comment/81851045
accepted answer: http://stackoverflow.com/a/47448037
has comment: http://stackoverflow.com/comment/81851092
linked to: http://stackoverflow.com/q/47441197
linked to: http://stackoverflow.com/q/47463593
answer count: 1
downvote count: 0
has title: Dumping to JSON file not working properly in class/function
upvote count: 1
has comment: http://stackoverflow.com/comment/81851042
linked to: http://stackoverflow.com/q/47444585
favorite count: 0
has comment: http://stackoverflow.com/comment/81850978
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81851065
has body: I am trying to transfer a dictionary from python using a function/class. I have already made a simple transfer, more information about it here and here. So far I have the following functioning code which simply transfers the data dictionary from Python to PHP: Python (Basic Script) (Must run first for PHP to work) import sys, json, random data = {'form_type':'default'} with open('data.json', 'w') as outfile: json.dump(data, outfile) PHP (Basic Script) <?php $string = file_get_contents("data.json"); $json_a = json_decode($string, true); echo $json_a['form_type']; ?> Python (Main Script) I have implemented this into my main PHP page, which works fine with the simple Python script. However, the advanced python script with lots of unrelated code is not functioning. These are the first lines of that code: import dill import random import sys import os import json restart = 'yes' user_action = 'inventory' pickle = 'rpg.pickle' restart = sys.argv[1] user_action = sys.argv[2] pickle = sys.argv[3] + ".pickle" if restart == "no" and os.path.isfile(pickle) == False: restart = "yes" data = {'form_type':'potato'} with open('data.json', 'w') as outfile: json.dump(data, outfile) # Lots of more code afterward This code completely crashes when run by PHP, and the JSON file is not edited and no output is received by PHP. Any ideas why this is or is more information needed to answer this question?
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47448037
tagged with: python
has comment: http://stackoverflow.com/comment/81850977
tagged with: php
type: Question

http://stackoverflow.com/comment/81892434
score: 0
type: Comment
has text: Thank you for all the effort of trying to understand the issue, but I think I cannot explain it any better. Not via comments anyway. But the issue is resolved right now (see my own answer), so I think it is best to save further energy. Thank you anyways :)
type: AnswerComment
comment on: http://stackoverflow.com/a/47418827

http://stackoverflow.com/a/47440749
score: 3
answers question: http://stackoverflow.com/q/47440662
type: Answer
has body: if context is not None is comparing the object reference to 'None', not checking if the object itself is empty. This post may help you understand it better.
upvote count: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47440662
has comment: http://stackoverflow.com/comment/81837985

http://stackoverflow.com/comment/81804994
type: QuestionComment
type: Comment
has text: Well looks like the problem is not how to use shutil, but that you don't have permission... Can you do the copy manually?
comment on: http://stackoverflow.com/q/47425001
score: 0

http://stackoverflow.com/a/47397608
accepted answer of: http://stackoverflow.com/q/47385700
answers question: http://stackoverflow.com/q/47385700
has comment: http://stackoverflow.com/comment/81762015
has body: The problem is that you're feeding your network a string sequence. Double check the dtype of your input data and be absolutely sure that its a numpy array with float numbers inside it.
type: Answer
has comment: http://stackoverflow.com/comment/81760110
has comment: http://stackoverflow.com/comment/81796041
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47391497
tagged with: python
has comment: http://stackoverflow.com/comment/81736802
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has title: Rotate textured mesh object or rotate camera around 3D textured object in Python
has body: I'm trying to load a .obj file corresponding to a textured mesh, rotate it in different angles and take a snapshot of it, in Python. Thank you
has comment: http://stackoverflow.com/comment/81739191

http://stackoverflow.com/comment/81881247
comment on: http://stackoverflow.com/q/47463145
type: Comment
type: QuestionComment
has text: What's your expected output?
score: 0

http://stackoverflow.com/q/47422946
has answer: http://stackoverflow.com/a/47423373
tagged with: pandas
has title: Pivot table returns a key error in Pandas
answer count: 1
has body: I have a dataframe called performanceData that looks like: id settle_price settle_price_acc pos trade \ date 2016-01-04 BBG.XTKS.9716.S 14.096973 14.096973 8100.0 -1700.0 2016-01-04 BBG.XTKS.9065.S 4.460498 4.460498 4000.0 20000.0 2016-01-04 BBG.XTKS.7966.S 17.599029 17.599029 -500.0 27700.0 2016-01-04 BBG.XTKS.3774.S 19.514999 19.514999 0.0 200.0 2016-01-04 BBG.XTKS.5110.S 15.143828 15.143828 -200.0 0.0 nominal_posn_size abs_nominal_posn_size abs_nominal_trade_size date 2016-01-04 114185.481138 114185.481138 23964.854066 2016-01-04 17841.990960 17841.990960 89209.954800 2016-01-04 -8799.514730 8799.514730 487493.116042 2016-01-04 0.000000 0.000000 3902.999806 2016-01-04 -3028.765682 3028.765682 0.000000 The dataframe is large and has dates for the last 10 years (above is the head). I am trying to create a pivot table on date (for example summing all of the abs_nominal_trade_size values for each date. However I get a key error KeyError: 'date' When I try and pivot on the date using the following code: e = performanceData.pivot_table(index='date', columns=['abs_nominal_trade_size','abs_nominal_posn_size','nominal_posn_size'], values='Value')
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81800535
score: 0

http://stackoverflow.com/comment/81814804
has text: Can you share your code trials?
score: 0
comment on: http://stackoverflow.com/q/47429496
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81910657
type: Comment
comment on: http://stackoverflow.com/a/47477898
type: AnswerComment
score: 0
has text: I would suggest to use `numpy.where` on the first step `df["temp"] = np.where(df["memo"]=="neg", -df["amount"], df["amount"])`

http://stackoverflow.com/comment/81754096
has text: `grep` will read the start of the file every time. Not very efficient when you reach letter `Z`.
score: 0
comment on: http://stackoverflow.com/q/47400218
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81987819
comment on: http://stackoverflow.com/a/47515211
score: 0
type: Comment
has text: Okay so, when I fetch the data from the database it gives me multiple tuples. How would I then insert each element of this tuple into the tree view. (sorry to bother you again)
type: AnswerComment

http://stackoverflow.com/a/47402041
has comment: http://stackoverflow.com/comment/81758231
has comment: http://stackoverflow.com/comment/81758374
score: 1
type: Answer
has body: Use str.extract + merge: df1 Col 0 test1(arizona) 1 NJtest2 df2 keyword Label 0 test1 First Cycle Test 1 test2 Second Cycle Test p = '(?P&lt;Key&gt;.*(?P&lt;keyword&gt;{}).*)'.format('|'.join(df2.keyword)) df1.Col.str.extract(p, expand=True)\ .merge(df2).drop('keyword', 1) Key Label 0 test1(arizona) First Cycle Test 1 NJtest2 Second Cycle Test The regex pattern extracts the keyword as well as the complete string, which makes the merge painless.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47401961
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47401961
has comment: http://stackoverflow.com/comment/81765527

http://stackoverflow.com/comment/81866543
type: Comment
has text: Do you mean pull from another database's table? multi databases ?
score: 0
comment on: http://stackoverflow.com/q/47454771
type: QuestionComment

http://stackoverflow.com/comment/81927656
comment on: http://stackoverflow.com/a/47412501
type: Comment
has text: You need more data. And first try training your model with some of the basic classes like dogs/cats, and see if it works. https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition. In there you will find people discussing and uploading good working kernels. So you will get a good idea of what's going wrong
score: 0
type: AnswerComment

http://stackoverflow.com/a/47458723
answers question: http://stackoverflow.com/q/47458172
has comment: http://stackoverflow.com/comment/81873321
has comment: http://stackoverflow.com/comment/90842592
score: 1
downvote count: 0
has body: Your error happens because you installed virtualenv for Python 2.7, but you try use it with Python 3. Use pip3 to install Python 3 packages on multi-version system. pip uninstall virtualenvwrapper pip3 install virtualenv virtualenvwrapper
upvote count: 1
type: Answer

http://stackoverflow.com/q/47518068
has body: In Python 3, I should be able to use super() in a class method as a substitute for the parent class: class demodict(OrderedDict): def __setitem__(self, key, val): print(key) super().__setitem__(self, key, val) The above behaves as expected when I instantiate a demodict() and add values to it. But if I use it as the data type for a ConfigParser object, something goes wrong: &gt;&gt;&gt; Config = configparser.ConfigParser(dict_type=demodict) Traceback (most recent call last): File "&lt;pyshell#15&gt;", line 1, in &lt;module&gt; conf = configparser.ConfigParser(dict_type=demodict) File ".../anaconda/lib/python3.4/configparser.py", line 588, in __init__ self._proxies[default_section] = SectionProxy(self, default_section) File "&lt;pyshell#14&gt;", line 5, in __setitem__ super().__setitem__(self, key, val) File ".../anaconda/lib/python3.4/collections/__init__.py", line 67, in __setitem__ if key not in self: TypeError: unhashable type: 'demodict' If I replace OrderedDict with plain dict as the parent class, the error gets even weirder: Traceback (most recent call last): File "&lt;pyshell#9&gt;", line 1, in &lt;module&gt; conf = configparser.ConfigParser(dict_type=demodict) File ".../anaconda/lib/python3.4/configparser.py", line 588, in __init__ self._proxies[default_section] = SectionProxy(self, default_section) File "&lt;pyshell#7&gt;", line 6, in __setitem__ super().__setitem__(self, key, val) TypeError: expected 2 arguments, got 3 If instead of super() I write OrderedDict or dict explicitly, I can use demodict as the dict_type with no problems. Can someone explain what is going on? (Since there is an easy work-around, I'm more curious about the cause than about the solution...)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81992259
has comment: http://stackoverflow.com/comment/81993789
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/47518174
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/81992511
has title: Why can't I use super() in a configparser constructor?
has comment: http://stackoverflow.com/comment/81992401
has comment: http://stackoverflow.com/comment/81993802
answer count: 1
tagged with: configparser
linked to: http://stackoverflow.com/q/39478747
favorite count: 0
type: Question

http://stackoverflow.com/comment/81849466
has text: Hi Wen. I have attached the dataframe head values in excel sheet
score: 0
comment on: http://stackoverflow.com/q/47446929
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47399311
answers question: http://stackoverflow.com/q/47399116
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47399116
upvote count: 2
score: 2
has body: You may change the location of the legend via the _set_loc() method. Possible locations are numbers from 0 to 10, which denote the edges of the axes. g = sns.jointplot(...) g.ax_joint.get_legend()._set_loc(4) E.g. loc=4 is the lower right corner. The upper left corner would be loc=2 [Image taken from this answer]
downvote count: 0

http://stackoverflow.com/q/47391774
has comment: http://stackoverflow.com/comment/81737351
has comment: http://stackoverflow.com/comment/81736878
has comment: http://stackoverflow.com/comment/81736436
has answer: http://stackoverflow.com/a/67197220
linked to: http://stackoverflow.com/q/17667903
tagged with: sockets
has comment: http://stackoverflow.com/comment/81736693
tagged with: python
has body: I have searched a lot on the Internet, but I haven't been able to find the solution to send an object over the socket and receive it as is. I know it needs pickling which I have already done. And that converts it to bytes and is received on the other hand. But how can I convert those bytes to that type of object? process_time_data = (current_process_start_time, current_process_end_time) prepared_process_data = self.prepare_data_to_send(process_time_data) data_string = io.StringIO(prepared_process_data) data_string = pack('>I', len(data_string)) + data_string self.send_to_server(data_string) This is the code which is converting the object to StringIO on the client and sending to the server. And on the server side I am getting bytes. Now I am searching for bytes to be converted to StringIO again so that I can get the object value. In the code, Object is wrapped in StringIO and is being sent over the socket. Is there a better approach? The server-side code is as follows. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #server.setblocking(0) server.bind(('127.0.0.1', 50000)) server.listen(5) inputs = [server] outputs = [] message_queues = {} while inputs: readable, writeable, exceptional = select.select(inputs, outputs, inputs) for s in readable: if s is server: connection, client_address = s.accept() print(client_address) connection.setblocking(0) inputs.append(connection) message_queues[connection] = queue.Queue() print('server started...') else: print('Getting data step 1') raw_msglen = s.recv(4) msglen = unpack('>I', raw_msglen)[0] final_data = b'' while len(final_data) < msglen: data = s.recv(msglen - len(final_data)) if data: #print(data) final_data += data message_queues[s].put(data) if s not in outputs: outputs.append(s) else: if s in outputs: outputs.remove(s) else: break inputs.remove(connection) #s.close() del message_queues[s] process_data = ProcessData() process_screen = ProcessScreen()…
has answer: http://stackoverflow.com/a/47396267
upvote count: 13
has comment: http://stackoverflow.com/comment/81742918
downvote count: 6
has answer: http://stackoverflow.com/a/74515975
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/81743436
has comment: http://stackoverflow.com/comment/81736610
score: 7
has comment: http://stackoverflow.com/comment/81737798
has comment: http://stackoverflow.com/comment/81742771
has comment: http://stackoverflow.com/comment/81738328
accepted answer: http://stackoverflow.com/a/47396267
linked to: http://stackoverflow.com/q/24423162
has comment: http://stackoverflow.com/comment/81737079
possible better answer: http://stackoverflow.com/a/74515975
favorite count: 0
tagged with: marshalling
has comment: http://stackoverflow.com/comment/81737255
type: Question
tagged with: serialization
has title: Send and receive objects through sockets in Python
linked to: http://stackoverflow.com/q/17003109

http://stackoverflow.com/comment/81920291
comment on: http://stackoverflow.com/q/47482708
score: 0
type: QuestionComment
has text: try using pip install -e "Path where you downloaded locally"
type: Comment

http://stackoverflow.com/comment/82008156
score: 0
comment on: http://stackoverflow.com/q/47526059
has text: And index values are duplicated? `print (df.index.has_duplicates)` ?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47458521
possible better answer: http://stackoverflow.com/a/47459527
answer count: 2
has answer: http://stackoverflow.com/a/47459038
tagged with: deep-learning
tagged with: matrix
has answer: http://stackoverflow.com/a/47459527
has comment: http://stackoverflow.com/comment/81871876
downvote count: 0
has body: I'm trying to implement fprop for MaxPooling layer in Conv Networks with no overlapping and pooling regions 2x2. To do so, I need to split my input matrix into matrices of size 2x2 so that I can extract the maximum. I am then creating a mask which I can use later on in bprop. To carry out the splitting I am splitting my input matrix first vertically and then horizontally and then finding the maximum using vsplit, hsplit and amax respectively. This keeps crashing however with index out of bounds exceptions and I am not sure where the error is. Is there a simpler way to split the 24 x 24 input matrix into 144 2x2 matrices so that I can obtain the maximum. I am doing the following to do so: for i in range(inputs.shape[0]): for j in range(inputs.shape[1]): for k in range(inputs.shape[2] // 2): for h in range(inputs.shape[3] // 2): outputs[i,j,k,h] = np.amax(np.hsplit(np.vsplit(inputs[i,j], inputs.shape[2] // 2)[k], inputs.shape[1] // 2)[h]) max_ind = np.argmax(np.hsplit(np.vsplit(inputs[i,j], inputs.shape[2] // 2)[k], inputs.shape[1] // 2)[h]) max_ind_y = max_ind // inputs.shape[2] if (max_ind_y == 0): max_ind_x = max_ind else: max_ind_x = max_ind % inputs.shape[3] self.mask[i,j,max_ind_y + 2 * k, max_ind_x + 2 * h] = outputs[i,j,k,h] EDIT: This is the output produced by reshape: What I would like instead is [0 1 4 5] [2 3 6 7] and so on...
favorite count: 0
accepted answer: http://stackoverflow.com/a/47459038
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/16856788
upvote count: 2
has title: Divide matrix into square 2x2 submatrices - maxpooling fprop
has comment: http://stackoverflow.com/comment/81872222
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/81872151
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/47524358
has answer: http://stackoverflow.com/a/47524948
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
answer count: 3
has body: How do I place the QUIT button in below code to the extreme right of the Frame? I tried several things like: padx and self.pack(side="top", anchor="e") but after trying some 15 times both buttons are coming close to each other. Maybe Some help from anyone would be really appreciated. I need one button on extreme right and other on extreme left import tkinter as tk from tkinter.ttk import * class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() self.master.title("Log Parser") def createWidgets(self): self.Run_Main = tk.Button(self) self.Run_Main["text"] = "Browse.." # self.Run_Main["fg"] = "blue" self.Run_Main["command"] = self.Sayhello self.Run_Main.pack(side='left') self.Label = tk.Label(self) self.Label["text"] = 'Processing...' self.progressbar = Progressbar(mode="indeterminate", maximum=20) self.QUIT = tk.Button(self) self.QUIT["text"] = "Quit!" self.QUIT["command"] = self.quit self.QUIT.pack(anchor='e') self.pack(side="top", anchor="w") def Sayhello(self): print("Hello") # scroll text inside application frame class scrollTxtArea: def __init__(self, root): frame = tk.Frame(root) frame.pack() self.textPad(frame) return def textPad(self, frame): # add a frame and put a text area into it textPad = tk.Frame(frame) self.text = tk.Text(textPad, height=18, width=60) self.text.config() # add a vertical scroll bar to the text area scroll = tk.Scrollbar(textPad) self.text.configure(yscrollcommand=scroll.set,background="black", foreground="green") # pack everything self.text.pack(side=tk.LEFT, pady=2) scroll.pack(side=tk.RIGHT, fill=tk.Y) textPad.pack(side=tk.TOP) return root = tk.Tk() root.resizable(width=False, height=False) root.option_add('*font', ('verdana', 9, 'bold')) app = Application(master=root) scrollFrame = scrollTxtArea(root) app.mainloop()
linked to: http://stackoverflow.com/q/28089942
score: 1
downvote count: 0
upvote count: 1
has title: Python-Tkinter Place button on left of frame
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47524984
has answer: http://stackoverflow.com/a/47524984
possible better answer: http://stackoverflow.com/a/47524948
has answer: http://stackoverflow.com/a/47532120

http://stackoverflow.com/comment/129714548
comment on: http://stackoverflow.com/a/47518380
score: 0
type: Comment
has text: This doesn't work for me. Dask version 2022.8.0 and Python version 3.8.10
type: AnswerComment

http://stackoverflow.com/comment/81945777
score: 0
has text: @Kad what do you mean?! the duplicate addresses exactly how to get from what you've got now to what you want to have in the end!
comment on: http://stackoverflow.com/q/47495263
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81907789
type: QuestionComment
comment on: http://stackoverflow.com/q/47473479
score: 0
has text: @zaph i know, but they claim that the output is different somehow.. anyway my comment is more about the title of the question. (assuming that by salt they mean iv)
type: Comment

http://stackoverflow.com/comment/81803066
has text: Your initial question has neither `ProcessPoolExecutor` nor `run_in_executor` words. I don't see your problem and cannot help.
type: Comment
comment on: http://stackoverflow.com/a/47387807
score: 0
type: AnswerComment

http://stackoverflow.com/q/47440114
downvote count: 0
answer count: 1
has title: Export Tensorflow Estimator
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/47470281
type: Question
type: UnansweredQuestion
tagged with: python
score: 4
upvote count: 4
tagged with: tensorflow-estimator
has body: I'm trying to build a CNN with Tensorflow (r1.4) based on the API tf.estimator. It's a canned model. The idea is to train and evaluate the network with estimator in python and use the prediction in C++ without estimator by loading a pb file generated after the training. My first question is, is it possible? If yes, the training part works and the prediction part works too (with pb file generated without estimator) but it doesn't work when I load a pb file from estimator. I got this error : "Data loss: Can't parse saved_model.pb as binary proto" My pyhon code to export my model : feature_spec = {'input_image': parsing_ops.FixedLenFeature(dtype=dtypes.float32, shape=[1, 48 * 48])} export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec) input_fn = tf.estimator.inputs.numpy_input_fn(self.eval_features, self.eval_label, shuffle=False, num_epochs=1) eval_result = self.model.evaluate(input_fn=input_fn, name='eval') exporter = tf.estimator.FinalExporter('save_model', export_input_fn) exporter.export(estimator=self.model, export_path=MODEL_DIR, checkpoint_path=self.model.latest_checkpoint(), eval_result=eval_result, is_the_final_export=True) It doesn't work neither with tf.estimator.Estimator.export_savedmodel() If one of you knows an explicit tutorial on estimator with canned model and how to export it, I'm interested

python-mss
type: Tag
tag name: python-mss
tags question: http://stackoverflow.com/q/47540672

http://stackoverflow.com/q/47464900
has comment: http://stackoverflow.com/comment/81884585
has answer: http://stackoverflow.com/a/47464922
score: 1
has comment: http://stackoverflow.com/comment/81884549
has body: import requests, bs4, webbrowser url = 'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=' keywords = "keyboard" full_link = url + keywords res = requests.get(full_link) soup = bs4.BeautifulSoup(res.text) webbrowser.open(full_link) a = soup.find('a', {'class': 'a-link-normal s-access-detail-page s-color-twister-title-link a-text-normal'}) print(a) Hi, I'm trying to get a very specific html element that is buried deep in divs but to no avail. Here is the HTML: AmazonBasics Wired Keyboard and this is buried pretty deep. I want to get the href of this element, but currently my variable a returns None.
tagged with: http://stackoverflow.com/tag/html
has title: How to get a specific HTML element of a page (bs4)
type: Question
has comment: http://stackoverflow.com/comment/81884622
upvote count: 1
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/81934485
has text: Nothing has changed. None error occured, and the plot looks the same. I thought about defining that e.g "samples" are equals 266336, and then somehow link and then substract first and last record, but don't know if this work or how to do thi.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47489625

http://stackoverflow.com/q/47431050
answer count: 0
has comment: http://stackoverflow.com/comment/81818613
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81816865
has comment: http://stackoverflow.com/comment/81824640
has comment: http://stackoverflow.com/comment/81817284
has title: Any alternative for absolute file paths for sub-processes when we convert .py into .exe?
has comment: http://stackoverflow.com/comment/81817050
tagged with: pyinstaller
tagged with: python
has comment: http://stackoverflow.com/comment/81819121
has body: I used pyinstaller to convert two files from .py to .exe . My file(A).exe has subprocess.Popen and it runs file(B).exe . File(A) runs just fine. Now I have used absolute path for file(B) in file(A). My question : Is there anyway to avoid using absolute path? For example, just use shortcuts of both files in the same directory. In this way I can run my code on any machine.
type: Question
tagged with: python-3.x
score: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/81816747
has comment: http://stackoverflow.com/comment/81818627

http://stackoverflow.com/comment/82036290
type: Comment
score: 0
type: AnswerComment
has text: Not usually, no. Because they default to the first one created. But if you use more than one `Tk()` then you have to explicitly provide the correct one. [I made you an example](https://gist.github.com/novel-yet-trivial/a354fef60905db5a781de309a45c8740).
comment on: http://stackoverflow.com/a/47539274

http://stackoverflow.com/a/47512453
has body: mydict={} for i in List: splited=i.split(":") if(splited[0] in mydict): mydict[splited[0]]+=int(splited[1]) else: mydict[splited[0]]=int(splited[1])
answers question: http://stackoverflow.com/q/47512347
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/81981228
has comment: http://stackoverflow.com/comment/81980657
score: 0
type: Answer

http://stackoverflow.com/q/47386409
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23905817
has comment: http://stackoverflow.com/comment/81726203
tagged with: python
has comment: http://stackoverflow.com/comment/81725728
duplicate of: http://stackoverflow.com/q/23905817
has comment: http://stackoverflow.com/comment/81726353
has title: Efficiently adding numpy arrays with duplicate destination indices
answer count: 0
score: 1
tagged with: arrays
downvote count: 0
has body: Suppose I have two numpy arrays, A and B, which are potentially very large. I'd like to find a way to efficiently add values to certain entries in A by specifying the indices at which each entry of B should be added. Normally, one could use the following syntax: A[indices] += B The problem is that this doesn't behave as I would expect in cases where indices contains duplicate values. The only solution I've found is to use a manual for-loop, but I was hoping there might be a more efficient way. For example: A = np.array([100, 200, 300, 400]) B = np.array([1, 2, 3, 4, 5, 6]) indices = [1, 2, 0, 2, 1, 1] for i, index in enumerate(indices): A[index] += B[i] This yields A = [103, 212, 306, 400], as desired. In contrast, A[indices] += B yields A = [103, 206, 304, 400], which suggests that the operations A[1] += 1, A[1] += 5, A[2] += 2 are being omitted. Note: I view the desired behavior as being somewhat similar to a "group by" operation in SQL -- for each value of k, I want to group all entries of B where indices == k and add them into the kth position of A. My question is: is there a more efficient way to perform this operation? I'm hoping there's some built-in numpy functionality which would be better-optimized for performance than my for-loop above. For reference, I'm using numpy version 1.13.3. Higher-dimensional case If it's possible to generalize this to higher-dimensional arrays, I'd be interested to hear that, too. For example, is there a more efficient way to perform the following? A = (1 + np.arange(12).reshape(3,4)) * 100 B = (1 + np.arange(18)).reshape(3,6) row_indices = [2, 0, 2] col_indices = [1, 2, 0, 2, 1, 1] for i, row_index in enumerate(row_indices): for j, col_index in enumerate(col_indices): A[row_index, col_index] += B[i, j]
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81726099

http://stackoverflow.com/comment/82038062
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47540492
type: AnswerComment
has text: I asked about headers, not about Basic Authentication, also your code does not work too

http://stackoverflow.com/comment/81762726
type: AnswerComment
comment on: http://stackoverflow.com/a/47403879
has text: Good hint. Thanks alot
score: 1
type: Comment

http://stackoverflow.com/q/47481696
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47482012
has title: Pandas: concatenate a list of columns into one column
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/81918229
upvote count: 5
has body: I am wondering if I could build such a module in Pandas: def concatenate(df,columnlist,newcolumn): # df is the dataframe and # columnlist is the list contains the column names of all the columns I want to concatnate # newcolumn is the name of the resulted new column for c in columnlist: ...some Pandas functions return df # this one has the concatenated "newcolumn" I am asking this because that len(columnlist) is going to be very big and dynamic. Thanks!
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47482012
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/19377969
has answer: http://stackoverflow.com/a/47481743
accepted answer: http://stackoverflow.com/a/47481743
has comment: http://stackoverflow.com/comment/104859913

http://stackoverflow.com/comment/81927970
type: QuestionComment
comment on: http://stackoverflow.com/q/47486563
score: 2
has text: Possible duplicate of [python - find char in string - can I get all indexes?](https://stackoverflow.com/questions/11122291/python-find-char-in-string-can-i-get-all-indexes)
type: Comment

http://stackoverflow.com/comment/81932379
type: QuestionComment
score: 0
has text: You also need to figure out what it is you are trying to do.
comment on: http://stackoverflow.com/q/47470196
type: Comment

newrelic
tag name: newrelic
type: Tag
tags question: http://stackoverflow.com/q/47390954
tags question: http://stackoverflow.com/q/47462540

http://stackoverflow.com/a/47424492
has comment: http://stackoverflow.com/comment/81804090
answers question: http://stackoverflow.com/q/47424407
type: Answer
downvote count: 1
upvote count: 0
has comment: http://stackoverflow.com/comment/81836597
has comment: http://stackoverflow.com/comment/81820244
score: -1
has body: In ExtArcTan(x,N) you use if x&gt;0: (and other comparisons) which is ambiguous if x is an array as the error says. And you send X from N,X=np.meshgrid(N,X) which is an array. You need to use an element by element check with np.where for example instead of checking the whole array with x==0. EDIT: What about something along this (untested): def ExtArcTan(x,N): x = np.sum(ArcTanComponent(x,i) for i in range(N+1)) if (x&gt;0): return PI/2 - BaseArcTan(1/x,N) elif(x&lt;0): return -PI/2 - BaseArcTan(1/x,N) elif(x==0): return 0 EAT = np.array([[ExtArcTan(x,N) for x in row] for row in X]) Diff=abs(EAT-atan(X))
has comment: http://stackoverflow.com/comment/81804329
has comment: http://stackoverflow.com/comment/81804665

http://stackoverflow.com/a/47457899
type: Answer
has comment: http://stackoverflow.com/comment/81870775
has comment: http://stackoverflow.com/comment/81870723
answers question: http://stackoverflow.com/q/47457749
has body: Try to lower everything from your input first: initialInput = input("Write a sentence or phrase :") lowerInput = initialInput.lower() symbol = 'abcdefghijklmnopqrstuvwxyz' for key in symbol: print(key, lowerInput.count(key))
accepted answer of: http://stackoverflow.com/q/47457749
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81999037
comment on: http://stackoverflow.com/q/47521116
type: Comment
score: 0
type: QuestionComment
has text: The *point* is, np.shape isn't even detecting the correct dimensions. The shape doesn't matter, jeez.

http://stackoverflow.com/comment/81744582
type: Comment
has text: Look at `operator.itemgetter`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47393056

http://stackoverflow.com/q/47417436
accepted answer: http://stackoverflow.com/a/47417479
type: Question
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/47417479
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 1
has body: I use threading.Thread(target=ftp1.ftptester, args=[self.finallist], daemon=False).start() for processing a list of files it may take upto 3 mins to finish ftptester function the code comes below only have to execute after finishing the thread I have tried kl=threading.Thread(target=ftp1.ftptester, args=[self.finallist], daemon=False).start() kl.join() But it was giving me error AttributeError: 'NoneType' object has no attribute 'join' Note * the thread is called from asyncio ->eventloop-> run_until_complete
answer count: 1
has title: How can i wait until a thread finish its process?

http://stackoverflow.com/comment/82028764
type: Comment
comment on: http://stackoverflow.com/a/47525463
type: AnswerComment
has text: @Hongrun Zhou, I think that you should accept this answer. There's things that can be contributed to this answer (for e.g. an obvious notice that `.txt` is a [plain text](https://stackoverflow.com/questions/14492138/mime-type-for-txt-files) and a notice about [`dump`](http://effbot.org/tkinterbook/text.htm#Tkinter.Text.dump-method) method, which produces a sequence (a list) of tuples, which contains tag/text information and which can be potentially converted to format with code syntax or markup language (rtf, html, xml) without any dependency. But as is it's already an answer, so..
score: 0

http://stackoverflow.com/q/47429254
has body: When I write a function that accepts ndarray or scalar inputs def foo(a): # does something to `a` # # a: `x` dimensional array or scalar # . . . cast(a, x) # deal with `a` as if it is an `x`-d array after this Is there an effeicint way yo write that cast function? Basically what I'd want is a function that would cast: a, a scalar to ndarray with shape ((1,)*x) b, an ndarray with y&lt;x dims explicitly to shape ((1,) * (y-x) + b.shape) (same as broadcasting) c, an ndarray with x dims is unaffected d, an ndarray with y&gt;x dims throws an error do it all in-place (at least when starting with an array), to prevent double memory it seems like this functionality is repeated so often in built-in functions that there should be some shortcut for it, but I'm not finding it. I can do a_ = np.array(a, ndmin = x, copy = False) and then assert len(a_.shape) == x) , but that still makes a copy of arrays. (i.e. a_.base is a is False). Is there any way around this?
score: 1
accepted answer: http://stackoverflow.com/a/47441511
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47441511
upvote count: 1
has title: Efficient way to cast scalars to numpy arrays
favorite count: 0
has comment: http://stackoverflow.com/comment/81813986
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81817283
has comment: http://stackoverflow.com/comment/81813943
tagged with: python
linked to: http://stackoverflow.com/q/47426375
has comment: http://stackoverflow.com/comment/81821363
type: AnsweredQuestion

random
tags question: http://stackoverflow.com/q/47445394
tags question: http://stackoverflow.com/q/47462664
tags question: http://stackoverflow.com/q/47484260
tags question: http://stackoverflow.com/q/47410054
tags question: http://stackoverflow.com/q/47539524
tags question: http://stackoverflow.com/q/47476261
tags question: http://stackoverflow.com/q/47478016
tags question: http://stackoverflow.com/q/47460971
tag name: random
tags question: http://stackoverflow.com/q/47460663
tags question: http://stackoverflow.com/q/47514695
tags question: http://stackoverflow.com/q/47483450
tags question: http://stackoverflow.com/q/47538605
type: Tag
tags question: http://stackoverflow.com/q/47464362
tags question: http://stackoverflow.com/q/47410967
tags question: http://stackoverflow.com/q/47514332
tags question: http://stackoverflow.com/q/47472123
tags question: http://stackoverflow.com/q/47426241
tags question: http://stackoverflow.com/q/47424635
tags question: http://stackoverflow.com/q/47516428
tags question: http://stackoverflow.com/q/47433920

http://stackoverflow.com/comment/81917255
comment on: http://stackoverflow.com/q/47461823
has text: @serhatemreAkhanli it seems you need a cookie value in order to make the internal API working. The thing is that in order to get that cookie there are an antibot mecanism in place when you request https://www.whoscored.com/ with some call to https://www.whoscored.com/_Incapsula_Resource including Javascript being evaluated to perform a xhr request before reloading the page with the correct cookies. Also it requires a captcha if it detects that something was wrong with the previous handshake (I guess timing/header etc...)
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81882325
type: AnswerComment
comment on: http://stackoverflow.com/a/47439176
has text: Just opening the file and reading it again (what you would do in a real life setup) would do :)
type: Comment
score: 0

http://stackoverflow.com/a/58252612
upvote count: 5
has body: The browser is automatically disposed once the variable of the driver is out of scope. So, to avoid quitting the browser, you need to set the instance of the driver on a global variable: Dim driver As New ChromeDriver Private Sub Use_Chrome() driver.Get "https://www.google.com" ' driver.Quit End Sub
type: Answer
answers question: http://stackoverflow.com/q/47508518
score: 5
downvote count: 0

http://stackoverflow.com/comment/81773913
comment on: http://stackoverflow.com/a/47410142
type: Comment
score: 0
type: AnswerComment
has text: Thank you! Would it be wrong to append those values to a list so I can use it to get the cumulative distribution frequency?

http://stackoverflow.com/a/47444100
has comment: http://stackoverflow.com/comment/81879312
has comment: http://stackoverflow.com/comment/81878887
has comment: http://stackoverflow.com/comment/81873886
has comment: http://stackoverflow.com/comment/81882556
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47440035
has comment: http://stackoverflow.com/comment/81878340
has comment: http://stackoverflow.com/comment/81914476
has comment: http://stackoverflow.com/comment/81915180
has comment: http://stackoverflow.com/comment/81876913
has comment: http://stackoverflow.com/comment/81895809
has comment: http://stackoverflow.com/comment/81907379
has comment: http://stackoverflow.com/comment/81880690
has body: Yes you can, prioritized url (requests with higher priority) are taken first by the scheduler, to be sure you could set a lower concurrency CONCURRENT_REQUESTS = 1 the reason is that if you use greater concurrency some low priority urls might have been downloaded while you were queuing some new requests, and it might give you the impression that order is not respected. Another alternative (if you need higher concurrency) would be to define a spider_idle method (my bad, thanks to @eLRuLL for pointing this up) and yield the requests from the second group, yielding also a DontCloseSpider exception, something like this: # -*- coding: utf-8 -*- import scrapy from scrapy.exceptions import DontCloseSpider class ExampleSpider(scrapy.Spider): name = 'example' allowed_domains = ['example.com'] first_group_of_urls = [ 'http://quotes.toscrape.com/page/1/' ] second_group_of_urls = [ 'http://quotes.toscrape.com/page/2/' ] def start_requests(self): for url in self.first_group_of_urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): self.logger.debug('In response from %s', response.url) @classmethod def from_crawler(cls, crawler, *args, **kwargs): spider = super(ExampleSpider, cls).from_crawler(crawler, *args, **kwargs) crawler.signals.connect(spider.spider_idle, signal=scrapy.signals.spider_idle) return spider def spider_idle(self): self.crawler.signals.disconnect(self.spider_idle, signal=scrapy.signals.spider_idle) for url in self.second_group_of_urls: self.crawler.engine.crawl(scrapy.Request(url), self) raise DontCloseSpider
upvote count: 2
has comment: http://stackoverflow.com/comment/81874080
accepted answer of: http://stackoverflow.com/q/47440035
has comment: http://stackoverflow.com/comment/81876980
downvote count: 0
has comment: http://stackoverflow.com/comment/81859599
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81843506

http://stackoverflow.com/a/47719021
upvote count: 1
has body: In Python 3 all imports are absolute. To perform relative import do it explicitly: from .module1 import fortran_fn
type: Answer
answers question: http://stackoverflow.com/q/47463081
has comment: http://stackoverflow.com/comment/82424237
score: 1
downvote count: 0

http://stackoverflow.com/comment/81902413
type: QuestionComment
has text: The full output from your script could help
comment on: http://stackoverflow.com/q/47473877
score: 0
type: Comment

http://stackoverflow.com/q/47501251
type: Question
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: sql-server
score: 0
has answer: http://stackoverflow.com/a/47501354
tagged with: sql
has title: Returning a query
has body: I'm not sure why I get an error when I call this function. The output I want to get is this. Can anyone please help me fix this? Desired Output ('BIOA01H3F', '26', '17-12-19', '9:00') Code: def get_course_time(db, course): ''' Return the course number, ID, the date and start time of the given course's exam for all sections. Note there are only multiple sections if the course IDs are different. ''' return (run_query(db, '''SELECT ID, date, StartTime Where course?'''(course))) Error: return (run_query(db, '''SELECT ID, date, StartTime Where course = ?'''(course))) builtins.TypeError: 'str' object is not callable

http://stackoverflow.com/comment/82038176
type: Comment
score: 0
type: AnswerComment
has text: Hey @AJNeufeld, I'm still new to programming and Python. I understand what printing is for the most, but how does printing what is iterated going to help. Also how would I use that new list you have there are the bottom to del? I tried adding del row[linestart:lineend] after that and it doesn't do anything, surprisingly it still runs without error. :-)
comment on: http://stackoverflow.com/a/47540272

http://stackoverflow.com/comment/81964931
comment on: http://stackoverflow.com/q/47504523
type: Comment
score: 0
has text: `(h-w)/2` is floating-point.
type: QuestionComment

http://stackoverflow.com/a/47499563
score: 0
has body: The condition to append in your code is never met, thus, no value is being returned. Instead, return after the loop is finished. Also, your counting condition is reversed, as you should be finding the count of i occurring in the list, not n: k = [] for i in a_list: if a_list.count(i) &lt; n and i not in k: k.append(i) return k The reason why you are receiving None is that the return statement does not pass, so to satisfy the variable storage during the function call, None is returned.
downvote count: 2
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47499522

http://stackoverflow.com/a/47501089
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47500871
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81957968
has comment: http://stackoverflow.com/comment/81957939
has comment: http://stackoverflow.com/comment/81957933
type: Answer
has comment: http://stackoverflow.com/comment/81958012
answers question: http://stackoverflow.com/q/47500871
has body: You have to use previous value to calculate new one. def f10(start, n): result = [start] # I put first element for _ in range(n-1): # I have to put other n-1 elements yet if start % 5 == 0: start //= 5 else: start -= 4 result.append(start) return result # --- compare result with expected list --- print(f10(1, 10) == [1, -3, -7, -11, -15, -3, -7, -11, -15, -3]) # True print(f10(9, 12) == [9, 5, 1, -3, -7, -11, -15, -3, -7, -11, -15, -3]) # True EDIT: if you don't want range() then you can use while len(result) &lt; n: def f10(start, n): result = [start] while len(result) &lt; n: if start % 5 == 0: start //= 5 else: start -= 4 result.append(start) return result
score: 1
has comment: http://stackoverflow.com/comment/81957906

http://stackoverflow.com/a/47457583
upvote count: 1
answers question: http://stackoverflow.com/q/47456167
has comment: http://stackoverflow.com/comment/81869631
score: 1
has body: You can make use of series.mode i.e func = { 'late_count':['sum'], 'is_discount':['count'], 'is_not_discount':['count'], 'discount':['sum'], 'is_auto_renew':['mean'], 'is_cancel':['mean'], 'payment_type': lambda x : x.mode()} # Data from @ jezrael. grouped_object.agg(func).rename(columns={'&lt;lambda&gt;': 'mode'}) Output : is_not_discount is_auto_renew late_count payment_type discount \ count mean sum mode sum msno a 3 3.000000 13 0 24 d 3 2.666667 14 1 9 is_discount is_cancel count mean msno a 3 4.666667 d 3 5.000000
has comment: http://stackoverflow.com/comment/81869683
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81996650
score: 1
type: Comment
type: QuestionComment
has text: I think you have to share a couple of lines of your data file before anyone can help. Also why do the spectrogram yourself, why not just use the mpl built in [specgram](http://matplotlib.org/gallery/images_contours_and_fields/specgram_demo.html#sphx-glr-gallery-images-contours-and-fields-specgram-demo-py)? btw, you have actually not stated what is not working as you expect...
comment on: http://stackoverflow.com/q/47518937

http://stackoverflow.com/comment/81903764
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47473730
has text: And now integers that have a value larger that the maxval of floats are also handled properly.
type: Comment

http://stackoverflow.com/q/47447559
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81850709
has comment: http://stackoverflow.com/comment/81850519
tagged with: pyqt4
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47448112
accepted answer: http://stackoverflow.com/a/47448112
type: AnsweredQuestion
tagged with: python-2.7
has title: pyqt4 how to know textEdit field is empty
upvote count: 0
has body: I want to know if textbox is empty or not. So, I made this code. But, if self.row is ' ' &lt;- this is not working. Although, textEdit field is empty but, it's not recognize. def setUi(self): self.textEdit = QtGui.QTextEdit(MainWindow) self.textEdit.setGeometry(QtCore.QRect(155, 90, 471, 31)) self.textEdit.setObjectName(_fromUtf8("textEdit")) def bringcolumn(self): self.row = self.textEdit.toPlainText() if self.row is '': #I want to know if self.row is empty of not. QtGui.QMessageBox.information(self, "Message", "ERROR")
answer count: 1
has comment: http://stackoverflow.com/comment/81850538

http://stackoverflow.com/q/47502241
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/81970639
tagged with: mozilla-deepspeech
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82088347
tagged with: baidu
downvote count: 0
tagged with: python
score: 4
tagged with: windows
has answer: http://stackoverflow.com/a/48000098
answer count: 1
has title: How to install Mozilla's implementation of Baidu deep speech on Windows?
tagged with: speech-recognition
has body: I'm on Windows 10, and when I try to install Mozilla's implementation of Baidu Deep speech as shown here. Using: pip install deepspeech I get this error : "Could not find a version that satisfies the requirement deepspeech (from versions:) No matching distribution found for deepspeech" Is there another way to install it on windows?
favorite count: 0

http://stackoverflow.com/a/47526817
score: 0
has body: pushpendra's answer of closure is fantastic!!! I know very little about functional programming but this is really inspiring me to dig more into it. On the other hand, I just came up with an OOP solution for my specific issue: make the shared.py a class and all the shared_fun as class method while SHARE_GLOBAL_VAR is now a class data member. Each user_module1/2 will now just instantiate an object of the share class with different SHARE_GLOBAL_VAR. This achieves the similar idea of creating multiple copies of share_fun, via a class instead of duplicating module importing (which is impossible per Terry's answer). My very naive comparison between OOP and Functional in this case: Closure solution provides much more freedom in creating different versions of functions. Since closure provides function duplicate per function instead of per GLOBAL_SHARE_VAR, therefore it saves the overhead of creating unnecessary methods that are never used by the OOP solution. Time to get serious about functional programming!
answers question: http://stackoverflow.com/q/47524976
type: Answer

http://stackoverflow.com/a/47535627
type: Answer
has comment: http://stackoverflow.com/comment/82028978
has comment: http://stackoverflow.com/comment/82028902
accepted answer of: http://stackoverflow.com/q/47535540
score: 2
type: AcceptedAnswer
downvote count: 0
has body: You can use ast.literal_eval: import ast final_results = [a+b for a, b in zip(*ast.literal_eval(open('filename.txt')))] Output: [[1, 2, 5, 6, 7], [3, 4, 8, 9, 10]] Edit: without any imports, you can use eval. Note however that eval is quite insecure and thus must only run on strings from a trusted source: final_results = [a+b for a, b in zip(*eval(open('filename.txt').read()))]
answers question: http://stackoverflow.com/q/47535540
has comment: http://stackoverflow.com/comment/82028199
has comment: http://stackoverflow.com/comment/82059997
upvote count: 2
has comment: http://stackoverflow.com/comment/82054305

http://stackoverflow.com/q/47540314
tagged with: function
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82042178
has comment: http://stackoverflow.com/comment/82038260
score: 4
tagged with: pandas
has comment: http://stackoverflow.com/comment/82040329
tagged with: data-manipulation
has comment: http://stackoverflow.com/comment/82038131
has title: Python: How to use or get the column header in Pandas and use it as input/value
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47542585
has body: I have the following script that produces an empty DataFrame using Pandas: import pandas as pd import datetime #Creating a list of row headers with dates. start=datetime.date(2017,3,27) end=datetime.date.today() - datetime.timedelta(days=1) row_dates=[x.strftime('%m/%d/%Y') for x in pd.bdate_range(start,end).tolist()] identifiers=['A','B','C'] #Creating an empty Dataframe df=pd.DataFrame(index=identifiers, columns=row_dates) print(df) Now, suppose I have a function (let's call it "my_function(index,date)") that requires two inputs: an index, and a date. That function gives me an outcome and I want to fill the corresponding empty slot of the dataframe with that outcome. But for that, I need to be able to acquire both the index and the date. For example, let's say I want to fill the first slot of my DataFrame, I require index 'A' and the first Date which is '27/3/2017', so I have this: my_function('A', '27/3/2017') How can I make that happen for my entire DataFrame? My apologies if any of this sounds confusing.
favorite count: 0
type: Question
upvote count: 4
type: UnansweredQuestion

http://stackoverflow.com/comment/81731037
comment on: http://stackoverflow.com/q/47389066
has text: about subprocess - https://docs.python.org/2/library/subprocess.html#using-the-subprocess-module
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47474778
has body: 1. asyncore relies on operating system for whole connection handling, therefore what you are asking is OS dependent. It has very little to do with Python. Using twisted instead of asyncore wouldn't solve your problem. On Windows, for example, you can listen only for 5 connections coming in simultaneously. So, first requirement is, run it on *nix platform. The rest depends on how long your handlers are taking and on your bandwith. 2. What you can do is combine asyncore and threading to speed-up waiting for next connection. I.e. you can make Handlers that are running in separate threads. It will be a little messy but it is one of possible solutions. When server accepts a connection, instead of creating new traditional handler (which would slow down checking for following connection - because asyncore waits until that handler does at least a little bit of its job), you create a handler that deals with read and write as non-blocking. I.e. it starts a thread and does the job, then, when it has data ready, only then sends it upon following loop()'s check. This way, you allow asyncore.loop() to check the server's socket more often. 3. Or you can use two different socket_maps with two different asyncore.loop()s. You use one map (dictionary), let say the default one - asyncore.socket_map to check the server, and use one asyncore.loop(), let say in main thread, only for server(). And you start the second asyncore.loop() in a thread using your custom dictionary for client handlers. So, One loop is checking only server that accepts connections, and when it arrives, it creates a handler which goes in separate map for handlers, which is checked by another asyncore.loop() running in a thread. This way, you do not mix the server connection checks and client handling. So, server is checked immediately after it accepts one connection. The other loop balances between clients. If you are determined to go even faster, you can exploit the multiprocessor computers by having more maps for …
downvote count: 0
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47473750
answers question: http://stackoverflow.com/q/47473750

http://stackoverflow.com/q/47463177
type: AnsweredQuestion
score: 0
has title: How to get rid of nested for loop
has comment: http://stackoverflow.com/comment/81881334
has comment: http://stackoverflow.com/comment/81881190
possible better answer: http://stackoverflow.com/a/47463937
tagged with: python
has answer: http://stackoverflow.com/a/47463937
accepted answer: http://stackoverflow.com/a/47463310
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47463310
tagged with: python-2.7
answer count: 2
tagged with: for-loop
upvote count: 1
downvote count: 1
has body: mazeHow do i replace the nested for loop without affecting the functionality of the code: def addCoordinate(self, x, y, blockType): if self.x1 &lt; x : self.x1 = x if self.y1 &lt; y: self.y1 = y if self.x1 &gt;= len(self.mazeboard) or self.y1 &gt;= len(self.mazeboard): modified_board = [[1 for a in range(self.x1 + 1)] for b in range(self.y1 + 1)] for a in range(len(self.mazeboard)): for b in range(len(self.mazeboard[a])): modified_board[a][b] = self.mazeboard[a][b] self.mazeboard = modified_board self.mazeboard[x][y] = blockType

http://stackoverflow.com/comment/81993531
comment on: http://stackoverflow.com/q/47518601
type: Comment
type: QuestionComment
has text: Well, if you are using a list, then you know the length, and thus, you can calculate how many permuations will be created using math, and simply halt it yourself, no?
score: 0

http://stackoverflow.com/comment/82015596
score: 0
has text: @tripleee - expect solves the problem and I understand now the issue.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47527621

http://stackoverflow.com/q/47402445
has answer: http://stackoverflow.com/a/54068249
answer count: 2
accepted answer: http://stackoverflow.com/a/47403282
has body: I am trying to triangulate points from a projector and a camera using Structured Light in OpenCV Python. In this process I have a list of tuples that match one to one between the camera and the projector. I am passing this to cv2.undistortedPoints() as below: camera_normalizedPoints = cv2.undistortPoints(camera_points, camera_K, camera_d) However, python is throwing the following error and I am unable to understand what the error means. camera_normalizedPoints = cv2.undistortPoints(camera_points, camera_K, camera_d) cv2.error: /home/base/opencv_build/opencv/modules/imgproc/src/undistort.cpp:312: error: (-215) CV_IS_MAT(_src) &amp;&amp; CV_IS_MAT(_dst) &amp;&amp; (_src-&gt;rows == 1 || _src-&gt;cols == 1) &amp;&amp; (_dst-&gt;rows == 1 || _dst-&gt;cols == 1) &amp;&amp; _src-&gt;cols + _src-&gt;rows - 1 == _dst-&gt;rows + _dst-&gt;cols - 1 &amp;&amp; (CV_MAT_TYPE(_src-&gt;type) == CV_32FC2 || CV_MAT_TYPE(_src-&gt;type) == CV_64FC2) &amp;&amp; (CV_MAT_TYPE(_dst-&gt;type) == CV_32FC2 || CV_MAT_TYPE(_dst-&gt;type) == CV_64FC2) in function cvUndistortPoints Any help is greatly appreciated. Thanks.
upvote count: 2
has answer: http://stackoverflow.com/a/47403282
downvote count: 0
has comment: http://stackoverflow.com/comment/81760263
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/81760073
possible better answer: http://stackoverflow.com/a/54068249
favorite count: 0
tagged with: opencv
score: 2
type: AnsweredQuestion
tagged with: triangulation
has comment: http://stackoverflow.com/comment/81759971
tagged with: python
has comment: http://stackoverflow.com/comment/81759498
linked to: http://stackoverflow.com/q/44378098
linked to: http://stackoverflow.com/q/45817325
has comment: http://stackoverflow.com/comment/81760180
has title: Need help in understanding error for cv2.undistortPoints()
type: Question

http://stackoverflow.com/q/47480719
possible better answer: http://stackoverflow.com/a/47525523
answer count: 5
has title: Searching in multiple fields respecting the row order
has comment: http://stackoverflow.com/comment/81980825
tagged with: python
has body: I have a model like the following: class Foo(models.Model): fruit = models.CharField(max_length=10) stuff = models.CharField(max_length=10) color = models.CharField(max_length=10) owner = models.CharField(max_length=20) exists = models.BooleanField() class Meta: unique_together = (('fruit', 'stuff', 'color'), ) It is populated with some data: fruit stuff color owner exists Apple Table Blue abc True Pear Book Red xyz False Pear Phone Green xyz False Apple Phone Blue abc True Pear Table Green abc True I need to merge/join this with a collection (not a queryset): [('Apple', 'Table', 'Blue'), ('Pear', 'Phone', 'Green')] So basically rows 0 and 2 should return when I search this model with this list of tuples. Currently my workaround is to read Foo.objects.all() into a DataFrame and do a merge with the list of tuples and get the ID's to pass to Foo.objects.filter(). I also tried iterating over the list and calling Foo.object.get() on each tuple but it is very slow. The list is quite big. When I tried chaining Q's as suggested by the current answers, it threw an OperationalError (too many SQL variables). My main goal is the following: As it can be seen from the model these three fields together form my primary key. The table contains around 15k entries. When I get data from another source I need to check if the data is already in my table and create/update/delete accordingly (new data may contain up to 15k entries). Is there a clean and efficient way to check if these records are already in my table? Note: The list of tuples does not have to be in that shape. I can modify it, turn it into another data structure or transpose it.
score: 8
type: Question
has answer: http://stackoverflow.com/a/47480914
tagged with: django-queryset
tagged with: django-orm
accepted answer: http://stackoverflow.com/a/47526840
has answer: http://stackoverflow.com/a/47525523
downvote count: 0
has answer: http://stackoverflow.com/a/47533042
has comment: http://stackoverflow.com/comment/82081575
tagged with: django
has answer: http://stackoverflow.com/a/47526840
favorite count: 0
type: AnsweredQuestion
upvote count: 8
has answer: http://stackoverflow.com/a/47480920

http://stackoverflow.com/q/47516183
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47516641
score: 0
type: UnansweredQuestion
answer count: 1
has body: how to scrap the mobile reviews data from Flipkart I tried using selenium package and but unable to extract all the reviews at a glance except for one review so can anyone help me with the code... fk_path = ('[https://www.flipkart.com/moto-g-turbo-white-16-gb/product- reviews/itmecc4uhbue7ve6?pid=MOBECC4UQTJ5QZFR][1]') from selenium import webdriver browser = webdriver.Chrome('/home/subhasis/chromedriver') browser.get(fk_path) browser.find_element_by_xpath("//span[@class='_1EPkIx']/span").click() # Mimick clicking on 'Read More' [p.click() for p in browser.find_elements_by_xpath("//span[@class='_1EPkIx']/span")] # Expand all 'Read More' buttons browser.find_element_by_xpath("//div[@class='_3DCdKt']//div[@class='qwjRop']/div").text # Extract texts from respective Xpaths (1st review)
has title: How to Scrape data for mobile reviews in flipkart?

http://stackoverflow.com/comment/81786308
type: QuestionComment
has text: You can send an AJAX request to an endpoint you've defined. In jQuery, it's as simple as [`$.ajax()`](https://api.jquery.com/jquery.ajax)
score: 1
comment on: http://stackoverflow.com/q/47416061
type: Comment

http://stackoverflow.com/comment/130458820
has text: how? I've added testpaths = nested/dir/tests and still doesnt work
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/66464165

http://stackoverflow.com/q/47477122
tagged with: python
has answer: http://stackoverflow.com/a/47477265
linked to: http://stackoverflow.com/q/47469310
tagged with: batch-file
score: 3
tagged with: environment-variables
downvote count: 2
answer count: 3
tagged with: cmd
has answer: http://stackoverflow.com/a/47477123
has answer: http://stackoverflow.com/a/66860144
favorite count: 0
has body: I don't like the other post. because it involves renaming python executables.
type: Question
has comment: http://stackoverflow.com/comment/81909085
has title: Switch between different Python versions in Windows 10 cmd
upvote count: 5
linked to: http://stackoverflow.com/q/4583367
tagged with: windows
type: UnansweredQuestion

http://stackoverflow.com/a/47418580
upvote count: 15
answers question: http://stackoverflow.com/q/47410054
type: Answer
has comment: http://stackoverflow.com/comment/138443237
score: 15
downvote count: 0
has body: Here's some code that generates points uniformly on an arbitrary triangle in the plane. import random def point_on_triangle(pt1, pt2, pt3): """ Random point on the triangle with vertices pt1, pt2 and pt3. """ x, y = sorted([random.random(), random.random()]) s, t, u = x, y - x, 1 - y return (s * pt1[0] + t * pt2[0] + u * pt3[0], s * pt1[1] + t * pt2[1] + u * pt3[1]) The idea is to compute a weighted average of the three vertices, with the weights given by a random break of the unit interval [0, 1] into three pieces (uniformly over all such breaks). Here x and y represent the places at which we break the unit interval, and s, t and u are the length of the pieces following that break. We then use s, t and u as the barycentric coordinates of the point in the triangle. Here's a variant of the above that avoids the need to sort, instead making use of an absolute value call: def point_on_triangle2(pt1, pt2, pt3): """ Random point on the triangle with vertices pt1, pt2 and pt3. """ x, y = random.random(), random.random() q = abs(x - y) s, t, u = q, 0.5 * (x + y - q), 1 - 0.5 * (q + x + y) return ( s * pt1[0] + t * pt2[0] + u * pt3[0], s * pt1[1] + t * pt2[1] + u * pt3[1], ) Here's an example usage that generates 10000 points in a triangle: pt1 = (1, 1) pt2 = (2, 4) pt3 = (5, 2) points = [point_on_triangle(pt1, pt2, pt3) for _ in range(10000)] And a plot obtained from the above, demonstrating the uniformity. The plot was generated by this code: import matplotlib.pyplot as plt x, y = zip(*points) plt.scatter(x, y, s=0.1) plt.show() Here's the image: And since you tagged the question with the "numpy" tag, here's a NumPy version that generates multiple samples at once. Note that it uses the matrix multiplication operator @, introduced in Python 3.5 and supported in NumPy >= 1.10. You'll need to replace that with a call to np.dot on older Python or NumPy versions. import numpy as np def points_on_triangle(v, n): """ Give n random points uniformly on a triangle. The vertices of …

http://stackoverflow.com/q/47397734
answer count: 0
type: UnansweredQuestion
tagged with: inheritance
has comment: http://stackoverflow.com/comment/81748661
score: 0
tagged with: python
tagged with: class
type: Question
has body: I have an object "surface" which is stored in a "cell" as a list. You can think of a cube which is made of surfaces. Despite I can change surface properties using the "cell" object, there are times when is more convenient for me to change it directly on the "surface". Is it possible to change a property in "surface" object and then propagate it automatically to the same surface within "cell"? An example: class Surface(object): def __init__ (self, color): self.color = color class Cell(object): def __init__(self, surfaces) self.surface = surfaces surfaces = [] surfaces.append(Surfaces(color='blue')) surfaces.append(Surfaces(color='blue')) surfaces.append(Surfaces(color='blue')) surfaces.append(Surfaces(color='blue')) surfaces.append(Surfaces(color='blue')) surfaces.append(Surfaces(color='blue')) cell = Cell(surfaces) surface[0].color = 'red' print(cell.surface[0].color) 'red' When changing the surface color I would like it to be propagated to the same child within the "cell" object. Is this possible? Appreciate the help!
has title: python change child object and propagate to parent
has comment: http://stackoverflow.com/comment/81748873

http://stackoverflow.com/q/47385617
has comment: http://stackoverflow.com/comment/81724209
tagged with: python
tagged with: sorting
has title: Using max() and min() unsuccessfully in Python array
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47385799
answer count: 2
tagged with: min
has comment: http://stackoverflow.com/comment/81724251
score: 1
tagged with: max
downvote count: 0
upvote count: 1
has body: Context: Continuing with my self-learn of Python, I recently completed a textbook exercise that asked for a program that allowed the user to define 'x' number of years and to be able to input, for every month in 'x', a value for rainfall. Issue: Below is my code, which works 'ok', however the latest exercise demands I 'expand' my code to present the numerically largest and smallest user input rainfall value, in a print statement. Disclosure: I have looked on S.O to try finding the solution to my question, but nothing seems to be close enough to my challenge, to help me. What I've tried: I have tried using max() and min() however I keep getting a TypeError: 'int' object is not iterable when I type the code print(max(monthlyRainfall) or print(min(monthlyRainfall) def yearsToTrack(): userYearsTracking = int(input("How many years do you want to track: ")) return userYearsTracking def calculationAlgorithm(userYearsTracking): totalMonths = 0 totalRainfall = 0 for currentYear in range (1, userYearsTracking +1): for currentMonth in range (1, 13): monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " + format(currentYear, "d",)+": ")) totalMonths += 1 totalRainfall += monthlyRainfall averageRainfall = totalRainfall / totalMonths print("Total months: " + str(totalMonths)) print("Total rain:", format(totalRainfall), "(inch)") print("Total average rainfall:", round(averageRainfall,2), "(inch)") def main(): userYearsTracking = yearsToTrack() calculationAlgorithm(userYearsTracking) main() Is anyone able to offer some 'pointers' as to where I am going wrong?
has answer: http://stackoverflow.com/a/47385802
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47385799
has comment: http://stackoverflow.com/comment/81724246
has comment: http://stackoverflow.com/comment/81724358
has comment: http://stackoverflow.com/comment/81724220
accepted answer: http://stackoverflow.com/a/47385802

http://stackoverflow.com/comment/81751553
comment on: http://stackoverflow.com/a/47399155
type: AnswerComment
has text: Yep, your expression works. +1 for this. Gonna accept it in a while. Thanks.
score: 0
type: Comment

http://stackoverflow.com/comment/81724846
type: Comment
comment on: http://stackoverflow.com/q/47385933
score: 0
has text: You don't return from the `if`
type: QuestionComment

http://stackoverflow.com/q/47421486
has answer: http://stackoverflow.com/a/76259675
has answer: http://stackoverflow.com/a/47421938
type: AnsweredQuestion
has body: I tried using matplotlib's ArtistAnimation. The text and titles of the figure are supposed to change in each frame, but they don't. I have read tons of posts on similar problems, but I still don't understand what is the solution. The demos don't show updating titles as far as I could find. If anybody out there knows, I would be grateful! import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation fig =plt.figure() ims=[] for iternum in range(4): plt.title(iternum) plt.text(iternum,iternum,iternum) ims.append([plt.scatter(np.random.randint(0,10,5), np.random.randint(0,20,5),marker='+' )]) #plt.cla() ani = animation.ArtistAnimation(fig, ims, interval=500, blit=False, repeat_delay=2000) plt.show()
tagged with: matplotlib
answer count: 3
favorite count: 0
possible better answer: http://stackoverflow.com/a/47421950
has answer: http://stackoverflow.com/a/47421950
type: Question
upvote count: 9
has title: matplotlib artist animation : title or text not changing
score: 9
downvote count: 0
tagged with: animation
tagged with: python
accepted answer: http://stackoverflow.com/a/47421938

http://stackoverflow.com/q/47441452
type: Question
accepted answer: http://stackoverflow.com/a/47460004
tagged with: python-2.7
answer count: 1
tagged with: ubuntu
type: AnsweredQuestion
tagged with: openfoam
score: 0
has title: PVFoamReader not imported with paraview.simple
has body: I am starting to build python scripts for post-processing OpenFoam-5 results on paraview 5.4. I was able to record, alter and run scripts inside the paraview interface. I was also able to run some of these scripts outside of the paraview interface, using both the pvpython and my standart python 2 environment (adding the pvpython libraries folders to the system path). The problem I am facing now is that when I import paraview.simple, outside of the paraview interface (even if I use pvpython or pvbatch), it loads all the functions and modules but two: PVFoamReader and PVblockMeshReader. I checked the environment variables and the system path on both shells and they are the same, so I don't know what the issue might me. I am running the scripts under Ubuntu 16.04 Could somebody help me? Thank you
tagged with: paraview
tagged with: python
has answer: http://stackoverflow.com/a/47460004

http://stackoverflow.com/q/47468174
downvote count: 2
has answer: http://stackoverflow.com/a/47468893
has title: change the array value in python
upvote count: 1
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47468985
has answer: http://stackoverflow.com/a/47469035
has comment: http://stackoverflow.com/comment/81891066
has answer: http://stackoverflow.com/a/47468985
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/81891800
favorite count: 0
type: Question
has body: I have written a code for calculate maximum of a function with Genetic Algorithm in Python. this is here. When I want to change the value of an array, I get an error: def _crossover_chromosomes(chromosome1,chromosome2): crossover_chrom = Chromosome() for i in range(8): if random.random() &gt;= 0.5: crossover_chrom.get_genes()[0][i] = chromosome1.get_genes()[0][i] crossover_chrom.get_genes()[1][i] = chromosome1.get_genes()[0][i] else: crossover_chrom.get_genes()[0][i] = chromosome2.get_genes()[0][i] crossover_chrom.get_genes()[1][i] = chromosome2.get_genes()[0][i] return crossover_chrom in this part, 'for' run only once and When it wants to change the array value in the fifth line, exits the program. error: crossover_chrom.get_genes()[0][i] = chromosome1.get_genes()[0][i] TypeError: 'str' object does not support item assignment
has comment: http://stackoverflow.com/comment/81891025
possible better answer: http://stackoverflow.com/a/47468893
has comment: http://stackoverflow.com/comment/81890892
tagged with: algorithm

http://stackoverflow.com/comment/82034228
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47538647
has text: welcome, mark it as an answer if it has solved your problem this will help others as well

http://stackoverflow.com/a/47438310
has body: You should have started with an empty list and appended items to it: matching_words = [] for word in source_of_words: matching_words.append(word) print(matching_words) Also, just so you know about the remove method: print(matching_words) matching_words.remove('bar') print(matching_words) Sample Output: ['foo', 'bar', 'baz'] ['foo', 'baz']
type: Answer
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47438248

http://stackoverflow.com/comment/81933520
type: QuestionComment
comment on: http://stackoverflow.com/q/47489229
type: Comment
score: 0
has text: Your implementation is ok. You seem to be calling your function `function[ab]` whereas it should be `function(ab)`.

http://stackoverflow.com/comment/81741143
type: Comment
type: QuestionComment
has text: I am not sure if I expressed myself correctly, but what I meant was to change the result of the command ```which python``` and consequently which python version is used when I type ```python``` in the terminal, which is already accomplished by appending the path to the desired python version to the PATH environment variable.
comment on: http://stackoverflow.com/q/47391785
score: 0

http://stackoverflow.com/comment/81819624
comment on: http://stackoverflow.com/a/47432588
type: Comment
score: 2
type: AnswerComment
has text: Your code is working, it outputs `0`. It does exactly what it is supposed to do, but as noted in another answer, you have made and error in the math.

http://stackoverflow.com/comment/81957162
score: 0
comment on: http://stackoverflow.com/q/47500315
has text: I think it may be easier if you have first word same in every record that has to have same name for e.g. there are only `Tesco` instead of also having `Tescos` otherwise there may need of looking into similarity.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81800439
comment on: http://stackoverflow.com/a/47421968
score: 0
type: AnswerComment
has text: I have added it to my code, where the correct answer is always the last one in the file so that the correct answer is always detail[3]
type: Comment

http://stackoverflow.com/q/47494706
upvote count: 1
tagged with: python
answer count: 0
has body: I'm a beginner and have been stuck on this problem a few days now. This is on Windows 10 with python 3.6 MAIN PROBLEM: File "C:\Python 3.6\Lib\site-packages\zmq\backend\cython__init__.py", line 6, in from . import (constants, error, message, context, ImportError: cannot import name 'constants' I'm trying to build a little app and running it in the command prompt to check it for errors and immediately I got an ImportError with from ipywidgets import * Even after setting the PATH variable correctly it still wasn't finding ipywidgets. When I used the command prompt as an interpretor it imported ipywidgets without a problem, it's only when I run the script that it doesn't. So I added to the code import sys sys.path.append('C:\Python 3.6\Lib\site-packages') which is where the ipywidgets module is located and it is now giving me Traceback (most recent call last): File "C:\Python 3.6\Scripts\SQLapp.py", line 5, in from ipywidgets import Text File "C:\Python 3.6\Lib\site-packages\ipywidgets__init__.py", line 25, in from .widgets import * File "C:\Python 3.6\Lib\site-packages\ipywidgets\widgets__init__.py", line 4, in from .widget import Widget, CallbackDispatcher, register, widget_serialization File "C:\Python 3.6\Lib\site-packages\ipywidgets\widgets\widget.py", line 13, in from ipykernel.comm import Comm File "C:\Python 3.6\Lib\site-packages\ipykernel__init__.py", line 2, in from .connect import * File "C:\Python 3.6\Lib\site-packages\ipykernel\connect.py", line 18, in import jupyter_client File "C:\Python 3.6\Lib\site-packages\jupyter_client__init__.py", line 4, in from .connect import * File "C:\Python 3.6\Lib\site-packages\jupyter_client\connect.py", line 22, in import zmq File "C:\Python 3.6\Lib\site-packages\zmq__init__.py", line 34, in from zmq import backend File "C:\Python 3.6\Lib\site-packages\zmq\backend__init__.py", line 40, in reraise(*exc_info) File "C:\Python 3.6\Lib\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise raise value File "C:\Python 3.6\Lib…
score: 1
downvote count: 0
tagged with: import
favorite count: 0
type: Question
tagged with: python-3.x
has title: from . import (constants, error, message, context, ImportError: cannot import name 'constants'
type: UnansweredQuestion
tagged with: path

http://stackoverflow.com/comment/81998882
comment on: http://stackoverflow.com/a/47520930
type: Comment
type: AnswerComment
has text: Right! I forgot about that. Awesome.
score: 0

http://stackoverflow.com/a/47428113
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47427238
has body: Use pd.DataFrame.corr Also, no need to use Numpy here when the built in Pandas method does the job well for you. Correlations will be one because you've normalized the different series by their respective standard deviations. df.corr() A B A 1.0 1.0 B 1.0 1.0 While pd.DataFrame.cov gets you df.cov() A B A 1.666667 1.666667 B 1.666667 1.666667 The other posters are correct. We can see that performing the maths correctly, we get df.cov().div(df.std()).div(df.std(), 0) A B A 1.0 1.0 B 1.0 1.0
downvote count: 0

http://stackoverflow.com/q/47431431
has comment: http://stackoverflow.com/comment/81817408
favorite count: 0
has comment: http://stackoverflow.com/comment/81817464
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81818545
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81817402
has body: x=['Hello', 90, 8.9999, 4.6, 'DOG', 'CAT', 1] x.reverse() x Out[109]: ['Hello', 90, 8.9999, 4.6, 'DOG', 'CAT', 1] x.sort() Error Traceback (most recent call last): File "&lt;ipython-input-110-42dad5a67ac3&gt;", line 1, in &lt;module&gt; x.sort() TypeError: '&lt;' not supported between instances of 'int' and 'str' why I am getting this error?
has answer: http://stackoverflow.com/a/47432336
type: UnansweredQuestion
tagged with: python
tagged with: sorting
score: -4
answer count: 1
downvote count: 6
tagged with: list
has comment: http://stackoverflow.com/comment/81817406
has comment: http://stackoverflow.com/comment/81818976
has title: Error while doing sort operation in python

http://stackoverflow.com/a/47416561
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47415919
has body: If the newline is in appearing in the text of your column maybe something like this wouldwork. csv_writer.writerow([i[0].replace('\n',' ') for i in cur.description])

http://stackoverflow.com/q/47434924
tagged with: sorting
has comment: http://stackoverflow.com/comment/81824564
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47436818
type: Question
has comment: http://stackoverflow.com/comment/81825918
score: 5
has title: Is there a elegant way to only keep top[2~3] value for each row in a matrix?
has comment: http://stackoverflow.com/comment/81824211
tagged with: dataframe
tagged with: python
has body: A easier way has updated in the end of the question. What I have I have a user-user correlation matrix called matrixcorr_of_user like the one below: userId 316 320 359 370 910 userId 316 1.000000 0.202133 0.208618 0.176050 0.174035 320 0.202133 1.000000 0.242837 0.019035 0.031737 359 0.208618 0.242837 1.000000 0.357620 0.175914 370 0.176050 0.019035 0.357620 1.000000 0.317371 910 0.174035 0.031737 0.175914 0.317371 1.000000 What I want For every user, I just want to keep the 2 other users that are the most similar to him (the highest correlation values per row after excluding the elements of the diagonal). Like so: Out[40]: userId 316 320 359 370 910 corr_user 316 NaN 0.202133 0.208618 NaN NaN 320 0.202133 NaN 0.242837 NaN NaN 359 NaN 0.242837 NaN 0.357620 NaN 370 NaN NaN 0.357620 NaN 0.317371 910 NaN NaN 0.175914 0.317371 NaN I know how to achieve it, but the way I came up with is too complicated. Could anyone provide a better idea? What I have tried I first melt the matrix: melted_corr = corr_of_user.reset_index().melt(id_vars ="userId",var_name="corr_user") melted_corr.head() Out[23]: userId corr_user value 0 316 316 1.000000 1 320 316 0.202133 2 359 316 0.208618 3 370 316 0.176050 4 910 316 0.174035 filter it row by row: get_secend_third = lambda x : x.sort_values(ascending =False).iloc[1:3] filted= melted_corr.set_index("userId").groupby("corr_user")["value"].apply(get_secend_third) filted Out[39]: corr_user userId 316 359 0.208618 320 0.202133 320 359 0.242837 316 0.202133 359 370 0.357620 320 0.242837 370 359 0.357620 910 0.317371 910 370 0.317371 359 0.175914 and finally reshape it: filted.reset_index().pivot_table("value","corr_user","userId") Out[40]: userId 316 320 359 370 910 corr_user 316 NaN 0.202133 0.208618 NaN NaN 320 0.202133 NaN 0.242837 NaN NaN 359 NaN 0.242837 NaN 0.357620 NaN 370 NaN NaN 0.357620 NaN 0.317371 910 NaN NaN 0.175914 0.317371 NaN Updated: I came up with a easier way to do this after saw the answer of @John Zwinck Let's say there is…
upvote count: 6
possible better answer: http://stackoverflow.com/a/47435278
has answer: http://stackoverflow.com/a/47435697
accepted answer: http://stackoverflow.com/a/47435697
has answer: http://stackoverflow.com/a/47435278
has comment: http://stackoverflow.com/comment/81824034
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81825996
answer count: 3

http://stackoverflow.com/comment/81912180
has text: You want to use `str.join()` instead; `'-'.join(["1","2","3"])` does what you want *already*.
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/47478684
type: Comment

http://stackoverflow.com/comment/81838470
has text: Could you provide a simple copy-paste minimum working example? (https://stackoverflow.com/help/mcve) This way you motivate more people to help you because it makes it easy for them to help you.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47441547
type: QuestionComment

http://stackoverflow.com/comment/81786019
comment on: http://stackoverflow.com/a/47412487
score: 0
has text: I have updated the question, with my complete solution and more input.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47443988
has comment: http://stackoverflow.com/comment/81843146
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47444030
has comment: http://stackoverflow.com/comment/81843532
linked to: http://stackoverflow.com/q/27494758
has answer: http://stackoverflow.com/a/47444030
tagged with: python
has title: bash: python: .py: command not found
score: 2
upvote count: 4
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/27494758
tagged with: bash
downvote count: 2
has body: I am trying to run the following command in QIIME2 virtual machine, installed on macbook but the code is not working validate_mapping_file.py -m Fasting_Map.txt -o mapping_output Here is the link: http://qiime.org/tutorials/tutorial.html I get the following message bash: validate_mapping_file.py: command not found I am new to unix/linux as well as on qiime. I would be very thankful for the help...
tagged with: qiime
answer count: 1

http://stackoverflow.com/comment/81994527
has text: Are you doing any batching, or just passing each image as an individual `sess.run`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47482493
type: Comment

http://stackoverflow.com/q/47389635
tagged with: wsgi
tagged with: javascript
accepted answer: http://stackoverflow.com/a/47393513
answer count: 1
tagged with: ajax
has answer: http://stackoverflow.com/a/47393513
linked to: http://stackoverflow.com/q/34976794
type: Question
tagged with: eve
tagged with: python
has body: I'm running a simple wsgi server, from run import app if __name__ == "__main__": app.run(threaded=True, debug=True) And I am hitting the server with a get request, the server returns a 200 message, but doesn't return any data. I get the following error message Error on request: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/werkzeug/serving.py", line 209, in run_wsgi execute(self.server.app) File "/Library/Python/2.7/site-packages/werkzeug/serving.py", line 200, in execute write(data) File "/Library/Python/2.7/site-packages/werkzeug/serving.py", line 175, in write self.send_header('Server', self.version_string()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.py", line 401, in send_header self.wfile.write("%s: %s\r\n" % (keyword, value)) IOError: [Errno 32] Broken pipe I've read in a few places that using the threaded option should get round a broken pipe error, but hasn't seemed to help in my case. Does anyone have any ideas? Flask version is 0.12.2. !!!EDIT!!! So the point of the page I'm developing is to take user defined coordinates from a leaflet map and make a call to a database, in this case neo4j. The query works fine, as does the API as it all works well in postman. So the problem must be somewhere in my web app. Here is my server app for the web page. Maybe in the Ajax call? from flask import Flask, render_template from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/demo') def webMap(): return render_template('demo3.html') if __name__ == '__main__': app.config['DEBUG'] = True app.run(host='localhost', port=8090) Here is the JS: var map = L.map('map1').setView([51.506725, -0.076486], 12); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &amp;copy; &lt;a href="http://openstreetmap.org"&gt;OpenStreetMap&lt;/a&gt; contributors, &lt;a href="http://creativecommons.org/licenses/by-sa/2.0/"&gt;CC-BY-SA…
has title: WSGI with python eve [Errno 32] Broken pipe... Ajax call
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47481271
has title: How to make a sum of all Values from an List in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/81917343
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/81918063
tagged with: python
has answer: http://stackoverflow.com/a/47481310
upvote count: 0
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/47481313
has body: So I have a List which looks like this: values = { '123456':['Value1':41235534], '543123':['Value1':12958362], '34573':['Value1':1295937]} And when I try to make a sum like this: sum1 = sum(int(i['Value1']) for i in values) I get "TypeError: 'int' object is not subscriptable". What am I doing wrong ?

http://stackoverflow.com/a/47398972
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47395529
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47395529
has body: When you open the T_MainWindow in the second example, the ui variable is global, so it does not get garbage-collected. But when you open it from the park method, the ui variable is local, so it will be garbage-collected when the method returns (and thus before the window is shown). To fix that, you can change the local variable to an attribute, so that a reference is kept for the window: def park(self, N): from time_dialog import T_MainWindow self.t_window = T_MainWindow(self, N) self.t_window.show()

http://stackoverflow.com/a/47448201
has comment: http://stackoverflow.com/comment/81868351
downvote count: 0
has comment: http://stackoverflow.com/comment/81854849
has body: Instead of using countvec.fit_transform() on testset, only use transform(). Change this line: documenttermmatrix_test=countvec.fit_transform(testset['description']) To this: documenttermmatrix_test=countvec.transform(testset['description']) This will make sure that those features which are present in training set are only taken from the test set and if not available, put 0 there. fit_transform() will forget the previous trained data and make new matrix which can have different features than previous output. Hence the error.
has comment: http://stackoverflow.com/comment/81860151
has comment: http://stackoverflow.com/comment/81862895
has comment: http://stackoverflow.com/comment/81852069
has comment: http://stackoverflow.com/comment/81853003
has comment: http://stackoverflow.com/comment/81863348
has comment: http://stackoverflow.com/comment/81868386
has comment: http://stackoverflow.com/comment/81863051
type: Answer
has comment: http://stackoverflow.com/comment/81854620
answers question: http://stackoverflow.com/q/47407996
has comment: http://stackoverflow.com/comment/81862986
score: 3
upvote count: 3

http://stackoverflow.com/q/47458775
has comment: http://stackoverflow.com/comment/81944396
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion
has title: Python json.dumps adding backslash
has comment: http://stackoverflow.com/comment/81872160
tagged with: serialization
tagged with: c#
score: 0
has body: My c# code using Python Provider with 3.5 version. I am sending REST request to my Python Provider, and I getting a weird response with to many backslashes, like the following: This is how the response looks in my c# code "\"{\\\"IsSuccess\\\": true, \\\"Value\\\": null, \\\"ErrorCode\\\": 0, \\\"ErrorMessage\\\": \\\"\\\", \\\"RequestId\\\": \\\"09ea4b59-52a9-4796-a967-62317457ea91\\\"}\"\n" In my Python Provider I using json.dumps(object2Serialize.__dict__) in order the info to be serialized. Any ideas why I am getting the object in my C# code like this?
tagged with: http://stackoverflow.com/tag/json

debugging
tags question: http://stackoverflow.com/q/47455452
tags question: http://stackoverflow.com/q/47534405
tags question: http://stackoverflow.com/q/47416854
tags question: http://stackoverflow.com/q/47445310
tag name: debugging
tags question: http://stackoverflow.com/q/47434489
type: Tag
tags question: http://stackoverflow.com/q/47519531
tags question: http://stackoverflow.com/q/47435749
tags question: http://stackoverflow.com/q/47411156
tags question: http://stackoverflow.com/q/47522316

http://stackoverflow.com/q/47506698
tagged with: google-oauth
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
tagged with: authentication
upvote count: 1
accepted answer: http://stackoverflow.com/a/47507576
has body: In Step 3 of Gmail API instruction they show how to use it and access data. But after running program it opens up the browser and then it ask us to authenticate and shows allow button to give access to your data. Now my question is that, is it possible to Authenticate any account without really opening any browser. Like set up username and password and then it will automatically do all the authentication stuff and get the data from there without really opening browser. Or I will have to use scraping techniques like BeautifulSoup and then open up that link and then click on that button. Thanks
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47507576
tagged with: gmail-api
tagged with: oauth
has title: Python: Is it possible to Authenticate through Gmail API without opening browser
tagged with: python

http://stackoverflow.com/q/47453085
has answer: http://stackoverflow.com/a/47453593
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47453710
answer count: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81861487
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/81863131
type: AnsweredQuestion
score: 3
has title: Numpy broadcast_to for masked array
has comment: http://stackoverflow.com/comment/81861744
has answer: http://stackoverflow.com/a/59648428
has body: I'm using the np.broadcast_to function to get a view on a reshaped array just like the example: &gt;&gt;&gt; x = np.array([1, 2, 3]) &gt;&gt;&gt; np.broadcast_to(x, (3, 3)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) Passing a masked array to this function loses me the mask though: &gt;&gt;&gt; y = np.ma.array([1, 2, 3], mask=[False, True, False]) &gt;&gt;&gt; np.broadcast_to(y, (3, 3)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) How do I get the following view? array([[1, --, 3], [1, --, 3], [1, --, 3]])
tagged with: python
possible better answer: http://stackoverflow.com/a/47453593
tagged with: masked-array
has comment: http://stackoverflow.com/comment/81861530
accepted answer: http://stackoverflow.com/a/47453710

database
tags question: http://stackoverflow.com/q/47453453
tags question: http://stackoverflow.com/q/47414063
tags question: http://stackoverflow.com/q/47529906
tags question: http://stackoverflow.com/q/47470557
tags question: http://stackoverflow.com/q/47428758
tags question: http://stackoverflow.com/q/47393518
tags question: http://stackoverflow.com/q/47465930
tags question: http://stackoverflow.com/q/47502752
tags question: http://stackoverflow.com/q/47431178
tags question: http://stackoverflow.com/q/47453611
type: Tag
tags question: http://stackoverflow.com/q/47446530
tags question: http://stackoverflow.com/q/47430996
tags question: http://stackoverflow.com/q/47514886
tags question: http://stackoverflow.com/q/47432988
tags question: http://stackoverflow.com/q/47452552
tags question: http://stackoverflow.com/q/47397117
tags question: http://stackoverflow.com/q/47507428
tags question: http://stackoverflow.com/q/47481101
tags question: http://stackoverflow.com/q/47407720
tag name: database

http://stackoverflow.com/comment/81881274
has text: I tried that, too, but that does not give me the response content. I think there might be something wrong with .json(), or somehow the URL does not work.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47461823

http://stackoverflow.com/a/47383718
upvote count: 1
score: 1
has body: Just another way of doing using collections.defaultdict(int) from collections import defaultdict l = [(2,'x'),(-5,'y'),(-3,'x')] d_dict = defaultdict(int) for k, v in l: d_dict[v]+=k [(v,k) for k,v in d_dict.items()] #Output: #[(-1, 'x'), (-5, 'y')]
answers question: http://stackoverflow.com/q/47383667
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82013508
comment on: http://stackoverflow.com/a/47526930
score: 1
type: Comment
has text: @Karn: `yield` makes something a generator function, see [What does the "yield" keyword do?](//stackoverflow.com/q/231767)
type: AnswerComment

http://stackoverflow.com/q/47525379
type: AnsweredQuestion
has body: I am a new in Python pandas, so sorry if this question is very easy. I have three lists: A = ['A','B','C'] M = ['1','2','3'] F = ['plus','minus','square'] I want to make those lists combined and show it in data frame. I have tried to use list.append new_list = [] for i in A: new_list.append(i) for j in (M): new_list.append(j) print(new_list) ['A', '1', '2', '3', 'B', '1', '2', '3', 'C', '1', '2', '3'] I confused, how to get the output like this (in dataframe):
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82006933
type: Question
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/82006878
tagged with: loops
has comment: http://stackoverflow.com/comment/82006916
has answer: http://stackoverflow.com/a/47525447
has answer: http://stackoverflow.com/a/47525474
possible better answer: http://stackoverflow.com/a/47525474
accepted answer: http://stackoverflow.com/a/47525447
has title: Create python dataframe based on nested loop

http://stackoverflow.com/comment/81910593
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47477868
has text: def NBAquestions(): x = 0 question6 = Question("What does the NBA stand for?", "National Basketball Live", "National Fun Live", "National Basketball League", "Nothin But Liberals", 3) if question6.ask() == True: print("You are correct") x += 1

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/47439355

http://stackoverflow.com/q/47482206
downvote count: 0
has answer: http://stackoverflow.com/a/47482222
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/81919274
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: I need to scrape all 'a' tags with "result-title" class, and all 'span' tags with either class 'results-price' and 'results-hood'. Then, write the output to a .csv file across multiple columns. The current code does not print anything to the csv file. This may be bad syntax but I really can't see what I am missing. Thanks. f = csv.writer(open(r"C:\Users\Sean\Desktop\Portfolio\Python - Web Scraper\RE Competitor Analysis.csv", "wb")) def scrape_links(start_url): for i in range(0, 2500, 120): source = urllib.request.urlopen(start_url.format(i)).read() soup = BeautifulSoup(source, 'lxml') for a in soup.find_all("a", "span", {"class" : ["result-title hdrlnk", "result-price", "result-hood"]}): f.writerow([a['href']], span['results-title hdrlnk'].getText(), span['results-price'].getText(), span['results-hood'].getText() ) if i &lt; 2500: sleep(randint(30,120)) print(i) scrape_links('my_url')
type: UnansweredQuestion
tagged with: python
has title: Short & Easy - soup.find_all Not Returning Multiple Tag Elements
score: 1
answer count: 1

http://stackoverflow.com/comment/81873558
has text: I still don't understand why it worked for snippets/2 but not for snippets/1 when my url pattern was missing the slash at the end
score: 0
comment on: http://stackoverflow.com/q/47459216
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81770958
comment on: http://stackoverflow.com/q/47408683
score: 0
type: Comment
type: QuestionComment
has text: I have pasted the error message @GrzegorzOledzki

http://stackoverflow.com/comment/81840143
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47440757
has text: it gives me the same error
score: 0

http://stackoverflow.com/comment/88832009
type: Comment
comment on: http://stackoverflow.com/a/47672159
type: AnswerComment
has text: Thanks for the update. So you did not have to increase the l2 regularization or use dropout in the end?
score: 0

http://stackoverflow.com/comment/82038327
type: Comment
has text: Apologies, I forgot to add the condition in the question.. well the condition that I am looking is rows starting and ending with , tag
comment on: http://stackoverflow.com/a/47539689
type: AnswerComment
score: 0

http://stackoverflow.com/q/47437988
has comment: http://stackoverflow.com/comment/81830461
has body: I just made a keylogger with python 2.7 but it doesn't work. Here is the keylogger code: import pyHook, pythoncom, sys, logging file_log = 'C:\keyloggeroutput.txt' def OnKeyboardEvent(event): logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s') print "You pressed: ", chr(event.Ascii) logging.log(10,chr(event.Ascii)) return True hooks_manager = pyHook.HookManager() hooks_manager.KeyDown = OnKeyboardEvent hooks_manager.HookKeyboard() pythoncom.PumpMessages()﻿ And this is the error i get: Traceback (most recent call last): File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch return func(event) File "&lt;stdin&gt;", line 2, in OnKeyboardEvent File "C:\Python27\lib\logging\__init__.py", line 1547, in basicConfig hdlr = FileHandler(filename, mode) File "C:\Python27\lib\logging\__init__.py", line 913, in __init__ StreamHandler.__init__(self, self._open()) File "C:\Python27\lib\logging\__init__.py", line 943, in _open stream = open(self.baseFilename, self.mode) IOError: [Errno 13] Permission denied: 'C:\\keyloggeroutput.txt' My python folder is here: C:\Python27 How can I make the keylogger work?
tagged with: python-2.7
score: 0
has title: Python 2.7 keylogger
answer count: 3
has answer: http://stackoverflow.com/a/75946231
has comment: http://stackoverflow.com/comment/81830589
tagged with: cmd
has answer: http://stackoverflow.com/a/47438072
type: Question
tagged with: keylogger
type: UnansweredQuestion
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/47438023

http://stackoverflow.com/a/47392217
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47391785
score: 2
answers question: http://stackoverflow.com/q/47391785
type: Answer
has body: If what you want is to get a specific version of the Python interpreter when you type python in your shell, there is no environment variable that can help you in that sense. It is the shell that decides the binary of the interpreter to use, and by the time it is spawned it cannot be swapped to a different one. Some ways that you can work around this: As you said, making a symlink somewhere. It does not need to be in a system directory, many users have something like $HOME/bin in their $PATH (some Linux distributions do this by default). Make an alias (e.g. in your .bashrc or similar). Make a function (same as previous). You could even program it to receive some argument that decides which version of the interpreter you want to use, or to use the value of some environment variable, as you suggested. In distributions supporting it, set up an alternative. Make a virtual environment using the interpreter that you want and work within that environment. In any case, there are a few things you should take into account: As mentioned in another answer, changing the version of the Python interpreter system-wide may break things. Particularly, switching the command python from Python 2 to Python 3 (or the other way around) is almost guaranteed to cause quite a lot of trouble. Some of the solutions above may be unaffected by this (e.g. setting and alias or function in .bashrc should not affect other scripts, unless sourced), but you should be careful about it. A common pitfall here is that changing the python command does not change every Python-based command. For example, if you use IPython and just type ipython you need to make sure that the correct interpreter and script are launched. Depending on your context there may be a few tools that you may need to consider in that sense. A virtual environment is probably the easiest and cleanest solution, since it was designed for that particular problem (even though issues still arise sometimes, e.g. if you run ipython but you forgo…

integer
tags question: http://stackoverflow.com/q/47441379
tag name: integer
tags question: http://stackoverflow.com/q/47462866
tags question: http://stackoverflow.com/q/47473676
tags question: http://stackoverflow.com/q/47455461
type: Tag

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/47389447
type: Tag
tags question: http://stackoverflow.com/q/47488506

http://stackoverflow.com/q/47463826
type: UnansweredQuestion
tagged with: bit-manipulation
has comment: http://stackoverflow.com/comment/81882598
has comment: http://stackoverflow.com/comment/81883027
tagged with: python
has title: How can I optimize a somewhat complex binary algorithm in python
tagged with: optimization
score: 0
answer count: 1
has body: I am trying to iterate over a large chunk of data and organize the values properly. Context: data is a large set of integers that were interpreted from raw bye data. The integers are actually densely packed data and on top of that the bytes are in a "little endian" order. So, in order to get proper values I have found that I need to read in 3 values, extract each nibble, then reorder them all into the proper orientation. So, finally to my question. How can I speed up this process or optimize, as right now it takes over a minute to get through all of the data from a single file and I could potentially have thousands of files. for i in range(0, len(data), 3): j = struct.pack("=I", data[i]) p = struct.pack("=I", data[i + 1]) q = struct.pack("=I", data[i + 2]) nibble0 = j[1] &gt;&gt; 4 nibble1 = j[1] &amp; 15 nibble2 = j[0] &gt;&gt; 4 nibble3 = j[0] &amp; 15 nibble4 = j[3] &gt;&gt; 4 nibble5 = j[3] &amp; 15 nibble6 = j[2] &gt;&gt; 4 nibble7 = j[2] &amp; 15 nibble8 = p[1] &gt;&gt; 4 nibble9 = p[1] &amp; 15 nibble10 = p[0] &gt;&gt; 4 nibble11 = p[0] &amp; 15 nibble12 = p[3] &gt;&gt; 4 nibble13 = p[3] &amp; 15 nibble14 = p[2] &gt;&gt; 4 nibble15 = p[2] &amp; 15 nibble16 = q[1] &gt;&gt; 4 nibble17 = q[1] &amp; 15 nibble18 = q[0] &gt;&gt; 4 nibble19 = q[0] &amp; 15 nibble20 = q[3] &gt;&gt; 4 nibble21 = q[3] &amp; 15 nibble22 = q[2] &gt;&gt; 4 nibble23 = q[2] &amp; 15 k.append((nibble0 &lt;&lt; 12) | (nibble1 &lt;&lt; 8) | (nibble2 &lt;&lt; 4) | 0) k.append((nibble3 &lt;&lt; 12) | (nibble4 &lt;&lt; 8) | (nibble5 &lt;&lt; 4) | 0) k.append((nibble6 &lt;&lt; 12) | (nibble7 &lt;&lt; 8) | (nibble8 &lt;&lt; 4) | 0) k.append((nibble9 &lt;&lt; 12) | (nibble10 &lt;&lt; 8) | (nibble11 &lt;&lt; 4) | 0) k.append((nibble12 &lt;&lt; 12) | (nibble13 &lt;&lt; 8) | (nibble14 &lt;&lt; 4) | 0) k.append((nibble15 &lt;&lt; 12) | (nibble16 &lt;&lt; 8) | (nibble17 &lt;&lt; 4) | 0) k.append((nibble18 &lt;&lt; 12) | (nibble19 &lt;&lt; 8) | (nibble20 &lt;&lt; 4) | 0) k.append((nibble21 &lt;&lt; 12) | …
type: Question
tagged with: python-3.x
tagged with: binary
has comment: http://stackoverflow.com/comment/81886226
has answer: http://stackoverflow.com/a/47505870
has comment: http://stackoverflow.com/comment/81936587

http://stackoverflow.com/comment/81752129
score: 0
comment on: http://stackoverflow.com/q/47399339
type: Comment
has text: It *is* referenced outside the loop, no? `c.execute('''INSERT INTO ...''', (k,v))`
type: QuestionComment

http://stackoverflow.com/q/47442944
score: 0
has comment: http://stackoverflow.com/comment/81841564
has comment: http://stackoverflow.com/comment/81841085
has comment: http://stackoverflow.com/comment/81841153
has comment: http://stackoverflow.com/comment/81841513
type: Question
has title: Attribute error when calling function
has comment: http://stackoverflow.com/comment/81840934
has comment: http://stackoverflow.com/comment/81841005
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81840961
has comment: http://stackoverflow.com/comment/81841158
tagged with: python
tagged with: inheritance
has comment: http://stackoverflow.com/comment/81841201
tagged with: class
has comment: http://stackoverflow.com/comment/81841715
answer count: 0
has body: I am coding a date program using classes and inheritance. I am trying to define the function advance, which makes the seconds, minute, and hour advance according to some rules. I defined second, minute, and hour as another class called "Counter". The problem is, when calling the functions defined in counter, I get an error saying : while self._hora!=self._hora.getMax(): AttributeError: 'function' object has no attribute 'getMax' This is the code of the class Reloj. I will also post the code to a git with the whole code so you can check it out. class Reloj(object): _segundo = Contador(0, 59) _minuto = Contador(0, 59) _hora = Contador(0, 24) def __init__(self, s, minu, h): self._segundo = Contador(0, 59) self._minuto = Contador(0, 59) self._hora = Contador(0, 24) self.set(s,minu,h) def set(self, s, minu, h): self._segundo.setCuenta(s) self._minuto.setCuenta(minu) self._hora.setCuenta(h) def tic(self): while self._segundo != self._segundo.getMax(): self._segundo=self._segundo.getCuenta while self._minuto!=self._minuto.getMax(): self._minuto=self._minuto.getCuenta while self._hora!=self._hora.getMax(): self._hora=self._hora.getCuenta else: self._hora.contar() else: self._minuto.contar() else: self._segundo.contar() def display(self): return print (str(self._segundo.getCuenta())+":"+str(self._minuto.getCuenta())+":"+str(self._hora.getCuenta())) CODE: https://gist.github.com/anonymous/1ce55e50f3c3f53e937279475c0336bc

http://stackoverflow.com/comment/81992173
type: AnswerComment
has text: Another clarification: are you assuming that the top columns level has only two entries? If I had A, B, C, would you do as below? a[:,:n][a_mask] = 0 ; a[:,n:2*n][a_mask] = 0; a[:,2*n:][a_mask] = 0
score: 0
comment on: http://stackoverflow.com/a/47517319
type: Comment

http://stackoverflow.com/comment/82022033
comment on: http://stackoverflow.com/a/47525331
type: Comment
type: AnswerComment
has text: Yes. I have uploaded pics of the error when I try to use **data.loc[:,['r_name','reviewtext','date']]**
score: 0

http://stackoverflow.com/comment/81848623
type: Comment
type: QuestionComment
has text: I got it to stop hanging in the LXD container by changing the invocation to: `subprocess.call(['/bin/bash', 'test.sh'], shell=True) `
score: 0
comment on: http://stackoverflow.com/q/47408993

http://stackoverflow.com/comment/82014076
comment on: http://stackoverflow.com/q/47511885
type: Comment
has text: @N.Ivanov Thank you very much for your time !
type: QuestionComment
score: 0

http://stackoverflow.com/q/47518985
has answer: http://stackoverflow.com/a/47519111
upvote count: 1
has answer: http://stackoverflow.com/a/47519992
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81995857
linked to: http://stackoverflow.com/q/3570796
has comment: http://stackoverflow.com/comment/81996403
tagged with: python
has title: pythonic way to expose user override hooks
has comment: http://stackoverflow.com/comment/81994592
score: 0
answer count: 2
type: UnansweredQuestion
has body: Note: although my particular use is Flask related, I think the question is more general. I am building a Flask web application meant to be customized by the user. For example, the user is expected to provide a concrete subclass of a DatabaseInterface and may add to the list of certain ModelObjects that the application knows how to handle. What is the best way to expose the various hooks to users, and indicate required and optional status? 'Best' here primarily means most 'pythonic', or "easiest for python users to grasp", but other criteria like not causing headaches down the road are certainly worth mentioning. Some approaches I've considered: Rely solely on documentation Create a template file with documented overrides, much like default config files for many servers. E.g. app = mycode.get_app() ##Add your list of extra foo classes here #app.extra_foos = [] Create a UserOverrides class with an attr/method for each of the hooks; possibly split into RequiredOverrides and OptionalOverrides Create an empty class with unimplemented methods that the user must subclass into a concrete instance

http://stackoverflow.com/q/47399339
answer count: 0
has comment: http://stackoverflow.com/comment/81752098
has comment: http://stackoverflow.com/comment/81776554
type: Question
has body: def foo() : for i in range(0, 5): path2 = "data." + str(i) + "\\log." + str(i) file = path + path2 try: if os.path.getsize(file) &gt; 0: print("All good") f=open(file) string=f.read() pattern="(cd\s/[a-zA-Z0-9]*.*)" matches=re.findall(pattern,string) for input in matches: print(input) a=input.split(";") x=len(a) print(x) cmd.append(x) y=0 if y &lt;= x: y=y+1 print(a) listofcmd.append(a) continue print(cmd) print(listofcmd) dictionary=dict(zip(cmd,listofcmd)) print("Number of commands : List of Commands") print(dictionary) for k,v in dictionary.items(): print(k,v) row=c.fetchall() c.execute('''INSERT INTO log (Numberofcmds, Listofcmds) VALUES (?, ?)''', (k,v)) conn.commit() sqlstr1=('SELECT (Numberofcmds, Listofcmds) FROM log ') for row in c.execute(sqlstr1): print(str(row[0]), row[1]) except OSError: print("File not found") i=i+1 return i foo() I want to insert the data into the database and i am getting a unboundlocalerror for the variable 'k' which is not referenced outside the loop. What might the problem here? I tried to insert session id and time similarly i did not face any problem but now when i'm trying to add this data i m continuously getting this error how much ever i change. Error : VALUES (?, ?)''', (k,v)) UnboundLocalError: local variable 'k' referenced before assignment
has comment: http://stackoverflow.com/comment/81752129
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81776510
tagged with: python
has title: UnboundLocalError: local variable referenced before assignment which is not referenced
score: 0

http://stackoverflow.com/q/47416747
score: 0
has title: Use getattr inside of another getattr
tagged with: django
tagged with: django-rest-framework
type: Question
has body: How can I use getattr method inside of another getattr? I want to write something like that: my_attr = 'group.getattr(name)' my_list = list() for q in queryset_for_table: y = getattr(q, my_attr, None) my_list.append(y) How can i write my_attr string correct?
has comment: http://stackoverflow.com/comment/81787317
tagged with: python
has comment: http://stackoverflow.com/comment/81787757
accepted answer: http://stackoverflow.com/a/47416867
possible better answer: http://stackoverflow.com/a/47527663
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47416867
answer count: 2
has comment: http://stackoverflow.com/comment/81787324
has answer: http://stackoverflow.com/a/47527663
has comment: http://stackoverflow.com/comment/81787380

http://stackoverflow.com/q/47514444
tagged with: python-3.x
has title: Is there an easy way of installing PySide 2 for Windows?
tagged with: pyside2
has answer: http://stackoverflow.com/a/47518796
possible better answer: http://stackoverflow.com/a/47518796
has body: Is there any way to "simply" install PySide 2 on Windows 10? If not are there tutorials for installing it? Can I export a PySide 2 project to an .exe file?
tagged with: python
has answer: http://stackoverflow.com/a/53297903
accepted answer: http://stackoverflow.com/a/53297903
type: AnsweredQuestion
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/27885397
tagged with: pyside
has answer: http://stackoverflow.com/a/49258943
type: Question

http://stackoverflow.com/comment/81794233
comment on: http://stackoverflow.com/q/47419659
has text: @Bharath just tried - got ` ValueError: Item wrong length 1 instead of 8107.`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47399565
has comment: http://stackoverflow.com/comment/81752558
type: Answer
score: 0
has body: You can check out Schedule Python job scheduling for humans. An in-process scheduler for periodic jobs that uses the builder pattern for configuration. Schedule lets you run Python functions (or any other callable) periodically at pre-determined intervals using a simple, human-friendly syntax.
answers question: http://stackoverflow.com/q/47399473

http://stackoverflow.com/q/47412744
has title: Replace a text and save in a new file text - Python
has comment: http://stackoverflow.com/comment/81786523
has comment: http://stackoverflow.com/comment/81779049
score: 0
has comment: http://stackoverflow.com/comment/81784457
has body: They are the first Python weapons and I would need to create a simple script that takes all text files in input (a folder of choice). For each text file, delete line "# Constructed from biom file" and replace "#OTU ID" with "OTU_ID". Then save it to another text file that keeps the first portion of the file name and then adds "_mod.txt" to the end of the file name. The script must perform all these operations automatically for all the files in the directory. #!/usr/bin/python # import os,sys,uuid # with open("/home/antonino/Scrivania/Prove_python/otu_table_filtered_L1.txt","r") as input: # Apro il file di testo with open("/home/antonino/Scrivania/Prove_python/otu_table_filtered_L1.txt","wb") as output: # Creo un nuovo file modificato for line in input: print line # alvo tutte le linee diverse da # Constructed from.... if line!="# Constructed from biom file"+"\n": newline = line.replace('OTU ID', 'OTU_ID') output.write(newline) os.rename("/home/antonino/Scrivania/Prove_python/otu_table_filtered_L1_mod.txt",'result_otu_table_filtered_'+str(uuid.uuid4())+'.txt') This works only in this mode, but that's not what I want.
has comment: http://stackoverflow.com/comment/81778751
type: Question
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81791414

http://stackoverflow.com/comment/81882649
score: 1
comment on: http://stackoverflow.com/q/47463593
has text: Sounds like a privilege issue, although I am not experienced enough with calling Python from php to know whether that could be an issue here.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81816053
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47430612
has text: @M.Jones , You can't insert '1 2 3' as input. You run in a loop (in your case three iterations), you need to insert 1 and then press enter, than 2 than press enter, than 3 and enter. this would work.

http://stackoverflow.com/q/47510544
upvote count: 0
tagged with: jsp
tagged with: python
tagged with: tornado
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81977451
has comment: http://stackoverflow.com/comment/81976699
has body: I have shared a part of my code and in the Class 'Room',variable 'nw' has the query string value.Now,I want the html file to autofill the 'nw' field with the query string value dynamically.How do I get that?Does self.get_namespaces help? class Room(tornado.web.RequestHandler): def get(self): nw=self.get_argument("nw") print(nw) self.render("RoomPost.html") class static(tornado.web.RequestHandler): def get(self,key): iname="static/" +key print iname self.render(iname) settings = { 'debug': True, 'static_path': 'static'} application = tornado.web.Application([ (r"/room",Room ), #(r"/static/(.*)",static) ], **settings) if __name__ == "__main__": application.listen(5500) tornado.ioloop.IOLoop.instance().start() Following is the html file <c:import url="InnerHeader.js"></c:import> Room Add Name of NW/Name of Home &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
tagged with: http://stackoverflow.com/tag/html
answer count: 1
accepted answer: http://stackoverflow.com/a/47510943
has comment: http://stackoverflow.com/comment/81976731
tagged with: web
downvote count: 1
has answer: http://stackoverflow.com/a/47510943
favorite count: 0
has title: How to pass arguments from tornado to a html file?
type: Question
linked to: http://stackoverflow.com/q/19112296

http://stackoverflow.com/a/47481743
has comment: http://stackoverflow.com/comment/81918418
has body: Try this: import numpy as np np.add.reduce(df[columnlist], axis=1) What this does is to "add" the values in each row, which for strings means to concatenate them ("abc" + "de" == "abcde"). Originally I thought you wanted to concatenate them lengthwise, into a single longer series of all the values. If anyone else wants to do that, here's the code: pd.concat(map(df.get, columnlist)).reset_index(drop=True)
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/81918717
upvote count: 10
has comment: http://stackoverflow.com/comment/82031194
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82043716
has comment: http://stackoverflow.com/comment/81989425
accepted answer of: http://stackoverflow.com/q/47481696
has comment: http://stackoverflow.com/comment/82002757
answers question: http://stackoverflow.com/q/47481696

http://stackoverflow.com/q/47455680
has body: For a machine learning task at school I wrote my own MLP network. The data set is quite big, and training takes forever. I was alerted to the option of running my script on the Google Cloud Compute Engine. I tried to set this up, but did not succeed (yet). The steps I undertook where: Create an account Create a VM Open the VM via the browser Can anyone help me with importing and running my python script into the Google Cloud. Or does anyone have clear a tutorial on how to solve this? I tried finding these myself, but had no success so far.
favorite count: 0
has comment: http://stackoverflow.com/comment/81865765
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61846806
answer count: 5
has comment: http://stackoverflow.com/comment/137360545
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47548802
has answer: http://stackoverflow.com/a/47466330
accepted answer: http://stackoverflow.com/a/47548802
downvote count: 2
has title: Running a python script on Google Cloud Compute Engine
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/65275185
possible better answer: http://stackoverflow.com/a/65275185
upvote count: 24
has answer: http://stackoverflow.com/a/52784348
score: 22

http://stackoverflow.com/q/47403072
downvote count: 0
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45988474
tagged with: google-app-engine
has title: Google App Engine appspotmail - setup an inbox?
tagged with: python
tagged with: php
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47407290
accepted answer: http://stackoverflow.com/a/47407290
has body: My PHP GAE app has a Python sub service that receives mail. It's address is email@service-dot-myappname.appspotmail.com The Python script just breaks down the message and inserts it into the database for processing. Every so often a bad email is received that the database doesn't like (strange encoding, way too long etc.) so to investigate, I need to go digging in the logs. My question is, is there a way to have this email address attached in an inbox as well? I don't see anything in the Google docs, but I'm hoping someone else has done something similar?
score: 1
upvote count: 1
tagged with: email

http://stackoverflow.com/a/47518585
score: 1
answers question: http://stackoverflow.com/q/47518405
type: Answer
accepted answer of: http://stackoverflow.com/q/47518405
has comment: http://stackoverflow.com/comment/82025548
has body: It is hard to tell exactly what you want, but I assume you want to check the data_column key of the dict that you have just appended to results. Again, I'm not sure if this is what is desired, but you can get the last element from results by taking an index of -1: for recordset in return_stored_procedure: results.append(dict(zip(sp_column_names, recordset))) if results[-1]['days_column'] &lt;= 30: print variable else: print variable
type: AcceptedAnswer
downvote count: 0
upvote count: 1

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/47403435
type: Tag

http://stackoverflow.com/a/47441055
type: AcceptedAnswer
type: Answer
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/81858859
answers question: http://stackoverflow.com/q/47440568
downvote count: 1
has body: The arguments and names of some functions are not correct, I think they are caused because you have tried to copy and remove the secondary part but remember that the order is interesting in python. If you want to assign a property to a Widget you must first obtain it and for them an id must be placed, this id will be the name of the variable that will be created and assigned, we can access it through ids as I show below: from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.clock import Clock import random root = Builder.load_string(''' &lt;Demo&gt;: cols: 1 BoxLayout: orientation: 'vertical' Button: id: btn size_hint: .2, .2 pos_hint: {'x':0, 'center_y': .1} ''') class Demo(BoxLayout): def __init__(self, *args, **kwargs): BoxLayout.__init__(self, *args, **kwargs) Clock.schedule_interval(self.randgen, 0.01) def randgen(self, dt): rand_val = random.randint(0, 10) self.ids.btn.text = str(rand_val) print(rand_val) class MainApp(App): def build(self): return Demo() if __name__ == '__main__': MainApp().run()
accepted answer of: http://stackoverflow.com/q/47440568

http://stackoverflow.com/a/47476741
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47476595
has body: No you cannot have a function using the Python 3 form in a file used by the Python 2 interpreter. That's because the keyword-only argument placed after the *args is a change to the Python syntax so it will cause a syntax error in Python 2 before you even get near executing the code. You will have to either use the Python 2 version in both cases, or use separate source files and only import the correct one.

http://stackoverflow.com/q/47507272
has comment: http://stackoverflow.com/comment/81970414
has answer: http://stackoverflow.com/a/47507855
has body: the python gurus, i got this task i was given to complete, i have ended up writing the code, but i keep getting this error "Oops! Don't forget to use the setters in your constructor, and print "&lt;attribute name&gt; changed" whenever a setter is called (regardless of whether the correct type was supplied)" my code has one constructor and six methods. the first three methods are getters while the last three are setters. My problem is how do i resolve this error Oops! Don't forget to use the setters in your constructor, and print "&lt;attribute name&gt; changed" whenever a setter is called (regardless of whether the correct type was supplied) Because it seems am using the setters already but don't know why this error persist thanks. Here is my full code: class TodoItem: def __init__(self, title, description, completed=False): self.title = title self.description = description self.completed = completed def getTitle(self): print ("title accessed") return self.title def getDescription(self): print ("description accessed") return self.description def getCompleted(self): print ("completed accessed") return self.completed def setTitle(self, newtitle): print ("title changed") if type(newtitle) == str: self.title = newtitle else: print ("invalid value title changed") self.title = None def setDescription(self, newdescription): print ("description changed") if type(newdescription) == str: self.description = newdescription else: print ("invalid value description changed") self.description = None def setCompleted(self, newbool): print ("completed changed") if type(newbool) == bool: self.completed = newbool else: print ("invalid value completed changed") self.completed = None This is my code to test the code above: mytodo = TodoItem(99,"make a list and go to the store") mytodo.setTitle(99) print (mytodo.getTitle())
tagged with: python
has comment: http://stackoverflow.com/comment/81970676
has comment: http://stackoverflow.com/comment/81970398
score: -1
has comment: http://stackoverflow.com/comment/81970622
has comment: http://stackoverflow.com/comment/81972126
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81972659
has title: How to use setter in python constructor
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81971927
tagged with: oop
has comment: http://stackoverflow.com/comment/81970429
type: UnansweredQuestion

http://stackoverflow.com/q/47401651
has comment: http://stackoverflow.com/comment/81756958
has comment: http://stackoverflow.com/comment/81757011
accepted answer: http://stackoverflow.com/a/47402115
has comment: http://stackoverflow.com/comment/81756964
has title: trying to install latset version of numpy but am getting syntax errors?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47402115
tagged with: syntax-error
tagged with: installation
has comment: http://stackoverflow.com/comment/81757180
tagged with: python
has comment: http://stackoverflow.com/comment/81757065
tagged with: opencv
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/23708898
has body: I am trying to use opencv but whenever I try to import the package I get the RuntimeError: module compiled against API version 0xa but this version of numpy is 0x7 Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; import cv2 ImportError: numpy.core.multiarray failed to import error. So I did some research and found the question with an identical problem to my own, but the answers provided there all cause a syntax error for me in the python command line. This is the most common answer I've seen that doesn't work for me: pip install -U numpy And several variations of that that all result in syntax errors. I have python 2.7.5 and did have numpy 1.9.1, but I uninstalled it when I was trying to figure out the problem, so I currently have numpy 1.7.1 downloaded. I asked for help with this in the comments section of my previous question, but a bunch of people marked my question as a duplicate of some other question (that doesn't work for me) and now I'm not getting much help. That said, if anyone knows how to solve my problem, that would be much appreciated.
answer count: 1

http://stackoverflow.com/q/47512227
tagged with: python
has comment: http://stackoverflow.com/comment/82010852
tagged with: forms
has body: I'm using UpdateView to edit data using forms. After cliking the Edit button a modal is being popped up with a few forms that can be edited and then after I edit and click confirm I get an error: TemplateDoesNotExist at /edit/117/ (or other pk...) DevOpsWeb/serverlist_form.html Request Method: POST Request URL: http://devopsweb:8000/edit/117/ Django Version: 1.11.6 Exception Type: TemplateDoesNotExist Exception Value: DevOpsWeb/serverlist_form.html Why do I get this error? Why when I get the modal the information of the PK is blank...? Does anyone know any of these questions? I'm really stuck :( Thank you! view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) #if not form.cleaned_data['ServerName']: #post.servername = " " post.save() #text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'tex…
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: mysql
accepted answer: http://stackoverflow.com/a/47512364
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47512364
has comment: http://stackoverflow.com/comment/81981394
type: Question
has title: Django Website - TemplateDoesNotExist at /edit/117/
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/81980363
tagged with: django

http://stackoverflow.com/comment/81846627
has text: @kKinga Jn What does "cen and cen2 must be constantly" mean? Also what does "but set center to f.ex. 5, not 0.0" mean? I think your "gaussian" function does not define a 2D Gaussian, but a sum of 2 1-D Gaussians. It would be helpful to explain better what you are trying to fit, and give both the entire script and the entire output.
score: 0
comment on: http://stackoverflow.com/q/47437560
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47404084
tagged with: django
favorite count: 0
type: Question
tagged with: beautifulsoup
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47404263
has title: django database update using BeautifulSoup
tagged with: django-models
tagged with: python
accepted answer: http://stackoverflow.com/a/47404263
score: 1
has body: Im very new to Django. I have been running through tutorials and decided to start on something of my own and need a little advice on the best way forward. I'm creating a simple site which runs through a small list of URLS stored in a postgreSQL table and uses Beautiful Soup to extract data from each of the URL pages and store it against the record.. (its just stats recorded on the home page of each) Ive set up the model and the relevant class listview to display them all. About to start running through the beautiful soup part and wondered where should physically put the code to run through and "scrape" the data for each site? Should it be something called when the class view is called? Some kind of Model Manager? Just a bespoke Function or something? I would like to use Ajax to update this data in intervals if possible so it needs to fit in with that. Hopefully that's not too vague. Happy to post what i have if you feel that's beneficial although it is literally just a simple model and Class ListView. Thanks!
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81970781
has text: Fair enough... answer has been removed.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47507321

http://stackoverflow.com/q/47464813
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python if-else mess
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/47464833
has answer: http://stackoverflow.com/a/47464882
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47464833
score: 2
type: AnsweredQuestion
has body: Is there a cleaner way to create msg? For each event (Ping, Pull request, Issue, Issue comment, Repo, Create, Delete, Pull requset review, Push, Commit comment) is there an if clause that checks the event and creates a message according to it's action. data = request.json event = request.headers['X-Github-Event'] msg = "" ... # Pull request elif event == "pull_request": if data['action'] == "opened": msg = PullRequest(data).opened() elif data['action'] == "closed": msg = PullRequest(data).closed() elif data['action'] == "assigned": msg = PullRequest(data).assigned() # Issue elif event == "issues": if data['action'] == "opened": msg = Issue(data).opened() elif data['action'] == "reopened": msg = Issue(data).reopened() elif data['action'] == "closed": msg = Issue(data).closed() elif data['action'] == "labeled": msg = Issue(data).labeled() elif data['action'] == "assigned": msg = Issue(data).assigned() ...
answer count: 2
possible better answer: http://stackoverflow.com/a/47464882
has comment: http://stackoverflow.com/comment/81884388

http://stackoverflow.com/a/47497779
type: Answer
answers question: http://stackoverflow.com/q/47497735
upvote count: 2
has body: You can do this with nested list comprehension: b = [ [ binary[h][i:i+2] for i in range(len(binary[h])-1)] for h in range(len(binary))] So here for every value h in range(len(binary)) we construct a separate list, with the list comprehension [ binary[h][i:i+2] for i in range(len(binary[h])-1)]. This list comprehension will let a variable i iterate over range(len(binary[h])-1) and for every element, add binary[h][i:i+2] to the sublist. That being said, we can improve the code, and iterate over the elements of binary directly: b = [ [ subbin[i:i+2] for i in range(len(subbin)-1)] for subbin in binary] So here for every subbin list in binary, we generate a sublist (again with list comprehension), this is the result of [ subbin[i:i+2] for i in range(len(subbin)-1)] so we generate a list of subbin[i:i+2]s for every i in range(len(subbin)-1).
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47497735
has comment: http://stackoverflow.com/comment/81950983

http://stackoverflow.com/q/47394745
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81750321
has title: Python UDP sockets: Broadcast works but Unicast doesn't
downvote count: 0
upvote count: 1
has body: Setup I am trying to send control commands to a sensor using UDP packets on an Ethernet network. The sensor has hard-coded source IP and port number that it will only reply to, thus I must bind the port before sending. And since I have several interfaces on my machine I must also bind the IP address. A sample code is presented below. import socket DST_IP = "..." SRC_IP = "..." PORT_NO = . message = "..." sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.bind((SRC_IP, PORT_NO)) sock.connect((DST_IP, PORT_NO)) sock.sendto(bytes(message, "utf-8"), (DST_IP, PORT_NO)) sock.sendto(bytes(message, "utf-8"), ("255.255.255.255", PORT_NO)) print("src ", sock.getsockname()) # verify binding successful print("dst ", sock.getpeername()) # verify connecting successful sock.close() I am monitoring the packets using Wireshark and checking for the sent data to verify that the commands were successful. Problem After binding and connecting, I cannot detect a unicast on Wireshark but only the broadcast. If I don't bind, the program will choose a different interface and the sending will be successful I tried to disable all network interfaces except the one I need and try to run the program without binding the IP or port and nothing was sent in unicast but only in broadcast I am out of ideas for debugging. Suggestions?
favorite count: 0
type: Question
tagged with: sockets
tagged with: python
tagged with: udp
has comment: http://stackoverflow.com/comment/81769602
answer count: 0

http://stackoverflow.com/q/47417474
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47417643
has comment: http://stackoverflow.com/comment/81797457
has comment: http://stackoverflow.com/comment/81799081
has comment: http://stackoverflow.com/comment/81799030
downvote count: 0
has answer: http://stackoverflow.com/a/47417643
favorite count: 0
accepted answer: http://stackoverflow.com/a/47431402
type: Question
has title: Pandas counting occurrence of list contained in column of lists
has comment: http://stackoverflow.com/comment/81797608
has answer: http://stackoverflow.com/a/47431402
tagged with: python
tagged with: vectorization
has body: I have this Pandas DataFrame that has a column with lists: &gt;&gt;&gt; df = pd.DataFrame({'m': [[1,2,3], [5,3,2], [2,5], [3,8,1], [9], [2,6,3]]}) &gt;&gt;&gt; df m 0 [1, 2, 3] 1 [5, 3, 2] 2 [2, 5] 3 [3, 8, 1] 4 [9] 5 [2, 6, 3] I want to count the number of times a list v = [2, 3] is contained in the lists of the DataFrame. So in this example the correct answer would be 3. Now this is just an example, in my actual data the df['m'] can contain more than 9 million rows and the lists are actually lists of strings with up to about 20 elements. Some more details if it matters: The elements of v contain no duplicates and neither do the lists of m, so they can be sets instead of lists. The first iteration of my program iterated over each row and checked all(e in data['m'][i] for e in v) and if that's True, I increment a counter. But as addressed in many SO questions and blog posts, iterating over the rows of a DataFrame is slow and can be done much faster. So for my next iteration I added a column to the DataFrame that contains a copy of the list v: &gt;&gt;&gt; df['V'] = [[2, 3]] * len(df) &gt;&gt;&gt; df V m 0 [2, 3] [1, 2, 3] 1 [2, 3] [5, 3, 2] 2 [2, 3] [2, 5] 3 [2, 3] [3, 8, 1] 4 [2, 3] [9] 5 [2, 3] [2, 6, 3] and a helper function that simply returns the containment boolean like I did before: def all_helper(l1, l2): return all(v in l1 for v in l2) which I can then use with np.vectorize to add a column with the boolean value: df['bool'] = np.vectorize(all_helper)(df['m'], df['V']) And lastly, calculate the sum of these booleans with a simple df['bool'].sum() I also tried to use .apply(): df['bool'] = df.apply(lambda row: all(w in row['m'] for w in v), axis=1) count = df['bool'].sum() but this was slower than the vectorisation. Now these methods work, and the vectorisation is much faster than the initial approach, but it feels a bit clunky (creating a column with identical values, using a helper function in such a way). So my question, performance is key, is there a bett…
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/81798984
has comment: http://stackoverflow.com/comment/81795143
type: AnsweredQuestion

http://stackoverflow.com/a/47419508
upvote count: 1
downvote count: 1
type: Answer
has body: you can try splitting the lines with open('input_file_name.txt') as input_file: line_number = 1 for line in input_file.readlines(): print( 'Line {} : {}'.format(line_number,len(line.split(' ')))) line_number +=1
answers question: http://stackoverflow.com/q/47419371
score: 0

http://stackoverflow.com/a/47401004
downvote count: 1
has comment: http://stackoverflow.com/comment/81758089
has body: This if((len(password) == len(password2)) and (len(password) and len(password2)) &gt;= 3 &lt; 20 ): should probably be this if((len(password) == len(password2)) and (len(password) and len(password2)) &gt;= 3 and (len(password) and len(password2)) &lt; 20 ): Though I'm sure there is a simpler way, that seemed like the smallest change to your code.
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47400968
upvote count: 0
has comment: http://stackoverflow.com/comment/81758255

http://stackoverflow.com/q/47405394
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
downvote count: 0
has title: Chromedriver is not being found in python, windows Anaconda
tagged with: python
has answer: http://stackoverflow.com/a/58069946
has answer: http://stackoverflow.com/a/47408894
possible better answer: http://stackoverflow.com/a/47408894
type: AnsweredQuestion
score: 2
answer count: 3
has body: I have freshly installed Chrome on my pc. I have installed Anaconda. I have tried putting Chrome in the Anaconda directory wtih Chrome. I've got a clean Anaconda, I've installed chromedriver through Anaconda, as well as downloaded it and tried it through Cmd. I also have tried just about every relevant folder I can think of but it just can't seem to find path. I've deleted every visible Chromedriver in case it's getting that. Any idea on how to fix this issue as I've spent the better half of 4 hours attempting to get Python to stop creating issues. The last time I did this was 4 months ago and I remember a similar headache. Is there a set directory I am overlooking where chromedriver must go or you shall suffer the fate of selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH for all eternity
has answer: http://stackoverflow.com/a/47405466
accepted answer: http://stackoverflow.com/a/47405466
tagged with: selenium
tagged with: google-chrome

http://stackoverflow.com/comment/82243887
score: 0
type: Comment
type: AnswerComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160464/discussion-between-coderboy-and-vasia).
comment on: http://stackoverflow.com/a/47398609

http://stackoverflow.com/q/47434658
has comment: http://stackoverflow.com/comment/81823789
has comment: http://stackoverflow.com/comment/81823717
possible better answer: http://stackoverflow.com/a/47437814
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47437814
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/81828202
has answer: http://stackoverflow.com/a/47437830
has body: I would like to add a border to an irregular 3 dimensional image that is stored as a binary numpy array. I thought of perhaps shifting the image a voxel left/right, forward/back, up/down and then combining those 6 images and subtracting the original image; using the below code: #make copy of the image shifted one voxel to the left image_border = np.zeros((img_dim[0], img_dim[1], img_dim[2])) for x in xvoxels: x_slice_original = image[x, :, :] x_slice_new = np.zeros((img_dim[1], img_dim[2])) for y in yvoxels: for z in zvoxels: if x_slice_original[y, z] == 1: x_slice_new[(y-1), z] = 1 else: x_slice_new[(y-1), z] = 0 image_border[x, :, :] = x_slice_new That seems a bit inefficient though and was wondering if anyone had any neater solutions? Edit: The image is an MRI image 91*109*91 voxels. xvoxels and zvoxels are lists 0:90, yvoxels is a list 0:108.A 2D slice of the image in question is below:
tagged with: image
has comment: http://stackoverflow.com/comment/81824284
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47437830
has title: Add a border to a irregular image in python
has comment: http://stackoverflow.com/comment/81824474
tagged with: python
has comment: http://stackoverflow.com/comment/81823425

http://stackoverflow.com/comment/81736099
has text: The error in your original post means that the package you're trying to install either doesn't exist or hasn't been released for your combination of OS and Python versions.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47390300

http://stackoverflow.com/q/47440247
favorite count: 0
type: Question
has title: Python: Click Package - Having trouble with non ASCII chars & cmd.exe
tagged with: encoding
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81835589
tagged with: line
tagged with: click
has comment: http://stackoverflow.com/comment/81835705
has body: I am writing a command line tool using the Click Python Package: http://click.pocoo.org/5/ Which is quite usefull but I can't get one issue fixed with that, which is when I enter non ASCII chars as parameter for my Command Line Tool, it will always give me that encoding error: And yeah I know about encode() and decode() in python, but as you can see in my code I am not touching this string anywhere. Is it the fault of my console? Am I missing any settings here? I am using Windows 7 cmd.exe and know that Windows likes his own encoding for filenames etc. Do I have to use another console? Tried python one with same result. The click Documentation states all strings are treated as Unicode... I would appreciate your help really much. Installing click is as easy as pip install click Kind regards, Marcurion My Code: import click from click_shell import shell import os @shell(prompt='Tool &gt; ', intro='some test...', hist_file=os.path.dirname(os.path.realpath(__file__))) def stRec(): pass @stRec.command() @click.argument('name', required=True, type=click.STRING) def set(name): print "nothing" if __name__ == '__main__': stRec()
has answer: http://stackoverflow.com/a/47443180
downvote count: 1
tagged with: command
score: -1

http://stackoverflow.com/comment/81905777
score: 0
comment on: http://stackoverflow.com/a/47475419
has text: No sir, maybe I messed Up I want 2D array each row with elements between the corressponding ranges. Sorry if the question was misleading
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81837680
type: Comment
type: QuestionComment
has text: So, `len(set(str))`?
comment on: http://stackoverflow.com/q/47441353
score: 2

http://stackoverflow.com/a/47504421
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47503913
has comment: http://stackoverflow.com/comment/134464175
upvote count: 4
answers question: http://stackoverflow.com/q/47503913
has comment: http://stackoverflow.com/comment/81975969
type: Answer
has body: You definitely update all label when you press the button. Just crate a StringProperty for each and do what you are doing now. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.properties import StringProperty from kivy.lang import Builder #used because I didn't want to create two files import random Builder.load_string(''' &lt;TestingWidget&gt;: BoxLayout: orientation: 'horizontal' Button: text: 'test' on_press: root.button_pressed() Label: id: label_to_update text: root.label_to_update ''') class TestingWidget(BoxLayout): # This is the kv id of the Label I would like to update label_to_update = StringProperty('Trying to get this to update') #default text set # This is the action I would like to happen when the button is pressed def button_pressed(self): self.label_to_update = 'Updated!' class TestButtonApp(App): def build(self): return TestingWidget() if __name__ == '__main__': TestButtonApp().run()
score: 4
has comment: http://stackoverflow.com/comment/135712828
type: AcceptedAnswer

http://stackoverflow.com/comment/82216702
has text: Hi Jay.. i tried your solution #1 and it works. I am able to replicate the local file system in D: drive of webjob. However, my application has a reference to a path from remote VM which is mounted in my VM. May i know is there a way to mount or reference a file available in a different VM in webjob?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47546364
type: Comment

http://stackoverflow.com/comment/81998368
score: 0
comment on: http://stackoverflow.com/a/47520536
type: Comment
has text: nevermind, your solution worked. i was misunderstanding a bit. thank you very much :)
type: AnswerComment

http://stackoverflow.com/q/47444756
has comment: http://stackoverflow.com/comment/81848321
has title: Trying to use skimage.morphology in an image processing code but get error message
answer count: 1
has comment: http://stackoverflow.com/comment/81848311
has comment: http://stackoverflow.com/comment/81848659
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81849035
has body: I'm working thru an image processing example in python 2.7.13. The code has import skimage.morphology as morph and then later has the line lm1 = morph.is_local_maximum(fimg). I get the error message: File "2dlocalmaxima.py", line 29, in &lt;module&gt; lm1 = morph.is_local_maximum(fimg) AttributeError: 'module' object has no attribute 'is_local_maximum'. I've googled this and have found many instances of this module being used. I can find no instance of this being deprecated. Am I doing something wrong? I have tried running in python 2.7.13 and 3.6. Both give same error message. The total code from the book is: import numpy as np import matplotlib.pyplot as mpl import scipy.ndimage as ndimage import skimage.morphology as morph # Generating data points with a non-uniform background x = np.random.uniform(low=0, high=200, size=20).astype(int) y = np.random.uniform(low=0, high=400, size=20).astype(int) # Creating image with non-uniform background func = lambda x, y: np.cos(x)+ np.sin(y) grid_x, grid_y = np.mgrid[0:12:200j, 0:24:400j] bkg = func(grid_x, grid_y) bkg = bkg / np.max(bkg) # Creating points clean = np.zeros((200,400)) clean[(x,y)] += 5 clean = ndimage.gaussian_filter(clean, 3) clean = clean / np.max(clean) # Combining both the non-uniform background # and points fimg = bkg + clean fimg = fimg / np.max(fimg) # Calculating local maxima lm1 = morph.is_local_maximum(fimg) x1, y1 = np.where(lm1.T == True) # Creating figure to show local maximum detection # rate success fig = mpl.figure(figsize=(8, 4)) ax = fig.add_subplot(111) ax.imshow(fimg) ax.scatter(x1, y1, s=100, facecolor='none', edgecolor='#009999') ax.set_xlim(0,400) ax.set_ylim(0,200) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) fig.savefig('scikit_image_f02.pdf', bbox_inches='tight')
accepted answer: http://stackoverflow.com/a/47450451
tagged with: python
has answer: http://stackoverflow.com/a/47450451
has comment: http://stackoverflow.com/comment/81848480
has comment: http://stackoverflow.com/comment/81853625
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81849214
score: 0
has comment: http://stackoverflow.com/comment/81855382

http://stackoverflow.com/comment/81849376
has text: First of all, correct your test string. You have written `Ubutu` instead of `Ubuntu`. Secondly, you can try this regex: [`Ubuntu\s*\d+(?:\.\d+)?`](https://regex101.com/r/iGzyET/1)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47447043
type: Comment

http://stackoverflow.com/q/47510135
has title: Should I first train_test_split and then use cross validation?
accepted answer: http://stackoverflow.com/a/47510334
has body: If I plan to use cross validation (KFold), should I still split the dataset into training and test data and perform my training (including cross valid) only on the training set? Or will CV do everything for me? E.g. Option 1 X_train, X_test, y_train, y_test = train_test_split(X,y) clf = GridSearchCV(... cv=5) clf.fit(X_train, y_train) Option 2 clf = GridSearchCV(... cv=5) clf.fit(X y)
upvote count: 5
tagged with: cross-validation
has answer: http://stackoverflow.com/a/47510334
tagged with: python
has comment: http://stackoverflow.com/comment/81976413
type: AnsweredQuestion
score: 5
has comment: http://stackoverflow.com/comment/81980764
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: Question

http://stackoverflow.com/q/47395545
tagged with: api
has title: How to send this http request in python?
has answer: http://stackoverflow.com/a/47530303
possible better answer: http://stackoverflow.com/a/47530303
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/47568300
has body: I want to make this request in python, via python requests: curl -X POST \ --form fileItems[0].fileToUpload=@"/path/to/file.mp4" \ --form fileItems[0].path="/something/" \ --form fileItems[0].replacing=false \ --form fileItems[1].fileToUpload=@"/path/to/file.mp4" \ --form fileItems[1].path="/something/" \ --form fileItems[1].replacing=false \ someurl.com/files/ what would be the equivalent in python? I wrote this : files = {'fileItems[0].fileToUpload': open('/path/to/file.mp4', 'rb'), 'fileItems[0].path': '/medias/videos/comedian_contest/', 'fileItems[0].replacing': False} response = requests.post(url='http://storage.backtory.com/files', files=files, headers=headers) but I get this error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3/dist-packages/requests/api.py", line 107, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/lib/python3/dist-packages/requests/api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "/usr/lib/python3/dist-packages/requests/sessions.py", line 454, in request prep = self.prepare_request(req) File "/usr/lib/python3/dist-packages/requests/sessions.py", line 388, in prepare_request hooks=merge_hooks(request.hooks, self.hooks), File "/usr/lib/python3/dist-packages/requests/models.py", line 296, in prepare self.prepare_body(data, files, json) File "/usr/lib/python3/dist-packages/requests/models.py", line 447, in prepare_body (body, content_type) = self._encode_files(files, data) File "/usr/lib/python3/dist-packages/requests/models.py", line 150, in _encode_files fdata = fp.read() AttributeError: 'bool' object has no attribute 'read'
tagged with: python
has comment: http://stackoverflow.com/comment/82016028
tagged with: curl
accepted answer: http://stackoverflow.com/a/47568300
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82015749
score: 0
answer count: 2

http://stackoverflow.com/a/47426291
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47424843
score: 0
accepted answer of: http://stackoverflow.com/q/47424843
has body: There are two separate issues with the code that are causing this error: (1) Your code is initializing results and Gain to length-1 lists. Instead (based on what it appears you're trying to do), you should be initializing them to length lenght (sic*) lists, i.e.results = [None] * lenght and Gain = [None] * lenght. (2) Files is an array of dicts. In each loop iteration, files (sic**) becomes one of those dicts. If you instead want files to be an index into the Files list, then your loop should be for files in range(0, lenght):. Alternatively, if you want results and Gain to be dicts, you can initialize them as results = {} and similarly for Gain, and then in each iteration you can set their values like results(&lt;filename&gt;) = ... (where &lt;filename&gt; is the current file name. Also, if you want to keep the loop of the form for files in Files:, that's fine, but keep in mind that files will actually be an element of Files rather than an index into Files. * From a style perspective, you should correct the spelling of lenght to length. ** Also from a style perspective, you should probably not name the list index files; perhaps something like f. But this is more subjective.

http://stackoverflow.com/q/47486763
has comment: http://stackoverflow.com/comment/81928691
has comment: http://stackoverflow.com/comment/81928693
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/81928766
score: 1
has body: Image of how my dataframe looks at the minute I am trying to put a new column into my dataframe called "council" which will be based upon the Town field. So for example, if the Town == Belfast, I want the new column council to hold the value Belfast. However a note to make is, some of these council values are not the same as the town. Another example may be, the town could be Clogher and I want to put in the council value Fermanagh. I am very new to python and would really appreciate any help. If you need any more information that I have left out please ask. (So far I have only tried this for the council area Belfast) What I want to do is loop over every row in my data frame and check the "Town" Column. If the Town column is equal to "Belfast" Then I would like to input the value "Belfast" into a new Column called "Council." count = 0 for index, row in PsniYear1617Cleaned.iterrows(): grabtown = PsniYear1617Cleaned["Town"] for value in grabtown: if value["Town"][0] == "Belfast": PsniYear1617Cleaned.set_value(index, 'Council', value["Belfast"]) count = count + 1 TypeError Traceback (most recent call last) &lt;ipython-input-122-31f11c973fc5&gt; in &lt;module&gt;() 3 grabtown = PsniYear1617Cleaned["Town"] 4 for value in grabtown: ----&gt; 5 if value["Town"][0] == "Belfast": 6 PsniYear1617Cleaned.set_value(index, 'Council', value["Belfast"]) 7 count = count + 1 TypeError: string indices must be integers, not str`
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47487023
has comment: http://stackoverflow.com/comment/81928825
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81928725
has comment: http://stackoverflow.com/comment/81928572
has answer: http://stackoverflow.com/a/47487023
has title: How can I add a value to a new column based on a value existing in my dataframe in Python?
possible better answer: http://stackoverflow.com/a/47487004
has comment: http://stackoverflow.com/comment/81928586
has answer: http://stackoverflow.com/a/47487004
tagged with: dataframe
tagged with: python
tagged with: jupyter

http://stackoverflow.com/comment/82033602
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47536681
type: AnswerComment
has text: @mgokhanbakal And where was that specified in your question? Why did you try and mention sklearn then when i asked? There is no detailed/formal model in your question! And if so, you probably have to implement it yourself (the whole learning-procedure).

http://stackoverflow.com/q/47481101
favorite count: 0
tagged with: extract
tagged with: sql
upvote count: 0
has title: Extracting separate tables from a database
answer count: 1
tagged with: ms-access
has answer: http://stackoverflow.com/a/47481552
has comment: http://stackoverflow.com/comment/81920572
has comment: http://stackoverflow.com/comment/81939659
type: Question
has body: I have 12 075 400 entries on my MS Access database. Each entry corresponds to an employee. There are total of 270 employees, i.e. each employee has multiple entries. There are other multiple columns for each employee such as salary, location etc. I wanted to create 270 separate tables corresponding to each employee in the same database. The employees are entered into the database as 1, 2, 3, 4....till 270 with all their other details in other columns. I tried writing an SQL query for that, but its not working. How can I extract multiple tables out of this database to create separate 270 tables for each employee? I was also thinking of using a relational database, but don't know how will it work! I am also allowed to use python for the same. If anyone can suggest how to do it using python that will be great too.
has comment: http://stackoverflow.com/comment/81931389
tagged with: database
downvote count: 3
tagged with: python
type: UnansweredQuestion
score: -3

http://stackoverflow.com/comment/81719919
type: Comment
type: QuestionComment
score: 1
has text: @ayhan Yeah, I think it's a windows problem - windows appends carriage returns to newlines (there's historical significance, but I'm not sure of what it is).
comment on: http://stackoverflow.com/q/47383584

http://stackoverflow.com/comment/81766957
has text: how to sort 'd' based on value 'y'
comment on: http://stackoverflow.com/a/47406177
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47477942
tagged with: neural-network
tagged with: scikit-learn
tagged with: python
type: UnansweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/47478439
has comment: http://stackoverflow.com/comment/81911471
type: Question
tagged with: perceptron
answer count: 1
has body: I am still in learning phase of sklearn and need some help in understanding how to come with a relation between output and input. Using data I was able to train sklearn MLPClassifier. clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes = (7,), random_state = 1) #Print Coef print clf.coefs_.shape print clf.coefs_ The output looks like this: Output print Any help will be useful. Thanks!!
score: 2
upvote count: 2
has title: sklean MLPClassifier: how to find relation/equation between output and input features
downvote count: 0

http://stackoverflow.com/comment/81809034
comment on: http://stackoverflow.com/q/47427271
type: Comment
has text: just sequentially is good @C.Feenstra
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81763010
comment on: http://stackoverflow.com/q/47404589
score: 1
type: Comment
type: QuestionComment
has text: I believe this may answer your question [How do I stop a python script from running via a webpage?](https://raspberrypi.stackexchange.com/questions/23615/how-do-i-stop-a-python-script-from-running-via-a-webpage)

http://stackoverflow.com/q/47480111
has answer: http://stackoverflow.com/a/47481888
type: Question
tagged with: numpy
has body: I have neural network in Keras using LSTM for training chatbot. contextTrain, contextTest, utteranceTrain, utteranceTest = train_test_split(context, utterance, test_size=0.1, random_state=1) model = Sequential() model.add(LSTM(input_shape=contextTrain.shape[1:], return_sequences=True, units=300, activation="sigmoid", kernel_initializer="glorot_normal", recurrent_initializer="glorot_normal")) model.add(LSTM(return_sequences=True, units=300, activation="sigmoid", kernel_initializer="glorot_normal", recurrent_initializer="glorot_normal")) model.compile(loss="cosine_proximity", optimizer="adam", metrics=["accuracy"]) model.fit(contextTrain, utteranceTrain, epochs=5000, validation_data=(contextTest, utteranceTest), callbacks=[ModelCheckpoint("model{epoch:02d}.h5", monitor='val_acc', save_best_only=true, mode='max')]) Context and utterance are numpy arrays with shape e.g. (1000, 10, 300) or (10000, 10, 300). Input_shape of first LSTM should be (10, 300). Vector with size 300 is word represented by word embedding created by Word2vec model. So input data are 10 of these vectors in this example. The biggest problem is that loss and val_loss are both almost steadily increasing during training. Epoch 1/5000 900/900 [==============================] - 18s 20ms/step - loss: -0.5855 - acc: 0.0220 - val_loss: -0.6527 - val_acc: 0.0260 Epoch 2/5000 900/900 [==============================] - 13s 14ms/step - loss: -0.6299 - acc: 0.0239 - val_loss: -0.6673 - val_acc: 0.0240 Epoch 3/5000 900/900 [==============================] - 12s 14ms/step - loss: -0.6387 - acc: 0.0213 - val_loss: -0.6764 - val_acc: 0.0160 Epoch 4/5000 900/900 [==============================] - 12s 13ms/step - loss: -0.6457 - acc: 0.0229 - val_loss: -0.6821 - val_acc: 0.0240 Epoch 5/5000 900/900 [==============================] - 12s 14ms/step - loss: -0.6497 - acc: 0.0274 - val_loss: -0.6873 - val_acc: 0.0230 Epoch 6/5000 900/900 [==============================] - 14s 15ms/step - loss: -0.6507 - acc: 0.0276 - val_l…
upvote count: 0
tagged with: loss
has title: Keras - loss and val_loss increasing
score: -3
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/81915459
tagged with: keras
favorite count: 0
tagged with: lstm
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81918324
tagged with: python
accepted answer: http://stackoverflow.com/a/47481888

http://stackoverflow.com/comment/82424237
type: AnswerComment
has text: Thank you, root cause was me not paying attention to this particular `py3` change. I wonder why, when using import incorrectly, was there one package that made it though the import
type: Comment
comment on: http://stackoverflow.com/a/47719021
score: 0

http://stackoverflow.com/comment/81754491
type: Comment
comment on: http://stackoverflow.com/a/47400385
type: AnswerComment
score: 1
has text: I don't think you need to use `sorted`, the list is already sorted. Using sort + groupby is a clear indicator that something else should be done

http://stackoverflow.com/a/47551616
accepted answer of: http://stackoverflow.com/q/47404898
has comment: http://stackoverflow.com/comment/84357187
type: Answer
answers question: http://stackoverflow.com/q/47404898
has comment: http://stackoverflow.com/comment/84353942
has comment: http://stackoverflow.com/comment/96610623
upvote count: 4
has comment: http://stackoverflow.com/comment/82525415
has comment: http://stackoverflow.com/comment/82432881
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/82432030
has comment: http://stackoverflow.com/comment/82502504
has body: Since you don't provide a working example, it's bit unclear what your starting point is. I made a dataset with 1 polygon, if you have a dataset with multiple but only want to target a specific polygon you can add SQLStatement or where to the gdal.Rasterize call. Sample polygon geojson = """{"type":"FeatureCollection", "name":"test", "crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}, "features":[ {"type":"Feature","properties":{},"geometry":{"type":"MultiPolygon","coordinates":[[[[-110.254,44.915],[-114.176,37.644],[-105.729,36.41],[-105.05,43.318],[-110.254,44.915]]]]}} ]}""" Rasterizing Rasterizing can be done with gdal.Rasterize. You need to specify the properties of the target grid. If there is no predefined grid these could be extracted from the polygon itself ds = gdal.Rasterize('/vsimem/tmpfile', geojson, xRes=1, yRes=-1, allTouched=True, outputBounds=[-120, 30, -100, 50], burnValues=1, outputType=gdal.GDT_Byte) mask = ds.ReadAsArray() ds = None gdal.Unlink('/vsimem/tmpfile') Converting to indices Retrieving the indices from the rasterized polygon can be done with Numpy: y_ind, x_ind = np.where(mask==1)

http://stackoverflow.com/q/47531797
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47532660
has body: So I'm trying to add a new list to a 2d array inside a for loop, by taking the last letter of the list and putting it to the start, and adding this new list to the 2d array. But although the new lists work, when I append to the 2d array, it just appends the normal alphabet, not my new one. Can anybody see what I'm doing wrong? def tabulaRecta(): import string alpha = list(string.ascii_uppercase) l2d = [] l2d.append(alpha) for i in range(26): temp = alpha[len(alpha)-1] alpha.pop() alpha.insert(0,temp) l2d.append(alpha) print(l2d) tabulaRecta() The program is supposed to output something like this, but all of these within a list: ['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'] ['Z', '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'] ['Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X'] ['X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W'] ['W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'] ['V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U'] ['U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'] ['T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S'] ['S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R'] ['R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q'] ['Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A'…
has answer: http://stackoverflow.com/a/47543179
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/47532543
possible better answer: http://stackoverflow.com/a/47532543
tagged with: append
has comment: http://stackoverflow.com/comment/82020084
has comment: http://stackoverflow.com/comment/82020094
score: 2
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/47532660
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/82020328
has title: Trying to append modified lists within a for loop

http://stackoverflow.com/a/47535325
has comment: http://stackoverflow.com/comment/82028635
has comment: http://stackoverflow.com/comment/82088099
has body: Whilst it's absolutely a question about your editor rather than Python, many editors actually use the same key combo for this. On my Mac, it's the same in VS-Code, Sublime3 and TextMate: cmd-a to select all text (or select a smaller region if you prefer) cmd-[ to un-indent the selected block one stop (and cmd-] to indent) Here's a video I made demonstrating the process in TextMate on a MacBook Pro: https://www.youtube.com/watch?v=vyHRi2xXAnA
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47535208
score: 3
has comment: http://stackoverflow.com/comment/82027791
type: Answer

http://stackoverflow.com/q/47398441
score: -1
has comment: http://stackoverflow.com/comment/81752397
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/47399620
has title: Find all elements that appear more than n/4 times in a sorted array
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47398683
downvote count: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/81750325
upvote count: 1
has comment: http://stackoverflow.com/comment/81749976
favorite count: 0
linked to: http://stackoverflow.com/q/24691048
has body: My question is similar to Find all elements that appear more than n/4 times in linear time, you are given an array of size n, find all elements that appear more than n/4 times, the difference is that the array is sorted and the runtime should be better than O(n). My approach is to do 3 binary searches for the first occurrence of each element in position n/4, n/2 and 3*n/4, since the array is sorted, we can know if each element appears more than n/4 times by checking if the next n/4 element has the same value. I have written the following code in python3, do you guys think my approach is correct and if there is anything that can be simplified?: import bisect # return -1 if x doesn't exist in arr def binary_search(arr, x): pos = bisect.bisect_left(arr, x) return pos if pos != len(arr) and arr[pos] == x else -1 def majority(arr): n = len(arr) output = [] quarters = [arr[n//4],arr[n//2],arr[3*n//4]] # avoid repeating answer in output array if arr[n//4] == arr[n//2]: quarters.remove(arr[n//4]) quarters.remove(arr[n//2]) output.append(arr[n//2]) if arr[n//2] == arr[3*n//4]: if arr[n//2] in arr: quarters.remove(quarters[n//2]) if arr[3*n//4] in arr: quarters.remove(quarters[3*n//4]) if arr[n//2] not in output: output.append(arr[n//2]) for quarter in quarters: pos = binary_search(arr, quarter) if pos != -1 and pos+n//4 &lt; len(arr) and arr[pos] == arr[pos+n//4]: output.append(arr[pos]) return output print(majority([1,1,1,6,6,6,9,145]))
has comment: http://stackoverflow.com/comment/81754408
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81750350
tagged with: refactoring
has comment: http://stackoverflow.com/comment/81754257
tagged with: python

http://stackoverflow.com/q/47407837
has comment: http://stackoverflow.com/comment/81769382
has comment: http://stackoverflow.com/comment/81768803
tagged with: ubuntu
favorite count: 0
has body: I'm trying to run the following commands in Ubuntu 16.04, but I get the following errors. It works fine on Windows, but I don't understand why it fails to work on Ubuntu. I've tried with both Python 3.6 and Python 2.7. Commands: import os os.system("del file1.txt") Error message: sh: 1: del: not found Can anyone help please? Thank you.
has answer: http://stackoverflow.com/a/47409620
tagged with: os.system
tagged with: python
has comment: http://stackoverflow.com/comment/81768827
has comment: http://stackoverflow.com/comment/81768814
type: Question
has title: Python os.system() command not working (Ubuntu 16.04, Python 3.6/2.7)
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1

http://stackoverflow.com/q/47427966
answer count: 1
accepted answer: http://stackoverflow.com/a/47428037
has answer: http://stackoverflow.com/a/47428037
type: Question
tagged with: python
has body: Sorry if this is a dumb question. I have just started learning Python. I agree the below snippet does not work before the definition is not written before calling it. repeat() def print_lyrics(): print('hi') print('hello') def repeat(): print_lyrics() print_lyrics() However, if i change the order of print_lyrics() and repeat(), it still works. def repeat(): print_lyrics() print_lyrics() def print_lyrics(): print('hi') print('hello') repeat() Does it not expect us to be in order same as above since repeat() calls print_lyrics(). I m just trying to understand how this works (or) scans this internally(during run time?)
has title: Python function calling logics
type: AnsweredQuestion
score: 0
tagged with: function

http://stackoverflow.com/a/47492574
has comment: http://stackoverflow.com/comment/81968689
answers question: http://stackoverflow.com/q/47492546
has body: See if you could use __doc__ attribute. &gt;&gt;&gt; def func(): """ Return 인사합니다 """ pass &gt;&gt;&gt; func.__doc__ ' Return 인사합니다 ' Edit: I tried help(func) on Windows 10: &gt;&gt;&gt; help(func) Help on function func in module __main__: func() Return \uc778\uc0ac\ud569\ub2c8\ub2e4 I could print it right with the escape character u prefixed to it: &gt;&gt;&gt; print(u'\uc778\uc0ac\ud569\ub2c8\ub2e4') 인사합니다 But I got the docstring as is on Linux: &gt;&gt;&gt; help(func) Help on function func in module __main__: func() Return 인사합니다
type: Answer
score: 0

http://stackoverflow.com/a/47384590
has comment: http://stackoverflow.com/comment/82185091
has comment: http://stackoverflow.com/comment/81722042
upvote count: 15
answers question: http://stackoverflow.com/q/47383244
type: AcceptedAnswer
has body: After seeing a few comments on the question suggesting that this can't be done, I had another go a it myself, and here is one approach that works pretty nicely. legend.sizes = seq(80, 160, 20) ax = list(zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE) mk = list(sizeref=0.1, sizemode="area") p.map = plot_geo(DF, locationmode = 'USA-states') %&gt;% add_markers(x = ~long, y = ~lat, color = ~Group, size = ~Value, marker = mk) %&gt;% layout(geo = list(scope = 'usa')) p.legend = plot_ly() %&gt;% add_markers(x = 1, y = legend.sizes, size = legend.sizes, showlegend = F, marker = mk) %&gt;% layout(xaxis = ax, yaxis = list(showgrid = FALSE)) subplot(p.legend, p.map, widths = c(0.1, 0.9))
has comment: http://stackoverflow.com/comment/82176775
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47383244
type: Answer
score: 15
has comment: http://stackoverflow.com/comment/82356386

http://stackoverflow.com/a/47528236
has comment: http://stackoverflow.com/comment/82070501
has comment: http://stackoverflow.com/comment/82035335
answers question: http://stackoverflow.com/q/47505872
has body: There are some issues with the generateNewPopulation function. child_one and child_two are referenced before assignment You need two individuals from the population to perform the crossover. There are several selection algorithms, but just to give an idea you could start with a form of tournament selection: def extractFromPopulation(population): best = random.choice(list(population.keys())) for _ in range(4): gene = random.choice(list(population.keys())) if population[gene] &gt; population[best]: best = gene return best Here the selection pressure (range(4)) is fixed. It's one of the parameters you've to tune in a real case. Now we have: def generateNewPopulation(population, population_size): newPopulation = dict() while len(newPopulation) &lt;= POP_SIZE: child_one = extractFromPopulation(population) child_two = extractFromPopulation(population) # ... The code still doesn't work because new individuals aren't inserted in newPopulation Just indent the two lines: newPopulation[child] = 0 newPopulation[child_two] = 0 (they must be part of the while loop) The revised generateNewPopulation function follows: def generateNewPopulation(population, population_size): newPopulation = dict() while len(newPopulation) &lt;= POP_SIZE: child_one = extractFromPopulation(population) child_two = extractFromPopulation(population) child_one, child_two = crossover(child_one, child_two) child_one = mutate(child_one) child_two = mutate(child_two) newPopulation[child_one] = 0 newPopulation[child_two] = 0 return newPopulation The crossover function cannot be based on a fixed RAND_NUM value Delete the RAND_NUM = random.random() assignment and change the crossover function to use a new random value at each call: def crossover(parentA, parentB): if random.random() &lt; CROSSOVER_RATE: random_index = random.randint(0, len(target)) parentASlice = parentA[:random_index] parentBSlice = parentB[random_index:] return (parentASlice + parentBSlice), (parentBSlice + parentASlice) return parentA, parentB…
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82033020
type: Answer

http://stackoverflow.com/a/47524022
type: Answer
has body: You need to use the iteritems() method to iterate over the Pandas series. To iterate them both, use map() like such... with open("geotagged_manhattan.csv", 'wb') as result_file: wr = csv.writer(result_file) for a, z in map(None, data['ADDRESS'].iteritems(), data['ZIP CODE'].iteritems()): print(str(a[1]) + " New York City, NY " + str(z[1]))
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47523795
accepted answer of: http://stackoverflow.com/q/47523795

http://stackoverflow.com/a/47415462
has comment: http://stackoverflow.com/comment/81784597
has comment: http://stackoverflow.com/comment/138268281
type: AcceptedAnswer
score: 8
upvote count: 8
accepted answer of: http://stackoverflow.com/q/47415244
has body: You need to name your object (GroupBox) and apply the stylesheet directly to the name. Add this to your code: self.GB.setObjectName("ColoredGroupBox") # Changed here... self.GB.setStyleSheet("QGroupBox#ColoredGroupBox { border: 1px solid red;}") # ... and here Here is your modified code: import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class tabdemo(QMainWindow): def __init__(self): super(tabdemo, self).__init__() self.setGeometry(50,50,500,500) self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self.mainB = QVBoxLayout() self.GB = QGroupBox("GroupBox") self.GB.setObjectName("ColoredGroupBox") # Changed here... self.GB.setStyleSheet("QGroupBox#ColoredGroupBox { border: 1px solid red;}") # ... and here self.GB.setFixedWidth(100) self.mainHBOX = QVBoxLayout() self.GB1 = QGroupBox("GroupBox1") self.GB1.setFixedHeight(100) self.GB2 = QGroupBox("GroupBox2") self.GB2.setFixedHeight(100) self.GB3 = QGroupBox("GroupBox3") self.GB3.setFixedHeight(100) self.mainHBOX.addWidget(self.GB1) self.mainHBOX.addWidget(self.GB2) self.mainHBOX.addWidget(self.GB3) self.GB.setLayout(self.mainHBOX) self.mainB.addWidget(self.GB) self.centralWidget.setLayout(self.mainB) def main(): app = QApplication(sys.argv) ex = tabdemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The result is this:
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47415244

http://stackoverflow.com/q/47528955
tagged with: matplotlib
downvote count: 0
has answer: http://stackoverflow.com/a/47529821
has title: Adding a legend to a matplotlib boxplot with multiple plots on same axes
favorite count: 0
score: 30
type: Question
upvote count: 30
tagged with: plot-annotations
tagged with: boxplot
has body: I have a boxplot generated with matplotlib: However, I have no idea how to generate the legend. I get a warning saying: Legend does not support handles for dict instances. or No artists with labels found to put in legend. I've done a fair bit of searching and there doesn't seem to be an example showing how to achieve this. bp1 = ax.boxplot(data1, positions=[1,4], notch=True, widths=0.35, patch_artist=True) bp2 = ax.boxplot(data2, positions=[2,5], notch=True, widths=0.35, patch_artist=True) ax.legend([bp1, bp2], ['A', 'B'], loc='upper right')
tagged with: python
has answer: http://stackoverflow.com/a/78490832
tagged with: plot
possible better answer: http://stackoverflow.com/a/65237307
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/65237307
accepted answer: http://stackoverflow.com/a/47529821

http://stackoverflow.com/comment/81883232
has text: BTW: `tkinter` has standart messageboxes: [standard dialogs](http://effbot.org/tkinterbook/tkinter-standard-dialogs.htm)
score: 0
comment on: http://stackoverflow.com/q/47464001
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47504523
has answer: http://stackoverflow.com/a/47505024
answer count: 1
upvote count: 1
downvote count: 1
has title: TypeError: slice indices must be integers or None or have an __index__ method. How to resolve it?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81964931
has body: if w&lt;h: normalized_char = np.ones((h, h), dtype='uint8') start = (h-w)/2 normalized_char[:, start:start+w] = char else: normalized_char = np.ones((w, w), dtype='uint8') start = (w-h)/2 normalized_char[start:start+h, :] = char Running this on jupyter and getting this error &lt;ipython-input-8-15d17de04b9c&gt; in extractCharactersNew(function) 60 normalized_char = np.ones((h, h), dtype='uint8') 61 start = (h-w)/2 ---&gt; 62 normalized_char[:, start:start+w] = char 63 else: 64 normalized_char = np.ones((w, w), dtype='uint8') TypeError: slice indices must be integers or None or have an __index__ method How Can I resolve this error?
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47505024

http://stackoverflow.com/a/47438328
accepted answer of: http://stackoverflow.com/q/47438289
has body: It is not possible for an imported function to access global variables of the module where it [function] is imported. relative_path() function can not access __file__ of caller.py. You may pass it as a parameter: def relative_path(*x, __file__): this_file_dir = os.path.dirname(os.path.realpath(__file__)) return os.path.join(this_file_dir, *x)
answers question: http://stackoverflow.com/q/47438289
score: 1
type: AcceptedAnswer
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/68138512
score: -1
downvote count: 2
answers question: http://stackoverflow.com/q/47425520
upvote count: 1
has body: Edit activate.bat and place this line at the bottom: python yourscript.py Schedule the activate.bat itself and it will automatically run your script after the virtual environment activated.
type: Answer

http://stackoverflow.com/comment/81820490
type: AnswerComment
comment on: http://stackoverflow.com/a/47391352
has text: https://stackoverflow.com/questions/30734860/how-do-i-turn-off-info-logs-in-pocketsphinx-python
type: Comment
score: 0

http://stackoverflow.com/comment/81829055
score: 0
has text: @Bharath I am trying to create a new column that shows the exponential moving average in the function I created
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47436889

http://stackoverflow.com/a/47532603
type: Answer
has body: Without blitting If you're willing not to use blitting, the solution would be to set the RectangleSelector's patch visible (RS.to_draw.set_visible(True)) and set its extent to the data you want it to be (RS.extents = (0,4,0,1)). from __future__ import print_function from matplotlib.widgets import RectangleSelector import numpy as np import matplotlib.pyplot as plt def line_select_callback(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print("(%3.2f, %3.2f) --&gt; (%3.2f, %3.2f)" % (x1, y1, x2, y2)) fig, current_ax = plt.subplots() N = 100000 x = np.linspace(0.0, 10.0, N) plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5) plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3) # drawtype is 'box' or 'line' or 'none' RS = RectangleSelector(current_ax, line_select_callback, drawtype='box', useblit=False, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) RS.to_draw.set_visible(True) fig.canvas.draw() RS.extents = (0,4,0,1) plt.show() With blitting The above will unfortunately not work when blitting is used. A solution with blitting would need to involve copying the background, then setting the rectangle visible, but setting the animated property to false. Then for the first time the canvas is drawn the rectangle is shown. However for later use we would need to set the animated property to True again. Hence for the first time a click happens inside the figure, we need to set the animated property to True and blit the canvas with a background which has been saved before showing the rectangle. from __future__ import print_function from matplotlib.widgets import RectangleSelector import numpy as np import matplotlib.pyplot as plt def line_select_callback(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print("(%3.2f, %3.2f) --&gt; (%3.2f, %3.2f)"…
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/85363207
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47529558
answers question: http://stackoverflow.com/q/47529558
has comment: http://stackoverflow.com/comment/82062102

http://stackoverflow.com/a/47428820
downvote count: 0
score: 1
upvote count: 1
has body: Just change the value of obs_data in distance_from_center() from row[0] to row as you are already taking that particular column while calling that method. Then it should work out fine. I tried it and it is working in my system. import json import pandas as pd # json a = """{"cluster_id": 3,"cluster_observation_data": [[1, 2, 3, 4, 5,6, 7, 8], [2, 3, 4,5, 6, 7, 8, 1]],"cluster_observation_label": [0, 1], "cluster_centroid": [1, 2, 3, 4, 5, 6, 7, 10], "observation_id":["id_xyz_999","id_abc_000"]}""" # convert to dictionary data = json.loads(a) sub_dict = dict((k, data[k]) for k in ('cluster_observation_data', 'cluster_observation_label')) train = pd.DataFrame.from_dict(sub_dict, orient='columns') def distance_from_center(row): centre = data['cluster_centroid'] obs_data = row print('obs_data', obs_data) print('\n\n\n\n') print('center', centre) # print(type(obs_data)) # print(type(centre)) dist = sum([(a - b)**2 for a,b in zip(centre, obs_data)]) print(dist) return dist train.loc[:, 'center_dist'] = train.loc[:,'cluster_observation_data'].apply(distance_from_center) Output: obs_data [1, 2, 3, 4, 5, 6, 7, 8] center [1, 2, 3, 4, 5, 6, 7, 10] 4 obs_data [2, 3, 4, 5, 6, 7, 8, 1] center [1, 2, 3, 4, 5, 6, 7, 10] 88
answers question: http://stackoverflow.com/q/47428530
type: Answer

http://stackoverflow.com/comment/81851790
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47447719
has text: Comment the code sample where you import the models like **Permission** and **ContentType**
type: Comment

http://stackoverflow.com/q/47489804
has title: Changing colors on bokeh patches plot real time
downvote count: 0
tagged with: bokeh
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47523447
has answer: http://stackoverflow.com/a/47523447
tagged with: python
score: 4
possible better answer: http://stackoverflow.com/a/47532984
has body: I'm trying to create a bokeh plot of the US States, and color each of the state according to some data. Now using this tutorial I managed to create this, but I also want to enhance it, and add a slider to it, to change the values displayed. For example like displaying separate years. With the help of this tutorial, I managed to add the slider, and the underlying data does change, according to the hover text, but the colors aren't recalculated, and so the visual representation does not match the values. This is the code I've used, from a Jupyter notebook, so anybody who wants to try can reproduce from bokeh.io import show, output_notebook from bokeh.models import ( ColumnDataSource, HoverTool, LogColorMapper, Range1d, CustomJS, Slider ) from bokeh.palettes import Inferno256 as palette from bokeh.plotting import figure from bokeh.layouts import row, widgetbox from bokeh.sampledata.us_counties import data as counties from bokeh.sampledata.us_states import data as states from bokeh.sampledata.unemployment import data as unemployment import pandas as pd import random output_notebook() palette.reverse() states_accumulated ={} available_state_codes = states.keys() for key, value in counties.items(): state_name = value["state"].upper() if state_name in states.keys() and "number" not in states[state_name]: states[state_name]["number"] = key[0] for key,state in states.items(): state["code"] = key state_list = [] for key,state in states.items(): state_list.append(state) unemployment_transf = [] for key,value in unemployment.items(): unemployment_transf.append({ "State":key[0], "County":key[1], "Value":value }) unemp_df = pd.DataFrame(unemployment_transf) unemp_sum = unemp_df.groupby("State").mean()["Value"] unemp_sum = unemp_sum.sort_index() unemp_sum_flat = {key:value for key, value in unemp_sum.items()} for state in state_list: state["value"] = unemp_sum_flat[state["number"]] state_df = pd.DataFrame(state_list) color_mapper = LogColorMapper(palette=palette) state_xy = (list(…
has answer: http://stackoverflow.com/a/47532984
upvote count: 4
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/47393670
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
has body: I'm using flask-wtforms, flask-sqlalchemy and flask-bootstrap for my project. I can't for the life of me, understand why after submitting the form, it doesn't redirect to the page I set it to. Here is the python part: @app.route('/newevent', methods=['GET', 'POST']) #TAGGED @login_required def newevent(): form = NewEvent() msgs = '' if request.method=='POST' and form.validate_on_submit(): check = Event.query.filter_by(eventid=form.eventid.data).first() if check is None: db.session.add( Event(eventid=form.eventid.data, eventName=form.eventName.data, eventDate=form.eventDate.data, allocation=form.allocation.data, Event_orgCode=current_user.orgCode)) db.session.commit() return redirect(url_for('adminevents')) elif check.eventid == form.eventid.data: msgs = 'Event already exists!' return render_template('events_new.html', form=form, msgs=msgs) return render_template('events_new.html', form=form, msgs=msgs) now here is the html part: {% block content %} {% with msg = get_flashed_messages() %} Create New Event {{ msgs }} {{ form.hidden_tag() }} {{ form.csrf_token }} {{ wtf.form_field(form.eventid, placeholder="Pick a 4-digit ID e.g., 0042") }} {{ wtf.form_field(form.eventName, placeholder="Name your event") }} {{ wtf.form_field(form.eventDate) }} {{ wtf.form_field(form.allocation, placeholder="Enter budget allocation") }} {% endwith %} {% endblock %} I have a similar function called newbudget. It is quite similar to the code in question and works perfectly fine. Please help I'm at my wit's end already.
has comment: http://stackoverflow.com/comment/82174125
tagged with: flask-wtforms
type: UnansweredQuestion
tagged with: wtforms
tagged with: python
answer count: 0
score: 1
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has title: after submitting form it keeps on making POST requests only
upvote count: 1

http://stackoverflow.com/comment/81900027
type: Comment
type: QuestionComment
has text: @JohnZwinck I think, what you mean by "one big frame with all the wildcards expanded" is the same as I wanted to describe with "a solution where I get a series of all types existing in entitities and creating a row for each type for each row in recommendations with a wildcard type". Yes, I can do so. But it would be better to have a function which makes use of the pandas dataFrame structure. And I feel like loosing the advantages of pandas.merge if I do it that way. But of course it's possible,
comment on: http://stackoverflow.com/q/47472207
score: 0

http://stackoverflow.com/a/49452978
downvote count: 0
upvote count: 1
has body: There are two issues here. The first is covered by the other answer: you need to from ddt import ddt rather than import ddt. The second is that your test function is decorated with @unpack, so the tuple you pass to @data will be unpacked by ddt, creating two function calls: test_search_1("phones") and test_search_2(2). This isn't what you want. You probably want something like: @data([ {"search_val": "phones", "expected_count": 2}, {"search_val": "things", "expected_count": 3}, {"search_val": "stuff", "expected_count": 4}, ]) @unpack def test_search(self, search_val, expected_count): There's a bonus third issue, which is the indentation of your test and tearDown functions, which should not be within setUp.
answers question: http://stackoverflow.com/q/47485710
score: 1
type: Answer

http://stackoverflow.com/a/47518994
accepted answer of: http://stackoverflow.com/q/47518902
type: Answer
has body: Instead of appending to the file with each call to get(), append the results to a list and dump at the end. Also don't define response_dict in __main__. import dns.resolver import json def get(domain): ids = [ 'CNAME', 'A', 'NS', ] response_dict = {} for _iter in ids: try: inf = dns.resolver.query(domain, _iter) response_dict["Domain"] = domain for _resp in inf: print(_iter, ':', _resp.to_text()) response_dict[_iter] = _resp.to_text() except Exception as e: print(e) print(response_dict) return response_dict # return a value if __name__ == "__main__": response_list = [] # append each output of get() to this list response_list.append(get("apple.com")) response_list.append(get("google.com")) # write the list to a file with open('data.txt', 'a') as outfile: json.dump(response_list, outfile)
answers question: http://stackoverflow.com/q/47518902
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/47526363
has comment: http://stackoverflow.com/comment/82010662
linked to: http://stackoverflow.com/q/26911882
tagged with: multiprocessing
type: Question
tagged with: python-3.x
answer count: 2
has body: Edit: Running Apple MBP 2017 Model 14,3 with 2.8GHz i7 4-cores: multiprocessing.cpu_count() 8 I have a list of objects I'm performing object methods on in python once for each object. The process is for a genetic algorithm so I'm interested in speeding it up. Basically, each time I update the environment with data from the data list, the object (genome) performs a little bit of math including taking values from the environment, and referencing it's own internal values. I'm doing: from multiprocessing import Pool class Individual(object): def __init__(self): self.parameter1 = None self.parameter2 = None def update_values(): # reads the environment variables, does math specific to each instance # updates internal parameters a, b, c, d = environment_variables self.parameter1 = do_math(a, b, c, d, self.parameter1, self.parameter2) self.parameter2 = do_math(a, b, c, d, self.parameter1, self.parameter2) data_list = [data1, data2, data3, ..., data1000] object_list = [object1, object2, object3, ..., object20000] If I run this: for newdataset in data_list: update_parameters(newdataset) for object in object_list: object.update_values() It is much faster than if I try to split this up using multiprocessing/ map: def process_object(object): object.update_values() for newdataset in data_list: update_parameters(newdataset) with Pool(4) as p: p.map(process_object, object_list) If I run with object_list length of 200 (instead of 20000) the total time is 14.8 seconds in single threaded mode. If I run with the same in multiprocessing mode the total time is... still waiting... ok... 211 seconds. Also it doesn't appear to do what the function says it should at all. What am I missing here? When I check the values of each object they do not appear to have been updated at all.
tagged with: python
accepted answer: http://stackoverflow.com/a/47526825
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47526825
has comment: http://stackoverflow.com/comment/82009268
possible better answer: http://stackoverflow.com/a/47526603
has comment: http://stackoverflow.com/comment/82008602
has answer: http://stackoverflow.com/a/47526603
has title: Python Multiprocessing Slower and not really working for object methods
has comment: http://stackoverflow.com/comment/82009704

http://stackoverflow.com/comment/82004273
comment on: http://stackoverflow.com/q/47522611
score: 0
type: QuestionComment
has text: My point is that modules don't magically maintain state by being in a separate file. You'll at the very least need `pickle` to serialize your list, then deserialize, append, reserialize
type: Comment

http://stackoverflow.com/q/47488215
upvote count: 0
tagged with: anaconda
downvote count: 3
answer count: 1
has body: I installed Anaconda3-5.0.1 32 bits on window 7. When installation is about to complete it shows "Failed to run post python script (PIC 1)". After I clicked on ignore installation process is complete. Then in command it shows jupyter is not reorganized. Please help. ps://i.sstatic.net/2EHZo.jpg
favorite count: 0
tagged with: jupyter-notebook
type: Question
tagged with: python-3.x
tagged with: windows-7
has comment: http://stackoverflow.com/comment/81931372
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/47488803
tagged with: python
has title: Failed to run post python script & 'Jupyter' is not reorganised internal or external command

http://stackoverflow.com/q/47496829
tagged with: amazon-web-services
favorite count: 0
has answer: http://stackoverflow.com/a/47497825
type: Question
accepted answer: http://stackoverflow.com/a/47497825
tagged with: amazon-s3
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
has body: I'm working with boto3 to display various data about my s3 buckets in AWS. I have the following code in views.py to display s3 page: class s3(TemplateView): template_name = 'project/s3.html' def get_context_data(self, **kwargs): context = super(s3, self).get_context_data(**kwargs) aws = boto3.resource('s3') buckets = aws.buckets.all() for bucket in buckets: totalSize = 0 bucketName = bucket.name createdAt = bucket.creation_date fileBuckets = boto3.resource('s3').Bucket(bucketName) for file in fileBuckets.objects.all(): totalSize += file.size context['buckets'] = buckets context['bucket'] = buckets context['createdAt'] = createdAt context['bucketName'] = bucketName context['totalSize'] = totalSize return context I'm trying to display these variables in a template like this: {% for bucket in buckets %} {{ bucketName }} {{ createdAt }} {{ totalSize }}/4GB Delete {% endfor %} But obviously this doesn't work. How can I iterate through those buckets in template? I also tried the below and it worked but not completely as I cannot get the total sizes of all files in each bucket: {% for bucket in buckets %} {{ bucket.name }} {{ bucket.creation_date}} {{ ??? }}/4GB Delete {% endfor %} Can I create a new loop inside the template? Or should I create it in python file and call it in template? How can I do this? Thanks
tagged with: django
has title: Django how to loop through objects and display variables in a template

http://stackoverflow.com/a/47391759
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47391673
has comment: http://stackoverflow.com/comment/81736818
accepted answer of: http://stackoverflow.com/q/47391673
has comment: http://stackoverflow.com/comment/81736404
score: 1
type: AcceptedAnswer
has body: Something like filenames = { 'Math': 'COMP2101.txt', 'IT': 'STAT1001.txt', 'Biology': 'BIOL2101.txt', } for subject, filename in filenames.items(): with open(filename, 'r') as f: for line in f: line = line.rstrip() ... if studentId == iD: mark = part[1] print(subject, mark)
downvote count: 0

http://stackoverflow.com/q/47454771
type: Question
has comment: http://stackoverflow.com/comment/81879348
has comment: http://stackoverflow.com/comment/81864450
has comment: http://stackoverflow.com/comment/81879290
tagged with: django-models
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47473526
tagged with: mysql
tagged with: django
tagged with: django-forms
answer count: 1
has comment: http://stackoverflow.com/comment/81866543
has body: I am relatively new to Django, and web development in general. Basically, I'm trying to build a website with two types of users: customers, and suppliers. Both the customers and suppliers have user accounts (containing a username, email, and password) created using Django's built-in 'from django.contrib.auth import login -forms.Form' and stored in the table 'auth_user' in my mySQL database. But, the suppliers can also create a more detailed profile (name, bio, images etc) which is created using a 'forms.ModelForm' called 'SupplierSignupForm' and stored in a separate table to 'auth_user', called 'home_suppliersignup'. What I want to happen is, when a supplier is logged in, they can click on their 'my profile' link in the header and be taken to their profile located in the 'home_suppliersignup' table in my database. Currently, I know how to call a logged in users ID from the table 'auth_user' using their session info, and then use that to link to their respective 'auth_user' profile: views.py user = request.user template My profile urls.py url(r'^supplier-profile/(?P<id>[0-9]+)', supplier_profile, name="supplier_profile") But I don't know how to use this to pull up their information from another database table (i.e. home_suppliersignup). Any help would be much appreciated! My current code: models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User class SupplierSignUp(models.Model): LOCATION_CHOICES=( ("Central London", "Central London"), ("North London", "North London"), ("East London", "East London"), ("South London", "South London"), ("West London", "West London"), ) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50) bio = models.CharField(max_length=50) area = models.CharField(max_length=50, choices=LOCATION_CHOICES, null=True) booking_link = models.CharField(max_length=100, null=True) timestamp = mode…
has title: Show a logged in user their own information from a database model
accepted answer: http://stackoverflow.com/a/47473526

http://stackoverflow.com/q/47428717
has answer: http://stackoverflow.com/a/47428855
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I want to select rows by a year: import pandas as pd import numpy as np df = pd.DataFrame(columns=['Start','End'],data=[[np.datetime64('2001-01-01'),np.datetime64('2001-07-01')],[np.datetime64('2002-01-01'),np.datetime64('2002-11-01')]]) print(df) Start End 0 2001-01-01 2001-07-01 1 2002-01-01 2002-11-01 So i try: df_2001 = df.loc[df['Start'].year == 2001] AttributeError: 'Series' object has no attribute 'year' How can i select by year in a datetime64 column?
tagged with: pandas
has title: Select rows by year
tagged with: python
upvote count: 6
answer count: 1
accepted answer: http://stackoverflow.com/a/47428855
downvote count: 0
score: 6

http://stackoverflow.com/comment/82017711
has text: It would be good, if you put the path to pip in your environment variables.
type: AnswerComment
comment on: http://stackoverflow.com/a/47529947
score: 0
type: Comment

http://stackoverflow.com/comment/81854804
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47445043
has text: BTW: as for me you could make it more OOP - keep `main()` (with `pygame.init()`) inside `Board()` and create class `Button`. Outside classes you could keep only constant values.

http://stackoverflow.com/comment/81811871
type: AnswerComment
comment on: http://stackoverflow.com/a/47428578
has text: atleast you should have written your answer in pythonic way in last its not for the people who ask question from us but also for the benefit for the other people who are watching your code right
score: 0
type: Comment

http://stackoverflow.com/comment/81837005
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47440941
type: QuestionComment
has text: As an aside, you probably don't want a `vec.size()` method. You should stick to the Python data model, and implement `__len__` and use `len(vec)`

http://stackoverflow.com/comment/81833062
type: QuestionComment
comment on: http://stackoverflow.com/q/47438839
has text: That isn't a JSON. It looks like [ASN.1](https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One).
score: 1
type: Comment

http://stackoverflow.com/comment/81937859
type: Comment
score: 0
type: QuestionComment
has text: Why do you want to load-test your app from a unit-test framework? Add metric to your production code - they you will have it available for test and production usage. And you will be able to monitor it in you production environment (machines (which I take is different from the ones running your unit-tests)).
comment on: http://stackoverflow.com/q/47485261

http://stackoverflow.com/q/47464422
has title: Changing from lists to arguments in Python 3.0
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47464507
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81883597
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47464507
score: -2
tagged with: counter
has comment: http://stackoverflow.com/comment/81883708
tagged with: python
has body: I've recently constructed a piece of python code which finds the least commonly repeated number in a list! Here is my code... from collections import Counter def least_common(): from collections import Counter List = [1,1,1,0,0,3,3,2] CountList = Counter(List) Mincount = min(CountList.values()) least_common = next(n for n in reversed(List) if CountList[n] == Mincount) print (least_common) least_common() However as you can clearly see, this uses a list to call the numbers which will be compared. I'm now trying to get it to do the same task, but instead of using a built in list, I want it to use an argument of integers. For example def the_least_common(integers) --------code with argument which will find lowest repeated number--------- print the_least_common([1,1,1,0,0,3,3,2]) LEAST COMMON BEING 2 Is any of the code which I've already created reusable for what I now need to create? Apologies if this is a stupid question or comes across as really simple as I'm a little stuck Any advice is much appreciated!

http://stackoverflow.com/q/47508789
has body: I'm importing some data from a csv file in python and create a dataframe called frame5. I have daily data with the date for each day. So far I have used the following to tranfrom the dates to days of the week. frame5['day_of_week']=frame5['date'].dt.dayofweek days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'} frame5['day_of_week'] = frame5['day_of_week'].apply(lambda x: days[x]) Then, in order to calculate the daily mean I use: grouped_day_of_week=frame5.groupby('day_of_week') day_of_week_statistics=grouped_day_of_week['reward'].agg([np.mean,np.size,np.sum]) Then I want to make a plot with the daily means. However, in the dataframe day_of_week_statistics the days appear to be sorted in alphabetical order (each row is the statistics calculated for each day of week). How can I change the order of the days so that they appear in the right order as "Mon", "Tues","Weds","Thurs","Fri","Sat","Sun"?
linked to: http://stackoverflow.com/q/13838405
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81977570
upvote count: 2
has title: Sort days of week in the right order in Python
tagged with: python
has comment: http://stackoverflow.com/comment/81973568
has comment: http://stackoverflow.com/comment/81973675
accepted answer: http://stackoverflow.com/a/47508944
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47508944
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47533747
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82024143
tagged with: python
has comment: http://stackoverflow.com/comment/82024352
has body: I'm making a python script that accepts 7 letters and returns the highest scoring word along with all other possible words. At the moment it has a few "loops in loops" and others things that will slow down the process. import json #open file and read the words, output as a list def load_words(): try: filename = "dictionary_2.json" with open(filename,"r") as english_dictionary: valid_words = json.load(english_dictionary) return valid_words except Exception as e: return str(e) #make dictionary shorter as there will be maximum 7 letters def quick(): s = [] for word in load_words(): if len(word)&lt;7: s.append(word) return s # takes letters from user and creates all combinations of the letters def scrabble_input(a): l=[] for i in range(len(a)): if a[i] not in l: l.append(a[i]) for s in scrabble_input(a[:i] + a[i + 1:]): if (a[i] + s) not in l: l.append(a[i] + s) return l #finds all words that can be made with the input by matching combo's to the dictionary and returns them def word_check(A): words_in_dictionary = quick() for word in scrabble_input(A): if word in words_in_dictionary: yield word #gives each word a score def values(input): # scrabble values score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} word_total = 0 for word in word_check(input): for i in word: word_total = word_total + score[i.lower()] yield (word_total, str(word)) word_total = 0 #prints the tuples that have (scrabble score, word used) def print_words(a): for i in values(a): print i #final line to run, prints answer def answer(a): print ('Your highest score is', max(values(a))[0], ', and below are all possible words:') print_words(a) answer(input("Enter your 7 letters")) I have removed some of the for loops and have tried to make the json dictionary I found shorter by limiting it to 7 letter words max. I suppose I could do that initia…
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1
downvote count: 1
favorite count: 0
has title: What can I do to speed up this code for a scrabble cheat?
linked to: http://stackoverflow.com/q/10017808
type: Question

http://stackoverflow.com/comment/119133010
comment on: http://stackoverflow.com/a/67399730
type: Comment
has text: @gshpychka I didn't say it's required, I said you would need to add it in this case. You're right though, the error message they posted seems to relate to the fact they don't have a client_secrets file. Anyways, the program would have raised an error later on beacuse of the mimetype.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81804948
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47424682
type: Comment
has text: When working with numpy arrays, `shape` and `dtype` are the two most important attributes. Length and size are secondary.

http://stackoverflow.com/comment/81865638
has text: did you try to run this?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47455655

http://stackoverflow.com/q/47491390
has title: Flask url routing fails on all pages but index (/)
type: Question
answer count: 1
has body: I'm making complex application using Flask and Blueprints. It work great when I run it and ask for module index function with "/" path. However, as soon as I add another page/function (for example /verificator/dhashboard in the example below or any other), it routes such link to 404. Here is the code for one of my "backoffice" modules called "verificator": from flask import Blueprint, render_template from backoffice import login_required from backoffice import app # Define Blueprint mod_verificator = Blueprint("verificator", __name__, url_prefix='/verificator/', template_folder="templates") @mod_verificator.route('/', methods=['GET', 'POST']) @login_required def verificator(): return render_template("verificator.html") @mod_verificator.route('/dashboard/', methods=['GET', 'POST']) def dashboard(): return render_template("dashboard.html") # Register blueprint(s) app.register_blueprint(mod_verificator) and Log output: 2017-11-25 22:55:14,614 : DEBUG : verificator: 12: &lt;module&gt; : _ name _: backoffice.mod_verificator.verificator 2017-11-25 22:55:14,614 : DEBUG : verificator: 13: &lt;module&gt; : mod_name : verificator 2017-11-25 22:57:17,459 : INFO : _internal: 87: _log : 127.0.0.1 - - [25/Nov/2017 22:57:17] "GET /verificator/ HTTP/1.1" 200 - 2017-11-25 22:57:40,902 : INFO : _internal: 87: _log : 127.0.0.1 - - [25/Nov/2017 22:57:40] "GET /verificator/dashboard/ HTTP/1.1" 404 - so, "verificator" module renders template (and 200 http code) and verificator/dashboard fails miserable with 404. I'm totally lost and ask for your help!
accepted answer: http://stackoverflow.com/a/47492329
tagged with: flask
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81938656
has answer: http://stackoverflow.com/a/47492329
tagged with: python

http://stackoverflow.com/q/47446480
has answer: http://stackoverflow.com/a/72530731
has answer: http://stackoverflow.com/a/69968809
has answer: http://stackoverflow.com/a/63447691
answer count: 15
has title: How to use Google API credentials json on Heroku?
has answer: http://stackoverflow.com/a/63259498
has answer: http://stackoverflow.com/a/47449978
upvote count: 36
tagged with: google-api
score: 36
linked to: http://stackoverflow.com/q/65485072
downvote count: 0
type: UnansweredQuestion
favorite count: 0
tagged with: heroku
has answer: http://stackoverflow.com/a/72961190
has answer: http://stackoverflow.com/a/61803495
has answer: http://stackoverflow.com/a/60895103
type: Question
has answer: http://stackoverflow.com/a/72066100
has answer: http://stackoverflow.com/a/56818296
has body: I'm making an app using Google Calendar API, and planning to build it on Heroku. I have a problem about authentication. Usually I use credential json file for that, but this time I don't want to upload it on Heroku for security reason. How can I make authentiation on Heroku? For now, I put my json to an env variable, and use oauth2client's from_json method. def get_credentials(): credentials_json = os.environ['GOOGLE_APPLICATION_CREDENTIALS'] credentials = GoogleCredentials.from_json(credentials_json) if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials But this code isn't perfect. If the credentials is invalid, I want the code to write the new credentials to the env variable, not to a new file. Is there any better way?
has answer: http://stackoverflow.com/a/78680887
has answer: http://stackoverflow.com/a/62536750
tagged with: python
has answer: http://stackoverflow.com/a/64938691
has answer: http://stackoverflow.com/a/62010419
has answer: http://stackoverflow.com/a/71287185

http://stackoverflow.com/q/47508874
answer count: 1
tagged with: python
has title: How does Keras calculate the accuracy?
favorite count: 0
score: 8
type: Question
downvote count: 0
tagged with: neural-network
tagged with: machine-learning
tagged with: keras
has answer: http://stackoverflow.com/a/47515095
type: AnsweredQuestion
upvote count: 8
has body: If there's a binary classification problem, the labels are 0 and 1. I know the prediction is a floating-point number because p is the probability of belonging to that class. The following is the cross-entropy loss function. However, p is not necessarily 0 or 1, so how does Keras calculate the accuracy? Will Keras automatically round our predictions to 0 or 1? For example, in the following code, the accuracy is 0.749, but the targets are 0 and 1 and the predictions are floating-point numbers that are not necessarily 0.0 or 1.0. &gt;&gt;&gt; scores = model.evaluate(x=test_Features, y=test_Label) &gt;&gt;&gt; scores[1] 0.74909090952439739
accepted answer: http://stackoverflow.com/a/47515095

http://stackoverflow.com/q/47443370
answer count: 0
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/81842729
type: Question
has body: I am trying to check if my API Rest in Flask work with Gunicorn, but it doesn't response to my requests from the my web browser: my python code is: import flask import flask.ext.sqlalchemy import flask.ext.restless import datetime import os from flask import Response app = flask.Flask(__name__, static_url_path='') DATABASE_URL = os.environ.get('DATABASE_URL','sqlite:///test.db') app.config["DEBUG"] = True app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL db = flask.ext.sqlalchemy.SQLAlchemy(app) @app.route('/') def root(): return app.send_static_file('index.html') class News(db.Model): id = db.Column(db.Integer,primary_key=True) link = db.Column(db.Unicode, unique= True) received_date = db.Column(db.DateTime(), default=datetime.datetime.now) analysed_date = db.Column(db.DateTime()) status = db.Column(db.Unicode) info = db.Column(db.Unicode) publish_date = db.Column(db.DateTime()) text = db.Column(db.Unicode) link_image = db.Column(db.Unicode) keywords = db.Column(db.Unicode) videos = db.Column(db.Unicode) summary = db.Column(db.Unicode) title = db.Column(db.Unicode) if __name__ == '__main__': db.create_all() port = int(os.environ.get('PORT',5000)) manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db) manager.create_api(News,methods=['GET','POST','DELETE']) app.run(host='0.0.0.0', port = port) and I execute: gunicorn -b 0.0.0.0:5000 rest_api:app but If try connect to this web (without gunicorn works): http://localhost:5000/api/news I received a 400 error.
has comment: http://stackoverflow.com/comment/81841860
tagged with: python
type: UnansweredQuestion
tagged with: flask
has title: API Rest doesn't work with gunicorn+flask
score: 0

http://stackoverflow.com/a/48008919
has comment: http://stackoverflow.com/comment/86944154
has body: Check the solution posted here by andersskog. It worked for me. I made a patch here. For manual fix follow the below instructions: Make sure your yaml version is 1.4, eg: trainingInput: runtimeVersion: "1.4" scaleTier: CUSTOM masterType: standard_gpu workerCount: 5 workerType: standard_gpu parameterServerCount: 3 parameterServerType: standard Change setup.py to the following: """Setup script for object_detection.""" import logging import subprocess from setuptools import find_packages from setuptools import setup from setuptools.command.install import install class CustomCommands(install): def RunCustomCommand(self, command_list): p = subprocess.Popen( command_list, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout_data, _ = p.communicate() logging.info('Log command output: %s', stdout_data) if p.returncode != 0: raise RuntimeError('Command %s failed: exit code: %s' % (command_list, p.returncode)) def run(self): self.RunCustomCommand(['apt-get', 'update']) self.RunCustomCommand( ['apt-get', 'install', '-y', 'python-tk']) install.run(self) REQUIRED_PACKAGES = ['Pillow&gt;=1.0', 'protobuf&gt;=3.3.0', 'Matplotlib&gt;=2.1'] setup( name='object_detection', version='0.1', install_requires=REQUIRED_PACKAGES, include_package_data=True, packages=[p for p in find_packages() if p.startswith('object_detection')], description='Tensorflow Object Detection Library', cmdclass={ 'install': CustomCommands, } ) In object_detection/utils/visualization_utils.py, line 24 (before import matplotlib.pyplot as plt) add: import matplotlib matplotlib.use('agg') In line 184 of object_detection/evaluator.py, change tf.train.get_or_create_global_step() to tf.contrib.framework.get_or_create_global_step() Finally, in line 103 of object_detection/builders/optimizer_builder.py, change tf.train.get_or_create_global_step() to tf.contrib.framework.get_or_create_global_step() Hope this helps!
answers question: http://stackoverflow.com/q/47481893
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82988723
has comment: http://stackoverflow.com/comment/82986825

http://stackoverflow.com/comment/81866419
type: Comment
has text: Thanks! Conda did the trick after some troubleshooting. Here's what ended up solving the problem: `conda install -c conda-forge nb_conda`
comment on: http://stackoverflow.com/a/47450355
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82180671
type: Comment
has text: By the way, if this is ALL of your sonos devices, there's a shortcut: one.partymode().
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47610855

http://stackoverflow.com/comment/81918697
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47481188
type: Comment
has text: Yes, i do .....

http://stackoverflow.com/q/47483033
tagged with: linux
has answer: http://stackoverflow.com/a/47544958
has comment: http://stackoverflow.com/comment/81950095
linked to: http://stackoverflow.com/q/10503433
tagged with: python
has comment: http://stackoverflow.com/comment/81922126
has title: Keeping ports open in a python script that is run continuously
accepted answer: http://stackoverflow.com/a/47544958
type: AnsweredQuestion
score: 0
tagged with: cron
answer count: 1
type: Question
has body: I'm trying to develop a server script using python 3.4 that runs perpetually and responds to client requests on up to 5 separate ports. My preferred platform is Debian 8.0. The platform currently runs on a virtual machine in the cloud. My script works fine when I run it off the command line - I need to now (1) keep it running once I log off the server and (2) keep several ports open through the script so that a windows client can connect to them. For (1), After trying several options [I tried using upstart, added the script to rc.local, used nohup with &amp; to run it off the terminal, etc] that didn't seem to work, I eventually found something that does seem to keep the script running, even if it's not very elegant - I wrote an hourly cron script that checks to see if the script is running in the process list, and if not, to execute it. Whenever I login to the VM now, I see the following output when I type 'ps -ef': root 22007 21992 98 Nov10 14-12:52:59 /usr/bin/python3.4 /home/userxyz/cronserver.py I assume that the script is running based on the fact that there is an active process in the system. I mention this part because I suspect that there could be a correlation with part (2) of my issue. For (2), The script is supposed to open ports 49100 - 49105 and listen for connection requests, etc. When I run the script from the terminal, zenmap from my client machine verifies that these ports are open. However, when the cron job initiates the script, these ports don't seem to stay open. My windows client program can't connect to the script either. The python code I use for listening to a port: f = socket.socket(socket.AF_INET, socket.SOCK_STREAM) f.bind((serviceIP, 49101)) f.listen(5) while True: scName, address = f.accept() [code to handle request] scName.shutdown(socket.SHUT_WR) scName.close() Any insight or assistance would be greatly appreciated!

http://stackoverflow.com/q/47390563
downvote count: 0
accepted answer: http://stackoverflow.com/a/47390870
tagged with: python
has answer: http://stackoverflow.com/a/47390870
has answer: http://stackoverflow.com/a/47391194
type: AnsweredQuestion
tagged with: pandas
has body: I have a time-series that contains multiple values at each datetime. Each datetime index has an associated datetime where the value was loaded, or 'loadtime', like so: import datetime as dt import numpy as np import pandas as pd # time-series index t = pd.date_range('09/01/2017', '09/02/2017', freq='1H') t = t.repeat(3) n = len(t) # data values y = np.full((n), 0.0) y = y.reshape(n//3, 3) y[:, 1] = 1.0 y[:, 2] = 2.0 y = y.flatten() # load timestamp random_range = np.arange(0, 60) base_date = np.datetime64('2017-10-01 12:00') loadtimes = [base_date + np.random.choice(random_range) for x in range(n)] df = pd.DataFrame(index=t, data={'y': y, 'loadtime': loadtimes}) &gt;&gt;&gt; df.head(12) loadtime y 2017-09-01 00:00:00 2017-10-02 01:59:00 0.0 2017-09-01 00:00:00 2017-10-02 09:23:00 1.0 2017-09-01 00:00:00 2017-10-02 03:35:00 2.0 2017-09-01 01:00:00 2017-10-01 17:26:00 0.0 2017-09-01 01:00:00 2017-10-01 16:44:00 1.0 2017-09-01 01:00:00 2017-10-02 12:50:00 2.0 2017-09-01 02:00:00 2017-10-02 11:30:00 0.0 2017-09-01 02:00:00 2017-10-02 11:17:00 1.0 2017-09-01 02:00:00 2017-10-01 20:23:00 2.0 2017-09-01 03:00:00 2017-10-02 15:27:00 0.0 2017-09-01 03:00:00 2017-10-02 18:08:00 1.0 2017-09-01 03:00:00 2017-10-01 16:06:00 2.0 So far, I have come up with this solution to iterate over all unique values...but this could be expensive as the time-series increasing in length (and multiple values). It looks like a bit of a hack and not so clean: new_index = df.index.unique() df_new = pd.DataFrame(index=new_index, columns=['y']) # cycle through unique indices to find max loadtime dfg = df.groupby(df.index) for i, dfg_i in dfg: max_index = dfg_i['loadtime'] == dfg_i['loadtime'].max() if i in df_new.index: df_new.loc[i, 'y'] = dfg_i.loc[max_index, 'y'].values[0] # WHY IS THIS A LIST? &gt;&gt;&gt; df_new.head() y 2017-09-01 00:00:00 1 2017-09-01 01:00:00 2 2017-09-01 02:00:00 0 2017-09-01 03:00:00 1 2017-09-01 04:00:00 1 How can I take a time-series with the latest 'loadtime' for each un…
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/47391194
favorite count: 0
type: Question
tagged with: numpy
tagged with: time-series
answer count: 2
has title: Pythonic way to choose most recent value from a time-series DataFrame
tagged with: datetime

http://stackoverflow.com/comment/81781553
type: AnswerComment
has text: Thanks .I will retrain and post back in couple of days.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47412501

http://stackoverflow.com/a/47479646
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47445786
type: AcceptedAnswer
has body: You might need to do the search manually rather than relying on the regular expression: from bs4 import BeautifulSoup soup = BeautifulSoup(html, "html.parser") header_title = "Unique Title 2" for h4 in soup.find_all('h4'): if header_title in h4.text: ...
type: Answer
accepted answer of: http://stackoverflow.com/q/47445786

http://stackoverflow.com/comment/81985044
type: Comment
type: AnswerComment
has text: I was just going to say, Jonathan, you would be better off stealing two lines from the answer chepner provided, starting: `name=student_grades[0]`. Now that's what **I** call explicit.
score: 0
comment on: http://stackoverflow.com/a/47514480

http://stackoverflow.com/q/47498288
has answer: http://stackoverflow.com/a/51043191
type: UnansweredQuestion
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/40492894
favorite count: 0
type: Question
score: 38
upvote count: 38
tagged with: python
has title: Number of max_workers when using ThreadPoolExecutor from concurrent.futures?
has body: What are the factors to consider when deciding what to set max_workers to in ThreadPoolExecutor from concurrent.futures? As long as you can expect Python 3.5+ to be available, is there any reason not to set max_workers to None which will then "default to the number of processors on the machine, multiplied by 5" as described in the docs here? https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
tagged with: concurrent.futures
tagged with: python-3.x

http://stackoverflow.com/q/47508088
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81974829
has comment: http://stackoverflow.com/comment/81975194
score: 0
tagged with: yaml
has title: ruamel.yaml: modify dump() to add extra '-' at the very start
has body: I'm using ruamel.yaml library to dump a dictionary into a yaml file. However it does not behave the way I'd like it to. How could I get: --- - a: - foo: bar - bar: foo instead of: a: - foo: bar - bar: foo with yaml.dump() I'm extracting the data from: data = { 'a': [ {'foo':'bar'}, {'bar':'foo'} ] } Any other library with the same functionality is open for proposal.
has answer: http://stackoverflow.com/a/47508446
tagged with: pyyaml
type: Question
has comment: http://stackoverflow.com/comment/81975501
type: UnansweredQuestion

generator
type: Tag
tags question: http://stackoverflow.com/q/47456631
tags question: http://stackoverflow.com/q/47468129
tags question: http://stackoverflow.com/q/47383376
tag name: generator
tags question: http://stackoverflow.com/q/47470825
tags question: http://stackoverflow.com/q/47488167
tags question: http://stackoverflow.com/q/47394184
tags question: http://stackoverflow.com/q/47411492
tags question: http://stackoverflow.com/q/47423512
tags question: http://stackoverflow.com/q/47433826

http://stackoverflow.com/a/47537212
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47536858
type: Answer
downvote count: 0
has body: This XPath, //tr[td/div/@class='textA']/td/div[@class='checkbox'] will select the div with class='checkbox' within the tr that has a td/div with class='textA', as requested.

http://stackoverflow.com/q/47539760
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82043942
upvote count: 0
accepted answer: http://stackoverflow.com/a/47544925
has comment: http://stackoverflow.com/comment/82037462
has comment: http://stackoverflow.com/comment/82043790
has comment: http://stackoverflow.com/comment/82039568
has answer: http://stackoverflow.com/a/47544925
tagged with: vectorization
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82038302
tagged with: chi-squared
has body: I'm currently trying to apply Chi-Squared analysis to some data. I want to plot a colourmap of varying values depending on the two coefficients of a model def f(x, coeff): return coeff[0] + numpy.exp(coeff[1] * x) def chi_squared(coeff, x, y, y_err): return numpy.sum(((y - f(x, coeff) / y_err)**2) us = numpy.linspace(u0, u1, n) vs = numpy.linspace(v0, v1, n) rs = numpy.meshgrid(us, vs) chi = numpy.vectorize(chi_squared) chi(rs, x, y, y_error) I tried vectorizing the function to be able to pass a meshgrid of the varying coefficents to produce the colormap. The values of x, y, y_err are all 1D arrays of length n. And u, v are the various changing coefficients. However this doesn't work, resulting in IndexError: invalid index to scalar variable. This is because coeff is passed as a scalar rather than a vector, however I don't know how to correct this. Update My aim is to take an array of coordinates rs = [[[u0, v0], [u1, v0],..,[un, v0]],...,[[u0, vm],..,[un,vm]] Where each coordinate is the coefficient parameters to be passed to the chi-squared method. This should return a 2D array populated with Chi-Squared values for the appropriate coordinate chi = [[c00, c10, ..., cn0], ..., [c0m, c1m, ..., cnm]] I can then use this data to plot a colormap using imshow
tagged with: python
score: -1
has title: Vectorizing A Function With Array Parameter
tagged with: numpy

http://stackoverflow.com/comment/81739315
has text: return '{:.5f}'.format(min(1.0, res)) NameError: name 'res' is not defined It gives me this error
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47393058

http://stackoverflow.com/q/47518815
has answer: http://stackoverflow.com/a/47518868
has answer: http://stackoverflow.com/a/47518875
type: Question
answer count: 2
has body: # Reading line of text text = input("Enter text: ") print("English: " ,text) # Removing punctuation text = removePunctuation(text) # Converting to lower case text = text.lower() # Iterating over words for word in text.split(" "): # Converting word to Pig Latin form word = pigLatin(word) # Printing word print(word, end = " "); How can I get it to say Pig: and then the Pig Latin form? Every time i try this, it just adds the Pig Latin transformation to the previous word.
upvote count: 0
type: UnansweredQuestion
downvote count: 2
favorite count: 0
score: -2
has comment: http://stackoverflow.com/comment/81993877
tagged with: python
has title: syntax error and string words together. Print command
has comment: http://stackoverflow.com/comment/81993859
has comment: http://stackoverflow.com/comment/81993825

http://stackoverflow.com/comment/81984288
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47513816
score: 0
has text: When `textChanged` signal (`QTextEdit`) is raised the new text (`s` argument) isn't passed to slot: http://doc.qt.io/qt-5/qtextedit.html#textChanged vs http://doc.qt.io/qt-5/qlineedit.html#textChanged

http://stackoverflow.com/comment/81882444
has text: This limits it to MY path on MY computer. If I have someone else use the program and provide them with the files they would have to place it in the exact same path on their computer for it to work.
score: 0
comment on: http://stackoverflow.com/q/47461844
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47481463
has comment: http://stackoverflow.com/comment/81920413
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47481370
has body: A QTreeWidgetItem can be passed directly to the parent, but it needs a list or tuple of items as shown below: import sys from PyQt5.QtWidgets import * TreeList = ({ 'Header1': (( 'Item11', 'Item12', )), 'Header2': (( 'Item21', 'Item22' )) }) app = QApplication(sys.argv) tree = QTreeWidget() for key, value in TreeList.items(): root = QTreeWidgetItem(tree, [key]) for val in value: item = QTreeWidgetItem([val]) root.addChild(item) # Or # QTreeWidgetItem(root, [val]) tree.expandAll() tree.show() sys.exit(app.exec_()) Output:
has comment: http://stackoverflow.com/comment/81917979
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47481370
score: 5

http://stackoverflow.com/q/47539524
has answer: http://stackoverflow.com/a/47539663
tagged with: random
downvote count: 0
type: UnansweredQuestion
answer count: 1
has body: I am looking an networks. I find this topic https://iamtrask.github.io/2015/07/12/basic-python-network/ Its going good but i cant understand that part: # seed random numbers to make calculation # deterministic (just a good practice) np.random.seed(1) # initialize weights randomly with mean 0 syn0 = 2 * np.random.random((3, 1)) - 1 so whats the mean that np.random.seed(1)? why it isnt (0)? whats the mean of (1)) and page writer says "initialize weights randomly with mean 0" for syn0 = 2 * np.random.random((3, 1)) - 1 what does it mean for ann weights?
has title: Difference between np.random.seed(1) and np.random.seed(0)?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82037397
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/107668366
has comment: http://stackoverflow.com/comment/82151537
tagged with: python
upvote count: 4
score: 4
tagged with: artificial-intelligence
has comment: http://stackoverflow.com/comment/82120696

http://stackoverflow.com/a/47476713
score: -1
upvote count: 0
has body: Indeed, your current method is very heavy. It's really trying to store and work on (sample+sort) an array of 123,456,789 python integers in memory. I don't believe you actually need the "skip" rows in an array in advance. If that's so, you could instead use a generator. Here's how you could go about generating your sample set instead: def random_sampler_generator(input_seq, skip_chance=0.5): for i in input_seq: if random.random() &gt; skip_chance: yield i for m in random_sampler_generator(xrange(1, n+1), skip_chance=0.1): print m It's a good bit slower because it's instead calling random.random() more than 100 million times but it's extremely memory efficient thanks to the yield function. You should probably also be using xrange in lieu of range for the exact same reason. Here, random_sampler_generator uses a heuristic method of sampling in that you're not guaranteed to have X% but the result will tend towards it as the input set size grows. skip_chance expects a float between 0 and 1 where .1 is 10% skipped, .5 is 50% skipped, and .75 is 75% skipped, etc.
type: Answer
answers question: http://stackoverflow.com/q/47476261
downvote count: 1

http://stackoverflow.com/comment/81761238
has text: session.get(action='query', params = {"Earth Wind and Fire"})
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47403134
score: 0

http://stackoverflow.com/q/47388015
has answer: http://stackoverflow.com/a/47388058
tagged with: django
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81729149
linked to: http://stackoverflow.com/q/39983695
type: AnsweredQuestion
answer count: 2
upvote count: 0
has title: Why doesn't None put in variable?
accepted answer: http://stackoverflow.com/a/47388058
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47388062
possible better answer: http://stackoverflow.com/a/47388062
has comment: http://stackoverflow.com/comment/81729409
has body: Why doesn't None put in variable? I wrote in code like def check(request): if len(request.POST.get('access_key')) >= 25: return HttpResponse(' Hello ') elif request.POST.get('access_key', None) == None: id_json = {} return JsonResponse(id_json, safe=False) else: return HttpResponse(' Good ') Now I put anything to access_key in POSTMAN like I think in this case the program goes into elif request.POST.get('access_key', None) == None:,but now it goes into else:. I really cannot understand why the null value is not recognized as None. I wrote print(type(request.POST.get('access_key'))) and blank is printed out. I wanna make a system if no value is put, and the program should go into elif request.POST.get('access_key', None) == None:. How should I fix this?

http://stackoverflow.com/q/47496949
score: -2
accepted answer: http://stackoverflow.com/a/47496998
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47496998
answer count: 3
has comment: http://stackoverflow.com/comment/81949135
downvote count: 3
has answer: http://stackoverflow.com/a/47498062
upvote count: 1
possible better answer: http://stackoverflow.com/a/47497013
has comment: http://stackoverflow.com/comment/81949234
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47497013
has title: How do I replace a string in an array in Python?
has body: I have some code where I have an array with the days of the week. I don't know how to replace "Thursday" with "Tuesday". I've tried researching with no luck... :/ Any help is appreciated. daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
tagged with: arrays
tagged with: python

http://stackoverflow.com/q/47519605
has comment: http://stackoverflow.com/comment/81996211
tagged with: python-3.x
tagged with: ctypes
has answer: http://stackoverflow.com/a/47538527
accepted answer: http://stackoverflow.com/a/47538527
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/81995692
has body: It is possible to create a count property for threading._RLock._count by inheriting from the class and exposing the data from the underlying attribute. This is easily demonstrated by example: import threading # noinspection PyProtectedMember class RLock(threading._RLock): """RLock() -&gt; RLock instance with count property""" @property def count(self): """Count property showing current level of lock ownership.""" return self._count Is it possible to do the same with the _thread.RLock by getting the count via ctypes? If it is possible, would the code have any advantages over the version shown above? If it would be advantageous, what code would one have to write to access the count?
has comment: http://stackoverflow.com/comment/81996142
has comment: http://stackoverflow.com/comment/81996569
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81995842
tagged with: recursive-mutex
answer count: 1
has title: Is it possible to conveniently access the count of _thread.RLock via ctypes?
favorite count: 0
type: Question
upvote count: 2

min
type: Tag
tags question: http://stackoverflow.com/q/47411649
tags question: http://stackoverflow.com/q/47385617
tag name: min
tags question: http://stackoverflow.com/q/47460260

http://stackoverflow.com/comment/82006637
has text: thanks it worked...
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47509720

http://stackoverflow.com/comment/82042085
has text: You're a star, I never thought about transposing.... I tried using reshape for hours with no luck, this is a much better way than what I did as this can be used for more than three variable (which I might need to do) Thanks :D Is there a way of making this as the answer?
comment on: http://stackoverflow.com/a/47510627
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47440732
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/81839343
type: UnansweredQuestion
tagged with: python
tagged with: graphviz
has comment: http://stackoverflow.com/comment/81845246
upvote count: 4
has comment: http://stackoverflow.com/comment/81839435
answer count: 0
has title: Rendering graphs in GUI with graphviz
has body: I am trying to display a graph with graphviz. I have managed to display the graph by generating files. Now I want to display the graph in GUI with pyQT or any other GUI manager. I am thinking about animating the graph for example color the nodes while using DFS or BFS algorithm. What I have found on the internet: I have tried networkx with matplotlib but the display was a mess. I have thought about generating images and then render them in GUI but this consumes a lot of time. I have find python-igraph but it can not be customized like graphviz and I think it don't work with gui either. So what should I do? I am only going to use this lib in a school project so I don't want to draw the nodes by myself because it will take me some time. If there is an easy method to use the position given by graphviz I don't mind using it but plz give me some hints. By the way, If you know any other lib i can use, please tell me. Note: I need to display a graph in GUI and render it in real time.
has comment: http://stackoverflow.com/comment/81852570
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47444424
has comment: http://stackoverflow.com/comment/81844141
accepted answer of: http://stackoverflow.com/q/47444353
type: AcceptedAnswer
downvote count: 1
has body: Your logic is far too complex. The problem involves only the final two characters; there's no need to loop through the string. Check the string length; if it's 0, return -1. If it's 1, return 0. Check the last two characters against each other s[-1] == s[-2]. If they're equal, return len(s)-2; else return len(s)-1. I trust you can turn that into code.
answers question: http://stackoverflow.com/q/47444353
has comment: http://stackoverflow.com/comment/81844095
type: Answer
score: 2
upvote count: 3

http://stackoverflow.com/comment/81960262
score: 0
type: Comment
type: QuestionComment
has text: Thanks for the response. The problem is that the length of my list is not always the same. Currently, the length is 4 but it can also be 5/6/7. So I need to do something that will essentially push everything back one if a '0' is present at the end or even in the middle.
comment on: http://stackoverflow.com/q/47502172

http://stackoverflow.com/comment/82028890
type: AnswerComment
has text: Given the information I have at my disposal I can in no way find out why you have white spaces around your image. The code above runs fine and gets rid of the whitespace. Also the code in the question does not produce white spaces. So you have something, which causes this, but how could I know what that is?
type: Comment
comment on: http://stackoverflow.com/a/47510838
score: 0

http://stackoverflow.com/comment/81979942
type: QuestionComment
has text: No, not in general. You'd need processes instead of threads for this. Processes can be killed from the outside (via signals). Single threads of a process only can terminate from the inside (they have to do it themselves). You might be able to program the threads in a way so that they terminate on a timeout, e. g. a network timeout.
type: Comment
comment on: http://stackoverflow.com/q/47512079
score: 0

http://stackoverflow.com/a/47408840
downvote count: 0
answers question: http://stackoverflow.com/q/47408608
score: 16
upvote count: 16
has body: Usually, you get killed message when the program runs out of RAM (as opposed to hard disk which you have in plenty). You should keep a watch on main memory. Run top and have a look at the memory being taken by your program, or alternatively use a tool like guppy (https://pypi.python.org/pypi/guppy/) to track memory utilization programmatically. I would hazard a guess that you are creating some big in memory data structure while processing files, perhaps not de-allocating them as you iterate through the files.
type: Answer
has comment: http://stackoverflow.com/comment/81887952

http://stackoverflow.com/q/47497458
accepted answer: http://stackoverflow.com/a/47497631
has body: Here is my models.py: class Category(models.Model): category = models.CharField(max_length=50, verbose_name=u"文章分类", default="") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = u"文章分类" verbose_name_plural = verbose_name def __unicode__(self): return self.category class Article(models.Model): category = models.ForeignKey(Category, verbose_name=u"文章分类") title = models.CharField(max_length=100, verbose_name=u"文章题目", default="") content = UEditorField(width=1000, height=500,imagePath="media/", filePath="media/",verbose_name=u"文章内容") read_nums = models.IntegerField(default=0, verbose_name=u"阅读量") comment_nums = models.IntegerField(default=0, verbose_name=u"评论数") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = u"文章" verbose_name_plural = verbose_name def __unicode__(self): return self.title Now I need to show how many articles in category at django-admin page, in this page: How should I do?
has title: Get sub-key's count in admin list-filter
answer count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47497631
tagged with: django
tagged with: python
score: 0

http://stackoverflow.com/comment/81780536
type: QuestionComment
comment on: http://stackoverflow.com/q/47413270
score: 0
type: Comment
has text: i can login using paramiko and python, but then editing it at the remote place using jq is giving me trouble.

http://stackoverflow.com/q/47419345
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/81792857
possible better answer: http://stackoverflow.com/a/47419771
has answer: http://stackoverflow.com/a/47419695
has comment: http://stackoverflow.com/comment/81793247
score: 1
has title: Save rows of a bidimensional numpy array in another array
has answer: http://stackoverflow.com/a/47419927
tagged with: python
has comment: http://stackoverflow.com/comment/81793102
has comment: http://stackoverflow.com/comment/81793128
type: Question
tagged with: numpy
has body: I have a bidimensional np array V (100000x50). I want to create a new array V_tgt in which I keep just certain rows of V, so the dimension will be (ix50). It may be easy to do it but I tried different things and it seems to save just the first of the 50 elements. My code is the following: V_tgt = np.array([]) for i in IX_items: if i in IX_tgt_items: V_tgt=np.append(V_tgt, V[i]) I tried with functions such as insert and delete as well but it didn't work.How can I save all the values and create an array with the right dimension? Any help is really appreciated.
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/47419771
upvote count: 1
has comment: http://stackoverflow.com/comment/81792919
favorite count: 0
accepted answer: http://stackoverflow.com/a/47419695

http://stackoverflow.com/comment/81734570
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47390846
type: Comment
has text: how you are calling from main these methods ?

http://stackoverflow.com/q/47473773
score: 0
has title: Bokeh DataTable Multiple Inputs/Widgets/Filters
answer count: 1
tagged with: bokeh
has answer: http://stackoverflow.com/a/47474741
accepted answer: http://stackoverflow.com/a/47474741
type: Question
has body: I'm trying to display a table based on multiple filters. def update(): current = df[(df['nb_words'] &gt;= slider.value[0]) &amp; (df['nb_words'] &lt;= slider.value[1])].dropna() source.data = { 'id' : current.id, 'author' : current.author, 'nb_words' : current.nb_words, 'text' : current.text, 'topic' : current.topic, 'national' : current.national } nb_words = RangeSlider(title="Min nb employees", start=0, end=1000, value=(0, 1000), step=10, format="0,0") topic = CheckboxButtonGroup(labels=list(df.topic.unique())) national = RadioButtonGroup(labels=['Yes', 'No'], active=0) text = TextInput() nb_words.on_change('value', lambda attr, old, new: update()) data_table = DataTable(source=source, columns=columns, width=1000, fit_columns=False) controls = widgetbox(nb_words, button) table = widgetbox(data_table) Here the update is effective only when the slider of nb_words is changed. However I would like to allow the user multiple selects at a time. For example, The table will adequately update if the user selects rows with - 20 &lt;= nb_words &lt;= 200 - topic = ["topic1", "topic2"] - national = 1 - and text that contains the word "fantastic" How to update the table using multiple widgets?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47421299
tagged with: numpy
linked to: http://stackoverflow.com/q/42382263
accepted answer: http://stackoverflow.com/a/47424833
has title: Iterating over the rows of two dataframes
upvote count: 2
tagged with: pandas
score: 2
has comment: http://stackoverflow.com/comment/81804365
has answer: http://stackoverflow.com/a/47424833
answer count: 1
downvote count: 0
favorite count: 0
has body: I have two dataframes let's call first one df and the second one compare_df: First one is like this: Date cell tumor_size (assume it is three dimensional) 25/10/2015 113 [51, 52, 55] 22/10/2015 222 [50, 68, 22] 22/10/2015 883 [45, 23, 67] 20/10/2015 334 [35, 23, 76] and second one is like that: Date cell tumor_size 19/10/2015 564 [47, 23, 56] 19/10/2015 123 [56, 11, 23] 22/10/2014 345 [36, 66, 78] 13/12/2013 456 [44, 21, 83] For each row in the dataframe I want to go through each row in the second dataframe and record the euclidean distances then get the minimum one. This is my code tries to accomplish this: # These will be our lists of pairs and size differences. pairs = [] diffs = [] for row in df.itertuples(): compare_df['distance'] = np.linalg.norm(compare_df.tumor_size - row.tumor_size) # I get error for this line row_of_interest = compare_df.loc[compare_df.distance == compare_df.distance.min()] pairs.append(row_of_interest.cell.values[0]) diffs.append(row_of_interest.distance.values[0]) df['most_similar_to'] = pairs df['similarity'] = diffs However I get: ValueError: Length of values does not match length of index Although size of the vectors are the same, and I drop Nan values. Any ideas?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81798104
has comment: http://stackoverflow.com/comment/81804374
tagged with: python
has comment: http://stackoverflow.com/comment/81797251
type: Question

http://stackoverflow.com/comment/81912508
score: 1
type: Comment
has text: @Piinthesky No, I’m interested in the unbounded ones as well.
type: AnswerComment
comment on: http://stackoverflow.com/a/47470808

http://stackoverflow.com/q/47415735
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47415825
has answer: http://stackoverflow.com/a/47415825
has comment: http://stackoverflow.com/comment/81785232
tagged with: python
has title: python import csv function
score: -1
has body: Attempting to learn python and am starting off by simply trying to duplicate some powershell scripts I use for daily productivity tasks. I'd like to ask you folks why this method doesn't work in python: def csvIn(path): import csv with open(path) as myFile: csv = csv.reader(myFile) return csv a = csvIn('C:/Users/xxxxxx/Desktop/DL/add.csv') for row in a: print(row) I'm trying to write a function that imports the CSV file and puts its output into a list (array). The whole thing works if I call the import csv outside of a function call. When I try it from inside the function, I get this: "ValueError: I/O operation on closed file."
type: AnsweredQuestion
tagged with: list
tagged with: return-value
has comment: http://stackoverflow.com/comment/81785037
tagged with: function
downvote count: 2
answer count: 1

http://stackoverflow.com/q/47432198
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47433720
tagged with: pandas
score: 1
has title: pandas dataframes resample over uneven periods / minutes
has answer: http://stackoverflow.com/a/47433720
answer count: 1
downvote count: 0
upvote count: 1
tagged with: average
favorite count: 0
type: Question
has body: searched for it but found no solution - if there is already one sry for asking but i would be thankful for a link I have a dataframe (df) like this: timestamp value 2016-03-11 07:37:40 24.6018 2016-03-11 07:37:45 24.6075 2016-03-11 07:37:50 24.599 2016-03-11 07:37:55 24.6047 2016-03-11 07:38:00 24.5905 2016-03-11 07:38:05 24.551 ... important start not at a even minute like 07:40:00 but 07:37:40 (could be any time) and i want to resample it - calculate mean values over e.g. 5 minutes labeled with last timestamp of used lines. Desired result with first timestamp 2016-03-11 07:37:40 of raw data : 2016-03-11 07:42:40 24.608 2016-03-11 07:47:40 24.605 2016-03-11 07:52:40 24.59 ... i tried to use df.resample('5T',how='mean',label='right') and df.resample('300S',how='mean',label='right') with the same result: 2016-03-11 07:40:00 24.618 2016-03-11 07:45:00 24.675 2016-03-11 07:50:00 24.599 ... it calculates over full minute periods. I found no option to correct this propperly. Saw that "base" could be an option but it seems not very ituitive or nice coded. Any help would be appreciated.
tagged with: resampling
tagged with: python
tagged with: timestamp

http://stackoverflow.com/comment/82009877
comment on: http://stackoverflow.com/a/47526761
type: Comment
score: 0
type: AnswerComment
has text: How does `np.maximum.reduceat(weight_s, cut_idx)` work here? By the way, if the array is large, will `argsort()` quite slow?

http://stackoverflow.com/comment/82020020
type: Comment
type: QuestionComment
has text: First of all, overriding the `save()` method should be done in the `Model` not in the `Manager`. Next, `similars.create()` is wrong you can't create an empty QuerySet. So you should not have `else` clause. Last, your call to `super` is wrongly indented (should be inside the `def save()` method). If you're using python3, remove the arguments (just `super().save(*args, **kwargs)` so you don't have to worry about using the correct class. In your code the class is actually wrong (but correct if you change to the `Model` instead of the `Manager`).
comment on: http://stackoverflow.com/q/47526387
score: 0

http://stackoverflow.com/q/47501711
tagged with: python
has comment: http://stackoverflow.com/comment/81986272
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/40796117
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81975216
accepted answer: http://stackoverflow.com/a/47517494
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47517494
has title: Matplotlib add signature bar at the bottom of figure
has body: I'm trying to add a signature bar at the bottom of a figure. I would like to be able to do it without all the manual labor of playing with text x and y values and adding empty strings. I was thinking about using annotate but I'm having a couple of issues: import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = ax.plot(t, s, lw=2) ax.set_ylim(-2,2) ax.set_xlabel('Angle') ax.annotate('What what?', xy=(0, 0), xycoords='figure fraction',backgroundcolor = 'blue') My main issues: 1. I want the bar to go across the whole width of the figure. I can add blank text to extend the bar but I was hoping for something automated so I don't have to do it manually for different scenarios. 2. I want to move the bar a little lower without the bar disappearing or cropping it. Any advice would be great!
tagged with: matplotlib

http://stackoverflow.com/a/59852149
has body: When using custom arguments, each top-level element of an argument string that's separated by space on the command line must be a separate item in the arguments list. For example: "python.formatting.autopep8Args": [ "--max-line-length", "120", "--experimental" ], "python.formatting.yapfArgs": [ "--style", "{based_on_style: chromium, indent_width: 20}" ], "python.formatting.blackArgs": [ "--line-length", "100" ] For proper formatting of these Python settings you can check Formatter-specific settings: Also check the answers here: Allow statements before imports with Visual Studio Code and autopep8
answers question: http://stackoverflow.com/q/47406741
score: 14
downvote count: 1
upvote count: 15
type: Answer

http://stackoverflow.com/q/47418924
score: -3
has answer: http://stackoverflow.com/a/47418989
downvote count: 6
has body: I'm trying to make just a simple numerology but I can't find a way without creating a variable for every letter like a=1 b=2 c=3 d=4...
has title: How can I make a numerology?
upvote count: 3
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/47392697
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81738930
has body: I am using 64-bit 3.6.3 python on a 64-bit windows 10 laptop, with 12 gigs of RAM. I have python code that can extract a zip file (tar.gz). If I use the code, it takes a really long time (~1.5 hour) but if I unzip it directly using 7zip it takes less than 5 minutes, so I am guessing there is something impeding the processing power of python. I am trying to run this code https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb for convenience, here are the specific commands for unzipping. import tarfile tar = tarfile.open(filename) sys.stdout.flush() tar.extractall(data_root) tar.close() Here is full code. from __future__ import print_function import os import sys import tarfile from six.moves.urllib.request import urlretrieve # Config the matplotlib backend as plotting inline in IPython url = 'https://commondatastorage.googleapis.com/books1000/' last_percent_reported = None data_root = '.' # Change me to store data elsewhere def download_progress_hook(count, blockSize, totalSize): """A hook to report the progress of a download. This is mostly intended for users with slow internet connections. Reports every 5% change in download progress. """ global last_percent_reported percent = int(count * blockSize * 100 / totalSize) if last_percent_reported != percent: if percent % 5 == 0: sys.stdout.write("%s%%" % percent) sys.stdout.flush() else: sys.stdout.write(".") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False): """Download a file if not present, and make sure it's the right size.""" dest_filename = os.path.join(data_root, filename) if force or not os.path.exists(dest_filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook) print('\nDownload Complete!') statinfo = os.stat(dest_filename) if statinfo.st_size == expected_bytes: print('Found and verified', dest_filename) else: raise Except…
tagged with: allocation
tagged with: ram
has comment: http://stackoverflow.com/comment/81744581
tagged with: python
tagged with: memory
has comment: http://stackoverflow.com/comment/81738417
has title: Python code is running too slow, do I need to find a way to allocate more memory to python process?
accepted answer: http://stackoverflow.com/a/47395685
has comment: http://stackoverflow.com/comment/81738842
tagged with: memory-management
linked to: http://stackoverflow.com/q/26067471
has answer: http://stackoverflow.com/a/47395685
has comment: http://stackoverflow.com/comment/81739106
has comment: http://stackoverflow.com/comment/81738907
score: 1
has comment: http://stackoverflow.com/comment/81738411
answer count: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/45621476
favorite count: 0
has comment: http://stackoverflow.com/comment/81738871
type: Question
has comment: http://stackoverflow.com/comment/81738443

http://stackoverflow.com/q/47447767
favorite count: 0
type: Question
score: 0
answer count: 2
tagged with: selenium
has answer: http://stackoverflow.com/a/47447831
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/81850816
has comment: http://stackoverflow.com/comment/81850801
downvote count: 1
has answer: http://stackoverflow.com/a/47449614
has comment: http://stackoverflow.com/comment/81850853
tagged with: python
has body: Need to match a set of words in a text file. The set of words are present separately in different lines. A number of occurrences do not matter, but there must be at least 1 occurrence. Only if all the words match exactly it's a PASS, else test is a FAIL. I have created a file with contents : file1 = open("MyFile.txt","a+") Now, the list is list = ["SIMPLE", "QUICK", "ADVANCED"] Below code works for a single string but does not work with a list. with open("C:/Users/vikp/Desktop/MyFile.txt") as file1: for line in file1: if list in line: &lt;assert pass condition&gt; else: &lt;assert fail condition&gt;
has title: Python - To match a list of string words present in a existing text file

xcode
tag name: xcode
tags question: http://stackoverflow.com/q/47393426
type: Tag

http://stackoverflow.com/q/47446284
tagged with: indexing
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/81850508
has answer: http://stackoverflow.com/a/47446346
has comment: http://stackoverflow.com/comment/81848515
has title: Python: How do you make a variable which can be used as an index call to slice another variable?
tagged with: python
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47447952
type: UnansweredQuestion
tagged with: arrays
has body: I am coming from a MATLAB background and moving over to Python. I am trying to figure out a way to set up a variable which is some vector which contains a range of indices which can then be used to slice some other array. In MATLAB I would do this: A = [2,3,4,5,6; 9,4,3,2,1; 5,4,3,2,5]; %some arbitrary matrix begin = 2; %the first index I want to pull end = 4; %the last index I want to pull idx = 2:4; %the vector of indices I want A(:,idx) %results in me pulling out the 2nd, 3rd and 4th column of A Now in Python, what is the equivalent? import numpy as np A = np.array([[2,3,4,5,6],[9,4,3,2,1],[5,4,3,2,5]]) #some arbitrary matrix begin = 1 #first index end = 3 #last index idx = ??? #This is the part I don't know! &lt;&lt;&lt;------------------- A[:,idx] #I want the same result as the Matlab example above Obviously for this trivial example I could just have idx = [1,2,3], but I have much more complicated scenario in real life where I cannot write out the indices manually. I have tried using the range and np.arange functions but they give the error that the object is not callable. When I look at some MATLAB-to-Numpy conversions such as here, it suggests that the idx = 2:4 command in MATLAB command is equivalent to idx = range(1,3) in Python, but this is apparently not quite true? Any help is appreciated.
has answer: http://stackoverflow.com/a/47446490
tagged with: matlab

http://stackoverflow.com/q/47425823
type: AnsweredQuestion
score: 0
tagged with: docker-compose
has title: Container not staying up on docker-compose up
tagged with: python
has body: Writing a simple producer/consumer example of RabbitMQ and I am not able to get my consumer container to keep running on docker-compose up -d. It should be running on an infinite loop. As you can see I can get it to stay up when running docker-compose run consumer as well as docker-compose run -d consumer app.py #!/usr/bin/env python import argparse import pika import json connection = None channel = None TYPES = ['producer', 'consumer'] def producer(): global connection, channel connection = pika.BlockingConnection(pika.ConnectionParameters('rabbit')) channel = connection.channel() channel.queue_declare(queue='hello') # Currently a python dict data = { 'key': 'myvalue' } channel.basic_publish(exchange='', routing_key='hello', body=json.dumps(data)) # Encode as a JSON string print(f' [x] Sent {data}') connection.close() def consumer(): global connection, channel connection = pika.BlockingConnection(pika.ConnectionParameters('rabbit')) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): data = json.loads(body) # decode JSON string into a python dict print(f' [x] Received: {data} type {type(data)}') channel.basic_consume(callback, queue='hello', no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') # Infinite loop try: channel.start_consuming() except KeyboardInterrupt: print('\nExiting...') def main(): parser = argparse.ArgumentParser() parser.add_argument('type', help='producer/consumer') args = parser.parse_args() client_type = args.type.lower() if client_type not in TYPES: print(f'{client_type} is not a valid type {TYPES}') elif client_type == TYPES[0]: producer() elif client_type == TYPES[1]: consumer() if __name__ == '__main__': main() As you can see it is fairly straight forward. Copied it basically from the RabbitMQ docs. I ran docker-compose logs consumer after writing most of this and got the following. Which shows it failing to connect on initial build. It also fails to stay up when…
answer count: 1
accepted answer: http://stackoverflow.com/a/47425855
tagged with: rabbitmq
type: Question
has answer: http://stackoverflow.com/a/47425855
tagged with: docker

apache
tags question: http://stackoverflow.com/q/47463593
tag name: apache
tags question: http://stackoverflow.com/q/47419339
tags question: http://stackoverflow.com/q/47420805
tags question: http://stackoverflow.com/q/47387266
tags question: http://stackoverflow.com/q/47537675
type: Tag
tags question: http://stackoverflow.com/q/47387906
tags question: http://stackoverflow.com/q/47449502
tags question: http://stackoverflow.com/q/47447939
tags question: http://stackoverflow.com/q/47515714
tags question: http://stackoverflow.com/q/47514884

http://stackoverflow.com/q/47537952
tagged with: import
favorite count: 0
has body: I have a question. My python project path is as below: code_root | - code_sub | |- b.py | -- c.py - a.py imported c.py of code_sub from b.py. so I want to be able to load b.py from both code_root and code_sub path. for example: code_root>$ python nlp.py or code_root/code_sub>$ python b.py The problem here is to call c.py. b.py should not import c.py like this: # b.py import c so i found my solution. like below: from os.path import dirname curpath = dirname(__file__) if len(curpath) == 0: curpath = '.' c = imp.load_source('c', curpath+'/c.py') This works but it doesn't seem like the best solution. Is there a more standard Python approach I could use to accomplish the same thing?
type: Question
tagged with: python-3.x
answer count: 1
downvote count: 0
has title: I want to be able to load class from both root and sub path
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47538311
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47538311
score: 1

http://stackoverflow.com/comment/82025891
has text: @DataPsycho contents or uri are empty in some fields, you can try list slicing: `df = pd.DataFrame(data = ((*key["ko_id"][0:1], *key["concepts"][0]["prefLabel"][0:1], *key["concepts"][0]["uri"][0:1]) for key in json_sample), columns = ("ko_id", "prefLabel", "uri"))` Would it be possible for you to share the entire file using Google Drive, DropBox, etc? It would be much easier to give you a possible solution.
type: Comment
comment on: http://stackoverflow.com/a/47520980
score: 0
type: AnswerComment

http://stackoverflow.com/q/47439924
downvote count: 3
has comment: http://stackoverflow.com/comment/81835323
has comment: http://stackoverflow.com/comment/81834817
has comment: http://stackoverflow.com/comment/81836031
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81835481
has comment: http://stackoverflow.com/comment/81835275
has comment: http://stackoverflow.com/comment/81835709
upvote count: 2
has answer: http://stackoverflow.com/a/47440027
linked to: http://stackoverflow.com/q/45640690
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81835425
has comment: http://stackoverflow.com/comment/81841301
has comment: http://stackoverflow.com/comment/81834975
has comment: http://stackoverflow.com/comment/81835355
has comment: http://stackoverflow.com/comment/81836203
has comment: http://stackoverflow.com/comment/81835666
has comment: http://stackoverflow.com/comment/81838138
has comment: http://stackoverflow.com/comment/81835587
tagged with: python
tagged with: decorator
has comment: http://stackoverflow.com/comment/81835809
score: -1
has body: Answer talks about contract of a functional decorator. Below is the code for class based decorator, def hello_world(obj): return 'Hello World' @hello_world class C: pass It is obvious that class based decorator accept Class type object as parameter. For returning an object, What is the contract of a class based decorator?
has comment: http://stackoverflow.com/comment/81836174
has comment: http://stackoverflow.com/comment/81834930
has answer: http://stackoverflow.com/a/47440783
has title: Contract of a class based decorator
has comment: http://stackoverflow.com/comment/81844076
has comment: http://stackoverflow.com/comment/81844186
has comment: http://stackoverflow.com/comment/81836545
has comment: http://stackoverflow.com/comment/81836463

http://stackoverflow.com/a/49489611
type: Answer
score: 4
upvote count: 4
has body: In Anaconda this worked for me: sudo &lt;anaconda path&gt;/bin/python3.6 -m pip install tqdm (after your working env is activated) On my linux machine I substituted &lt;anaconda path&gt; with: anaconda3 Ubuntu machines: sudo /usr/bin/python3.5 -m pip install tqdm
downvote count: 0
has comment: http://stackoverflow.com/comment/107782065
answers question: http://stackoverflow.com/q/47529792

python-mock
tags question: http://stackoverflow.com/q/47407741
type: Tag
tag name: python-mock
tags question: http://stackoverflow.com/q/47398502

http://stackoverflow.com/q/47422617
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47424427
tagged with: pandas
has body: I am trying to retrieve data from National Stock Exchange for a given Scrip name. I already have created a database name "NSE" in MySQL. But did not create any table. Following script I am using to retrieve per minute data from the NSE website (let's say I want to retrieve data for scrip (stock) 'CYIENT'. from alpha_vantage.timeseries import TimeSeries import matplotlib.pyplot as plt import sys import pymysql #database connection conn = pymysql.connect(host="localhost", user="root", passwd="pwd123", database="NSE") c = conn.cursor() your_key = "WLLS3TVOG22C6P9J" def stockchart(symbol): ts = TimeSeries(key=your_key, output_format='pandas') data, meta_data = ts.get_intraday(symbol=symbol,interval='1min', outputsize='full') sql.write_frame(data, con=conn, name='NSE', if_exists='replace', flavor='mysql') print(data.head()) data['close'].plot() plt.title('Stock chart') plt.show() symbol=input("Enter symbol name:") stockchart(symbol) #commiting the connection then closing it. conn.commit() conn.close() On running the above script I am getting following errors: 'sql' is not defined. Also I am not sure if the above script will also create a table in NSE for (user input) stock 'CYIENT'.
score: 0
tagged with: mysql
answer count: 1
type: Question
has title: error in getting pandas time series data into mysql database on localhost
tagged with: pymysql

http://stackoverflow.com/q/47461721
has comment: http://stackoverflow.com/comment/81878185
tagged with: python
has comment: http://stackoverflow.com/comment/81902023
has comment: http://stackoverflow.com/comment/81878314
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81878478
answer count: 0
type: UnansweredQuestion
has body: It is showing an error in SQL syntax: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1 Code: if(options==2): query = ("SELECT Sl_NO,Title,Genre FROM dvdstore WHERE Genre = %s") genre_type = raw_input("Enter the type of genre: ") print genre_type try: y=x.execute(query,(genre_type)) print y for (Sl_NO,Title,Genre) in x: print Title except Error as error: print(error)
has comment: http://stackoverflow.com/comment/81878985
tagged with: mysql
duplicate of: http://stackoverflow.com/q/21740359
has title: Why is this is showing 1064 (42000): You have an error in your SQL syntax?
linked to: http://stackoverflow.com/q/7992559
has comment: http://stackoverflow.com/comment/81878916
has comment: http://stackoverflow.com/comment/81878223
linked to: http://stackoverflow.com/q/23600286

http://stackoverflow.com/comment/82030413
has text: I figured it was possible with my own function, but I just wanted to see if there might have been a built in way I didn't already know about. Either way, I figured it out with my own function, thanks a ton!
type: AnswerComment
comment on: http://stackoverflow.com/a/47535781
score: 0
type: Comment

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/47423854
tags question: http://stackoverflow.com/q/47407996
tag name: countvectorizer

http://stackoverflow.com/comment/81745619
comment on: http://stackoverflow.com/q/47396204
score: 0
has text: Most likely you have some issue with your data source.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47493441
score: 1
type: AcceptedAnswer
has body: As I mentioned in the question edits, the issue was related to the overwritten __init__ method and used my class variables in other ways. I don't know why, but removing __init__ solved the problem. Methods are still class methods; which means both static and class methods are treated the same here.
type: Answer
accepted answer of: http://stackoverflow.com/q/47486843
answers question: http://stackoverflow.com/q/47486843
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81799183
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47422178
has text: @xaav I agree, they haven't tried anything but that doesn't deserve `-5`

oracle-database
tags question: http://stackoverflow.com/q/47390478
tags question: http://stackoverflow.com/q/47435629
tag name: oracle-database
tags question: http://stackoverflow.com/q/47430796
tags question: http://stackoverflow.com/q/47510581
tags question: http://stackoverflow.com/q/47386932
type: Tag
tags question: http://stackoverflow.com/q/47506070

http://stackoverflow.com/comment/81993569
type: AnswerComment
has text: @LarryZ what are your column types initially?
comment on: http://stackoverflow.com/a/47482012
type: Comment
score: 0

http://stackoverflow.com/comment/81877960
score: 0
has text: And I am completely aware of that, I know that `exec(" print\(\"a\"\) ")` is a better replacement
type: QuestionComment
comment on: http://stackoverflow.com/q/47461480
type: Comment

http://stackoverflow.com/comment/81804460
type: AnswerComment
comment on: http://stackoverflow.com/a/47424522
type: Comment
has text: Check this link, it explains the issue really well. https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas
score: 0

http://stackoverflow.com/a/47779253
type: Answer
score: 2
type: AcceptedAnswer
has body: The problem appears to have been connected to tests that throw errors. After that the patch is not torn down correctly.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47473021
answers question: http://stackoverflow.com/q/47473021
upvote count: 2

http://stackoverflow.com/comment/81755943
comment on: http://stackoverflow.com/q/47401086
score: 0
type: Comment
has text: In `fitness`, store the result of `x * x` in a variable, add that result to the log and then return it.
type: QuestionComment

http://stackoverflow.com/q/47499002
type: Question
has title: Create all possible combinations of a list in Python
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81954388
type: UnansweredQuestion
score: -2
has body: does anybody know how can I find out all the possible combinations of a given list using Python 3? My lists look like this: usersArray = ["John", "Mike", "Robert", "Tom"] foodsArray = ["hamburger", "cake", "cheese"] I would like to have something like this: Johnhamburger Mikehamburger Roberthamburger Tomhamburger Johncake Mikecake Robertcake Tomcake Johncheese Mikecheese Robertcheese Tomcheese #and then the opposite hamburgerJohn hamburgerMike hamburgerRobert hamburgerTom cakeJohn ... ... ... cheeseJohn ... ... ... Can I use itertools? Thank you!
tagged with: python
linked to: http://stackoverflow.com/q/25634489
tagged with: combinations
has comment: http://stackoverflow.com/comment/81953341
duplicate of: http://stackoverflow.com/q/25634489
has answer: http://stackoverflow.com/a/47499035
duplicate of: http://stackoverflow.com/q/533905
downvote count: 3
has answer: http://stackoverflow.com/a/47499047
upvote count: 1
tagged with: permutation
has comment: http://stackoverflow.com/comment/81953257
favorite count: 0

http://stackoverflow.com/comment/81725738
comment on: http://stackoverflow.com/q/47385950
type: Comment
score: 0
has text: @COLDSPEED yes but while appending it into a different array I'm getting this problem.
type: QuestionComment

http://stackoverflow.com/a/47514693
type: Answer
score: 4
type: AcceptedAnswer
downvote count: 0
has body: As discussed in the comments, the problem is that the GPU version of TensorFlow for Mac OS X was installed on a Mac without CUDA installed. Uninstalling and reinstalling the CPU version of TensorFlow should fix the problem. (Note that the GPU version of TensorFlow for Mac OS X is no longer officially supported.)
accepted answer of: http://stackoverflow.com/q/47485847
upvote count: 4
answers question: http://stackoverflow.com/q/47485847

http://stackoverflow.com/q/47529386
upvote count: 5
has comment: http://stackoverflow.com/comment/82016012
tagged with: python
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/40694470
has body: I am leaning n-gram, and building a dictionary to save n-gram values. I have something like this: { "it is" : 0.01, "this is" : 0.005, "hello i" : 0.2 "hello you" : 0.3 ... } My dictionary has about 3million keys and it takes 0.0002(s) to get a bigramvalue. Is there anything faster than dict that I could use?
type: AnsweredQuestion
has title: Is there anything faster than a dictionary?
has comment: http://stackoverflow.com/comment/82015645
answer count: 1
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/47529424
has comment: http://stackoverflow.com/comment/82015601
accepted answer: http://stackoverflow.com/a/47529424
favorite count: 0
has comment: http://stackoverflow.com/comment/82015215
tagged with: n-gram
score: 5
linked to: http://stackoverflow.com/q/19629682
linked to: http://stackoverflow.com/q/40694470

http://stackoverflow.com/a/47459022
type: Answer
score: 0
has body: ax2.set_xscale(value='log') l just added this line of code. It allows to make x-axis scale varies in a log way rather than in a linear way
answers question: http://stackoverflow.com/q/47455969

http://stackoverflow.com/comment/81884327
has text: There it has been added above :)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47464697
type: QuestionComment

http://stackoverflow.com/q/47472574
duplicate of: http://stackoverflow.com/q/11177533
linked to: http://stackoverflow.com/q/929777
tagged with: python-3.x
upvote count: 2
linked to: http://stackoverflow.com/q/11177533
score: 2
has body: I have the following code: def proc1(p): p.append(1) x=[2,5] proc1(x) print(x) def proc2(p): p=p+[1] y=[2,5] proc2(y) print(y) z=[2,5] z=z+[1] print(z) The output of the code is: [2, 5, 1] [2, 5] [2, 5, 1] I understand why the value of x and z have become [2,5,1]. But I don't understand why the value of y remains unchanged. I thought that after running proc2(y), y should have referred to [2,5,1]. My point is, I understand that y is not modified/mutated to [2,5,1]. But y is reassigned to a new list, which is [2,5,1], right? Then why does y still refer to the original value? If the value of z has changed, why not y? I have checked the question What's the difference between plus and append in python for list manipulation, but I'm still confused.
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: Confused with list assignment in Python
has comment: http://stackoverflow.com/comment/81900715
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81901530
tagged with: python

http://stackoverflow.com/q/47390236
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I need to create a program that, given a matrix, asks for a row in the matrix and gives the position of the highest value in that row. For example with the matrix: D = [(0 1 3), (1 0 4), (3 4 0)] when given the value 2 should return 1 (because in the row[2] the highest value is 4 which is in position 1 in that row). Right now I'm trying: def farthest(matrix, row, point): maxdist = 0 matrix2 = [] for i in range(0, len(matrix)): if i == int(point): matrix2.append(i) if i != int(point): pass for j in range(0, len(matrix2)): if j &lt; maxdist : pass if j &gt; maxdist: maxdist = maxdist + j print(matrix2) print(maxdist) return matrix2 I should find a solution using loops. The current output that I get is [2] and [0].
has comment: http://stackoverflow.com/comment/81734035
has title: How to get the position of the highest value in a row of a matrix
has answer: http://stackoverflow.com/a/47390314
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81733893
score: -1
tagged with: row
has comment: http://stackoverflow.com/comment/81734661
has comment: http://stackoverflow.com/comment/81734200
upvote count: 0
tagged with: matrix
has comment: http://stackoverflow.com/comment/81754074
has comment: http://stackoverflow.com/comment/81734836
has comment: http://stackoverflow.com/comment/81738931

http://stackoverflow.com/q/47512640
linked to: http://stackoverflow.com/q/62086013
downvote count: 0
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/81982942
has comment: http://stackoverflow.com/comment/111281306
tagged with: file
has body: How do I download from a public repository with Python? https://console.aws.amazon.com/s3/buckets/WQ3/?region=us-West-2&amp;tab=overview My code: import boto3 s3client = boto3.client('s3', region_name='us-West-2') objects = s3client.list_objects(Bucket='WQ3') raise NoCredentialsError botocore.exceptions.NoCredentialsError: Unable to locate credentials
linked to: http://stackoverflow.com/q/34865927
favorite count: 0
type: Question
upvote count: 2
tagged with: download
answer count: 0
type: UnansweredQuestion
has title: Unable to download a file from Amazon s3 with Python (no credentials)
tagged with: python
has comment: http://stackoverflow.com/comment/81984164
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/81983006
score: 2

http://stackoverflow.com/q/47449931
has body: How can I retrieve a specified field for a particular user in Django? I got user: A, B, C and user A got 10 url records in the database. The problem is how to retrieve the 10 url records of user A? Thank you so much. class Bookmark(models.Model): url = models.CharField(max_length=500) shortlisted_by = models.ForeignKey(User, related_name='bookmark') shortlisted_date = models.DateTimeField(auto_now_add=True)
accepted answer: http://stackoverflow.com/a/47450106
answer count: 1
has answer: http://stackoverflow.com/a/47450106
tagged with: django
tagged with: python
tagged with: model-view-controller
type: AnsweredQuestion
score: 0
has title: Django: How to retrieve a particular item for specific user from a model?
type: Question
tagged with: model

http://stackoverflow.com/q/47525872
favorite count: 0
has comment: http://stackoverflow.com/comment/82008062
has body: I'm trying to upload my django project to Google Cloud Platform. When I run python manage.py runserver an error occurs. Until a while ago, it worked well. After fixing codes of just one file 'setting.py' the error occurred. Here's a screenshot image below. C:\Users\sgc109\PycharmProjects\pyproj\djenv\Scripts\python.exe C:/Users/sgc109/PycharmProjects/pyproj/my_project/manage.py runserver Traceback (most recent call last): File "C:/Users/sgc109/PycharmProjects/pyproj/my_project/manage.py", line 24, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 62, in execute super(Command, self).execute(*args, **options) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 101, in handle self.run(**options) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in run autoreload.main(self.inner_run, None, options) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.py", line 341, in main reloader(wrapped_main_func, args, kwargs) File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.p…
has comment: http://stackoverflow.com/comment/82007627
linked to: http://stackoverflow.com/q/38363566
type: Question
has comment: http://stackoverflow.com/comment/82008117
has comment: http://stackoverflow.com/comment/82007739
has comment: http://stackoverflow.com/comment/82008090
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/30900294
has title: UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 27: invalid continuation byte django
answer count: 1
has comment: http://stackoverflow.com/comment/82007768
has comment: http://stackoverflow.com/comment/82007693
has comment: http://stackoverflow.com/comment/82007967
has answer: http://stackoverflow.com/a/47556719
tagged with: mysql
tagged with: utf-8
score: 1

http://stackoverflow.com/a/47394082
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47393251
accepted answer of: http://stackoverflow.com/q/47393251
type: Answer
score: 2
has body: The logits that you have provided are for classes 0 and 1 respectively (that's how tensorflow understands it). So, for res1 - prob(class1) is 0.6 for the 1st data point By definition, Cross Entropy is - -np.log(np.exp([0.6]) / np.sum(np.exp([0.4, 0.6]))) Similarly, for the second case - -np.log(np.exp([0.5]) / np.sum(np.exp([0.5, 0.5]))) gives the desired output. This is inline with Tensorflow's output. Hope this helps!
upvote count: 2

http://stackoverflow.com/q/47404678
has answer: http://stackoverflow.com/a/47404785
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81859242
tagged with: python
has answer: http://stackoverflow.com/a/74915309
has body: I have problem in convert date time. Here is my code: @api.multi def action_confirm(self): if picking.state not in ['cancel', 'draft']: for schedule_delivery in sorted_key: print "line 105: ", schedule_delivery dup_picking = picking.copy() if shift == "afternoon": date_object = datetime.strptime(schedule_delivery, '%Y-%m-%d') print "Line 146", date_object # raise EnvironmentError tanggal = datetime.strftime(date_object, "%Y-%m-%d") + ' 06:00:00' print "Line 145", tanggal dup_picking.min_date = tanggal else: dup_picking.min_date = schedule_delivery Error: date_object = datetime.strptime(schedule_delivery, '%Y-%m-%d') File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime data_string[found.end():]) ValueError: unconverted data remains: 00:00:00
has title: ValueError: unconverted data remains: 00:00:00
answer count: 3
downvote count: 0
tagged with: odoo
score: 7
upvote count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/63947571
type: Question

http://stackoverflow.com/q/47520970
tagged with: python
has title: Django: override save method on ModelForm that inherits values from another ModelForm
answer count: 0
score: 1
upvote count: 1
has body: For convention at my company any validation must be done in the form and not in the view of any Django APP. I've this code that applies to my form, as a regular form. But I've "upgraded" it to be a 'ModelForm' and this code, works but doesn't save the "document" attribute on the 'Nana'. 1.- What am I doing wrong? 2.- What benefits are of doing the validation in the 'form' vs 'view'? forms.py from django import forms from django.core.exceptions import ObjectDoesNotExist from django.db import transaction from nucleo.models.documento import Documento from nucleo.models.nana import Nana from nucleo.models.tipo_documento import TipoDocumento class NanaForm(forms.ModelForm): class Meta: model = Nana fields = ['nombre', 'apellido_paterno', 'apellido_materno', 'fecha_de_nacimiento', 'direccion', 'telefono_o_celular', 'genero', 'foto', 'latitud', 'longitud'] def clean(self): form_data = self.cleaned_data try: tipo_documento = TipoDocumento.objects.get(form_data['tipo_documento']) if not tipo_documento.validar_documento(form_data['documento']): self._errors["documento"] = ["El documento no cumple el formato."] del form_data['documento'] except ObjectDoesNotExist: self._errors["tipo_documento"] = ["No existe el tipo de documento seleccionado."] del form_data['tipo_documento'] return form_data @transaction.atomic() def save(self): valid_data = self.cleaned_data documento_codigo = valid_data.pop('documento') documento_tipo_id = valid_data.pop('tipo_documento') documento = Documento(codigo=documento_codigo, tipo_documento_id=documento_tipo_id) documento.save() nana = Nana(documento=documento, **valid_data) nana.save() return nana class DocumentoForm(forms.ModelForm): class Meta: model = Documento fields = ['tipo_documento', 'codigo'] models.py class TipoDocumento(models.Model): nombre_corto = models.CharField(blank=False, null=False, max_length=25) nombre_largo = models.CharField(blank=False, null=False, max_length=100) tipo_patron = models.IntegerField(blank=False, null=False, c…
has comment: http://stackoverflow.com/comment/82021855
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82024387
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/82025223
type: AnswerComment
comment on: http://stackoverflow.com/a/47534117
score: 0
type: Comment
has text: For both? aand if use `df = df[~pd.Series(df.index.values).duplicated()]` ?

http://stackoverflow.com/comment/82003534
comment on: http://stackoverflow.com/q/47523483
score: 0
type: Comment
type: QuestionComment
has text: @Sheshnath I don't seem to be able to figure out how to use that example to apply to mine, with only having %b from date in the index. Also I get an error 'Index' object has no attribute 'strftime'

http://stackoverflow.com/q/47411319
favorite count: 0
has comment: http://stackoverflow.com/comment/81776110
tagged with: list
type: Question
score: 1
has answer: http://stackoverflow.com/a/47411704
has title: 'dict' object has no attribute 'decode'
has body: I'm working on examples from book wrangling with Python. Trying to read data from a CSV file into a dictReader object named header_rdr. header_rdr = DictReader(open('/Users/tcssig/Downloads/data-wrangling-master/data/unicef/mn_headers.csv', 'r')) When I try list comprehension to read all dict values in a list, using header_rows = [h.decode('utf-32') for h in header_rdr] Error message i get is: 'dict' object has no attribute 'decode'. How do I proceed without decoding the string before passing into a string. Also, without decoding the elements, I got the error as : UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2807: ordinal not in range(128)
upvote count: 2
has comment: http://stackoverflow.com/comment/81776002
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81776047
tagged with: dictionary
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/81952534
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47498483
has text: I understand. check 3. file, there is less columns as you think, so raise error. Also is possible check columns names before droping by `print (data.columns.tolist())`
score: 0

http://stackoverflow.com/q/47525175
upvote count: 2
possible better answer: http://stackoverflow.com/a/47525264
accepted answer: http://stackoverflow.com/a/47525191
has answer: http://stackoverflow.com/a/47525264
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47525191
has title: python dataframe creating new column
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/733454
score: 1
downvote count: 1
favorite count: 0
type: Question
has body: I am using plotly and in their document, I saw this statement. df['text'] = df['state'] + '&lt;br&gt;' +\ 'Beef '+df['beef']+' Dairy '+df['dairy']+'&lt;br&gt;'+\ 'Fruits '+df['total fruits']+' Veggies ' + df['total veggies']+'&lt;br&gt;'+\ 'Wheat '+df['wheat']+' Corn '+df['corn'] Plotly creating map Without any doubt, I tried to implement my dataset into this code, df_region["text"] = df_region["addr_state"] + '&lt;br&gt;' + "Total loan amount ($ USD): " + df_region["loan_amnt"] + "&lt;br&gt;" + "Avg loan amount ($ USD): " + df_region["avg_loan_amnt_by_state"] + '&lt;br&gt;' + "Avg employment length (Years): " + df_region["avg_emp_length_by_state"] But I got these error message TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('&lt;U33') dtype('&lt;U33') dtype('&lt;U33') I used to have all columns as numeric(int64 or float64) except addr_state. Later, I changed all column types to object but still didn't get any luck. Can someone give hint what I miss here? Head part of my dataset look like this amnt num avg_loan emp_length addr_state 1 36978050 2205 16770 6.00 AK 2 164627650 11200 14698 6.15 AL 3 93416075 6640 14068 5.90 AR 4 290110100 20412 14212 5.37 AZ 5 1898145250 129517 14655 5.66 CA Thanks!
answer count: 2

http://stackoverflow.com/q/47443985
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81844276
type: Question
has title: Bug not allowing users to select the third row for tic tac toe
has answer: http://stackoverflow.com/a/47445507
has body: As the title suggest, the bug I am running into is not allowing the first person to select the third row of my Tic Tac Toe grid. It's is behaving like that row does not exist. Perhaps I did something wrong that I do not see or I over complicated it. Anyway, everything else works as I want it to. This is last thing I want to fix. Also, if you guys have suggestions to make my code better and more efficient please tell me. This is my first year programming. The code that edits the grid: #Edit the Tic Tac Toe grid. def editGrid(grid, selectedRow, selectedColumn, player): validRow = 0 #Determine which player is editing the #grid. if player == " X ": for rows in grid: #Determine which row was selected. if selectedRow - 1 == validRow: #Determine what to do based on the column selected. if selectedColumn == 1: #Check to see if a player is in the spot selected. if grid[selectedRow - 1][selectedColumn] == " O " or grid[selectedRow - 1][selectedColumn] == " X ": print("\nA player is already there.") else: rows.insert(selectedColumn, player) rows.pop(selectedColumn + 1) elif selectedColumn == 2: if grid[selectedRow - 1][selectedColumn + 1] == " O " or grid[selectedRow - 1][selectedColumn + 1] == " X ": print("\nA player is already there.") else: rows.insert(selectedColumn + 1, player) rows.pop(selectedColumn + 2) elif selectedColumn == 3: if grid[selectedRow - 1][selectedColumn + 2] == " O " or grid[selectedRow - 1][selectedColumn + 2] == " X ": print("\nA player is already there.") else: rows.insert(selectedColumn + 2, player) rows.pop(selectedColumn + 3) validRow = grid.index(rows) + 1 else: for rows in grid: #Determine which row was selected. if selectedRow - 1 == validRow: #Determine what to do based on the column selected. if selectedColumn == 1: #Check to see if a player is in the spot selected. if grid[selectedRow - 1][selectedColumn] == " X " or grid[selectedRow - 1][selectedColumn] == " O ": print("\nA player is already there.") else: rows.insert(selectedColumn, player…
has comment: http://stackoverflow.com/comment/81844042
tagged with: python
accepted answer: http://stackoverflow.com/a/47445507
type: AnsweredQuestion

http://stackoverflow.com/comment/81824883
type: Comment
type: QuestionComment
score: 0
has text: @ElisByberi, to simplify the post.
comment on: http://stackoverflow.com/q/47434724

http://stackoverflow.com/q/47416343
has body: I have a CSV file with a list of names that I am trying to edit. There are multiple changes I am trying to make. When opened with the code below, the printed csv shows as follows: with open ('wedding table cards.csv',newline='') as f: reader = csv.reader(f) for row in reader: print(row) ['Mr. and Mrs. Scott Summers'] ['Ms. Lorna Dane'] ['Mr. Hank McCoy and Ms. Ororo Munroe'] ['Mr. Logan Wolverine'] ['Mr. and Mrs. Warren Worthington'] ['Ms. Anna Marie and Mr. Remy Lebeau'] Below are the actions I need help with. Not sure if I should be using Regex or other functions to solve these problems. For strings that have "Mr. and Mrs." in them, split the string into two columns (comma separated) Ex: "Mr. and Mrs. Scott Summers" --> "Mr. and Mrs." , "Scott Summers" For strings that have "Mr." or "Ms." in them, remove the title from the string ex: "Ms. Lorna Dane" --> "Lorna Dane" For strings that have are structured as "Title. Name and Title Name" split string into two columns (comma separated) ex: "Mr. Hank McCoy and Ms. Ororo Munroe" --> "Mr Hank McCoy" , "Ms. Ororo Munroe" For #1, here is what I have tried so far. It works except that it adds an extra space to the second column. with open('wedding table cards.csv') as inf: with open('test_1.csv','w') as outf: for line in inf: outf.write('Mr. and Mrs.'.join(line.split('Mr. and Mrs.')))
tagged with: substring
type: Question
score: 0
tagged with: list
tagged with: split
answer count: 1
accepted answer: http://stackoverflow.com/a/47417207
has answer: http://stackoverflow.com/a/47417207
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Remove substring + split column in list of names in CSV

http://stackoverflow.com/comment/81820802
type: QuestionComment
comment on: http://stackoverflow.com/q/47432965
score: 0
has text: no i'm using sqlachemy (sqlite3)
type: Comment

http://stackoverflow.com/a/47491823
downvote count: 0
has comment: http://stackoverflow.com/comment/81939182
has comment: http://stackoverflow.com/comment/81939012
type: Answer
accepted answer of: http://stackoverflow.com/q/47491433
score: 2
answers question: http://stackoverflow.com/q/47491433
upvote count: 2
has body: The reason your first snippet of code does what it does is because you're passing a mutable object (the list named index) when creating each of the class A instances, so when they print its value they all display whatever is currently in it—which will be the last thing was that was assigned to index[0] just before the Thread instance itself is created in the following line. So a workaround would be to avoid passing the function a mutable object. The change indicated below is a trivial way of doing that in this case: class A(): def __init__(self, a): self.a = a def run(self): print(self.a) if __name__=='__main__': index = [0] thread_list = [] for i in range(10): index[0] = i # thread_list.append(threading.Thread(target=A(index).run)) thread_list.append(threading.Thread(target=A(index[0]).run())) for thread in thread_list: thread.start() time.sleep(0.5) for thread in thread_list: thread.join()
type: AcceptedAnswer

http://stackoverflow.com/comment/81817917
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47431752
has text: I don't think it's a duplicate, since he wants to keep the pairs

http://stackoverflow.com/comment/86497525
comment on: http://stackoverflow.com/a/47443126
type: Comment
type: AnswerComment
has text: Exactly what I needed for generating higher (7+) dimensional lines quickly and easily.
score: 0

http://stackoverflow.com/a/47485840
has body: The problem lies in the lines fig = plt.figure() ax = fig.add_axes([0,0,30,30]) This will create an axes which is 30 times larger than the figure in each dimension. Hence you only see 1./(30*30) = 1 per mille of the axes. What you would probably like to do is add a normal subplot and set its data range to 0..30 in both directions. fig, ax = plt.subplots() ax.axis([0,30,0,30]) Complete example: import matplotlib.pyplot as plt import matplotlib.patches as patches plt.close('all') pts={} #defining points pts.update({1:(0,0)}) pts.update({2:(10,0)}) pts.update({3:(10,20)}) pts.update({4:(0,20)}) pts.update({5:(30,0)}) pts.update({6:(30,20)}) #defining rectangle connecting to points rect={} rect.update({10:(1,2,3,4)}) rect.update({11:(2,5,6,3)}) #plotting fig, ax = plt.subplots() ax.axis([0,30,0,30]) for i in rect: p2=rect[i] dx,dy = pts[p2[0]] wd = pts[p2[1]][0] - pts[p2[0]][0] ht = pts[p2[3]][1] - pts[p2[0]][1] midpt = [ (pts[p2[0]][0] + pts[p2[2]][0])/2, (pts[p2[0]][1] + pts[p2[2]][1])/2 ] #finding midpoint of points zeroth and second #x_mid= (x_0+x_2)/2 and similar for y_mid p = patches.Rectangle((dx,dy), wd,ht,fill=False, clip_on=False) ax.add_patch(p) plt.text(midpt[0],midpt[1],i,color='k') else: plt.show()
answers question: http://stackoverflow.com/q/47482052
accepted answer of: http://stackoverflow.com/q/47482052
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47526001
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82011384
accepted answer of: http://stackoverflow.com/q/47525790
has comment: http://stackoverflow.com/comment/82010020
has comment: http://stackoverflow.com/comment/82011451
has comment: http://stackoverflow.com/comment/82011121
has comment: http://stackoverflow.com/comment/82010586
answers question: http://stackoverflow.com/q/47525790
has body: What you are getting is not 1 batch size output from this generator. Let me give you an example here: If you have total 1000 samples and you are dividing this in batches 10. Then using fit_generator you will get only 10 batches which means you have 10 batches each of 10 samples. So, the crux is fit_generator shows number of batches instead of total number of samples.
has comment: http://stackoverflow.com/comment/82010669
type: Answer
has comment: http://stackoverflow.com/comment/82011579
has comment: http://stackoverflow.com/comment/82009867
has comment: http://stackoverflow.com/comment/82010869
score: 0
has comment: http://stackoverflow.com/comment/82010117
has comment: http://stackoverflow.com/comment/82011753

http://stackoverflow.com/q/47479541
has comment: http://stackoverflow.com/comment/81914093
score: 1
has comment: http://stackoverflow.com/comment/81914153
has answer: http://stackoverflow.com/a/47479929
tagged with: kubernetes
has comment: http://stackoverflow.com/comment/81914226
has body: Can someone example to me how CSRF works in the cluster setup? I have a kubernetes cluster hosting a django website, and I'm having some occasional issues with 403 errors. I have multiple instances of the site load balanced in kubernetes. How does CSRF work when a POST is sent from 1 instance and handled by another? Does CSRF site work if the docker images are updated during the time the form is being filled out? Thanks!
downvote count: 1
has title: Django CSRF in a cluster
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47479929
upvote count: 2
has comment: http://stackoverflow.com/comment/81914311
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47479741
tagged with: docker
has answer: http://stackoverflow.com/a/47479741
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/72659306
score: 1
type: Answer
has body: The coefficients are saved as a dictionary in the result.params data frame, that's a pandas Series. In it, the constant term is stored as Intercept, as others pointed. The variable terms are stored with their variable names. So, if your model is y ~ x, the regression coefficients will be available as result.params['Intercept'] (that's b) and result.params['x'] (that's a) for the equation y = a*x + b.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47388258

http://stackoverflow.com/q/47479869
has title: How can I return all shards when using the Elasticsearch Python API?
tagged with: python
has answer: http://stackoverflow.com/a/47510248
type: AnsweredQuestion
score: 0
tagged with: elasticsearch
has answer: http://stackoverflow.com/a/47480119
has body: I am trying to run a search against an ELK setup using the elasticsearch python API. It seems that by default, the search returns only 5 results from an index. How can i configure this so that it can return all the shards that are available from an index? The kibanna dashboard is showing 900 + shards, but the API is only returning 5. My code at the moment is: es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) data = es.search( index='scapy' ) Output from the script shows (top part): {u'_shards': {u'failed': 0, u'skipped': 0, u'successful': 5, u'total': 5}, Screenshot from kibanna dashboard: Thanks!
accepted answer: http://stackoverflow.com/a/47480119
tagged with: elasticsearch-plugin
type: Question
possible better answer: http://stackoverflow.com/a/47510248
answer count: 2

http://stackoverflow.com/q/47483015
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81933648
tagged with: django
tagged with: python
answer count: 6
tagged with: contact-form
has answer: http://stackoverflow.com/a/72742350
has answer: http://stackoverflow.com/a/48750034
linked to: http://stackoverflow.com/q/45324416
has comment: http://stackoverflow.com/comment/81922523
has title: Sending Godaddy email via Django using python
has answer: http://stackoverflow.com/a/61214841
has answer: http://stackoverflow.com/a/52848489
tagged with: email
downvote count: 0
has body: I have these settings EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True Speaking to Godaddy I have found out these are the ports and settings smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF I have tried all the combinations. If I set TLS to True I am getting STARTTLS extension not supported by the server. If I set to 465 I am getting If I set other combinations like EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
tagged with: smtp
score: 8
favorite count: 0
type: Question
upvote count: 8
has answer: http://stackoverflow.com/a/65810921
has answer: http://stackoverflow.com/a/73179010

http://stackoverflow.com/comment/81975216
score: 0
has text: What exactly is a "signature bar"? Can be more precise of what the desired output is?
comment on: http://stackoverflow.com/q/47501711
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81745145
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47393688
has text: Thank you :) And to put into the data frame I use now `pandas.concat([count.to_frame().T, finDF], axis=0)`.

http://stackoverflow.com/q/47513316
duplicate of: http://stackoverflow.com/q/20449427
score: 0
accepted answer: http://stackoverflow.com/a/47513498
has title: Prompting for numbers instead of letters Python 2.7.x
answer count: 1
linked to: http://stackoverflow.com/q/20449427
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47513498
tagged with: prompt
tagged with: python
has body: So I have a few questions about the code below. from sys import exit def gold_room(): print "This room is full of gold. How much do you take?" next = raw_input("&gt; ") gold_greedy = "50" if next &gt; gold_greedy: dead("You are too greedy to live, die.") elif next &lt; gold_greedy: dead("You are fair and therefore you win.") else: dead("Man, you BARELY made it") def bear_room(): print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How are you going to move the bear?" bear_moved = False while True: next = raw_input("&gt; ") if next == "Take honey": dead("The bear looks at you then slaps you.") elif next == "taunt bear" and not bear_moved: print "The bear has moved from the door. You can go through it now." bear_moved = True elif next == "Taunt Bear" and bear_moved: dead("The bear gets pissed off and chews your legs off.") elif next == "open door" and bear_moved: gold_room() else: print "I got no idea what that means." def cthulhu_room(): print "Here you see the great evil Cthulhu." print "He, it, whatever stares at you and you go insane." print "Do you flee for your life or eat your head?" next = raw_input("&gt; ") if "flee" in next: start() elif "head" in next: dead("Well that was tasty!") else: cthulhu_room() def dead(why): print why, "Good job!" exit(0) def start(): print "You are in a dark room." print "There is a door to your right and left." print "Which one do you take?" next = raw_input("&gt; ") if next == "left": bear_room() elif next == "right": cthulhu_room() else: dead("You stumble around the room until you starve.") start() When I get to the gold_room, why when I take any letters instead of numbers it gives me "You are too greedy to live, die. Good job!", shouldn't it give me an error message? or give me the "Man, you BARELY made it" message? If the user types anything other than whole numbers, how can I prompt him to type a number?
type: Question

django-generic-views
type: Tag
tag name: django-generic-views
tags question: http://stackoverflow.com/q/47534373

ubuntu-16.04
tags question: http://stackoverflow.com/q/47481748
tags question: http://stackoverflow.com/q/47444042
tag name: ubuntu-16.04
tags question: http://stackoverflow.com/q/47393518
type: Tag
tags question: http://stackoverflow.com/q/47460889
tags question: http://stackoverflow.com/q/47398758

http://stackoverflow.com/a/47517486
has comment: http://stackoverflow.com/comment/81991114
has comment: http://stackoverflow.com/comment/82012846
has comment: http://stackoverflow.com/comment/82014070
type: Answer
score: 2
has body: Make a mapping of ancestors to counts, and use that as a key to max, so: &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(ancestors, width=300) {'island': ['island', 'landform', 'landscape', 'pysio-geographical object', 'geographical object'], 'peninsula': ['peninsula', 'landform', 'landscape', 'pysio-geographical object', 'geographical object'], 'short film': ['short film', 'film', 'artwork', 'creative work', 'work'], 'silent film': ['silent film', 'film', 'artwork', 'creative work', 'work'], 'ssf': ['ssf', 'short film', 'film', 'artwork', 'creative work']} Now, use a collections.Counter, or just implement this with a regular dict if you want: &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; counts = Counter(v for vals in ancestors.values() for v in vals) &gt;&gt;&gt; counts Counter({'film': 3, 'creative work': 3, 'artwork': 3, 'landform': 2, 'pysio-geographical object': 2, 'geographical object': 2, 'work': 2, 'landscape': 2, 'short film': 2, 'silent film': 1, 'island': 1, 'ssf': 1, 'peninsula': 1}) Now, finally, create your new, desired dictionary: &gt;&gt;&gt; final = {k:max(v, key=counts.get) for k, v in ancestors.items()} &gt;&gt;&gt; pprint(final) {'island': 'landform', 'peninsula': 'landform', 'short film': 'film', 'silent film': 'film', 'ssf': 'film'} Note, a collections.Counter is just a subclass of dict except the constructor takes an iterable of items that it counts for you automatically, but you could have done: &gt;&gt;&gt; counts = {} &gt;&gt;&gt; for vals in ancestors.values(): ... for v in vals: ... if v in counts: ... counts[v] += 1 ... else: ... counts[v] = 1 ... &gt;&gt;&gt; counts {'landform': 2, 'silent film': 1, 'pysio-geographical object': 2, 'geographical object': 2, 'island': 1, 'ssf': 1, 'work': 2, 'film': 3, 'landscape': 2, 'short film': 2, 'peninsula': 1, 'creative work': 3, 'artwork': 3}
has comment: http://stackoverflow.com/comment/82012569
answers question: http://stackoverflow.com/q/47516963
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82013897

http://stackoverflow.com/comment/81923140
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47449208
has text: First thing: using anaconda, you probably have a recent enough pip and setuptools and should use conda itself to update those. With anaconda, `conda install` is the primary resource for installing anaconda-provided packages. Then, "2.0b9" is a beta release (as indicated by the "b9") and might suffer from a configuration problem for the install. The setup.py file is not located at the root of the downloaded archive file, I suppose that creates the problem.

http://stackoverflow.com/comment/82082921
type: Comment
has text: @jonrsharpe True for this case but there is a difference when a class is derived from `Page`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47521548
score: 0

http://stackoverflow.com/a/47421968
has comment: http://stackoverflow.com/comment/81800253
answers question: http://stackoverflow.com/q/47421918
has comment: http://stackoverflow.com/comment/81800439
has comment: http://stackoverflow.com/comment/81800322
type: Answer
has body: Just modify the main for-loop to print the result there and then: for line in file: detail = line.split(",") print(detail[0]) select = input("Select 1 or 2: ") if select == detail[3]: print("correct!") else: print("incorrect :(")
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81800589

http://stackoverflow.com/a/47519883
answers question: http://stackoverflow.com/q/47518203
accepted answer of: http://stackoverflow.com/q/47518203
type: Answer
has body: Okay, I found the problem. In fact, my LearnerRun was too large for Multiprocessing to handle. But the way in which it was is pretty subtle, so I'll describe. Evidently it is not just the arguments that need to be pickled; the function is pickled too, including the LearnerRun object its execution will rely on (the self). LearnerRun's constructor takes all the things in the options dictionary passed to it and uses setattr to turn all the keys and values in to member variables with values. This alone is fine, but my coworker realized that this left a couple of strings that will need to be database references and set self.trainDatabase = LarData(self.trainDatabase) and self.coverageDatabase = LarData(self.coverageDatabase), which ordinarily would be fine. Except this means that to pickle the class you have to pickle the entirety of the databases! I discovered this during a sanity check wherein just serialized the LearnerRun itself to see what would happen with pickle.dumps(learner_run). My memory was flooded, and the swap began filling up alarmingly quickly until stackoverflow. So what about pickling to the disk? pickle.dump(learner_run, filename) also blew up. It got to 14.3 GiB before I terminated! What about removing those references and calling the LarData constructor later when needed? Bam. Fixed. Everything works. Multiprocessing doesn't give a mysterious SystemError anymore. This is the second time pickle has caused me major pain recently.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47532816
answers question: http://stackoverflow.com/q/47532500
accepted answer of: http://stackoverflow.com/q/47532500
type: Answer
has comment: http://stackoverflow.com/comment/82023037
has body: With BeautifulSoup &amp; urllib you should be able to collect the images in a webpage, iterate and download them. from urllib import urlretrieve import urlparse from bs4 import BeautifulSoup import urllib2 url = "&lt;your_url&gt;" soup = BeautifulSoup(urllib2.urlopen(url)) for img in soup.select('img'): img_url = urlparse.urljoin(url, img['src']) file_name = img['src'].split('/')[-1] urlretrieve(img_url, file_name) Python 3 compatible code, from bs4 import BeautifulSoup from urllib.request import urlopen, urlretrieve from urllib.parse import urljoin url = "&lt;url&gt;" soup = BeautifulSoup(urlopen(url)) for img in soup.find_all('img'): img_url = urljoin(url, img['src']) file_name = img['src'].split('/')[-1] urlretrieve(img_url, file_name)
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82022442
type: AcceptedAnswer

http://stackoverflow.com/comment/81977757
type: QuestionComment
has text: so my solution works. but it's not using command line arguments.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47510830

http://stackoverflow.com/comment/81770480
comment on: http://stackoverflow.com/a/47408599
score: 0
type: Comment
has text: Important to note `yield from` is Python 3 syntax
type: AnswerComment

http://stackoverflow.com/comment/81835225
type: AnswerComment
has text: Maybe [this is relevant to you](https://stackoverflow.com/a/45384691/2320035) (and maybe a difference to gnuplot).
score: 0
comment on: http://stackoverflow.com/a/47439327
type: Comment

http://stackoverflow.com/comment/81936080
type: QuestionComment
comment on: http://stackoverflow.com/q/47490334
has text: For I/O bound tasks (like reading or writing from/to a file) you should consider `threading` module instead of `multiprocessing` module. multiprocessing works better for CPU bound tasks.
score: 1
type: Comment

http://stackoverflow.com/comment/81940384
has text: Are you actually running out of memory? If so, how much memory do you have, and what shapes are your actual data?
score: 0
comment on: http://stackoverflow.com/q/47492528
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47484375
has body: Using an instance of kivy.uix.image inside the button you can do: Disable animation at startup anim_delay = -1. Specify the number of loops to be played using anim_loop = 1 When the button is pressed, assign a positive value to anim_delay and restart animation using the anim_reset method of the kivy.core.image instance used by kivy.uix.image to contain the image. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder Builder.load_string(""" &lt;ExampleApp&gt;: orientation: "vertical" Button: text: "" on_press: gif.anim_delay = 0.10 on_press: gif._coreimage.anim_reset(True) Image: id: gif source: 'img.gif' center: self.parent.center size: 500, 500 allow_stretch: True anim_delay: -1 anim_loop: 1 """) class ExampleApp(App, BoxLayout): def build(self): return self if __name__ == "__main__": ExampleApp().run()
upvote count: 9
accepted answer of: http://stackoverflow.com/q/47481540
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47481540
score: 9

http://stackoverflow.com/comment/81816339
comment on: http://stackoverflow.com/q/47430517
has text: Using this method,actually the process been created.But I couldn't get the process id or status of the child process
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81735459
type: QuestionComment
has text: I'm putting everything together in an answer, plus links and explanation ;)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47390035

http://stackoverflow.com/q/47441501
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47463700
has comment: http://stackoverflow.com/comment/81856016
tagged with: python
tagged with: pyyaml
has answer: http://stackoverflow.com/a/47442759
score: 2
has comment: http://stackoverflow.com/comment/81869370
answer count: 2
has body: I have an yaml file as mentioned below test1.yaml resources: name:{get_param: vname} ssh_keypair: {get_param: ssh_keypair} Now I want to add test1_routable_net: { get_param: abc_routable_net } under resources of test1.yaml Here is the code which I tried import ruamel.yaml yaml = ruamel.yaml.YAML() test="{ get_param: abc_routable_net }".strip(‘\’’) with open('/tmp/test1.yaml') as fp: data = yaml.load(fp) data['resources'].update({‘test1_routable_net’:test}) yaml.dump(data,file('/tes2.yaml', 'w')) output of above code is tes2.yaml resources: name:{get_param: vname} ssh_keypair: {get_param: ssh_keypair} test1_routable_net: '{ get_param: abc_routable_net }' Desired output is tes2.yaml resources: name:{get_param: vname} ssh_keypair: {get_param: ssh_keypair} test1_routable_net: { get_param: abc_routable_net } I tried using test.strip('\'') , but no use still I see single quotes for the value .... How can I remove those quotes from the value?
downvote count: 0
has title: remove single quotes from dict values while adding content to yaml file using python ruamel.yaml
favorite count: 0
type: Question
tagged with: ruamel.yaml
upvote count: 2

http://stackoverflow.com/comment/85069497
type: QuestionComment
score: 0
has text: I'm voting to close this question as off-topic because questions asking for how to improve working code belong on Code Review, not Stack Overflow.
comment on: http://stackoverflow.com/q/47476419
type: Comment

http://stackoverflow.com/q/47519531
has title: VS 2017 python program doesn't start
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82453998
has comment: http://stackoverflow.com/comment/82216405
has comment: http://stackoverflow.com/comment/82075954
has body: Installed a fresh VS 2017 with Python 3.6 (64-bit) and wrote a little "hello World" program; when starting the program with the python interpreter in the cmd environment everything is fine, but when i try to start the program within Vs2017 (single step debuger, debber start >) hust nothing happens :-( Where can i find log files to investigate the problem? Windows 2010 Pro 10.0.16299 Build 16299 Microsoft Visual Studio Community 2017 VisualStudio.15.Release/15.4.4+27004.2009 Microsoft .NET Framework Version 4.7.02556 Installierte Version: Community Python 3.0.17310.2 Stellt IntelliSense, Projekte, Vorlagen, Debuggen, interaktive Fenster und weitere Unterstützung für Python-Entwickler bereit. Python – Django-Unterstützung 3.0.17310.2 Stellt Vorlagen und Integration für das Django-Webframework bereit. Python – IronPython-Unterstützung 3.0.17310.2 Stellt Vorlagen und Integration für IronPython-basierte Projekte bereit. Python – Unterstützung für die Profilerstellung 3.0.17310.2 Profilerstellungsunterstützung für Python-Projekte. Python – Unterstützung für VC-Projekte 3.0.17262.1 Bietet Unterstützung für das Starten von C++-Projekten mit aktivierter Python-Debugfunktion. Update 6.12.17 Recreated a fresh new project from scratch (even stated VS2017 new); see project environment / project explorer: Screen Shot Project environment / projedt explorer Startupfile is right (app-name.py) starting program works as expected; starting (with a breakpoint set) using "start with debugger" no effect; I didn't change any VS settings - just use it as installed; pylint returned no errors;
score: 0
has comment: http://stackoverflow.com/comment/82136337
has comment: http://stackoverflow.com/comment/82436966
has comment: http://stackoverflow.com/comment/82159852
has comment: http://stackoverflow.com/comment/82088179
type: Question
tagged with: visual-studio-2017
tagged with: debugging
has comment: http://stackoverflow.com/comment/82006874
has comment: http://stackoverflow.com/comment/82439428
has comment: http://stackoverflow.com/comment/82121746
answer count: 0

http://stackoverflow.com/comment/81983239
type: AnswerComment
has text: @EsbenEickhardt you can. I can't write it here, so give you a link: https://stackoverflow.com/questions/23231605/convert-pandas-dataframe-to-csv-string; this will retain csv string as a string object while you do `to_csv()`. you can then manipulate it at a later stage.
comment on: http://stackoverflow.com/a/47512945
type: Comment
score: 0

http://stackoverflow.com/a/47447793
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47403696
type: Answer
score: 0
has body: I have switched to One Hot Coding, using something like this: categoriesDF = pd.get_dummies(categoriesDF) This function will create a column for every non-category value, with 1 or 0.

http://stackoverflow.com/comment/81881728
score: 0
has text: Thanks! One more thing - the filters are produced programmatically by my API so it sounds like I’ll need to add the NULL filter (as shown in your post) whenever there is a filter on an association column. Does that sound right? To account for situations where someone actually wants to perform an IS NOT NULL filter (which doesn’t apply in this case because the column is not nullable but I’ll still need to account for it), I might do something like: or_(expr, Model.id == None) where expr is the filter expression added by the user and the second one is added automatically. Make sense?
type: Comment
comment on: http://stackoverflow.com/a/47454496
type: AnswerComment

http://stackoverflow.com/a/47430297
has comment: http://stackoverflow.com/comment/81817083
type: AcceptedAnswer
score: 0
has body: If you already have latlng object, just use it in the second code line. If not, choose needed constructor from repository file (or documentation if exists).
has comment: http://stackoverflow.com/comment/81815400
type: Answer
has comment: http://stackoverflow.com/comment/81816858
answers question: http://stackoverflow.com/q/47430010
accepted answer of: http://stackoverflow.com/q/47430010
has comment: http://stackoverflow.com/comment/81815197

http://stackoverflow.com/q/47390407
has answer: http://stackoverflow.com/a/47390569
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/81733824
upvote count: 1
tagged with: python
has title: Python pandas count occurrences in each column
type: AnsweredQuestion
has body: I am new to pandas. Can someone help me in calculating frequencies of values for each columns. Dataframe: id|flag1|flag2|flag3| --------------------- 1 | 1 | 2 | 1 | 2 | 3 | 1 | 1 | 3 | 3 | 4 | 4 | 4 | 4 | 1 | 4 | 5 | 2 | 3 | 2 | I want something like id|flag1|flag2|flag3| --------------------- 1 | 1 | 2 | 2 | 2 | 1 | 1 | 1 | 3 | 2 | 1 | 0 | 4 | 1 | 1 | 2 | Explanation - id 1 has 1 value in flag1, 2 values in flag2 and 2 values in flag3.
tagged with: pandas
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/47390569
linked to: http://stackoverflow.com/q/46863602
has comment: http://stackoverflow.com/comment/81734239
favorite count: 0

http://stackoverflow.com/q/47445753
has comment: http://stackoverflow.com/comment/81876129
favorite count: 0
type: Question
has body: I have a chart that I'm rendering using Plot.ly from a Pandas DataFrame: import pandas as pd import numpy as np import string df1 = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10), 'd':list(range(10)), 'e':list(string.ascii_lowercase[:10])}) df2 = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10), 'd':list(range(10)), 'e':list(string.ascii_lowercase[:10])}) fig = { 'data': [ {'x': df1.x, 'y': df1.y, 'text': df1.d, 'mode': 'markers', 'name': 'Example 1', }, {'x': df2.x, 'y': df2.y, 'text': df2.d, 'mode': 'markers', 'name': 'Example 2', } ] } py.iplot(fig, filename='couldbeanything') And this draws a nice chart with the dataframe's column 'd' used for the data labels. But actually I want to use a composite of two columns for the data labels (let's say d and e). Is this possible? I've tried passing a list or a dict and neither appear to work.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81847157
tagged with: python
has comment: http://stackoverflow.com/comment/81847191
answer count: 0
tagged with: pandas
score: 1
tagged with: plotly
has title: Plot.ly Pandas scatter plot text from multiple columns
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49261803
score: 1
answers question: http://stackoverflow.com/q/47453611
type: Answer
downvote count: 0
upvote count: 1
has body: I had similar needs for my stuff, therefore I purposed CSV Schema recently, see https://github.com/csv-schema/csv-schema I am still working on the documents and more example to make it clear. But basically it allows you writing a JSON as schema to validate CSV files. It borrows lots of keywords from jsonschema, so it might be really easy for you if you have written jsonschema. I also made a validator in Python https://pypi.python.org/pypi/pycsvschema Like what's shown in introduction, you can specify your schema like: schema = { 'fields': [ { 'name': 'value', 'type': 'number', 'multipleOf': 5 } ] } Then the validator will go through the CSV file, verifying if all value under column "value" are numbers and multiple of 5.

http://stackoverflow.com/comment/81934707
comment on: http://stackoverflow.com/q/47489595
has text: Thanks for that, but my question was how to reproduce the output of df.aggregate given we don't know your custom function definitions?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47517447
answers question: http://stackoverflow.com/q/47443880
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: Issue fixed in 8514. Keras Issue
accepted answer of: http://stackoverflow.com/q/47443880

http://stackoverflow.com/comment/81954503
type: AnswerComment
has text: @Sebastian I totally understand.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47499539

http://stackoverflow.com/q/47513734
score: 0
has comment: http://stackoverflow.com/comment/81983718
answer count: 3
has body: I need to make a list of values passed to variables var1 and var2 from env.py and use them inside Generic Suite Setup keyword without altering the arguments given to Generic Suite Setup. Setup.robot *** Keywords *** Generic Suite Setup [Arguments] &amp;{options} ${keys}= Get Dictionary Keys ${options} ${new1}= Convert To List ${keys} Log ${new1} env.py var1='xyz' var2='pqr' test.robot *** Settings *** Suite Setup Generic Suite Setup var1=abc var2=abc
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81983164
has answer: http://stackoverflow.com/a/47515856
tagged with: robotframework
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47515375
upvote count: 1
has comment: http://stackoverflow.com/comment/81983754
has answer: http://stackoverflow.com/a/47517480
downvote count: 1
has title: make list of values by getting keys from dictionary and overriding with values from .py file
linked to: http://stackoverflow.com/q/47490802

http://stackoverflow.com/a/58550086
upvote count: 4
score: 4
has body: Assuming you need your root Main in the sys.path. Giving your current dir is Main/: $python -m pytest Tests/A_test This will append Main to the sys.path and run tests in the A_test subdirectory. More about pythonpath and pytest relationship here: http://doc.pytest.org/en/latest/pythonpath.html#pythonpath
downvote count: 0
answers question: http://stackoverflow.com/q/47498390
type: Answer

http://stackoverflow.com/a/47400918
upvote count: 1
has body: You were actually on the right track, you just needed fill_value=0: df1.t0.add(df2.t1, fill_value=0).to_frame('t2') t2 ACC 75.0 ACER 100.0 BBV 40.0 CEL 0.0 DECO 58.0 DIA 25.0 IRAL 25.0 Note here that you'd have to add the Series objects together to prevent misalignment issues.
score: 1
answers question: http://stackoverflow.com/q/47400460
downvote count: 0
type: Answer

http://stackoverflow.com/q/47491451
possible better answer: http://stackoverflow.com/a/47491520
tagged with: textbox
type: Question
has title: How to implement two input boxes in pygame, without having to repeat code
has answer: http://stackoverflow.com/a/47491808
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/47491520
has body: def InputBox(): font = pygame.font.Font(None, 32) inputBox = pygame.Rect(50, 50, 140, 32) colourInactive = pygame.Color('lightskyblue3') colourActive = pygame.Color('dodgerblue2') colour = colourInactive text = '' active = False isBlue = True while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if inputBox.collidepoint(event.pos): active = not active else: active = False colour = colourActive if active else colourInactive if event.type == pygame.KEYDOWN: if active: if event.key == pygame.K_RETURN: print(text) text = '' elif event.key == pygame.K_BACKSPACE: text = text[:-1] else: text += event.unicode screen.fill(screenGray) txtSurface = font.render(text, True, colour) width = max(200, txtSurface.get_width()+10) inputBox.w = width screen.blit(txtSurface, (inputBox.x+5, inputBox.y+5)) pygame.draw.rect(screen, colour, inputBox, 2) if isBlue: color = (0, 128, 255) else: color = (255, 100, 0) pg.display.flip() clock.tick(60) InputBox() Above is a working function to make a screen that has a text box on it. Now, how would you make two text boxes on the same screen, without just copying and pasting the same code twice? My idea is that the text box that is clicked on, or activated, will do the stuff in the event part, so you don't have to repeat it all twice. However, I have no idea how to implement that. Thanks in advance
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47491808
score: 0
answer count: 2

http://stackoverflow.com/comment/81815217
type: Comment
comment on: http://stackoverflow.com/q/47430027
score: 0
type: QuestionComment
has text: Also side note: There shouldn't be a `commit` parameter in your model's `save()` method. That's only for ModelForms.

http://stackoverflow.com/comment/81818380
type: QuestionComment
comment on: http://stackoverflow.com/q/47432043
has text: try printing: `inputdirectory+"*."+inputfileextensions`
type: Comment
score: 1

http://stackoverflow.com/comment/81923191
comment on: http://stackoverflow.com/q/47484166
has text: What is `df.columns.difference(['innings'])` doing here? From your previous question, there was no column called "innings"
score: 1
type: Comment
type: QuestionComment

date
tags question: http://stackoverflow.com/q/47441418
type: Tag
tag name: date
tags question: http://stackoverflow.com/q/47383540
tags question: http://stackoverflow.com/q/47496261
tags question: http://stackoverflow.com/q/47502584
tags question: http://stackoverflow.com/q/47435216
tags question: http://stackoverflow.com/q/47468039
tags question: http://stackoverflow.com/q/47476974
tags question: http://stackoverflow.com/q/47524363
tags question: http://stackoverflow.com/q/47508174

http://stackoverflow.com/q/47515561
has title: 'AttributeError: 'dataProcess' object has no attribute 'load_data'' What aspect of OOP am I doing wrong?
tagged with: python
has comment: http://stackoverflow.com/comment/81988420
tagged with: class
score: 0
has body: I am trying to execute a function that is a method of class I have imported and instantiated in another script - however, terminal returns the following error Here is the flow of my code (please ignore indentation errors)... I create the class DataProcess with a function to load data in the first file class dataProcess(object): def __init__(self, out_rows, out_cols, data_path = "./data/train/img", ... img_type = "png"): def load_data(self): mydata = dataProcess(self.img_rows, self.img_cols) imgs_train, imgs_mask_skulls = mydata.load_train_data() imgs_test = mydata.load_test_data() return imgs_train, imgs_mask_skulls, imgs_test And then in the other file I try to instantiate the class and call the load_data function. from dataProcess import * from dataPreperation import * from myUnet import * class runUnet(): def __init__(self, img_rows=img_rows, img_cols=img_cols): self.img_rows = img_rows # set values for these as default in definition arguments or as shape of input data self.img_cols = img_cols def train_and_predict(self): print("loading data") mydata = dataProcess(self.img_rows, self.img_cols) imgs_train, imgs_mask_skulls, imgs_test = mydata.load_data() print("loading data done") myUnet = myUnet(self.img_rows, self.img_cols) model = myUnet.get_unet() print("got unet") model_checkpoint = ModelCheckpoint('unet.hdf5', monitor='loss', verbose=1, save_best_only=True) print('Fitting model...') model.fit(imgs_train, imgs_mask_skulls, batch_size=4, nb_epoch=2, verbose=1, validation_split=0.2, # validation_split vs validation_data shuffle=True, callbacks=[model_checkpoint]) print('predict test data') imgs_mask_test = model.predict(imgs_test, batch_size=1, verbose=1) print(imgs_mask_test.shape()) print(imgs_mask_test) np.save("./results/imgs_mask_test.npy", imgs_mask_test)
answer count: 0
has comment: http://stackoverflow.com/comment/81987453
type: Question
tagged with: oop
type: UnansweredQuestion

http://stackoverflow.com/q/47520470
accepted answer: http://stackoverflow.com/a/47520536
has body: I have a list of some characters. When I print it I get the following output: ['a', 'b', 'c', 'd', 'e'] But what I want is this: ['a', 'b', 'c', 'd', 'e'] I have tried .join but that removes the [] and the '' and I dont want that. Any help appreciated. I have tried to search but I can only find .join solutions. Thanks Edit: is it possible to return the list this way also? or just print it like that?
tagged with: python
has answer: http://stackoverflow.com/a/47520536
has answer: http://stackoverflow.com/a/47520582
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/47520694
has title: how do i add a newline after each item in a list?
possible better answer: http://stackoverflow.com/a/47520535
answer count: 4
has comment: http://stackoverflow.com/comment/81997845
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47520535
score: 0

http://stackoverflow.com/a/47428278
has body: Your regex "\[(.*?)\s\w+\s\w+\]\[\w\]\[INFO\]\&gt;\s+\w+Amount" has one mistake in it, the \w+ before Amount, since you were trying to match ---- with \w+, but a dash (-) is not in the \w character set. You will need to change that part of the regex to include the dash, so making a set [\w-]+ should solve your problem. The final regex will be "\[(.*?)\s\w+\s\w+\]\[\w\]\[INFO\]\&gt;\s+[\w-]+Amount" When you use this regex, you will get your desired output: ['01012017']
answers question: http://stackoverflow.com/q/47428132
score: 0
type: Answer

http://stackoverflow.com/a/47440127
accepted answer of: http://stackoverflow.com/q/47440037
type: Answer
has comment: http://stackoverflow.com/comment/81835186
answers question: http://stackoverflow.com/q/47440037
score: 2
upvote count: 3
has body: The issue with your code is that numbers[pos] is an integer that you are trying to add to numbers[:pos] and numbers[pos:], which are lists. A simple solution is to replace return numbers[:pos] + numbers[pos] + numbers[pos:] with return numbers[:pos] + [numbers[pos]] + numbers[pos:] However, a shorter solution would be: vals = [([1, 2, 3], 0), ([1, 2, 3], 1), ([1, 2, 3], 2)] new_vals = [[*a[:b], a[b], *a[b:]] for a, b in vals] Output: [[1, 1, 2, 3], [1, 2, 2, 3], [1, 2, 3, 3]] In Python2: import itertools new_vals = [list(itertools.chain.from_iterable([[c, c] if c == a[b] else [c] for c in a])) for a, b in vals] Output: [[1, 1, 2, 3], [1, 2, 2, 3], [1, 2, 3, 3]]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81835726
downvote count: 1
has comment: http://stackoverflow.com/comment/81835814

http://stackoverflow.com/a/47457307
type: Answer
accepted answer of: http://stackoverflow.com/q/47433582
has comment: http://stackoverflow.com/comment/81871648
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47433582
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81871216
has body: This is the common problem while Saving data into Hive tables with TIMESTAMP Data type. When you save data into Hive table, TIMESTAMP values represent the local timezone of the host where the data was written. Here 2017-10-16 00:00:00 - UTC (By Default) got converted to 2017-10-16 21:00:00 - Local TimeZone of Hive host. To avoid undesired results from unexpected time zone issues, in Impala Timestamps are stored and interpreted relative to UTC, both when written to or read from data files. You can refer below documentation for necessary configuration settings. https://www.cloudera.com/documentation/enterprise/5-9-x/topics/impala_timestamp.html#timestamp

http://stackoverflow.com/comment/81958154
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47495538
has text: Voted up as I think this is the most *readable* and thus maintainable solution.
type: Comment

http://stackoverflow.com/comment/81827683
has text: pseudo element in not a part of the Dom, it's added with CSS
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47436655
score: 1

http://stackoverflow.com/comment/81994740
comment on: http://stackoverflow.com/a/47518754
type: Comment
score: 0
type: AnswerComment
has text: Great, you rock!

http://stackoverflow.com/comment/81834811
type: AnswerComment
comment on: http://stackoverflow.com/a/47423849
has text: Did notice that... Thanks
score: 0
type: Comment

http://stackoverflow.com/q/47456261
downvote count: 0
has comment: http://stackoverflow.com/comment/81867357
has answer: http://stackoverflow.com/a/47457023
favorite count: 0
has body: Im trying to get the timestamps of all of the files within a text file. Files listed in text file: folder/file1 folder/file2 System should output timestamp of: folder/file1 timestamp-of-file folder/file2 timestamp-of-file Here is my code: import os f = open('config.dat','r') list_contents = f.read().split('\n') timestamp=os.path.getmtime(list_contents) for a in timestamp: print(timestamp) f.close()
type: Question
has comment: http://stackoverflow.com/comment/81868898
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47457341
possible better answer: http://stackoverflow.com/a/47457341
tagged with: python
has title: get timestamp of all files listed within text file
accepted answer: http://stackoverflow.com/a/47457023
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/81867005

http://stackoverflow.com/q/47483184
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: javascript
has title: How to access SQLite from JavaScript in Django?
has comment: http://stackoverflow.com/comment/81921286
has body: I am trying to build a web-app using Django where I take in a stream of csv data, write a Python script to upload the data to the local SQLite database, then later connect to the database and use that data to build a JS-based graph. Currently, I am trying to do this: from .models import GraphData def getdata(request): return JsonResponse({'graphdata': GraphData}) And the JavaScript is: var dataxhttp = new XMLHttpRequest(); dataxhttp.open("GET", "/testGraph/getdata/", true); //this is where I try to connect to the URL that gets the data dataxhttp.send(); var j = 0; dataxhttp.onreadystatechange = function() { if (dataxhttp.readyState == 4 &amp;&amp; (dataxhttp.status == 200 || dataxhttp.status == 0)) { console.log("Ready state: " + dataxhttp.readyState); console.log("Status: " + dataxhttp.status); console.log(dataxhttp.response); // Not working, unless I change {'graphdata': GraphData} to {'graphdata': GraphData.objects.get(id=1).customerName} } } The way I want to use it is this way: data = dataxhttp.response; console.log(data.get(id=1).customerName); or: for (int i = 0; i &lt; 2; i++) { console.log(data.get(id=i).customerName; } Also, is it possible to access 'dataxhttp.response' or 'data' outside 'dataxhttp.onreadystatechange()'? This way, I can get the data inside 'readystatechange' then use it outside to build my graph.
has comment: http://stackoverflow.com/comment/82042505
tagged with: dygraphs
downvote count: 0
upvote count: 1
score: 1
tagged with: sqlite
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81922777

http://stackoverflow.com/q/47505666
has title: How to use youtube-dl from python & use postprocessor_args option
tagged with: youtube-dl
tagged with: youtube
favorite count: 0
has comment: http://stackoverflow.com/comment/81967526
duplicate of: http://stackoverflow.com/q/27473526
score: 1
has body: Im trying to figure out how to use youtube-dl using a python script, I want to download mp3 only &amp; can't figure out how to use "postprocessor_args" option. Does it take a string or a dict of options &amp; what options are available ? I tried reading the source code but could not find where or how the "postprocessor_args" is to be used import youtube_dl options = {'outtmpl': '%(id)s%(ext)s' 'postprocessor_args': "What to add here? dict or string?" } ydl = youtube_dl.YoutubeDL(options) with ydl: result = ydl.extract_info( 'http://www.youtube.com/watch?v=xxxxxx', download=False # We just want to extract the info )
has comment: http://stackoverflow.com/comment/81967571
has comment: http://stackoverflow.com/comment/81967336
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/27473526
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47517909
answer count: 1
accepted answer: http://stackoverflow.com/a/47518029
has answer: http://stackoverflow.com/a/47518029
type: AnsweredQuestion
tagged with: python
favorite count: 0
has body: I have been going through every question ever asked in regards to this issue but can't seem to find the solution. I am trying to allow a user to submit multiple objects and save to the data base using a formset with 2 foreignkeys. I can get the Forms to save that data into the database but cannot get the forms in the formset to save because of the ManagementForm error. The issue is not that I don't have it in the HTML. (check the HMTL code below.) I also have a prefix set for the formset. I don't know if i need to create a custom form and formset instead of using model's. Maybe I need to Validate the information in formsets better. The error I get is: /home/aking/signatureProject/signatureApp/views.py in signatures if formset.is_valid(): ... Variable Value DD <DDForm bound=True, valid=True, fields=(downdraft_id)> PR <PRForm bound=True, valid=True, fields=(report_id;report_desc)> SignatureFormSet <class 'django.forms.formsets.SigFormFormSet'> formset <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> request <WSGIRequest: POST '/signatureApp/signatures/'> views.py /usr/lib64/python2.7/site-packages/django/forms/formsets.py in is_valid forms_valid True self <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> /usr/lib64/python2.7/site-packages/django/forms/formsets.py in errors self.full_clean() self <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> /usr/lib64/python2.7/site-packages/django/forms/formsets.py in full_clean for i in range(0, self.total_form_count()): empty_forms_count 0 self <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> /usr/lib64/python2.7/site-packages/django/forms/formsets.py in total_form_count return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max) self <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> /usr/lib64/python2.7/site-packages/django/utils/functional.py in __get__ res = instance.__dict__[self.name] = self.func(instance) cls <class 'django.form…
type: Question
has title: Django issues : Django ManagementForm data is missing or has been tampered with
upvote count: 5
score: 5
downvote count: 0
tagged with: django

http://stackoverflow.com/q/47527060
has answer: http://stackoverflow.com/a/47527374
has comment: http://stackoverflow.com/comment/82225391
has title: undefined value in a fits header
has body: Thanks for taking time to help me! Below is the issue that I am facing. Let's say I am reading the header of a fits image. One of the header cards is undefined object and I don't know how to handle this. from astropy.io import fits as pf hdu = pf.open('myfitsfile') hdu.info() img_hd= hdu[0].header print(img_hd['IMAGEZPT']) &lt;astropy.io.fits.card.Undefined object at 0x109b35a20&gt; I am running my code iteratively over thousands of images and almost all of them have some values for it. e.g. hdu_base = pf.open(a_lof[38]) img_hd= hdu_base[0].header print(img_hd['IMAGEZPT']) 23.61687 I just want to assign some other values to this and continue. So, I tried if img_hd['IMAGEZPT'] == None: img_hd['IMAGEZPT'] = base_ZPT #some value I know print(img_hd['IMAGEZPT']) But as expected this didn't work since the keyword is not defined. So '== None' cannot work. The keyword exists, it is undefined though. Any help will be appreciated! Best, Abhi
has comment: http://stackoverflow.com/comment/82216725
type: AnsweredQuestion
tagged with: header-files
downvote count: 0
has comment: http://stackoverflow.com/comment/82123831
score: 1
tagged with: undefined
has comment: http://stackoverflow.com/comment/82073877
favorite count: 0
has comment: http://stackoverflow.com/comment/82123880
type: Question
has comment: http://stackoverflow.com/comment/82125090
accepted answer: http://stackoverflow.com/a/47527374
upvote count: 1
tagged with: python
tagged with: astropy
answer count: 1

http://stackoverflow.com/q/47502898
has title: Giving Syntax error in Scrapy (Python) - XPath
has answer: http://stackoverflow.com/a/47502937
has body: I'm using Scrapy Crawler to extract some details like username, upvotes, join date etc. I'm using XPath for extracting the contents from each user's webpage. Code: import scrapy from scrapy.selector import HtmlXPathSelector from scrapy.http import Request from scrapy.spiders import BaseSpider from scrapy.http import FormRequest from loginform import fill_login_form from scrapy.selector import Selector from scrapy.http import HtmlResponse class UserSpider(scrapy.Spider): name = 'userspider' start_urls = ['<website-to-scrape>'] #Getting the list of usernames user_names = ['Bob', 'Tom'] #List of Usernames def __init__(self, *args, **kwargs): super(UserSpider, self).__init__(*args, **kwargs) def parse(self, response): return [FormRequest.from_response(response, formdata={'registerUserName': 'user', 'registerPass': 'password'}, callback=self.after_main_login)] def after_main_login(self, response): for user in self.user_names: user_url = 'profile/' + user yield response.follow(user_url, callback=self.parse_user_pages) def parse_user_pages(self, response): yield{ "USERNAME": response.xpath('//div[contains(@class, "main") and contains(@class, "no-sky-main")]/h1[contains(@class, "thread-title")]/text()').extract_first() "UPVOTES": response.xpath('//div[contains(@class, "proUserInfoLabelLeft") and @id="proVotesCap"]/text()').extract()[0] } if __name__ == "__main__": spider = UserSpider() Error looks like this P.S. I have manually checked the syntax of my XPath on the Scrapy Shell and it was working fine Is there anything that I'm not noticing in the code?
answer count: 1
tagged with: scrapy
type: Question
tagged with: python
tagged with: xpath
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47502937

http://stackoverflow.com/q/47398665
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47861093
has body: My system has these packages (reported with pip list): C:\WINDOWS\system32&gt;pip list numpy (1.13.1+mkl) opencv-python (3.3.0) pip (9.0.1) setuptools (28.8.0)* Then, when I try to install Pyinstaller, I get this error: C:\WINDOWS\system32&gt;pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org pyinstaller Collecting pyinstaller Could not find a version that satisfies the requirement pyinstaller (from versions: ) No matching distribution found for pyinstaller* Is there not a Pyinstaller version compatible with my installations of Opencv-python (i.e. 3.3.0)?
has title: opencv-python compatibility with pyinstaller
score: 0
answer count: 1
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47518128
has answer: http://stackoverflow.com/a/47522315
has title: How to skip method call in the DRF unit-test?
tagged with: python
has body: I am not clear on how to properly use unittest.mock. I need to test APIView using rest_framework.test.APITestCase.client. But I don't need to call one of methods. class MyClass(MyMixin): def do_some_stuff(self, request): self.should_be_called_in_the_test() self.should_not_be_called_in_the_test() class MyView(views.APIView): def post(self, request): my_object = MyClass() my_object.do_some_stuff(request) return Response(status=status.HTTP_200_OK) #test.py: class MyViewTest(APITestCase): def test_post_request(self): url = reverse('my-view-url') # How properly skip call of "should_not_be_called_in_the_test()" ? response = self.client.post(url, data) # some asserts...
favorite count: 0
type: Question
tagged with: mocking
downvote count: 0
accepted answer: http://stackoverflow.com/a/47522315
answer count: 1
tagged with: django-rest-framework
tagged with: unit-testing
type: AnsweredQuestion
upvote count: 3
score: 3

http://stackoverflow.com/q/47502946
has title: freeradius dynamic client by python or rest
has comment: http://stackoverflow.com/comment/81967323
tagged with: freeradius
has comment: http://stackoverflow.com/comment/81972940
has comment: http://stackoverflow.com/comment/81961838
has comment: http://stackoverflow.com/comment/82129502
type: Question
has comment: http://stackoverflow.com/comment/81961778
answer count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81961816
type: UnansweredQuestion
has body: I have some implementation of freeradius that use rlm_python and some implementation using rlm_rest for Authorization. I cannot figureout how to implementing dynamic client using rlm_python or rlm_rest. Could you please give me some configuration sample on it, since all docs I read is about mysql, file, and ldap. Sincerely -bino-
score: 0

http://stackoverflow.com/q/47387283
has comment: http://stackoverflow.com/comment/81727638
has comment: http://stackoverflow.com/comment/81727557
upvote count: 1
answer count: 1
has title: why does this elif statement return a syntax error?
favorite count: 0
type: Question
has body: the error says File "Scantron.py", line 28 elif len(test_answers) != len(test_key): ^ SyntaxError: invalid syntax Command exited with non-zero status 1 def grade_scantron(test_answers, test_key): right = 0 for i in test_answers: if test_answers[i] == test_key[i]: right += 1 return right elif len(test_answers) != len(test_key): return -1
has answer: http://stackoverflow.com/a/47387375
downvote count: 5
type: UnansweredQuestion
score: -4
tagged with: python

http://stackoverflow.com/comment/81915416
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47480221
has text: Can't you just use a reverse sequence - probably reshape back to 4 and swapaxes?
type: Comment

http://stackoverflow.com/q/47528694
tagged with: python
has answer: http://stackoverflow.com/a/47543321
type: Question
score: 0
answer count: 1
has title: Arpabet phonetics to substrings of a word, with Python
type: AnsweredQuestion
tagged with: nltk
has body: The goal of this is that I would like to be able to turn a word into not just its phonemes but also the substrings that correspond to them. For instance, something like: from nltk.corpus import cmudict d = cmudict.dict() ... print foo('perfect', d['perfect']) &gt;&gt;&gt; (['p','er','f','e','c','t'], [u'P', u'ER0', u'F', u'EH1', u'K', u'T']) I'm hoping for something part of NLTK or a widely available resource that I can look into, but anything that would solve this would be welcome. Also, I'd rather whatever solution not have to lookup substrings of 'perfect' in cmudict. Sometimes the substrings will have different pronunciations than the full word. Bonus: I realize this may be difficult when multiple phonemes should correspond to a substring (correct me if I'm wrong, not a linguistics person) for instance: foo('ignoble', d['ignoble']) &gt;&gt;&gt; (['i','g','n','o','b', ['l', 'e'] ], [u'IH0', u'G', u'N', u'OW1', u'B', [u'AH0', u'L']] For the above, should both L and E correspond to both AH0 and L?
accepted answer: http://stackoverflow.com/a/47543321

http://stackoverflow.com/comment/81999391
type: Comment
type: QuestionComment
has text: Those are shell commands, and you are trying to type them into a Python repl, presumably.
comment on: http://stackoverflow.com/q/47521214
score: 0

django-1.11
tags question: http://stackoverflow.com/q/47447624
tags question: http://stackoverflow.com/q/47442937
tags question: http://stackoverflow.com/q/47409228
tags question: http://stackoverflow.com/q/47484336
tags question: http://stackoverflow.com/q/47509857
tags question: http://stackoverflow.com/q/47385727
type: Tag
tag name: django-1.11

http://stackoverflow.com/a/52386058
upvote count: 2
downvote count: 0
has body: In Anaconda, steps to install the package. Navigate to ‘Environments” and Search for your package. That package will be displayed and click on Apply. Now the package is installed and it can be used right away. Please share your feedback.
type: Answer
answers question: http://stackoverflow.com/q/47529792
score: 2

http://stackoverflow.com/q/47405898
tagged with: cython
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/81765503
has comment: http://stackoverflow.com/comment/81767280
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81768785
answer count: 1
has comment: http://stackoverflow.com/comment/81767682
upvote count: 1
tagged with: python
has body: I am running a simulation in Python 3.4 - that involves a lot of dot products between a sparse array (in csr format) and a dense vector. I am using Scipy for the sparse matrix, numpy for everything else. Using Cython gave me a massive boost (~x6 speed increase), after making sure that I cdef everything properly and after minimizing Python interaction (bt going through the html file that Cython gives me and modifying my code). Now, I profile the code and 50% of the simulation time is spent on the line with the dot product. I am wondering if it is possible to somehow accelerate this line, say by complining this one dot function in Cython? I know I could write my own implementation for (csr sprase 2d matrix) dot (dense vector), but I am trying to avoid that. Edit: I have included a minimal example of the code. I am sorry, I can't see how to make it smaller. It is a textbook exercise in statistical mechanics. Place marbles in pots until one of the pots exceeds capacity. Then, start a cascade which propagates according to a (here sparse) matrix. I am using batch sampling. Please focus on the line towards the end. from __future__ import division import numpy as np import cython cimport numpy as np cimport cpython.array import scipy.sparse as sps @cython.cdivision(True) @cython.nonecheck(False) @cython.boundscheck(False) @cython.wraparound(False) def simulate(long[:] capacity_vec, int random_array_size, long n, int seed, int[:] A_col, int[:] A_row, long[:] A_data): #### Initialise #################################################################################################### # Initialise states cdef int[:] damage = np.random.randint(0, int(np.min(capacity_vec)/2), n).astype(np.int32) cdef int[:] dr_list = np.random.choice(n, 1000).astype(np.int32) cdef int[:] states = np.zeros(n).astype(np.int32) cdef int[:] states_ = np.zeros(n).astype(np.int32) cdef int[:] change = np.zeros(n).astype(np.int32) # Initialise counters cdef int k, violations, violations_, counter= 0, dr…
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81765547
has answer: http://stackoverflow.com/a/47407644
has title: Compile Scipy function with Cython
accepted answer: http://stackoverflow.com/a/47407644

http://stackoverflow.com/q/47519104
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47519277
has title: TensorFlow Dataset API from_generator End of Sequence Error
has answer: http://stackoverflow.com/a/47519277
has body: Here is toy code that duplicates a problem I am encountering when trying to generate/feed training data on the fly using a generator. def makeRand(): yield np.random.rand(1) dataset = tf.data.Dataset.from_generator(makeRand, (tf.float32)) iterator = tf.contrib.data.Iterator.from_structure(tf.float32, tf.TensorShape([])) next_x = iterator.get_next() init_op = iterator.make_initializer(dataset) with tf.Session() as sess: sess.run(init_op) a = sess.run(next_x) print(a) a = sess.run(next_x) print(a) The trace looks like: Traceback (most recent call last): File “test_iterator_gen.py", line 31, in &lt;module&gt; a = sess.run(next_x) tensorflow.python.framework.errors_impl.OutOfRangeError: End of sequence [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[]], output_types=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](Iterator)]] Caused by op 'IteratorGetNext', defined at: File "test_iterator_gen.py", line 23, in &lt;module&gt; next_x = iterator.get_next() OutOfRangeError (see above for traceback): End of sequence [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[]], output_types=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](Iterator)]]
type: AnsweredQuestion
score: 1
answer count: 1

http://stackoverflow.com/q/47444695
has answer: http://stackoverflow.com/a/47444990
tagged with: multiprocessing
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: python
has title: Pathos multiprocessing in class produces garbled standard output
has body: I'm trying to use multiprocessing in a class I have written to speed up calculations. I'm using pathos.multiprocessing and dill, and using map on a ProcessingPool. I've tested the functionality of multiprocessing in a console and it performed as expected. The issue I'm having is that when I try to implement it in my code, as soon as it calls pool.map the terminal I'm using starts spitting out ridiculous nonsense. The output is recognizable as being from the code, but I have no idea how it's making it print. Some of it comes from a method like I defined below, where it includes the current datetime. In the nonsense I see that it's printing the current time, after pool.map was called, so this isn't just something that's just being repeatedly printed out, it's new output. Here is a little code illustrating how I'm using multiprocessing. My_func is a little more complicated than I have below, but as a first step I changed it to literally what is written below, and the problem still persists. Additionally, Ctr-C does trigger a KeyboardInterrupt, but does not completely stop the program. I'm using Visual Studio and python 2.7.13 on Windows 10. from pathos.multiprocessing import ProcessingPool import dill import datetime class my_class(Object): def __init__(self): pool = ProcessingPool(nodes=4) p1 = [1,2,3] p2 = [4,5,6] p3 = [7,8,9] results = pool.map(self.my_func, p1, p2, p3) def my_func(self,x,y,z): print(x,y,z) def status_printout(self,message): header = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') print(header+' -- '+message)
has answer: http://stackoverflow.com/a/47519495
tagged with: python-2.7
score: 0
tagged with: pathos

http://stackoverflow.com/comment/81898037
comment on: http://stackoverflow.com/q/47470772
type: QuestionComment
has text: You need to review your partition size when writing in parquet ! This is quite broad to answer
type: Comment
score: 0

http://stackoverflow.com/comment/81961124
has text: What line and where are you deleting? How are you printing given that there is not print statement in this function?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47502650

http://stackoverflow.com/comment/82151573
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47527454
type: Comment
has text: There's few instances I'd use splash just because it works so well with scrapy, but if you need proxies for it you must write a LUA script. Also, many sites must have their interfaces automated and the only way to do that again is with a LUA script. So for the sake of simplicity I always try to do with scrapy first. Always look for end points like furas said and if u need more than what scrapy can do consider Selenium.

http://stackoverflow.com/comment/82575274
has text: I haven't tested it on windows. If not conemu, there are other packages
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47806854
type: Comment

pip
tags question: http://stackoverflow.com/q/47417346
tags question: http://stackoverflow.com/q/47412518
tags question: http://stackoverflow.com/q/47467914
tags question: http://stackoverflow.com/q/47460382
tags question: http://stackoverflow.com/q/47536463
tags question: http://stackoverflow.com/q/47458172
tags question: http://stackoverflow.com/q/47394602
tags question: http://stackoverflow.com/q/47460435
tags question: http://stackoverflow.com/q/47484540
tags question: http://stackoverflow.com/q/47498061
tags question: http://stackoverflow.com/q/47483895
tags question: http://stackoverflow.com/q/47492494
tags question: http://stackoverflow.com/q/47503705
tags question: http://stackoverflow.com/q/47540445
tags question: http://stackoverflow.com/q/47403874
tags question: http://stackoverflow.com/q/47539693
tags question: http://stackoverflow.com/q/47411740
tags question: http://stackoverflow.com/q/47413574
tags question: http://stackoverflow.com/q/47405813
tags question: http://stackoverflow.com/q/47444636
tags question: http://stackoverflow.com/q/47482708
tags question: http://stackoverflow.com/q/47484251
type: Tag
tags question: http://stackoverflow.com/q/47531024
tags question: http://stackoverflow.com/q/47473458
tags question: http://stackoverflow.com/q/47497652
tags question: http://stackoverflow.com/q/47385446
tags question: http://stackoverflow.com/q/47425762
tags question: http://stackoverflow.com/q/47493017
tags question: http://stackoverflow.com/q/47460804
tags question: http://stackoverflow.com/q/47450508
tags question: http://stackoverflow.com/q/47539846
tags question: http://stackoverflow.com/q/47445519
tags question: http://stackoverflow.com/q/47423359
tags question: http://stackoverflow.com/q/47400675
tags question: http://stackoverflow.com/q/47504036
tags question: http://stackoverflow.com/q/47532858
tag name: pip
tags question: http://stackoverflow.com/q/47479613
tags question: http://stackoverflow.com/q/47481294
tags question: http://stackoverflow.com/q/47477396
tags question: http://stackoverflow.com/q/47443660
tags question: http://stackoverflow.com/q/47532009
tags question: http://stackoverflow.com/q/47449208

http://stackoverflow.com/a/47441442
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/94025448
answers question: http://stackoverflow.com/q/47421443
type: Answer
accepted answer of: http://stackoverflow.com/q/47421443
has body: I think the answer is "sort of, but it's a reasonable amount of work if you want to do any real calculations". The basic problem is that C doesn't support a 16-bit float type on most PCs (because the processor instructions don't exist). Therefore, what numpy has done is typedefed a 16-bit unsigned int to store the 16-bit float, and then written a set of functions to convert that to/from the supported float types. Any calculations using np.float16 are actually done on 32-bit or 64-bit floats but the data is stored in the 16-bit format between calculations. The consequence of this is that Cython doesn't have an easy way of generating valid C code for any calculations it needs to do. The consequence is that you may need to write out this C code yourself. There are a number of levels of complexity, depending on what you actually want to do: 1) Don't type anything Cython doesn't actually need you to specify any types - it compiles Python code happy. Therefore, don't assign types to the half-float arrays and just let them by Python objects. This may not be terribly fast but it's worth remembering that it will work. 2) To move data you can view it as uint16 If you're just shuffling data around then can define uint16 arrays and use those to copy it from one place to another. Use the numpy view function to get the data in a format that Cython recognises and to get it back. However, you can't do maths in this mode (the answers will be meaningless). from libc.stdint cimport uint16_t import numpy as np def just_move_stuff(x): assert x.dtype == np.float16 # I've used memoryviews by cdef np.ndarray should be fine too cdef uint16_t[:] x_as_uint = x.view(np.uint16) cdef uint16_t[:] y_as_uint = np.empty(x.shape,dtype=np.uint16) for n in range(x_as_uint.shape[0]): y_as_uint[n] = x_as_uint[n] return np.asarray(y_as_uint).view(dtype=np.float16) The view function doesn't make a copy so is pretty cheap to use. 3) Do maths with manual conversions If you want to do any calculations you'll …
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94023012
downvote count: 0

http://stackoverflow.com/a/47404263
accepted answer of: http://stackoverflow.com/q/47404084
has body: You shouldn't do any scraping in views. It might confuse the user because the page won't load while the scraping is happening. The user may also refresh the page and cause your code to run twice. Additionally a lot of proxies that you may install for your project may have timeouts. This is more of a background process type of work. The easiest way to do that is with a custom admin command. Create a file called scrape.py under management/commands. Don't forget __init__.py. For example: polls/ __init__.py models.py management/ __init__.py commands/ __init__.py scrape.py tests.py views.py In that file use: from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write(self.style.SUCCESS('I am a scraper!')) Finally don't forget to run your new command with: python manage.py scrape You probably want to set it up with a cron job. For more complex use cases, see Celery.
has comment: http://stackoverflow.com/comment/81771894
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47404084
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81781107
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47413844
has text: What kind of dataset are you working on?
type: Comment

http://stackoverflow.com/comment/81960645
has text: how to overcome its loop? RBM from the another file, rbm.py, maybe I'll add it in this post
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47502182
score: 0

http://stackoverflow.com/a/54913694
type: Answer
answers question: http://stackoverflow.com/q/47459747
has body: I had same error message when I tried to install Python packages on my laptop with Windows 10 OS. I tried all methods recommended online and it still didn't work. I have been noticing for a while that Windows 10 automatically set proxy off causing Internet access problem sometime. Then I googled with keywords: 'windows 10 automatic proxy setting off'. Someone mentioned to modify regedit key value of [ProxyEnabled=1] under Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings I opened the regedit and found it's [ProxyEnabled=1]. I compared HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings with another workstation with relatively clean image. It's [ProxyEnabled=0] and no other extra entry for Proxy. Solution: set ProxyEnabled=0 and delete any other Proxy entries. It worked successfully! pip install package_name
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/97181254
type: QuestionComment
score: 1
has text: [The Pandas user guide on reshaping](https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html#reshaping-by-melt) gives several example using `melt` (easier to rename the “variable” and “value” columns) or `stack` (designed to work together with MultiIndex objects).
type: Comment
comment on: http://stackoverflow.com/q/47462417

http://stackoverflow.com/comment/81978259
type: Comment
has text: how to check my pandas version
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47511103

http://stackoverflow.com/q/47499730
upvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47500670
accepted answer: http://stackoverflow.com/a/47501913
has answer: http://stackoverflow.com/a/47501913
tagged with: python
type: AnsweredQuestion
has body: I have a parent class that provides abstract functions for manipulating hardware, and a directory full of classes that subclass this parent class, and provide hardware-specific implementation (e.g. x86 functions, ARM functions...). I am looking for a Pythonic way to import the files in the directory, and instantiate them. At the moment the parent class is in the top level directory, and the files with the child classes in a subdirectory. This can be changed, for style or ease of implementation. Is it preferable to load all the hardware-specific classes in the subdirectory by defining a list of them in a configuration file, and iterating over that to import them? Or would it be better (more Pythonic) to do it automatically with importlib? Or does it not matter?
answer count: 2
has answer: http://stackoverflow.com/a/47500670
score: 1
has title: A clean way to organize and load files with subclasses
downvote count: 0

http://stackoverflow.com/q/47441374
tagged with: global
linked to: http://stackoverflow.com/q/47381962
tagged with: local
score: 2
upvote count: 2
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47442225
tagged with: web-scraping
answer count: 1
favorite count: 0
has body: I'm trying to get some datas from a javascript webpage. My code is generating multiple links and parsing them one by one. Parsing outputs are lists. I have written this code with help from here. But it produces the lists inside a class. I want to insert list items into an sqlite table, and because of this I want to make the local list items global. I've tried to create a global list, put it into the class, and then append to it and return it. I've tried to directly insert them into the database from the processCurrentPage method and tried to create a list under the class and reach it by Webpage.list. But none of these methods worked. One of my attempts is here, but not the best one - it's only an example. I've tried many alternatives like this. Can you suggest a good way to handle it please? P.S: I am new at Python, but researching it for whole two days, and read all class documentation, but couldn't find a way. import sys from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets import requests from bs4 import BeautifulSoup import bs4 as bs class WebPage(QtWebEngineWidgets.QWebEnginePage): alldatas=[] def __init__(self): super(WebPage, self).__init__() self.loadFinished.connect(self.handleLoadFinished) def start(self, urls): self._urls = iter(urls) self.fetchNext @property def fetchNext(self): try: url = next(self._urls) except StopIteration: return False else: self.load(QtCore.QUrl(url)) return True def processCurrentPage(self, html): url = self.url().toString() # do stuff with html... soup = bs.BeautifulSoup(html, 'html.parser') data = soup.find('div', class_='tablo_dual_board') data1 = data.text data2 = data1.splitlines() self.alldatas+=data2 if not self.fetchNext: QtWidgets.qApp.quit() def handleLoadFinished(self): self.toHtml(self.processCurrentPage) def javaScriptConsoleMessage(self, QWebEnginePage_JavaScriptConsoleMessageLevel, p_str, p_int, p_str_1): # disable javascript error output pass if __name__ == '__main__': # generate some test urls onexurl = "https:/…
type: Question
accepted answer: http://stackoverflow.com/a/47442225
has title: How can I get output from method of class into global variable
tagged with: python

http://stackoverflow.com/q/47479446
answer count: 0
has comment: http://stackoverflow.com/comment/81917190
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81913709
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81914369
has comment: http://stackoverflow.com/comment/81917080
has comment: http://stackoverflow.com/comment/81914026
has title: code skips counting the length when another list appears
tagged with: python
has comment: http://stackoverflow.com/comment/81913732
has body: I have a text file which is a tuple with labels ('neg', 'statements......') as shown below: ('neg', u'Without objection , approved .') ('posi', u'In intermeeting period , markets generally calm , investors perceived events generally positive outlook .') ('neg', u'Despite Committee \u2019 tightening policy August , yields fell across coupon curve , spreads narrowed , equities rose , asset markets continued exhibit unusually low volatility .') ('uncer', u'Despite Committee \u2019 tightening policy August , yields fell across coupon curve , spreads narrowed , equities rose , asset markets continued exhibit unusually low volatility .') ('neg', u'Despite Committee \u2019 tightening policy August , yields fell across coupon curve , spreads narrowed , equities rose , asset markets continued exhibit unusually low volatility .') ('uncer', u'Despite Committee \u2019 tightening policy August , yields fell across coupon curve , spreads narrowed , equities rose , asset markets continued exhibit unusually low volatility .') ('uncer', u'But forward rates falling gently time , apparently softer data more-tepid corporate outlooks caused market participants revise expected path monetary tightening .') ('uncer', u'But forward rates falling gently time , apparently softer data more-tepid corporate outlooks caused market participants revise expected path monetary tightening .') ('neg', u'But forward rates falling gently time , apparently softer data more-tepid corporate outlooks caused market participants revise expected path monetary tightening .') ('neg', u'The coupon curve also declined .') I am trying to get the length of labels, that is 'posi', 'neg', or 'uncer' occurrences in the list of tuples. when I run following code, I get negative= [(i, 'neg')for i in file_path if i not in i.split('neg')[:n_instances]] print (len(negative)) positive=[(i, 'posi') for i in file_path if i not in i.split('posi')[:n_instances]] print (len(positive)) uncertain=[(i, 'uncer') for i in file_path if i…

http://stackoverflow.com/comment/81734192
has text: @sascha- Above is what i have wrote till now, if you have any sample-reference for "also check your classifier/regressor if it's not already parallelized for this", plz post the link. Thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47390514
score: 0

http://stackoverflow.com/comment/81855478
has text: That somewhat helped. The counter is running in the background, but the GUI doesn't start/update until I click that window. Very odd.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47446217

http://stackoverflow.com/comment/86539653
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47490444
score: 0
has text: not from the top of my head, sorry. I use simple CSV files as the data storage backend for my python-telegram-bots. for simple use cases this is as workable as `sqlite` for me.

http://stackoverflow.com/comment/81983591
type: QuestionComment
comment on: http://stackoverflow.com/q/47513916
score: 1
has text: You are missing (at least) some colons...
type: Comment

http://stackoverflow.com/comment/81770828
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47407517
type: Comment
has text: Can you explain more? I actually don't have administrative access to the database.

http://stackoverflow.com/comment/81796999
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47401988
type: Comment
has text: Thank you for your comprehensive answer. Updated my code in the question to use the ignore parameter.

http://stackoverflow.com/comment/81760788
score: 0
comment on: http://stackoverflow.com/q/47403413
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82037932
comment on: http://stackoverflow.com/q/47540270
has text: Yes because 10, 15 and 12 are the sum of the x1 and x2 where t1 and t2 intersect
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47450508
has title: Rekall Forensic framwork: Failed building wheel for readline
answer count: 1
has answer: http://stackoverflow.com/a/47456793
has body: During installing latest version of google Rekall Forensic framwork, at the step of installing "rekall-agent" it says: "Failed building wheel for readline" I am installing it on Kali Linux(2016-02) default python version is 2.7.12 at the step of installing rekall-agent I face exception and error.here is the error part with verbose switch: ============ Building the readline extension module ============ running bdist_wheel running build running build_ext building 'readline' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/Modules creating build/temp.linux-x86_64-2.7/Modules/2.x x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-oH9M6v/python2.7-2.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DHAVE_RL_CALLBACK -DHAVE_RL_CATCH_SIGNAL -DHAVE_RL_COMPLETION_APPEND_CHARACTER -DHAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK -DHAVE_RL_COMPLETION_MATCHES -DHAVE_RL_COMPLETION_SUPPRESS_APPEND -DHAVE_RL_PRE_INPUT_HOOK -I. -I/usr/include/python2.7 -c Modules/2.x/readline.c -o build/temp.linux-x86_64-2.7/Modules/2.x/readline.o -Wno-strict-prototypes creating build/lib.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-oH9M6v/python2.7-2.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-oH9M6v/python2.7-2.7.12=. -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/Modules/2.x/readline.o readline/libreadline.a readline/libhistory.a -lncurses -o build/lib.linux-x86_64-2.7/readline.so /usr/bin/ld: cannot find -lncurses collect2: error: ld returned 1 exit status error: command 'x86…
tagged with: computer-forensics
type: Question
accepted answer: http://stackoverflow.com/a/47456793
tagged with: pip
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47488514
tagged with: python-2.7
score: 0
answer count: 1
tagged with: python
type: Question
has title: Import error with python gmond_python_modules in Ganglia
has body: I used gmond_python_modules, trying to monitor one cluster having several hosts with each has 8 GPUs. And after the last steps, I tried to restart gmond service on my web node, only to get: Starting GANGLIA gmond: Could not find platform independent libraries &lt;prefix&gt; Could not find platform dependent libraries &lt;exec_prefix&gt; Consider setting $PYTHONHOME to &lt;prefix&gt;[:&lt;exec_prefix&gt;] ImportError: No module named site [FAILED] I searched and thought initially it was because I compiled ganglia without --with-python option. But it wasn't. I recompiled with that option(checked configure output and it saied it found python) and everything works fine until I added GPU monitoring python module. Same error again. And I also tried to manually assign PYTHONHOME and PYTHONPATH, which makes no difference. I installed anaconda. Is it a possible reason that causes Ganglia not finding correct load path? Any thoughts are welcome. And will offer more details if needed. Distribution and version details: System: centos 6.8 Python: 2.7 on web node, 2.6 on computing node Ganglia: 3.7.2 gmond_python_modules: clone form Github today
tagged with: ganglia
has answer: http://stackoverflow.com/a/47710863
accepted answer: http://stackoverflow.com/a/47710863
tagged with: centos
type: AnsweredQuestion

http://stackoverflow.com/q/47463612
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/81882218
favorite count: 0
has comment: http://stackoverflow.com/comment/81882134
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81882088
has body: I have recently taken a online tutorial for python and I was given these lines of code: n = int(input()) a = [[abs(i - j) for j in range(n)] for i in range(n)] Please can someone explain what they mean. Thanks Adam!!
possible better answer: http://stackoverflow.com/a/47463690
score: -4
has comment: http://stackoverflow.com/comment/81882065
has title: Python line needs explaining please
upvote count: 1
has answer: http://stackoverflow.com/a/47463690
has answer: http://stackoverflow.com/a/47463740
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81882188
accepted answer: http://stackoverflow.com/a/47463714
answer count: 3
has comment: http://stackoverflow.com/comment/81882040
has answer: http://stackoverflow.com/a/47463714

http://stackoverflow.com/comment/83753454
type: QuestionComment
has text: No Yet, But I have contacted AWS Lambda customer support, they were calming that it is possible.
comment on: http://stackoverflow.com/q/47440757
score: 1
type: Comment

http://stackoverflow.com/q/47522072
answer count: 2
has comment: http://stackoverflow.com/comment/82000706
tagged with: python
has answer: http://stackoverflow.com/a/47522322
possible better answer: http://stackoverflow.com/a/47522322
has body: I am stuck on a seemingly trivial problem for a while now. I have a conditional loop where I get the user to enter a raw_input and assign variables based on the input entered. Here is the code to make my explanation clear: location = raw_input("Where are you located? : ") #print (location) if location == "London": recreationList = londonRec businessList = londonBus elif location == "California": recreationList = caliRec businessList = caliBus elif location == "Mumbai": recreationList = mumbaiRec businessList = mumbaiBus ....code to be executed based on location The issue I face is that the code below only gets executed when I input mumbai as the raw_input(), every other time it loops back up to "Where are you located?". I feel that this is a really simple thing, that I am completely overlooking, any guidance is appreciated! Thanks
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47522407
accepted answer: http://stackoverflow.com/a/47522407
has comment: http://stackoverflow.com/comment/82000725
has title: only the last elif chunk gets executed
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82000611
type: Question
has comment: http://stackoverflow.com/comment/82000638

http://stackoverflow.com/a/47446312
has body: Let us using reindex df1.set_index('PAUCode').reindex(df2.PAUCode).reset_index() Out[9]: PAUCode SubClass 0 2 RB 1 2 RB 2 2 RB 3 3 CZ 4 1 RA 5 2 RB 6 3 CZ
answers question: http://stackoverflow.com/q/47445936
upvote count: 2
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81750971
score: 0
type: Comment
type: QuestionComment
has text: Your data is going to be just one character? Then you could use `isdigit` and so https://docs.python.org/3/library/stdtypes.html
comment on: http://stackoverflow.com/q/47398885

http://stackoverflow.com/a/47462939
answers question: http://stackoverflow.com/q/47462735
type: Answer
score: 0
has body: Logic... if True then break, False then print error message... Two things... you want logical exclusive or so that True ^ True = False You aren't storing b. The text you're printing doesn't explain what's happening. while True: a = input("Enter first input: ") b = input("Enter second input: ") try: a = int(a) # like the readable code using a not val1... b = int(b) if (a != 5) ^ (b != 5): # added parens as suggested break else: print("I'm sorry but it must be a pos int and equal 5") continue except ValueError: print("That's not an int") Output Enter first input: 5 Enter second input: 5 I'm sorry but it must be a pos int and equal 5 Enter first input: 1 Enter second input: 5 runfile('...') Enter first input: 5 Enter second input: 5 I'm sorry but it must be a pos int and equal 5

http://stackoverflow.com/comment/82027826
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47535356
score: 0
has text: I know, I'm sorry, it's because I'm not sure wether to use this method or my original which involved the python just grabbing values from the db. Now I'm trying to use HTTP post to push 1 big JSON object directly from js, to py.

http://stackoverflow.com/a/47500839
upvote count: 1
downvote count: 1
has body: That is probably because you're adding a to x b times. You should multiply, not add.
answers question: http://stackoverflow.com/q/47500825
type: Answer
has comment: http://stackoverflow.com/comment/81957240
score: 0

http://stackoverflow.com/comment/81880706
type: Comment
type: QuestionComment
score: 0
has text: velocity.reshape(n, 2) .. semantically an array of the x and y components of the velocity given the polar coordinates v and theta.
comment on: http://stackoverflow.com/q/47462798

http://stackoverflow.com/comment/87597127
has text: this doesn't actually let you extract out the seasonal values, it just models with these seasonal components. I'm interested in elegantly extracting out the components, not in the modelling itself
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50289565

http://stackoverflow.com/comment/81993104
score: 1
type: QuestionComment
has text: This is because the default character encoding for Python is UTF-8 (I believe) whereas the default character encoding for Powershell is UTF-16
type: Comment
comment on: http://stackoverflow.com/q/47518260

http://stackoverflow.com/comment/81943437
type: QuestionComment
has text: @ David Z Thank you for telling me the etiquette! I posted how I solved it.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47492663

http://stackoverflow.com/q/47529493
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/82016729
has comment: http://stackoverflow.com/comment/82017309
has comment: http://stackoverflow.com/comment/82016646
has title: Call class and inherit from another class - python 3
has answer: http://stackoverflow.com/a/47530766
type: Question
tagged with: python-3.x
tagged with: tkinter
answer count: 2
has answer: http://stackoverflow.com/a/47529727
type: UnansweredQuestion
has body: I am in a trouble. I wrote two classes, the first is the main gui for the software and the second is the login. Now, in the login window I need to write a small validation function. I wrote it but I need after I validate this function calls the main gui class and inherits from Tk. I know my code is very poor but I need help please. class main_gui(Frame): def __init__(self,master, self.username, self.password): self.path = os.getcwd() self.master = master self.username = StringVar() self.password = StringVar() master.title("main menu") master.geometry("800x600") master.config(background="white") master.resizable(width="false", height="false") master.iconbitmap(self.path + r"/img/icon.ico") self.mmenu = Menu(master) self.menubar = Menu(self.mmenu, tearoff=0) self.menubar.add_command(label="about", command=aboutme) self.menubar.add_command(label="Exit!", command=master.destroy) self.mmenu.add_cascade(label="menu", menu=self.menubar) master.config(menu=self.mmenu) class login(main_gui): def __init__(self): self.master.title("login") self.master.geometry("350x250") self.master.config(background="white") self.master.resizable(width="false", height="false") self.master.iconbitmap(self.path + r"/img/icon.ico") self.user_label = Label(master, text="user name") self.user_label.pack() self.user_value = Entry(master, textvariable=self.username) self.user_value.pack() self.password_label = Label(master, text="password") self.password_label.pack() self.password_value = Entry(master, textvariable=self.password) self.password_value.pack() self.login = Button(master, text="login" ) self.login.pack() def validation(self): if self.username.get() == "admin" : main_gui() root = Tk() hm = main_gui(root) root.mainloop()
tagged with: python

http://stackoverflow.com/comment/136424384
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/77382994

http://stackoverflow.com/q/47419342
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47419512
tagged with: python
has answer: http://stackoverflow.com/a/47419515
linked to: http://stackoverflow.com/q/39983695
type: AnsweredQuestion
tagged with: logical-operators
tagged with: list
has answer: http://stackoverflow.com/a/55668626
has body: I get a weird result and I try to apply the and or the or operator to 2 Boolean lists in python. I actually get the exact opposite of what I was expecting. [True, False, False] and [True, True, False] &gt; [True, True, False] [True, False, False] or [True, True, False] &gt; [True, False, False] Is that normal, and if yes, why?
has comment: http://stackoverflow.com/comment/81792840
has answer: http://stackoverflow.com/a/47419399
accepted answer: http://stackoverflow.com/a/47419399
downvote count: 0
answer count: 7
upvote count: 16
score: 16
has comment: http://stackoverflow.com/comment/81868735
has answer: http://stackoverflow.com/a/53204346
has answer: http://stackoverflow.com/a/47419642
possible better answer: http://stackoverflow.com/a/47419642
has title: Logical operation between two Boolean lists
has answer: http://stackoverflow.com/a/47419468

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/47395529
type: Tag

http://stackoverflow.com/q/47488742
tagged with: list
linked to: http://stackoverflow.com/q/24609618
has comment: http://stackoverflow.com/comment/81932483
answer count: 1
duplicate of: http://stackoverflow.com/q/24609618
has body: For you this must be a really silly question for you but I'm new in this world of programming with python and I'm having some problems with lists. I have this: l=[['Pasta=3', 'Soup=2'], ['Soup=1', 'Fresh Vegetables=3', 'Milk=3', 'Plastic Utensils=2'], ['Cheese=2', 'Deodorizers=1', 'Hard Candy=2', 'Jam=2']] wich list of lists. I want to remove the '=' sign, as well as everything that is in front of it. But I still want to remain with a list os lists. So, what I want to be the final result is this: l=[['Pasta', 'Soup'], ['Soup', 'Fresh Vegetables', 'Milk', 'Plastic Utensils'], ['Cheese', 'Deodorizers', 'Hard Candy', 'Jam']] I've tryed a for cycle like this: for i in h: for j in i: f=(j.replace('=','')) But it didn't work. Can I get some help? Thanks
has title: how to delete elements of a string from a list of lists
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47488798

http://stackoverflow.com/comment/81896950
has text: Thanks for the tip, serafeim. I tried y_predicted = nb.predict(x_test) but it returns an array of numbers like 2,1,3.... What does it mean? My category should be like 'b','a' or 'c' in my training dataset.
comment on: http://stackoverflow.com/a/47439155
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/60003629
downvote count: 0
answers question: http://stackoverflow.com/q/47448063
upvote count: 2
has body: For an easy one-liner you can just style it like this: self.com_btn.setStyleSheet('QComboBox {border: 1px solid gray;}') Or you can make a stylesheet file, and add it to your app in the main function: if __name__ == '__main__': app = QApplication(sys.argv) css = open('path/to/my.css', 'r').read() app.setStyleSheet(css) mainWindow = Window() mainWindow.show() sys.exit(app.exec_()) You can style the QComboBox in many ways: QComboBox { border: 1px solid gray; border-radius: 3px; padding: 1px 18px 1px 3px; min-width: 6em; } QComboBox:editable { background: white; } QComboBox:!editable, QComboBox::drop-down:editable { background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); } For more, you can check the official documentation: https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox
type: Answer
score: 2

http://stackoverflow.com/a/47407083
upvote count: 1
has comment: http://stackoverflow.com/comment/81776827
answers question: http://stackoverflow.com/q/47406911
score: 0
has body: something like this would work while True: number = input('enter your number: ') if len(number) &gt;= 5 and number.isdigit(): break else: print('re-enter number')
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81767441
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47406911
type: Answer

http://stackoverflow.com/comment/81874907
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47460003
type: Comment
has text: I thought if I'd do it this way, that it would iterate over all the available items in the cart and giving their properties, but I'll give it a shot

http://stackoverflow.com/a/47383412
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81720736
has body: from collections import defaultdict def words_dict_by_length(): stop = "stop" words = defaultdict(list) while True: word = input("Enter a word: ") if word == stop: # exit the loop break words[len(word)].append(word) return words This uses a defaultdict to group the words by their lengths.
answers question: http://stackoverflow.com/q/47383380
type: Answer
downvote count: 0

http://stackoverflow.com/a/47544925
has body: Here's my first attempt to run your code: In [44]: def f(x, coeff): ...: return coeff[0] + numpy.exp(coeff[1] * x) ...: ...: def chi_squared(coeff, x, y, y_err): ...: return numpy.sum((y - f(x, coeff) / y_err)**2) (I had to remove the ( in that last line) First guess at possible array values: In [45]: x = np.arange(3) In [46]: y = x In [47]: y_err = x In [48]: us = np.linspace(0,1,3) In [49]: rs = np.meshgrid(us,us) In [50]: rs Out[50]: [array([[ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ]]), array([[ 0. , 0. , 0. ], [ 0.5, 0.5, 0.5], [ 1. , 1. , 1. ]])] In [51]: chi_squared(rs, x, y, y_err) /usr/local/bin/ipython3:5: RuntimeWarning: divide by zero encountered in true_divide import sys Out[51]: inf oops, y_err shouldn't have a 0. Try again: In [52]: y_err = np.array([1,1,1]) In [53]: chi_squared(rs, x, y, y_err) Out[53]: 53.262865105526018 It also works if I turn the rs list into an array: In [55]: np.array(rs).shape Out[55]: (2, 3, 3) In [56]: chi_squared(np.array(rs), x, y, y_err) Out[56]: 53.262865105526018 Now, what was the purpose of vectorize? The f function returns a (n,n) array: In [57]: f(x, rs) Out[57]: array([[ 1. , 1.5 , 2. ], [ 1. , 2.14872127, 3.71828183], [ 1. , 3.21828183, 8.3890561 ]]) Lets modify the chi_squared to give sum an axis In [61]: def chi_squared(coeff, x, y, y_err, axis=None): ...: return numpy.sum((y - f(x, coeff) / y_err)**2, axis=axis) In [62]: chi_squared(np.array(rs), x, y, y_err) Out[62]: 53.262865105526018 In [63]: chi_squared(np.array(rs), x, y, y_err, axis=0) Out[63]: array([ 3. , 6.49033483, 43.77253028]) In [64]: chi_squared(np.array(rs), x, y, y_err, axis=1) Out[64]: array([ 1.25 , 5.272053 , 46.74081211]) I'm tempted to change the coeff to coeff0, coeff1, to give more control from the start on how this parameter is passed, but it probably doesn't make a difference. update Now that you've been more specific about how the coeff values relate to x, y etc, I see that this can be solved with simple broadcasting. No need to…
answers question: http://stackoverflow.com/q/47539760
has comment: http://stackoverflow.com/comment/82079301
downvote count: 0
upvote count: 1
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/47539760
type: Answer
has comment: http://stackoverflow.com/comment/82075201

http://stackoverflow.com/a/47446661
score: 1
upvote count: 1
type: Answer
has body: What about for line1 in bob: teamname.append(line1.strip()) # .strip() removes the \n print (', '.join(teamname)) The .join() does the final formatting. Update. I now think a more pythonistic (and elegant) answer would be: file2 = input("Enter the team-names file: ") ## E.g. teamNames.txt with open(file2) as f: teamname = [line.strip() for line in f] print (', '.join(teamname)) The with statement ensures the file is closed when the block finishes. Instead of doing the for loop, it now uses a list comprehension, a cool way to create a list by transforming the elements from another list (or from an iterable object, like file).
downvote count: 0
has comment: http://stackoverflow.com/comment/81848616
answers question: http://stackoverflow.com/q/47446626

http://stackoverflow.com/a/47398292
answers question: http://stackoverflow.com/q/47397191
has body: The simplest way to search for a substring within a string is to use the method if substring in string. You can do it using re, but it is much less efficient. I've timed a couple methods to show this: with open('test.txt') as f: data = f.readlines() string = '00008f46c906349f1df99ccdea4104a1' def func_1(data, string): for line in data: if re.match(string, line) is not None: pass return def func_2(data, string): for line in data: if re.search(string, line) is not None: pass return def func_3(data, string): for line in data: if string in line: pass return def func_4(data, string): for line in data: if line.startswith(string): pass return def func_5(data, string): def thing(line): string = '00008f46c906349f1df99ccdea4104a1' if string in line: pass return map(thing, data) return def func_6(data, string): data = [line.split(':')[0] for line in data] if string in data: pass return And the results: -------------------- 100 iterations -------------------- func_1: 0.579837208991 func_2: 0.89487306496 func_3: 0.0426233092805 func_4: 0.0963648696288 func_5: 0.113332976336 func_6: 0.10395732091 -------------------- 1000 iterations -------------------- func_1: 5.49227099705 func_2: 5.43578546216 func_3: 0.457362410806 func_4: 0.971125123276 func_5: 1.00572267516 func_6: 1.00902133508 -------------------- 10000 iterations -------------------- func_1: 61.2676211896 func_2: 61.2018943197 func_3: 4.1501189249 func_4: 9.45583133638 func_5: 9.94970703866 func_6: 10.0233565828 *My test file contained 4472 lines.
type: Answer
score: 0

http://stackoverflow.com/q/47429196
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47430459
score: 3
upvote count: 3
has body: Some Library/Resource in my Robot Framework script are RED as shown below: bad script with red marks While other one (which I copied from) is looks OK: good script My working environment (tree) looks like this: working environment/tree What I don't understand is why in one script everything looks good and in the other one (which looks almost the same) some Library/Resource are RED. The main reason I ask is because my python script (stability_tests.py) is not getting the parameters I send (stability_args, see below). my robot framework script *** Settings *** Force Tags Critical template Conf=3 isTor=0 isSanity=0 headless rcmd Library BeAm.beacon.tests.BeaconTesting WITH NAME BeaconTesting Library Collections Library BeAm.beacon.stability_tests Library BeAm.beacon.tests Resource ../../BeAm/beacon/settings.txt Resource ../../BeAm/settings.txt Resource ../../BeAm/local_settings.txt *** Test Cases *** Create Test Object [Tags] must ${TEST} = BeaconTesting.Get Beacon Test 3 Set Suite Variable ${TEST} ${TEST} Prepare Beacon Server [Tags] prpr BeaconTesting.Change Mss Value ${None} BeaconTesting.Prepare Server ${TEST} Beacon Stability [Tags] stability ${stability_args} = Create Dictionary Set To Dictionary ${stability_args} RANDOM_BEACON_TYPES False Set To Dictionary ${stability_args} TIME_GAP 0.3 Set To Dictionary ${stability_args} STRESS_TEST_NUM_OF_REQ 20 Set To Dictionary ${stability_args} WORKERS 2 stability workers ${TEST} &amp;{stability_args} BTW, the python script include stability_workers function. def stability_workers(RANDOM_BEACON_TYPES=True, TIME_GAP=60, STRESS_TEST_NUM_OF_REQ=100000, WORKERS=25): s = NewStressTest(RANDOM_BEACON_TYPES, float(TIME_GAP), int(WORKERS), int(STRESS_TEST_NUM_OF_REQ)])
favorite count: 0
tagged with: robotframework
type: Question
has title: RIDE - some Library/Resource are RED
downvote count: 0

http://stackoverflow.com/comment/82035670
comment on: http://stackoverflow.com/q/47538391
has text: Hmmm, an interpretation difference. I'll just erase my comment.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81959174
score: 0
comment on: http://stackoverflow.com/a/47501674
has text: Option 2 works as: data = data[data['Recipe Start'].astype(str).str.isdigit() & data['Recipe End'].astype(str).str.isdigit()] Thank you!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81766290
has text: Sure, no problem. Done.
comment on: http://stackoverflow.com/a/47406290
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/47440467
accepted answer: http://stackoverflow.com/a/47440698
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47440698
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47440878
answer count: 2
has answer: http://stackoverflow.com/a/47440878
downvote count: 0
has title: Regex match multiple results between the same delimiters
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81835873
type: AnsweredQuestion
has body: Very poor title - feel free to update it if you feel you can help I'm trying to return a list [&lt;str1&gt;, &lt;str2&gt;,...,&lt;strX&gt;] in the following string: '%%&lt;str1&gt;%%_Anything_Can_Be_Here_%%&lt;str2&gt;%%' The following code works, but if the number of '%%'s in the line is greater than 2, it takes everything between the first and last set of '%%'. &gt;&gt;&gt; import re &gt;&gt;&gt; str = '%%nas_ip_address%%' &gt;&gt;&gt; re.match('%%(.*)%%', str, re.DOTALL).group(1) 'nas_ip_address' &gt;&gt;&gt; str = '%%nas_ip_address%%:/vx/%%sfs_storage_pool%%' &gt;&gt;&gt; re.match('%%(.*)%%', str, re.DOTALL).group(1) 'nas_ip_address%%:/vx/%%sfs_storage_pool' &gt;&gt;&gt; re.match('%%(.*)%%', str, re.DOTALL).groups() ('nas_ip_address%%:/vx/%%sfs_storage_pool',) Is there a way to somehow extract ['nas_ip_address', 'sfs_storage_pool'] from the string using regex? I'm looking to parse a very large file however the performance is not an issue as it's not for production
score: 1

http://stackoverflow.com/comment/81862919
comment on: http://stackoverflow.com/q/47420130
has text: @AlexanderReynolds Dear Alexander, thank you very much for the input! The images will come as .pdf so I will have to convert them to .png. This way, as you very well suggest, it will prevent information loss. As for the second question, I would very much like the algorithm to stop when it finds an arrow, a line end, a corner or another element. That will let the user to pick the another line he considers important. Please check the update on the post for more information.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47460882
has body: I am using Adafruit's Video Looper to loop on a video using python script and omxplayer. Although, I made a few modifications. I want a popup window to appear when a GPIO button is pressed. I have the GPIO and the python script for a tkinter window all done and working, but the omxplayer is always on top so my window don't appear. I tested without the omxplayer active and I guarantee the popup window is working (has 'always on top' on). Is there any options on omxplayer to adjust that? Or should I take a totally different approach? (I am also posting this question on Raspberry Pi Exchange. I don't know which forum is better suited for the question) EDIT 1: Same exact Question. But no solutions. I tried the same things as the other user.
has comment: http://stackoverflow.com/comment/81877033
has title: How to make omxplayer not always on top?
tagged with: python
has comment: http://stackoverflow.com/comment/81876569
score: 0
tagged with: raspberry-pi
answer count: 0
type: UnansweredQuestion
tagged with: omxplayer
type: Question
linked to: http://stackoverflow.com/q/34031727

http://stackoverflow.com/a/47734738
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47518226
has body: Kind of hard to follow your code, but I can break-down the dimensions and arithmetic operations. It all begins with a fixed vocabulary, lets say of size N, which was extracted from some collection of texts. This means that you have N IDF weights. This can either be a vector of size 1 X N or the diagonal of an N X N matrix which all zeros otherwise, both can work depending on the eventual arithmetic Now lets say you have some collection of texts of size K (doesn't have to be the original collection used to extract the vocabulary). Each text will be tokenized, according to the vocabulary, into a vector of size N of term frequency counts, so that the entire K sized collection will become a matrix of size K X N. So we have tf_matrix of K X N, idf_matrix of size N X N or idf_vector of size 1 X N. To get the tf_idf_matrix you either need to do a matrix multiplication: tf_matrix * idf_matrix or an element-wise matrix and vector multiplication tf_matrix * idf_vector. Both will achieve the goal of multiplying every i-th tf with the i-th idf weight. You can do some normalizations in between some of these steps, but that will never change any of these dimensions, only the numeric values in the corresponding positions. Hope this helps!
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47518226

http://stackoverflow.com/comment/81721377
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47384213
has text: Maybe I'm reading your question wrong, but you refer to the "first number in [a] set". One of the important things to realize about `set`s is that they do not have any internal order. Also, it's a little unclear what you're looking for. Could you reduce your code a little to just the parts that really matter to the problem you're having?
type: QuestionComment

http://stackoverflow.com/comment/81736414
has text: Is the service actually running after you start it, or is it starting and insta-stopping? Try putting `while self.run == True: time.sleep(30)` in the start_flask method.
comment on: http://stackoverflow.com/q/47391242
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81884219
comment on: http://stackoverflow.com/a/47464725
type: Comment
type: AnswerComment
score: 0
has text: Once again you have helped me so much. I honestly can't thank you enough. The world needs more people like you :)

http://stackoverflow.com/comment/81746550
comment on: http://stackoverflow.com/q/47396442
type: QuestionComment
has text: It's difficult to make the connection between the two dataframes. Can you elaborate on what you want? Dataframes also can't have semi-colon separated values in it, unless you intend to store the intervals as a string which is a bad idea.
score: 1
type: Comment

http://stackoverflow.com/a/47466041
has body: I would first flatten the list of lists, like this: flattened_color_list = [item for sub_list in color_list for item in sub_list] Then iterate through the list using a dictionary comprehension to create your frequency dictionary, like this: frequency = {} {item: 1 if item not in frequency and not frequency.update({item: 1}) else frequency[item] + 1 if not frequency.update({item: frequency[item] + 1}) else 1 for item in flattened_color_list} Then get the largest value out of the dictionary, like this: max(frequency.iterkeys(), key=(lambda key: frequency[key])) Also, the nested if statement probably doesn't need to exist in your code. In the first if statement, you're ensuring that newCard.rarity is equal to "Mythic Rare," so the second if statement would always return true, since newCard.rarity would always be "not equal" to "None" at that point. You could get rid of the second if statement and your code would work the same. def get_uncommon_colors(self): uncommon_colors_list=[] colors=['black','red','white','blue'] for newCard in self.cardlist: newCard.rarity.split() if newCard.rarity=="Mythic Rare": if newCard.rarity!="None": uncommon_colors_list.append(newCard.get_colors()) else: continue #test=(Counter(x for sublist in uncommon_colors_list for x in sublist)) return(uncommon_)
answers question: http://stackoverflow.com/q/47465825
type: Answer
has comment: http://stackoverflow.com/comment/81886930
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/81880474
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47462706
score: 0
has text: Hmm my goal here is to be able to change the positions of a class instance that otherwise have the same attributes. So my initial code is sufficient for this task, right? @WillemVanOnsem

http://stackoverflow.com/comment/81862115
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47437568
type: Comment
has text: Hi again Mikhail, sorry to bother you, but since you are so knowledgeable on this topic I thought I might ask you. I am now using the SDK as you suggested, and I am getting an IOError when trying to iterate through the files in my blob container. This is my code `for blob in generator: json = json.load(data.get_blob_to_text('containername', open(blob.name)))` and the error im getting is this: `IOError: [Errno 2] No such file or directory: 'test.json'` I realize that this might be an absolute path issue? How should I go about solving this?

http://stackoverflow.com/comment/105406826
score: 0
comment on: http://stackoverflow.com/a/47421938
type: Comment
type: AnswerComment
has text: NameError: name 'ax' is not defined

connected-components
tags question: http://stackoverflow.com/q/47520487
type: Tag
tag name: connected-components

http://stackoverflow.com/comment/81986382
type: Comment
type: QuestionComment
has text: Please fix your indentation before we can have a look at your code!
score: 2
comment on: http://stackoverflow.com/q/47515268

http://stackoverflow.com/a/47536832
has body: The error was being caused by y = df[y].astype(float) x = df[x].astype(float) z = df[z].astype(float) where ax1.set_ylabel(y, color = blue) ax1.set_xlabel(x, color = 'b') causing the labels to be dataframes. This was problem solved by significantly increasing the figure size via: fig, ax1 = plt.subplots(figsize=(8, 8)
type: Answer
score: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47536089
downvote count: 1

http://stackoverflow.com/a/47494020
type: Answer
answers question: http://stackoverflow.com/q/47493999
score: 0
has body: A concise one is: x = ['123', '12', '5'] r = list(map(int, x)) print(r) &gt;[123, 12, 5]

http://stackoverflow.com/comment/81853370
has text: I tried without sudo, but it throws a long error ending with this: ValueError: Unable to configure handler 'file_log': [Errno 13] Permission denied: '/www/XXX/logs/log.log' All the above things are done inside virtual env named, venv
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47449099

http://stackoverflow.com/a/47501661
has comment: http://stackoverflow.com/comment/81959402
has body: If every column is a column of tuples, then you could create individual dataframes from each and concatenate them at the end - df_list = [] for c in df.columns: df_list.append(pd.DataFrame(df[c].tolist())) ndf = pd.concat(df_list, 1, ignore_index=True).add_prefix('col_') ndf.index = df.index ndf col_0 col_1 col_2 col_3 col_4 2005-01-02 22:15:00 1 1 True 0 0 2005-01-02 22:30:00 0 0 True 0 0 2005-01-02 22:45:00 0 0 True 0 0 2005-01-02 23:00:00 0 0 True 0 0 2005-01-02 23:15:00 0 0 True 0 0
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47501552
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47501552

http://stackoverflow.com/comment/81808847
score: 0
has text: Try this in Anaconda3 instead of MIniconda3
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47427053

http://stackoverflow.com/a/47410544
type: Answer
score: 0
has body: Try this. First update selenium: pip install -U selenium then update your geckodriver https://github.com/mozilla/geckodriver/releases from selenium.webdriver.common.desired_capabilities import DesiredCapabilities firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities['marionette'] = False driver = webdriver.Firefox(capabilities=firefox_capabilities) https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver With Selenium 3.0 and later, you shouldn't need to do anything to use Marionette, as it's enabled by default. It could be some unknown bug in marionette, try disabling it with the code above to use the good old geckodriver, if it fails too show us the prompt.
answers question: http://stackoverflow.com/q/47394510

http://stackoverflow.com/a/47411223
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47411166
has body: The first argument of named tuple constructor, is the typename: the name of the named tuple, not the arguments. [documentation] So you should construct t as: # v parameters t = namedtuple('t', ('a', 'b')) # ^ type name To make it more convenient, you can also provide a space separated string of parameters. So an equivalent one is: #t = namedtuple('t', 'a b') # ^ space separated list of parameters
upvote count: 9
answers question: http://stackoverflow.com/q/47411166
score: 9

http://stackoverflow.com/q/47426938
has comment: http://stackoverflow.com/comment/81814572
has comment: http://stackoverflow.com/comment/81808531
has comment: http://stackoverflow.com/comment/81810584
answer count: 1
has comment: http://stackoverflow.com/comment/81808555
has comment: http://stackoverflow.com/comment/81810860
has title: Python Dictionary eating up huge amount of ram
type: Question
tagged with: linux
has body: I have build a python dictionary that will store the word as key and the list of files that they appear in. Below is the code snipet. if len(sys.argv) &lt; 2: search_query = input("Enter the search query") else: search_query = sys.argv[1] #path to the directory where files are stored, store the file names in list named directory_name directory_name = os.listdir("./test_input") #create a list list_of_files to get the entore path of the files , so that they can be opend later list_of_files = [] #appending the files to the list_files for files in directory_name: list_of_files.append("./test_input"+"/"+files) #empty dictionary search_dictionary = {} #iterate over the files in the list_of files one by one for files in list_of_files: #open the file open_file = open(files,"r") #store the basename of the file in as file_name file_name = os.path.basename(files) for line in open_file: for word in line.split(): #if word in the file is not in the dictionary, add the word and the file_name in the dictionary if word not in search_dictionary: search_dictionary[word] = [file_name] else: #if the filename of a particular word is the same then ignore that if file_name in search_dictionary[word]: continue #if the same word is found in the different file then append that filename search_dictionary[word].append(file_name) def search(search_dictionary, search_query): if search_query in search_dictionary: print 'found '+ search_query print search_dictionary[search_query] else: print 'not found '+ search_query search(search_dictionary, search_query) input_word = "" while input_word != 'quit': input_word = raw_input('enter a word to search ') start1 = time.time() search(search_dictionary,input_word) end1 = time.time() print(end1 - start1) but if the no. of files in the directory is like 500 MB the RAM and SWAP space is eaten up. How do I manage the memory usage.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81810574
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47427105
tagged with: search-engine
has comment: http://stackoverflow.com/comment/81810929
has comment: http://stackoverflow.com/comment/81808477
has comment: http://stackoverflow.com/comment/81808828
score: 0

visual-studio-code
tags question: http://stackoverflow.com/q/47402063
tags question: http://stackoverflow.com/q/47517869
tag name: visual-studio-code
type: Tag
tags question: http://stackoverflow.com/q/47461844
tags question: http://stackoverflow.com/q/47534219
tags question: http://stackoverflow.com/q/47400816
tags question: http://stackoverflow.com/q/47406741
tags question: http://stackoverflow.com/q/47480833
tags question: http://stackoverflow.com/q/47408124
tags question: http://stackoverflow.com/q/47483933

http://stackoverflow.com/comment/81844312
has text: If you are looking for compact, then `len(s)-1 if len(s)<2 else len(s)-1-(s[-1]==s[-2])` will do what you want, but I don't recommend writing _that_.
comment on: http://stackoverflow.com/q/47444353
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81859903
has text: Of course, just about everything besides function call functionality will break when you do this. Some of it can be handled manually, like the descriptor protocol. Some of it can sort of be handled, like signature introspection. Some of it is never going to work.
score: 5
comment on: http://stackoverflow.com/a/47452562
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47455814
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47455236
has comment: http://stackoverflow.com/comment/81866375
has body: In general this is very hard to do as smoothness is one of the core-assumptions of those optimizers. Problems where some variables are discrete and some are not are hard and usually tackled either by mixed-integer optimization (working good for MI-linear-programming, quite okay for MI-convex-programming although there are less good solvers) or global-optimization (usually derivative-free). Depending on your task-details, i recommend decomposing the problem: outer-loop for np.arange(0,10,0.01)-like fixing of variable inner-loop for optimizing, where this variable is fixed return the model with the best objective (with status=success) This will effect in N inner-optimizations, where N=state-space of your to fix-var. Depending on your task/data, it might be a good idea to traverse the fixing-space monotonically (like using np's arange) and use the solution of iteration i as initial-point for the problem i+1 (potentially less iterations needed if guess is good). But this is probably not relevant here, see next part. If you really got 2 parameters, like indicated, this decomposition leads to an inner-problem with only 1 variable. Then, don't use minimize, use minimize_scalar (faster and more robust; does not need an initial-point).
answers question: http://stackoverflow.com/q/47455236
type: Answer
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81866397
downvote count: 0

http://stackoverflow.com/a/47461726
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47460580
score: 1
has body: top by default uses ncurses so getting output from it will be tricky. Python has a package called psutil. You should use that instead. If you really want to use top you'll need to pass the -b option (batch mode) From the manpage In this mode, top will not accept input and runs until the iterations limit you've set with the -n command-line option or until killed. So you can try something like this &gt;&gt;&gt; output = subprocess.check_output(['top', '-b', '-n1'])

http://stackoverflow.com/comment/82018979
comment on: http://stackoverflow.com/a/47527622
has text: Where should I add this lines in my templalte? Since now it shows the data for only the first form {% with post.id as id %} {% with forms.id as form %} do something with {{ form }} {% endwith %} {% endwith %}
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47477868
has comment: http://stackoverflow.com/comment/81910607
has comment: http://stackoverflow.com/comment/81910620
has comment: http://stackoverflow.com/comment/81910647
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47478070
answer count: 1
has comment: http://stackoverflow.com/comment/81910582
has comment: http://stackoverflow.com/comment/81910773
type: Question
has title: Python: Printing out list when I dont want to
tagged with: python
has comment: http://stackoverflow.com/comment/81910508
has comment: http://stackoverflow.com/comment/81910716
has body: I made a list of functions and want to randomly select one for a trivia game, it keeps printing out the functions of my list.(I already defined functions) def NBAquestions(): x = 0 question6 = Question("What does the NBA stand for?", "National Basketball Live", "National Fun Live", "National Basketball League", "Nothin But Liberals", 3) if question6.ask() == True: print("You are correct") x += 1 else: print("incorrect") x -= 1 question7 = Question("What team won the championship last year (2016)?", "Golden State Warriors", "Miami Heat", "Minnesota Wild", "Clevland Caviliers", 1) if question7.ask() == True: print("You are correct") x += 1 else: print("incorrect") x -= 1 question8 = Question("What doesn't belong?", "Stephen Curry", "Kevin Durant", "Draymond Green", "Mitch Marner", 4) if question8.ask() == True: print("You are correct") x += 1 else: print("incorrect") x -= 1 question9 = Question("Is the Seattle Supersonics a current NBA team", "True", "False", "-", "-", 2) if question9.ask() == True: print("You are correct") x += 1 else: print("incorrect") x -= 1 question10 = Question("Micheal who?", "Jackson", "Johnson", "Jordan", "Jarret", 3) if question10.ask() == True: print("You are correct") x += 1 else: print("incorrect") x -= 1 print('Welcome to the Sports Trivia Game, you will compete head to head in a tivia matchup. One point will be awarded for getting 1 question right, but if you get 1 wrong you will lose a point') a = input("please enter player 1's name: ") b = input("please enter player 2's name: ") questionList = ([NBAquestions(), MLBquestions(), NHLquestions(), NFLquestions()]
score: 0
has comment: http://stackoverflow.com/comment/81910593

http://stackoverflow.com/q/47490584
has comment: http://stackoverflow.com/comment/81937731
has answer: http://stackoverflow.com/a/47491321
possible better answer: http://stackoverflow.com/a/47491321
tagged with: python
tagged with: linear-programming
tagged with: mixed-integer-programming
type: Question
answer count: 2
tagged with: mathematical-optimization
upvote count: 2
has title: Mixed Integer Linear Programming to And/Or Constraints
has body: I'm looking to satisfy a set of constraints using PuLP and I'm not exactly sure how to set up the variables to do so. For example, how would I set up variables for the following constraint: ((x_1 &lt; x_2) AND (x_1 &lt; x_3)) OR ((x_1 &gt; x_2) AND (x_1 &gt; x_3)) A variable x_1 is either less or greater than both, x_2 and x_3. Any help would be appreciated. Thanks!
has answer: http://stackoverflow.com/a/47493093
accepted answer: http://stackoverflow.com/a/47493093
tagged with: pulp
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/47496470
answer count: 0
has comment: http://stackoverflow.com/comment/81949398
has comment: http://stackoverflow.com/comment/81949487
tagged with: point-of-sale
type: Question
has title: Promise return Promise status pending and promise value undefined in Odoo js
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81949388
tagged with: odoo
tagged with: javascript
tagged with: python
has body: Hello I am trying to convert string html to image using html2canvas library in my Odoo POS Module v8. But, when I try to use this function var receipt_data = html2canvas($(receipt)).then(function(canvas) { $('body').appendChild(canvas); }); it gives - Promise {PromiseStatus: "pending", PromiseValue: undefined} in receipt_data I have included html2canvas.js in my assets module. Please help me...
tagged with: node.js
has comment: http://stackoverflow.com/comment/81948226
score: 0

http://stackoverflow.com/q/47427719
tagged with: tkinter
answer count: 0
score: 2
upvote count: 2
tagged with: user-interface
downvote count: 0
linked to: http://stackoverflow.com/q/5104330
has comment: http://stackoverflow.com/comment/81812326
has body: I am making a script which will copy directory or files to other directory.I used list directory os.listdir() to list all the files of directory and made all files checkbutton but i want to use Tree Structure instead of os.listdir().I did some research about it on google but did't get anything. Anyone can tell me how to do it ? Code: import tkinter as tk import os import tkinter.filedialog import shutil i = 0 class ScrolledFrame(tk.Frame): def __init__(self, parent, vertical=True, horizontal=False): global ent1 global ent2 super().__init__(parent) self._canvas = tk.Canvas(self) self._canvas.grid(row=0, column=0) self._vertical_bar = tk.Scrollbar(self, orient="vertical", command=self._canvas.yview) if vertical: self._vertical_bar.grid(row=0, column=1, sticky="ns") self._canvas.configure(yscrollcommand=self._vertical_bar.set) self._horizontal_bar = tk.Scrollbar(self, orient="horizontal", command=self._canvas.xview) if horizontal: self._horizontal_bar.grid(row=1, column=0, sticky="we") self._canvas.configure(xscrollcommand=self._horizontal_bar.set) self.frame = tk.Frame(self._canvas) self._canvas.create_window((0, 0), window=self.frame, anchor="nw") self.frame.bind("&lt;Configure&gt;", self.resize) btn1 = tkinter.Button(root, text="Source Path", command = call) btn1.pack(fill="both", expand=1) ent1 = tkinter.Entry(root) ent1.pack(fill="both", expand=1) btn1 = tkinter.Button(root, text="destination",command = des) btn1.pack(fill="both", expand=1) ent2 = tkinter.Entry(root) ent2.pack(fill="both", expand=1) cpy = tkinter.Button(root, text="Copy",command = copy_file) cpy.pack(fill="x") self.pack() def resize(self, event=None): self._canvas.configure(scrollregion=self._canvas.bbox("all")) #This is not in class def call(): global filez global buttons global i buttons = [] filez = tkinter.filedialog.askdirectory(parent=root,initialdir = "/",title='Choose a file') ent1.delete(0,"end") ent1.insert(0, filez) dirs = os.listdir(filez) # remove previous IntVars intvar_dict.clear() …
linked to: http://stackoverflow.com/q/16746387
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81812146
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81812300
has comment: http://stackoverflow.com/comment/81814677
tagged with: python
has comment: http://stackoverflow.com/comment/81812078
has comment: http://stackoverflow.com/comment/81812296
has title: How to make tree structure of directory in tkinter

http://stackoverflow.com/comment/81928257
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47486220
score: 0
has text: Then what is [:] used for at all when dealing with numpy arrays? I could just omit it and always get the same result in the examples above.

http://stackoverflow.com/a/47454733
score: 0
has comment: http://stackoverflow.com/comment/81864544
has comment: http://stackoverflow.com/comment/81867769
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81895540
answers question: http://stackoverflow.com/q/47454039
has comment: http://stackoverflow.com/comment/81865683
accepted answer of: http://stackoverflow.com/q/47454039
has comment: http://stackoverflow.com/comment/81864824
has body: The problem is that you aren't updating the var StringVar that is used to display the generated password. Here's a version of your code which fixes that, but it is a little messy. There are a couple of other problems with your code, but I'll let you discover those. ;) from tkinter import * import tkinter as tk from tkinter import font as tkfont import random import time global strength global gen strength = 0 gen = '[password will be here]' global mypw mypw = '' def generate(pwvar): alphabet = "abcdefghijklmnopqrstuvwxyz" pw_length = 8 mypw = "" for i in range(pw_length): next_index = random.randrange(len(alphabet)) mypw = mypw + alphabet[next_index] # replace 1 or 2 characters with a number for i in range(random.randrange(1,3)): replace_index = random.randrange(len(mypw)//2) mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:] # replace 1 or 2 letters with an uppercase letter for i in range(random.randrange(1,3)): replace_index = random.randrange(len(mypw)//2,len(mypw)) mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:] print(mypw) gen = mypw pwvar.set(gen) class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne, PageTwo): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. frame.grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage") def show_frame(s…
has comment: http://stackoverflow.com/comment/81864227
type: Answer
has comment: http://stackoverflow.com/comment/81864473

http://stackoverflow.com/comment/81760261
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47403174
type: Comment
has text: also all the apps have an `__init__.py` file when they are created so I dont have to really worry about that... right? @mtt2p

http://stackoverflow.com/a/61126926
answers question: http://stackoverflow.com/q/47478913
has comment: http://stackoverflow.com/comment/108141335
has body: app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_DATABASE_PORT'] = 3308 #here your port
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/108146507
has comment: http://stackoverflow.com/comment/108140743
type: Answer

http://stackoverflow.com/comment/82036126
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47537918
has text: @CharlesDuffy Thanks so much for improving the title of the question. This is my first post ever on stack and I appreciate the useful tip going forward.

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/47446285
tags question: http://stackoverflow.com/q/47503061
type: Tag

http://stackoverflow.com/comment/82025167
has text: Edited my question to add what my goal is using --create. @hpaulj using `nargs='+'` doesn't work for what i need. Since user could just use `--create` alone to make a party using the default list [1, 'world1.json]. After that what you suggest me to do is to just decode the list after?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47523544
score: 0

http://stackoverflow.com/comment/81793128
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47419345
has text: Consider rewriting your post with a much more detail. No one will be able to provide you an answer as is.

http://stackoverflow.com/comment/81961926
type: Comment
comment on: http://stackoverflow.com/a/47496454
type: AnswerComment
score: 2
has text: @TheNate You could make this an answer (I'm surprised none of the answers make this point). wrapping a dictionary in a function seems like an awful lot of work just to use round brackets rather than square brackets.

http://stackoverflow.com/comment/81949338
type: QuestionComment
has text: Can you try printing the value of `df.head()`?
comment on: http://stackoverflow.com/q/47496964
score: 0
type: Comment

http://stackoverflow.com/comment/81895363
type: Comment
has text: Possible duplicate of [Djano JSON field. 'module' object has no attribute 'JSONField'](https://stackoverflow.com/questions/38513827/djano-json-field-module-object-has-no-attribute-jsonfield)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47468669

http://stackoverflow.com/comment/81824211
has text: @timgeb only get the value that appears first . Like`row.sort_values(ascending = False)[1:3] for row in df`.
score: 0
comment on: http://stackoverflow.com/q/47434924
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47400424
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81756974
tagged with: python
has answer: http://stackoverflow.com/a/47400489
type: Question
score: 2
has body: Here is my code trying to learn unit testing. Create a Student class for the purpose of testing. The test invalid test case constantly failed. FAIL: test_invalid (__main__.TestStudent) ---------------------------------------------------------------------- Traceback (most recent call last): File "mystudent.py", line 46, in test_invalid s1.get_grade() AssertionError: ValueError not raised above is from running result. Could anyone help me to figure out why I have this failure while I think I have put the right 'Raise Error' code there.... import unittest class Student(object): def __init__(self, name, score): self.name = name self.score = score def get_grade(self): try: if self.score &gt;= 60 and self.score &lt; 80: return 'B' if self.score &gt;= 80 and self.score &lt;= 100: return 'A' if self.score &gt;= 0 and self.score &lt;60: return 'C' if self.score &lt; 0 or self.score &gt; 100: raise ValueError('Invalid score value') except Exception as e: print('Value error!') class TestStudent(unittest.TestCase): def test_invalid(self): s1 = Student('Bob', -1) s2 = Student('Bat', 101) with self.assertRaises(ValueError): s1.get_grade() with self.assertRaises(ValueError): s2.get_grade() if __name__ == '__main__': unittest.main() Thanks
upvote count: 2
has comment: http://stackoverflow.com/comment/81754503
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47400489
has title: Python unit test failure: should raise value error but not
favorite count: 0
tagged with: unit-testing
tagged with: raiserror

http://stackoverflow.com/a/47496833
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47462311
has body: You can change your is_in_convex_hull method in the following way: def convex_hull(A): vertices = A.T.tolist() vertices = [ i + [ 1 ] for i in vertices ] poly = PyNormaliz.Cone(vertices = vertices) hull_vertices = np.array([entry[:-1] for entry in poly.VerticesOfPolyhedron()]).T hull_indices = find_column_indices(A, hull_vertices) return hull_indices The Normaliz version of the algorithm will run much faster then.
answers question: http://stackoverflow.com/q/47462311
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/q/47503731
has body: I've two classes - MessageProducer and MessageConsumer. MessageConsumer does the following: receives messages and puts them in its message list "_unprocessed_msgs" on a separate worker thread, moves the messages to internal list "_in_process_msgs" on the worker thread, processes messages from "_in_process_msgs" On my development environment, I'm facing issue with #2 above - after adding a message by performing step#1, when worker thread checks length of "_unprocessed_msgs", it gets it as zero. When step #1 is repeated, the list properly shows 2 items on the thread on which the item was added. But in step #2, on worker thread, again the len(_unprocessed_msgs) returns zero. Not sure why this is happening. Would really appreciate help any help on this. I'm using Ubuntu 16.04 having Python 2.7.12. Below is the sample source code. Please let me know if more information is required. import threading import time class MessageConsumerThread(threading.Thread): def __init__(self): super(MessageConsumerThread, self).__init__() self._unprocessed_msg_q = [] self._in_process_msg_q = [] self._lock = threading.Lock() self._stop_processing = False def start_msg_processing_thread(self): self._stop_processing = False self.start() def stop_msg_processing_thread(self): self._stop_processing = True def receive_msg(self, msg): with self._lock: LOG.info("Before: MessageConsumerThread::receive_msg: " "len(self._unprocessed_msg_q)=%s" % len(self._unprocessed_msg_q)) self._unprocessed_msg_q.append(msg) LOG.info("After: MessageConsumerThread::receive_msg: " "len(self._unprocessed_msg_q)=%s" % len(self._unprocessed_msg_q)) def _queue_unprocessed_msgs(self): with self._lock: LOG.info("MessageConsumerThread::_queue_unprocessed_msgs: " "len(self._unprocessed_msg_q)=%s" % len(self._unprocessed_msg_q)) if self._unprocessed_msg_q: LOG.info("Moving messages from unprocessed to in_process queue") self._in_process_msg_q += self._unprocessed_msg_q self._unprocessed_msg_q = [] LOG.info("Moved messages fro…
tagged with: multithreading
has comment: http://stackoverflow.com/comment/81963348
upvote count: 1
downvote count: 1
has title: Python - Non-empty shared list on separate thread appears empty
has comment: http://stackoverflow.com/comment/81963509
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81963860
has comment: http://stackoverflow.com/comment/81963325
has comment: http://stackoverflow.com/comment/81964015
tagged with: python
has answer: http://stackoverflow.com/a/47504419
favorite count: 0
has answer: http://stackoverflow.com/a/47523067
type: Question
has comment: http://stackoverflow.com/comment/81963686
answer count: 2
has comment: http://stackoverflow.com/comment/81963584
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81963532

http://stackoverflow.com/comment/81965288
comment on: http://stackoverflow.com/q/47503987
score: 0
has text: @Alexander Reynolds: I am adding the matching features plotted between the two images. I see a lot of matches for the shadowed profile regions of the grass and no match for the camera shadows
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47522364
accepted answer of: http://stackoverflow.com/q/47522329
has comment: http://stackoverflow.com/comment/82001294
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82001227
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82001408
has body: Just decode and slice: b'570 (RFC822.SIZE 11377)'.decode('utf-8')[-6:-1]
answers question: http://stackoverflow.com/q/47522329
score: 1

http://stackoverflow.com/q/47462085
has answer: http://stackoverflow.com/a/47462747
type: Question
tagged with: serialization
answer count: 2
has body: I have a model serializer that creates a Program object, along with another OutboundProgram object. The json I receive has all the details of a program object and the additional ones I need to create the OutboundProgram. How do I retrieve the additional fields because serializer only reads the fields for a certain object. P.S. our team lead doesnt want me to use a nested JSON json received by the request: { "linkage": "AP", "name": "something", "academic_year": 2017, "terms_available":[1,2], "is_graduate": false, "requirement_deadline":"2011-10-16", "institution": 3 } models.py class Program(SoftDeletionModel): linkage = ForeignKey(Linkage) name = CharField(max_length=64) academic_year = ForeignKey(AcademicYear) terms_available = ManyToManyField(Term) is_graduate = BooleanField() def __str__(self): return self.name class OutboundProgram(SoftDeletionModel): program = ForeignKey(Program) requirement_deadline = DateField() institution = ForeignKey(Institution) serializers.py class OutboundProgramSerializer(ModelSerializer): class Meta: model = Program fields = "__all__" def create(self, validated_data): terms = validated_data.pop('terms_available') program = Program.objects.create(**validated_data) for term in terms: program.terms_available.add(term) program.save() outbound_program = OutboundProgram.objects.create(program=program) #how to assign outbound_program.requirements_deadline from json return program Any kind of help would be useful. Thanks!
tagged with: django
has title: How to retrieve additional JSON data from request in django ModelSerializer
tagged with: python
tagged with: django-rest-framework
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47465131
has answer: http://stackoverflow.com/a/47465131
score: 0
accepted answer: http://stackoverflow.com/a/47462747
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/81790604
score: 0
comment on: http://stackoverflow.com/q/47418299
type: Comment
type: QuestionComment
has text: Anything from threshold of total sum to any given value. Value in % would be more robust

http://stackoverflow.com/q/47418800
has title: How to run a shell command in a for loop in xonsh?
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47419091
tagged with: shell
accepted answer: http://stackoverflow.com/a/47420339
upvote count: 1
has answer: http://stackoverflow.com/a/47420339
favorite count: 0
type: Question
has body: I would like to use xonsh to execute pandoc on all the md files in a directory. I could use subprocess, but that seems like the kind of thing that would be unnecessary in xonsh. Here's what I've tried so far: from glob import glob import os for fn in glob('*.md'): bname, _ = os.path.splitext(fn) pandoc $fn &gt; ${bname}.html With this I get a SyntaxError: SyntaxError: :3:11: ('code: $fn',) pandoc $fn > ${bname}.html If I change the last line to: pandoc $fn &gt; $bname.html, I get: pandoc: $fn: openBinaryFile: does not exist (No such file or directory) I assume that the problem is that inside the for loop is Python mode, but the pandoc call has to be in subprocess mode. How is this supposed to be done?
tagged with: python
tagged with: xonsh
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47419091

http://stackoverflow.com/q/47492077
has title: Create a list of lists from a one-dimensional list, grouping each element by length
has comment: http://stackoverflow.com/comment/81939634
has comment: http://stackoverflow.com/comment/81939641
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81939745
has comment: http://stackoverflow.com/comment/81939574
has answer: http://stackoverflow.com/a/47492222
upvote count: 2
has answer: http://stackoverflow.com/a/47493799
tagged with: python
has body: Let's say that I have a flat list: flat_list = ["one", "a", "two", "b", "ab"] My goal is to get a list of lists, each one containing every element with the same length, something like this: list_lists = [["one", "two"], ["a", "b"], ["ab"]] Is it possible to accomplish this with a simple list comprehension?
tagged with: list-comprehension
downvote count: 1
answer count: 4
has comment: http://stackoverflow.com/comment/81939608
possible better answer: http://stackoverflow.com/a/47492222
accepted answer: http://stackoverflow.com/a/47492118
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81939632
tagged with: list
has comment: http://stackoverflow.com/comment/81939665
has answer: http://stackoverflow.com/a/47492118
has comment: http://stackoverflow.com/comment/81939645
score: 1
has answer: http://stackoverflow.com/a/47493025
has comment: http://stackoverflow.com/comment/81939651
has comment: http://stackoverflow.com/comment/81939766

http://stackoverflow.com/comment/81978358
comment on: http://stackoverflow.com/q/47511076
type: QuestionComment
has text: Failed to load http://localhost:8000/api/v1/login/: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
type: Comment
score: 0

http://stackoverflow.com/q/47531729
type: AnsweredQuestion
tagged with: widget
score: 1
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47531940
has title: Calling a widget from another class to change its properties in tKinter
favorite count: 0
type: Question
tagged with: tkinter
upvote count: 2
has body: I have made a function in the main constructor of my tKinter app which updates certain properties of widgets e.g. their text across multiple frames. What I'm trying to do is change widgets in multiple frames at the same time while in a controller frame. def update_widgets(self, frame_list, widget_name, criteria, output): for i in frame_list: i.widget_name.config(criteria=output) # update_widgets(self, [Main, AnalysisSection], text_label, text, "foo") # would result in Main.text_label_config(text="foo") and # AnalysisSection.text_label_config(text="foo") ideally. However with this code, I'm encountering two problems. Firstly, I'm getting an attribute error stating that both frames don't have the attribute widget_name. Secondly, when I tried to refer to the widget names with the self prefix, both frames say they don't have the attribute self. Is there a way to fix this? Full program below: import tkinter as tk class Root(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.frames = {} container = tk.Frame(self) container.pack(side="bottom", expand=True)#fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) for X in (A, B): frame=X(container, self) self.frames[X]=frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(A) def show_frame(self, page): frame = self.frames[page] frame.tkraise() def update_widgets(self, frame_list, widget_name, criteria, output): for i in frame_list: frame = self.frames[i] widget = getattr(frame, widget_name) widget[criteria] = output class A(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.text = 'hello' self.classLabel = tk.Label(self, text="Frame A") self.classLabel.pack(side=tk.TOP) # trying to change this widget self.wordLabel = tk.Label(self, text="None") self.wordLabel.pack(side=tk.TOP) self.changeTextLabel = tk.Label(self, text="Change text above across both frames").…
has comment: http://stackoverflow.com/comment/82020034
accepted answer: http://stackoverflow.com/a/47531940
has comment: http://stackoverflow.com/comment/82061641
downvote count: 1

string
tags question: http://stackoverflow.com/q/47534573
tags question: http://stackoverflow.com/q/47441353
tags question: http://stackoverflow.com/q/47465542
type: Tag
tags question: http://stackoverflow.com/q/47528885
tags question: http://stackoverflow.com/q/47399751
tags question: http://stackoverflow.com/q/47402722
tags question: http://stackoverflow.com/q/47403413
tags question: http://stackoverflow.com/q/47497309
tags question: http://stackoverflow.com/q/47535063
tags question: http://stackoverflow.com/q/47464939
tags question: http://stackoverflow.com/q/47403789
tags question: http://stackoverflow.com/q/47401818
tags question: http://stackoverflow.com/q/47523386
tags question: http://stackoverflow.com/q/47508980
tags question: http://stackoverflow.com/q/47509304
tags question: http://stackoverflow.com/q/47395826
tags question: http://stackoverflow.com/q/47516976
tags question: http://stackoverflow.com/q/47407179
tags question: http://stackoverflow.com/q/47492500
tags question: http://stackoverflow.com/q/47464658
tags question: http://stackoverflow.com/q/47500441
tags question: http://stackoverflow.com/q/47517899
tags question: http://stackoverflow.com/q/47510820
tags question: http://stackoverflow.com/q/47507835
tags question: http://stackoverflow.com/q/47514225
tags question: http://stackoverflow.com/q/47445780
tags question: http://stackoverflow.com/q/47464891
tags question: http://stackoverflow.com/q/47512118
tags question: http://stackoverflow.com/q/47483390
tags question: http://stackoverflow.com/q/47472590
tags question: http://stackoverflow.com/q/47427645
tags question: http://stackoverflow.com/q/47501324
tags question: http://stackoverflow.com/q/47530738
tags question: http://stackoverflow.com/q/47470180
tags question: http://stackoverflow.com/q/47450037
tags question: http://stackoverflow.com/q/47485638
tags question: http://stackoverflow.com/q/47448923
tags question: http://stackoverflow.com/q/47460722
tags question: http://stackoverflow.com/q/47496415
tags question: http://stackoverflow.com/q/47458888
tags question: http://stackoverflow.com/q/47446626
tags question: http://stackoverflow.com/q/47417825
tags question: http://stackoverflow.com/q/47460763
tags question: http://stackoverflow.com/q/47514258
tags question: http://stackoverflow.com/q/47395993
tags question: http://stackoverflow.com/q/47487932
tags question: http://stackoverflow.com/q/47384763
tags question: http://stackoverflow.com/q/47415746
tag name: string
tags question: http://stackoverflow.com/q/47483334
tags question: http://stackoverflow.com/q/47445995
tags question: http://stackoverflow.com/q/47477773
tags question: http://stackoverflow.com/q/47468742
tags question: http://stackoverflow.com/q/47393630
tags question: http://stackoverflow.com/q/47455461
tags question: http://stackoverflow.com/q/47475204
tags question: http://stackoverflow.com/q/47539880
tags question: http://stackoverflow.com/q/47522299
tags question: http://stackoverflow.com/q/47527122
tags question: http://stackoverflow.com/q/47393978
tags question: http://stackoverflow.com/q/47473676
tags question: http://stackoverflow.com/q/47441379
tags question: http://stackoverflow.com/q/47417003
tags question: http://stackoverflow.com/q/47464509
tags question: http://stackoverflow.com/q/47443445
tags question: http://stackoverflow.com/q/47530782

http://stackoverflow.com/a/47419568
answers question: http://stackoverflow.com/q/47418707
type: Answer
has body: I happened to find solution by myself. Let me share it. This is matter of mutable or immutable, not statical or dynamical. What I should have done is change TestList_log[time].extend(TestList0) into import copy TestList_log[time].extend(copy.deepcopy(TestList0))
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81818040
accepted answer of: http://stackoverflow.com/q/47418707

http://stackoverflow.com/q/47437591
tagged with: python
tagged with: curl
type: Question
has title: Execute python script From web browser(http/curl Request)
has body: I'm quit new with python, I use basic python for scripting, but never used for HTTP request. I used to learn django, wsgi but all tutorials have website development guidance 1- I don't want to build any website, just want to make python executable from remote example:(http://www.example.com/test.py) like PHP. 2- There is one python file called test.py, has some functions like retrieving info from database. Deploying some services on cloud and returning status. 3- Nginx for web server &amp; REST API Methods. I really appreciate if someone can help me :)
answer count: 0
type: UnansweredQuestion
tagged with: http
has comment: http://stackoverflow.com/comment/81839579
score: 0
tagged with: nginx
has comment: http://stackoverflow.com/comment/81829491

http://stackoverflow.com/q/47441456
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47441640
has body: Goal is to create a new column based on return values of row level information of data frames existing column. df = pd.DataFrame({"A": [The quick brown fox jumps over the lazy dog,Glib jocks quiz nymph to vex dwarf], "B": [10, 20]}) A B 0 The quick brown fox jumps over the lazy dog 10 1 Glib jocks quiz nymph to vex dwarf 20 there exist method: def returnTopic(model, query, numberOftopics): # strip out topics per query/row and return topics that are relevant to a query/row return topicDict` topicDict contain {'x': ['fox','brown'], 'y':['jumps','over','the']} I want to create two new columns from these return elements in the dictionary. A B x y 0 The quick brown fox jumps over the lazy dog 10 ['fox','brown'] ['jumps','over','the'] 1 Glib jocks quiz nymph to vex dwarf 20 Here is my attempt: df['x'] = df.apply(lambda x: returnTopic(tmodel['x'], x['A'], 2))
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: Pandas create a new column by applying function that returns dictionary
answer count: 2
has answer: http://stackoverflow.com/a/47441707
possible better answer: http://stackoverflow.com/a/47441707
accepted answer: http://stackoverflow.com/a/47441640
has comment: http://stackoverflow.com/comment/81838171
has comment: http://stackoverflow.com/comment/81838031
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47441518
type: Question
tagged with: nltk
has body: I would like to generate a list of antonyms lemmas of a given lemma using Python, NLTK, and WordNet. In fact I just want to share a small utility function.
tagged with: python
type: UnansweredQuestion
tagged with: nlp
has answer: http://stackoverflow.com/a/47441519
has comment: http://stackoverflow.com/comment/81847384
upvote count: 3
score: 3
linked to: http://stackoverflow.com/q/40957598
linked to: http://stackoverflow.com/q/24192979
has title: How to get a list of antonyms lemmas using Python, NLTK and WordNet?
downvote count: 0
tagged with: wordnet
answer count: 1
favorite count: 0

webhose
type: Tag
tag name: webhose
tags question: http://stackoverflow.com/q/47489476

http://stackoverflow.com/comment/81955410
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47499877
has text: You example doesn't quite work; the first row only has a single `;` between the parentheses.
score: 0

http://stackoverflow.com/q/47535861
tagged with: aws-lambda
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82028928
has comment: http://stackoverflow.com/comment/82030475
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/58488844
has comment: http://stackoverflow.com/comment/82033152
has body: I'm trying to create simple Lambda function using Python 3.6. The function should get a userId (my primary key in DynamoDB) in the request query string params and returns 200 if item exist in DB, here is my lambda function import boto3 import os from boto3.dynamodb.conditions import Key, Attr def lambda_handler(event, context): userId = event["userId"] dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['Customers']) items = table.query( KeyConditionExpression=Key('userId').eq(userId) ) return items["Items"] When i am doing tests in Lambda interface it works and return the correct user however, when trying from Postman or using API Gateway it returns the following error { "errorMessage": "'userId'", "errorType": "KeyError", "stackTrace": [ [ "/var/task/index.py", 7, "lambda_handler", "userId = event["userId"]" ] ] } What am i missing here ? Struggling to understand "event" , documentation states its a python dictionary but how can i print the result of it and actually debug the lambda when called from Postman or API Gateway?
tagged with: python
score: 11
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/75198753
has comment: http://stackoverflow.com/comment/116146585
has comment: http://stackoverflow.com/comment/82029212
has answer: http://stackoverflow.com/a/78664595
upvote count: 11
has title: Python lambda function returns KeyError
has comment: http://stackoverflow.com/comment/82030248
downvote count: 0
has answer: http://stackoverflow.com/a/48072229
has comment: http://stackoverflow.com/comment/82030060
has comment: http://stackoverflow.com/comment/82031765
has answer: http://stackoverflow.com/a/65418088
favorite count: 0

http://stackoverflow.com/comment/126023829
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59510230
score: 0
has text: thank you, that's correct the problem for me

http://stackoverflow.com/comment/81725417
type: QuestionComment
comment on: http://stackoverflow.com/q/47386149
type: Comment
has text: @srig no, that changes what the code is doing.
score: 1

mnist
tags question: http://stackoverflow.com/q/47438750
tags question: http://stackoverflow.com/q/47520820
tags question: http://stackoverflow.com/q/47493423
type: Tag
tags question: http://stackoverflow.com/q/47441022
tags question: http://stackoverflow.com/q/47411754
tag name: mnist

http://stackoverflow.com/a/47534612
has comment: http://stackoverflow.com/comment/128214559
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47523544
type: Answer
has body: The code below returns the expected results for the listed usecases. I decided to use an extra function to handle the argument, as the program must accept either an int or a string for the first argument passed. I use a "try" block to see whether the single argument can be parsed as an int before proceeding. import argparse parser = argparse.ArgumentParser() parser.add_argument('--create n file', dest='create', nargs='+', default=(1,'world1.json'), help='Create a party of n player with mission parameters in file') args = parser.parse_args() def get_n_file(arg): if len(arg)==1: try: i = int(arg[0]) result = int(arg[0]), 'world'+str(arg[0])+'.json' except: s = arg[0] result = 1, s return result elif len(arg)==2: return int(arg[0]), arg[1] print(args.create) n, f = get_n_file(args.create) print(n, f)

http://stackoverflow.com/comment/81986188
comment on: http://stackoverflow.com/q/47515137
score: 0
type: Comment
type: QuestionComment
has text: You could capture it in a group [`var hours = (.+),`](https://regex101.com/r/q2CAZe/1)

http://stackoverflow.com/a/47421582
has body: My problem was solved by adding an encoding to the read_csv part. df = pd.read_csv("filename.csv", encoding='latin-1')
answers question: http://stackoverflow.com/q/47421513
score: 0
type: Answer

http://stackoverflow.com/q/47521393
upvote count: 1
has title: Best way in Pytorch to upsample a Tensor and transform it to rgb?
has comment: http://stackoverflow.com/comment/82015186
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47573654
tagged with: deep-learning
score: 1
tagged with: tensorboard
answer count: 1
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: pytorch
has comment: http://stackoverflow.com/comment/81999622
has answer: http://stackoverflow.com/a/47573654
downvote count: 0
has body: For a nice output in Tensorboard I want to show a batch of input images, corresponding target masks and output masks in a grid. Input images have different size then the masks. Furthermore the images are obviously RGB. From a batch of e.g. 32 or 64 I only want to show the first 4 images. After some fiddling around I came up with the following example code. Good thing: It works. But I am really not sure if I missed something in Pytorch. It just looks much longer then I expected. Especially the upsampling and transformation to RGB seems wild. But the other transformations I found would not work for a whole batch. import torch from torch.autograd import Variable import torch.nn.functional as FN import torchvision.utils as vutils from tensorboardX import SummaryWriter import time batch = 32 i_size = 192 o_size = 112 nr_imgs = 4 # Tensorboard init writer = SummaryWriter('runs/' + time.strftime('%Y%m%d_%H%M%S')) input_image=Variable(torch.rand(batch,3,i_size,i_size)) target_mask=Variable(torch.rand(batch,o_size,o_size)) output_mask=Variable(torch.rand(batch,o_size,o_size)) # upsample target_mask, add dim to have gray2rgb tm = FN.upsample(target_mask[:nr_imgs,None], size=[i_size, i_size], mode='bilinear') tm = torch.cat( (tm,tm,tm), dim=1) # grayscale plane to rgb # upsample target_mask, add dim to have gray2rgb om = FN.upsample(output_mask[:nr_imgs,None], size=[i_size, i_size], mode='bilinear') om = torch.cat( (om,om,om), dim=1) # grayscale plane to rgb # add up all images and make grid imgs = torch.cat( ( input_image[:nr_imgs].data, tm.data, om.data ) ) x = vutils.make_grid(imgs, nrow=nr_imgs, normalize=True, scale_each=True) # Tensorboard img output writer.add_image('Image', x, 0) EDIT: Found this on Pytorchs Issues list. Its about Batch support for Transform. Seems there are no plans to add batch transforms in the future. So my current code might be the best solution for the time being, anyway?

http://stackoverflow.com/comment/81831592
has text: Can you please tell me in detail what exactly needs to be done like can I try with any other locators?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47438448
type: QuestionComment

http://stackoverflow.com/comment/82578353
has text: yeah you are correct, it does not fix the error
score: 0
comment on: http://stackoverflow.com/q/47399913
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47536318
score: 4
has body: Try this: In [7]: df2 = data.groupby(data.index.day % 2).agg(np.mean) In [8]: df2 Out[8]: value1 Date 0 1.665 1 1.600 Explanation: In [9]: data.index.day Out[9]: Int64Index([31, 31, 31, 31, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 5], dtype='int64', name='Date') In [10]: data.index.day % 2 Out[10]: Int64Index([1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1], dtype='int64', name='Date')
type: Answer
accepted answer of: http://stackoverflow.com/q/47536243
upvote count: 4
answers question: http://stackoverflow.com/q/47536243
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81772563
has text: Thanks for pointing that. So, now I have modified the code and am checking from the 3rd element, and it's working fine now.
comment on: http://stackoverflow.com/a/47409072
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/135355174
has text: @MollyTaylor this is called explicit import, you can read up further and see other ways one can make imports in python. Another way you could've done this is as below: import nltk stpwrds = nltk.corpus.stopwords.words('english') search "Absolute vs Relative Imports in Python" on realpython for further explanation
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47485908

http://stackoverflow.com/a/47487651
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81931782
answers question: http://stackoverflow.com/q/47487616
has body: That ‘b’ means bytes. So instead of working with strings encryption algorythms are actually using bytes. My experience is that what you give a library (str/bytes/array) it should give you back, which Fernet is doing. I would simply convert the bytes back to a string k.decode(“utf-8”)
type: Answer
accepted answer of: http://stackoverflow.com/q/47487616
has comment: http://stackoverflow.com/comment/81930429
downvote count: 0
upvote count: 1
score: 1

gmail
type: Tag
tag name: gmail
tags question: http://stackoverflow.com/q/47532061
tags question: http://stackoverflow.com/q/47451890

http://stackoverflow.com/q/47506092
possible better answer: http://stackoverflow.com/a/68788045
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/47506205
has comment: http://stackoverflow.com/comment/134851159
has answer: http://stackoverflow.com/a/47506205
upvote count: 18
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/68788045
has body: I would like to try send requests.get to this website: requests.get('https://rent.591.com.tw') and I always get &lt;Response [404]&gt; I knew this is a common problem and tried different way but still failed. but all of other website is ok. any suggestion?
downvote count: 2
score: 16
has answer: http://stackoverflow.com/a/59665218
tagged with: python
tagged with: python-requests
has title: python requests.get always get 404

http://stackoverflow.com/q/47383048
answer count: 0
type: UnansweredQuestion
has body: I have an extremely simple Luigi luigi.contrib.external_program.ExternalProgramTask. No dependencies on this task. The task simply gets a single input file, passes it to an exe and then a file is written out which completes the task. Each task runs for about 1-4 seconds. --workers 8 - 100 tasks takes about 3m20s --workers 1 --local-scheduler - 100 tasks takes about 1m:40s` This is on my laptop and not "distributed" but I don't understand how the --local-scheduler is substantially faster when Luigi should be scheduling multiple tasks to be running in parallel. When running with the centralized scheduler I see 8+ python processes pop up and running but the overall process is slower.
has comment: http://stackoverflow.com/comment/81745719
has comment: http://stackoverflow.com/comment/81745924
score: 0
tagged with: luigi
tagged with: python
type: Question
has title: Luigi Central Scheduler significantly slower than --local-scheduler

http://stackoverflow.com/q/47393597
favorite count: 0
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/47395062
tagged with: menubar
tagged with: qmainwindow
accepted answer: http://stackoverflow.com/a/47398369
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/81742762
has body: I am writing a small application using PyQT. I am trying to create a menu bar at the top of the application containing the usual options ("File", "Edit", "Options" etc.) but my toolbar is not appearing when I try to add it to my QMainWindow class. I have looked around but it is not obvious to me what I am doing wrong. Note that I have tried using the QMainWindow.menuBar() method instead of creating a QToolbar, but if I do that the bar remains invisible altogether. Using the code below, I at least get an empty bar, even if it is empty. The code below is a minimal example of this problem. I would like to know what I have to change for the actions to show up. import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QBrush from PyQt5.QtWidgets import QMainWindow, QGraphicsScene, QToolBar, QMenu, QAction, QGraphicsView, QApplication class GraphWindow(QMainWindow): def __init__(self): super().__init__() self.scene = QGraphicsScene() # a grid foreground self.scene.setBackgroundBrush(QBrush(Qt.lightGray, Qt.CrossPattern)) self.grid = True # Create upper toolbar with menu options tb = QToolBar() menu = QMenu() db_action = QAction("Open file") db_action.setStatusTip("Select a file to use as a database") db_action.triggered.connect(self.open_new_db) menu.addAction(db_action) tb.addWidget(menu) tb.setAllowedAreas(Qt.TopToolBarArea) tb.setFloatable(False) tb.setMovable(False) self.addToolBar(tb) self.statusBar().showMessage("Ready") # Demonstrate the results from the input. graphics = QGraphicsView(self.scene) self.setCentralWidget(graphics) self.showFullScreen() def open_new_db(self): pass def keyPressEvent(self, e): # Currently, we respond to a press of the Escape key by closing the program. if e.key() == Qt.Key_Escape: self.close() app = QApplication(sys.argv) gr = GraphWindow() sys.exit(app.exec_())
type: Question
has comment: http://stackoverflow.com/comment/81751880
answer count: 2
has title: How to create a menu-bar in a QMainWindow
tagged with: pyqt
upvote count: 3
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/47395062
has answer: http://stackoverflow.com/a/47398369

http://stackoverflow.com/comment/81824909
type: Comment
has text: It can be, but I just want to get them in one list, like [ 0.5 0.5 1.11803401 ].
comment on: http://stackoverflow.com/a/47412739
type: AnswerComment
score: 0

http://stackoverflow.com/q/47410778
has comment: http://stackoverflow.com/comment/81776041
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54794137
has title: Epoch counter with TensorFlow Dataset API
accepted answer: http://stackoverflow.com/a/47417440
has answer: http://stackoverflow.com/a/52338085
has answer: http://stackoverflow.com/a/47417440
has body: I'm changing my TensorFlow code from the old queue interface to the new Dataset API. In my old code I kept track of the epoch count by incrementing a tf.Variable every time a new input tensor is accessed and processed in the queue. I'd like to have this epoch count with the new Dataset API, but I'm having some trouble making it work. Since I'm producing a variable amount of data items in the pre-processing stage, it is not a simple matter of incrementing a (Python) counter in the training loop - I need to compute the epoch count with respect to the input of the queues or Dataset. I mimicked what I had before with the old queue system, and here is what I ended up with for the Dataset API (simplified example): with tf.Graph().as_default(): data = tf.ones(shape=(10, 512), dtype=tf.float32, name="data") input_tensors = (data,) epoch_counter = tf.Variable(initial_value=0.0, dtype=tf.float32, trainable=False) def pre_processing_func(data_): data_size = tf.constant(0.1, dtype=tf.float32) epoch_counter_op = tf.assign_add(epoch_counter, data_size) with tf.control_dependencies([epoch_counter_op]): # normally I would do data-augmentation here results = (tf.expand_dims(data_, axis=0),) return tf.data.Dataset.from_tensor_slices(results) dataset_source = tf.data.Dataset.from_tensor_slices(input_tensors) dataset = dataset_source.flat_map(pre_processing_func) dataset = dataset.repeat() # ... do something with 'dataset' and print # the value of 'epoch_counter' every once a while However, this doesn't work. It crashes with a cryptic error message: TypeError: In op 'AssignAdd', input types ([tf.float32, tf.float32]) are not compatible with expected types ([tf.float32_ref, tf.float32]) Closer inspection shows that the epoch_counter variable might not be accessible within the pre_processing_func at all. Does it live in a different graph perhaps? Any idea how to fix the above example? Or how to get the epoch counter (with decimal points, e.g. 0.4 or 2.9) through some other means?
has comment: http://stackoverflow.com/comment/81775658
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81775093
has comment: http://stackoverflow.com/comment/81774919
has comment: http://stackoverflow.com/comment/81776263
has answer: http://stackoverflow.com/a/54794012
tagged with: python
score: 10
upvote count: 10
answer count: 4
possible better answer: http://stackoverflow.com/a/52338085

http://stackoverflow.com/comment/81813196
type: Comment
comment on: http://stackoverflow.com/a/47425022
has text: its because, for some keywords its nan, or empty, so it is throwing that error.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/109555410
type: AnswerComment
has text: Could you please provide what value PYTHONSTARTUP was and currently is?
comment on: http://stackoverflow.com/a/47393831
type: Comment
score: 9

http://stackoverflow.com/comment/81825035
type: Comment
type: AnswerComment
has text: could you point me to some pythonic example of data been sent to garbage? I mean any SO question regarding that
score: 0
comment on: http://stackoverflow.com/a/47435389

http://stackoverflow.com/q/47458816
score: 2
answer count: 0
downvote count: 0
tagged with: wordpress
tagged with: web-scraping
has body: In my task to learn python I decided to start a project that could help me in some way, by automating manual tasks that I do. I started coding a web scraper using beautifulsoup that would pull content from another website and then post it to a wordpress blog of my own. The data pulled includes Post title, tags, images. I managed to get most of it to work (my code is probably terrible) , but ran into a snag when it came to the tags. #Getting tags def get_tags(): for url in modified_lines: SoupRequest(url) global tags global cats cats = [] tags = [tag['content'] for tag in soup("meta", attrs={"property": "article:tag"})] categories = soup.find('span', attrs={'class': 'cat-meta-color'}).findAll('a',limit=limiter) allcats = [cat.text for cat in categories] for singlecat in allcats: cats.append(singlecat) tags.extend(cats) strtag = tags with io.open('tags.txt', 'a', encoding='utf8') as tagfile: posttag ="".join(str(strtag)) tagfile.write(posttag[1:-1].replace("'","") + '\n') get_tags() with open('tags.txt') as t: taglists = list(t.readlines()) #Posting to wordpress def post_to_wordpress(title, allvideoLinks,alltags,images): filepaths = images.strip() filename = filepaths.split('/')[-1] data = { 'name': filename, 'type': mimetypes.MimeTypes().guess_type(filename)[0], # mimetype } with open(filepaths, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachment_id = response['id'] wp.call(GetPosts()) title = str(title) content = allvideoLinks post = WordPressPost() post.title = title post.thumbnail = attachment_id post.content = content post.terms_names = { 'post_tag': [alltags], 'category': ['Youtube'], } post.post_type = "post" post.post_status = 'publish' post.id = wp.call(NewPost(post)) wp.call(posts.EditPost(post.id, post)) for l,y,t,f in zip(scrubbed,scrummed,taglists,images): post_to_wordpress(l,y,t,f) time.sleep(3) While the tags do post, they seem to come attached as a string instead of individual list items ,…
has title: Python Wordpress Xmlrpc 'Post_tags' not separated by comma
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: xml-rpc

http://stackoverflow.com/comment/81831571
type: QuestionComment
comment on: http://stackoverflow.com/q/47438306
type: Comment
score: 0
has text: @roelofs It is correct btw. Newbie post here in Stackoverflow so I didn't know it would be messed up. My codes are working if run the script in the terminal. And i've edited the last parenthesis part too. Sorry. :)

http://stackoverflow.com/comment/81845275
score: 1
type: Comment
has text: @toxicl-16: there's a lot of indentation errors in your code. here's your code reformatted with (hopefully) correct indentations: http://dpaste.com/3A39W3X -- Try running it, and report back any errors
type: QuestionComment
comment on: http://stackoverflow.com/q/47444521

http://stackoverflow.com/comment/81992442
comment on: http://stackoverflow.com/a/47517525
score: 0
type: AnswerComment
has text: @BradSolomon adding the .loc method . :-)
type: Comment

http://stackoverflow.com/q/47405018
accepted answer: http://stackoverflow.com/a/47405208
has title: Conditional removal of items from list and iterate from beginning through Python loop
tagged with: python
has answer: http://stackoverflow.com/a/47405208
possible better answer: http://stackoverflow.com/a/47405233
type: AnsweredQuestion
score: 0
tagged with: while-loop
has answer: http://stackoverflow.com/a/47405233
has comment: http://stackoverflow.com/comment/81763793
tagged with: loops
type: Question
tagged with: python-3.x
answer count: 2
tagged with: for-loop
has body: I am trying to remove items from my list when a condition is true and then iterate again from the very beginning of the list. Following is my code: from random import randint x = [1,2,3,4,5] for item in x: print("item is " + str(item)) z = randint(1, 5) print("z is " + str(z)) if z == item: x[:] = [item for item in x if item != z] print("Remaining list is " + str(x)) else: print("Remaining list is " + str(x)) So for example, my first item in the x list is 1 and lets say z is also 1. When z == item ,my x list removes the first item(1) and gets updated to [2,3,4,5]. But I get the following output: item is 1 z is 1 Remaining list is [2, 3, 4, 5] item is 3 z is 2 Remaining list is [2, 3, 4, 5] Instead of restarting the loop from 2 in my recently updated list[2,3,4,5], the loop starts from the second position which is 3. How do I restart the loop from the very beginning everytime my list gets updated? Thanks!

werkzeug
tags question: http://stackoverflow.com/q/47413300
tags question: http://stackoverflow.com/q/47420805
tags question: http://stackoverflow.com/q/47433307
tag name: werkzeug
type: Tag

http://stackoverflow.com/q/47492663
tagged with: geometry
has body: I'd like to know how to determine if two points d1(920, 52.1), d2(920, 52) are inside of this orange parallelogram, which is comprised of p1~p4. As you can see, the base of the parallelogram is not parellel to x-axis. Are there any modules that deal with this kind problems? Or I'd like to get some math help in this problem.
has comment: http://stackoverflow.com/comment/81940764
has answer: http://stackoverflow.com/a/47494197
accepted answer: http://stackoverflow.com/a/47493986
has comment: http://stackoverflow.com/comment/81940798
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/21612976
has comment: http://stackoverflow.com/comment/81943437
has comment: http://stackoverflow.com/comment/81940693
has title: How can I determine if a point is inside a certain parallelogram in Python?
has comment: http://stackoverflow.com/comment/81940877
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81941340
answer count: 3
has answer: http://stackoverflow.com/a/47493986
upvote count: 1
has answer: http://stackoverflow.com/a/47508665
possible better answer: http://stackoverflow.com/a/47508665
tagged with: math
score: 1
has comment: http://stackoverflow.com/comment/81940799
has comment: http://stackoverflow.com/comment/81940719
has comment: http://stackoverflow.com/comment/81940784
has comment: http://stackoverflow.com/comment/81940644
favorite count: 0
has comment: http://stackoverflow.com/comment/81940871
type: Question

http://stackoverflow.com/comment/82004176
type: Comment
has text: Thank you so much for your help!
type: AnswerComment
comment on: http://stackoverflow.com/a/47508501
score: 0

http://stackoverflow.com/comment/81887696
score: 0
has text: Nvm I got what you're saying. Stupid of me not to consider the already existing encryption methods. :'D
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47466281

http://stackoverflow.com/comment/81939833
type: AnswerComment
has text: It's a nice suggestion but I think OP's asking for the specific logic related to checking if a matrix is squared
type: Comment
comment on: http://stackoverflow.com/a/47492215
score: 0

http://stackoverflow.com/a/47490001
answers question: http://stackoverflow.com/q/47489705
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Sascha basically gives it away in the comments, but if X denotes your data, and model the instance of KMeans, you can sort the values of X by the distance to their centers through X[np.argsort(np.linalg.norm(X - model.cluster_centers_[model.labels_], axis=1))] Alternatively, since you know that each point is assigned to the cluster whose center minimizes Euclidean distance to the point, you can fit and sort in one step through X[np.argsort(np.min(KMeans(n_clusters=2).fit_transform(X), axis=1))]

http://stackoverflow.com/a/47502166
has comment: http://stackoverflow.com/comment/120413100
has comment: http://stackoverflow.com/comment/120424340
answers question: http://stackoverflow.com/q/47498344
type: Answer
has comment: http://stackoverflow.com/comment/120472426
score: 2
upvote count: 2
downvote count: 0
has body: Setup import pandas as pd df = pd.DataFrame({'state_1': ['New York', 'Ohio'], 'state_2': ['Washington', 'Utah']}) # df: # state_1 state_2 # 0 New York Washington # 1 Ohio Utah Add the first of three desired dates to each row df['date'] = pd.to_datetime('2017-11-01') # df: # state_1 state_2 date # 0 New York Washington 2017-11-01 # 1 Ohio Utah 2017-11-01 For each row, create a new DataFrame with all three desired dates, broadcast state names across these dates, and concatenate the list of DataFrames into one pd.concat([ pd.DataFrame( {'state_1': row.state_1, 'state_2': row.state_2, 'date': pd.date_range(row.date, freq='3h', periods=3) } ) for i, row in df.iterrows() ], ignore_index=True).loc[:, ['state_1', 'state_2', 'date']] # df: # state_1 state_2 date # 0 New York Washington 2017-11-01 00:00:00 # 1 New York Washington 2017-11-01 03:00:00 # 2 New York Washington 2017-11-01 06:00:00 # 3 Ohio Utah 2017-11-01 00:00:00 # 4 Ohio Utah 2017-11-01 03:00:00 # 5 Ohio Utah 2017-11-01 06:00:00
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47498344

http://stackoverflow.com/comment/81835150
has text: https://stackoverflow.com/questions/20320022/why-in-numpy-nan-nan-is-false-while-nan-in-nan-is-true
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47440077

http://stackoverflow.com/q/47440787
downvote count: 0
has body: I'm not sure if the way i installed the tensorflow on my laptop is correct or not and still trying to figure out some of the issues. Initially i installed Tensorflow on my Mac book pro and have no luck there (will come to that later) then i installed on a vagrant box using a ubuntu 16.04 image. (tensorflow) ubuntu@ubuntu-xenial:~$ python Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow &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)) Hello, TensorFlow! &gt;&gt;&gt; (tensorflow) ubuntu@ubuntu-xenial:~$ go run testing_tensor.go 2017-11-22 15:50:43.747754: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX Hello from TensorFlow version 1.4.0 Not sure how different this is from using a python library and go library and how can i identify if the tensorflow is using the cpu instead gpu?
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47440891
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: go
type: UnansweredQuestion
tagged with: python
has title: Tensorflow Binary Error Python vs Go

http://stackoverflow.com/comment/81739751
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47391242
has text: Try `while True: time.sleep(30)`. It's 2 lines, with the `time.sleep(30)` on a new line and idented (sorry can't do multiline code in a comment). Might need to `import time`. Should appear after app.run. I have never done a windows service in python before, but when I have done them previously they usually have an infinite loop to stop them exiting.
score: 0

http://stackoverflow.com/comment/81823117
score: 0
has text: I edited my answer, There was an error. Now works fine.
type: Comment
comment on: http://stackoverflow.com/a/47426525
type: AnswerComment

http://stackoverflow.com/q/47474989
has title: python program won't print prompts in order
tagged with: python
has answer: http://stackoverflow.com/a/47476144
answer count: 4
score: 0
has comment: http://stackoverflow.com/comment/81904611
has answer: http://stackoverflow.com/a/47475106
has answer: http://stackoverflow.com/a/47475491
has answer: http://stackoverflow.com/a/47475102
type: Question
has body: count=1 while count&lt;6: number1=int(input('Enter first number: ')) count+=1 if count==2: number2=int(input('Enter second number: ')) count+=1 elif count==3: number3=int(input('Enter third number: ')) count+=1 elif count==4: number4=int(input('Enter fourth number: ')) count+=1 elif count==5: number5=int(input('Enter fifth number: ')) count+=1 else: print(' ') When I run this it prompts 1st number then 2nd the 4th then 1st. What am I doing wrong that it's not in order 1 to 5? Thanks.
tagged with: prompt
type: UnansweredQuestion

http://stackoverflow.com/a/47493967
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47493392
upvote count: 1
type: AcceptedAnswer
has body: According to Keras docs, when you set include_top to False, you omit 3 fully connected layers and if you set it to True, you need to have 1000 classes with imagenet pretrained weights. So what you need is to attach fully connected layers on top of the vgg network: model = Sequential([vgg, Dense(10), Activation('softmax')]) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) # now check the input/output shapes print(model.input_shape) print(model.output_shape)
accepted answer of: http://stackoverflow.com/q/47493392

http://stackoverflow.com/comment/81817633
comment on: http://stackoverflow.com/q/47413104
has text: @Beno if you know how to add glyphicons to a manually built html form, then all you're missing to do it with a django form is how to take hand on the form's rendering to get the desired html, which is what this article explains (in complement of the official documentation).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82011874
score: 0
comment on: http://stackoverflow.com/q/47505089
has text: I think you mean that, the behaviour isnt right when you do the request through browser, right? If yes, What exactly happens when you try to send a get request through browser?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81999016
has text: in the description you are saying `#tab-item-1090 > md-icon:nth-child(1)` but in the code you have `('#tab-item-1090 > div:nth-child(3)')`. Is it possible to add a unique `id` in that button so you don't have to traverse the DOM in Selenium ? Edit: I cannot see the problem cause I don't know the DOM, but probably the selector is not correct ..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47521206
score: 0

http://stackoverflow.com/a/47483819
has comment: http://stackoverflow.com/comment/139028568
score: 50
downvote count: 0
upvote count: 50
accepted answer of: http://stackoverflow.com/q/47483733
answers question: http://stackoverflow.com/q/47483733
has body: You can set the precision options: torch.set_printoptions(precision=10) There are more formatting options on the documentation page, it is very similar to numpy's.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47540607
score: 16
possible better answer: http://stackoverflow.com/a/53271375
favorite count: 0
has answer: http://stackoverflow.com/a/75355446
type: Question
has title: disk I/O error with SQLite3 in Python 3 when writing to a database
tagged with: disk-io
has answer: http://stackoverflow.com/a/48479810
upvote count: 16
has comment: http://stackoverflow.com/comment/82038690
has answer: http://stackoverflow.com/a/65453488
tagged with: python
answer count: 6
linked to: http://stackoverflow.com/q/29244788
has comment: http://stackoverflow.com/comment/82039552
has answer: http://stackoverflow.com/a/66573556
has answer: http://stackoverflow.com/a/53271375
has body: i am a student just starting out with python, and i was tasked with creating a relational database management system. I think i came pretty far, but i seem to have hit a wall. This is my code: import csv import sqlite3 conn = sqlite3.connect('unfccc.db') c = conn.cursor() c.execute('''CREATE TABLE unfccc ( Country TEXT, CodeCountryFormat TEXT, NamePollutant TEXT, NameYearSector TEXT, NameParent TEXT, Sector TEXT, CodeSector TEXT, CNUEDSPD TEXT )''') def insert_row(Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD): c.execute("INSERT INTO unfccc VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD)) conn.commit() with open('UNFCCC_v20.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter='\t') counter = 0 for row in readCSV: insert_row(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]) counter = counter+1 print('%d down, more to go' % counter) conn.close() when i run it with line 4 directing the input towards :memory: it works perfectly and i have myself what i think is a relational database. However, when i try to run the code like this, writing the data to a db file, i get this error: File "&lt;ipython-input-13-4c50216842bc&gt;", line 19, in insert_row c.execute("INSERT INTO unfccc VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD)) OperationalError: disk I/O error I've searched stackoverflow, and i've used google, but i don't think any of the cases i found match up to what i'm trying to do here (or i don't have the knowledge to figure out whats going on). One other thing i noticed about my code is that it inputs the data into memory super fast, but when i write to a db file it is really slow, it shouldn't be a hardware limit as i am using an SSD. Any help will be greatly appreciated!
type: AnsweredQuestion
tagged with: relational-database
has answer: http://stackoverflow.com/a/47716087
downvote count: 0
tagged with: sqlite
accepted answer: http://stackoverflow.com/a/48479810

http://stackoverflow.com/comment/81841739
comment on: http://stackoverflow.com/q/47443131
type: Comment
has text: Thanks for the quick reply. In what form should I give the private key to the pkey variable? As a string or as a file?
score: 0
type: QuestionComment

http://stackoverflow.com/a/47421828
answers question: http://stackoverflow.com/q/47405659
score: 0
type: Answer
has body: As a persistent person I couldn't let the problem be. Being unable to solve the issue with passing arguments from one function to another I got rid of the functions altogether. Sure, they look pretty, sure you can do a lot of things with them (probably), other people can understand the code better. Still, it's all for naught if it won't work. On the plus side I have managed to wrap my head around datetime.strptime, thanks to Nupur Garg. Here's what I came up with: import datetime mail_body = """ Maintenance Date/Time (Local): Nov 17 2017 00:01 CET - Nov 17 2017 06:00 CET Maintenance Date/Time (GMT): Nov 16 2017 23:30 GMT - Nov 17 2017 05:00 GMT""" word_list = mail_body.split() gmt = word_list.index("(GMT):") start_date = word_list[gmt + 1:gmt + 5] start_date = ",".join(start_date) end_date = word_list[gmt + 7:gmt + 11] end_date = ",".join(end_date) add_hour = datetime.timedelta(hours = 1) start_date_local = datetime.datetime.strptime(start_date, "%b,%d,%Y,%H:%M") start_date_local = start_date_local + add_hour print start_date_local end_date_local = datetime.datetime.strptime(end_date, "%b,%d,%Y,%H:%M") end_date_local = end_date_local + add_hour print end_date_local

shopify
tag name: shopify
type: Tag
tags question: http://stackoverflow.com/q/47521580
tags question: http://stackoverflow.com/q/47526004

http://stackoverflow.com/comment/82001686
type: Comment
type: QuestionComment
score: 0
has text: There have been many compressed data handlers added to the working code in the repository, but these are not in an official release yet. To use the repository code (quite stable), install with `pip install git+https://github.com/pydicom/pydicom.git` and use `import pydicom`.
comment on: http://stackoverflow.com/q/47520486

selenium
tags question: http://stackoverflow.com/q/47390161
tags question: http://stackoverflow.com/q/47448013
tags question: http://stackoverflow.com/q/47390107
tags question: http://stackoverflow.com/q/47387351
tags question: http://stackoverflow.com/q/47405394
tags question: http://stackoverflow.com/q/47447972
tags question: http://stackoverflow.com/q/47477225
tags question: http://stackoverflow.com/q/47397412
tags question: http://stackoverflow.com/q/47482291
tags question: http://stackoverflow.com/q/47403510
tags question: http://stackoverflow.com/q/47434202
tags question: http://stackoverflow.com/q/47424179
tags question: http://stackoverflow.com/q/47424400
tags question: http://stackoverflow.com/q/47503521
tags question: http://stackoverflow.com/q/47452107
tags question: http://stackoverflow.com/q/47437715
tags question: http://stackoverflow.com/q/47451704
tags question: http://stackoverflow.com/q/47450075
tags question: http://stackoverflow.com/q/47447024
tags question: http://stackoverflow.com/q/47472377
tags question: http://stackoverflow.com/q/47391514
tags question: http://stackoverflow.com/q/47398321
tags question: http://stackoverflow.com/q/47450286
tags question: http://stackoverflow.com/q/47447178
tags question: http://stackoverflow.com/q/47413099
tags question: http://stackoverflow.com/q/47417748
tags question: http://stackoverflow.com/q/47536858
tags question: http://stackoverflow.com/q/47391823
tags question: http://stackoverflow.com/q/47508518
tags question: http://stackoverflow.com/q/47512765
tags question: http://stackoverflow.com/q/47389130
tags question: http://stackoverflow.com/q/47386675
tags question: http://stackoverflow.com/q/47429496
tags question: http://stackoverflow.com/q/47528045
tags question: http://stackoverflow.com/q/47484698
tags question: http://stackoverflow.com/q/47449039
tags question: http://stackoverflow.com/q/47467098
tags question: http://stackoverflow.com/q/47532769
tags question: http://stackoverflow.com/q/47395757
tags question: http://stackoverflow.com/q/47407044
tags question: http://stackoverflow.com/q/47451131
tags question: http://stackoverflow.com/q/47529805
tags question: http://stackoverflow.com/q/47411800
tags question: http://stackoverflow.com/q/47483913
tags question: http://stackoverflow.com/q/47431465
tags question: http://stackoverflow.com/q/47434779
tags question: http://stackoverflow.com/q/47473877
tags question: http://stackoverflow.com/q/47503476
tags question: http://stackoverflow.com/q/47413147
tags question: http://stackoverflow.com/q/47489195
tags question: http://stackoverflow.com/q/47520524
tags question: http://stackoverflow.com/q/47447766
tags question: http://stackoverflow.com/q/47500449
tags question: http://stackoverflow.com/q/47469507
tags question: http://stackoverflow.com/q/47420957
tags question: http://stackoverflow.com/q/47491354
tags question: http://stackoverflow.com/q/47471057
tags question: http://stackoverflow.com/q/47494960
tags question: http://stackoverflow.com/q/47447767
type: Tag
tags question: http://stackoverflow.com/q/47515625
tags question: http://stackoverflow.com/q/47442201
tags question: http://stackoverflow.com/q/47483222
tags question: http://stackoverflow.com/q/47435230
tags question: http://stackoverflow.com/q/47523097
tags question: http://stackoverflow.com/q/47496474
tags question: http://stackoverflow.com/q/47485710
tags question: http://stackoverflow.com/q/47418345
tags question: http://stackoverflow.com/q/47521206
tags question: http://stackoverflow.com/q/47465586
tags question: http://stackoverflow.com/q/47424245
tags question: http://stackoverflow.com/q/47496039
tags question: http://stackoverflow.com/q/47439159
tag name: selenium
tags question: http://stackoverflow.com/q/47496680
tags question: http://stackoverflow.com/q/47385093
tags question: http://stackoverflow.com/q/47411156
tags question: http://stackoverflow.com/q/47436655
tags question: http://stackoverflow.com/q/47394510
tags question: http://stackoverflow.com/q/47386365

http://stackoverflow.com/q/47412268
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/47413994
has body: I have a migrations come from the work of another person, and I'm in on a code base controlled by the version too. I created a migration file after adding a new field but the problem is in the data migration (0003_datamigration_initial_service_configuration.py)that is created before through the function get_or_create () is executed in the head of the list while my migration file data in the end I should not change a migration already developed. This is my list of migrations 0001_initial.py 0002_datamigration_initial_users_list.py 0003_datamigration_initial_mymodel.py ... 0015.addnewfield 0003_datamigration_initial_mymodel.py: from __future__ import unicode_literals from django.db import migrations from ..models import MyModel def create_initial_mymodel(apps, schema_editor): current_product_type, created = MyModel.objects.get_or_create() class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_datamigration_initial_users_list'), ] operations = [ migrations.RunPython(create_initial_mymodel), ] Rhe error is no such column named new_field How can I fix the problem without editing any data migrations?
favorite count: 0
type: Question
tagged with: django-migrations
score: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81781509
has title: How can I add a new field in model when I already have a datamigration in Django?
accepted answer: http://stackoverflow.com/a/47413994

http://stackoverflow.com/comment/81742974
type: Comment
score: 0
type: AnswerComment
has text: And what's the point of parsing JSON, when your example sends invalid JSON data? BTW, if you really want to read JSON body, all you need is `query = request.json().get('query')`.
comment on: http://stackoverflow.com/a/47393402

http://stackoverflow.com/a/47421688
has body: Another way to split string to a list based on case. x = 'ATGAaagaaggagatatacAcATGAATTTGTCGGTTTACCCCAATTTAACCAAAgaaaacctgtacaaAaa' l=[] lstr='' ustr='' def createList(s): l.append(s) for i in list(x): if i.islower(): lstr+=i if ustr != '': createList(ustr) ustr = '' elif i.isupper(): if lstr != '': createList(lstr) ustr+=i lstr='' if list(x)[-1].islower(): createList(lstr) else: createList(ustr) print(l) Output ['ATGA', 'aagaaggagatatac', 'A', 'c', 'ATGAATTTGTCGGTTTACCCCAATTTAACCAAA', 'gaaaacctgtacaa', 'A', 'aa']
score: 0
answers question: http://stackoverflow.com/q/47420673
type: Answer

http://stackoverflow.com/q/47481047
downvote count: 0
has answer: http://stackoverflow.com/a/47550375
score: 1
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/81919817
has comment: http://stackoverflow.com/comment/81922926
has title: Python Sqlite3 passing BLOB to user-defined function gives None
has comment: http://stackoverflow.com/comment/81917248
type: Question
has comment: http://stackoverflow.com/comment/82043003
has comment: http://stackoverflow.com/comment/81917805
has comment: http://stackoverflow.com/comment/82043019
accepted answer: http://stackoverflow.com/a/47550375
upvote count: 1
has comment: http://stackoverflow.com/comment/82057642
answer count: 1
has body: I am trying to pass the data from a BLOB column into a user defined function, but it shows up in that function as None. Is this just a quirk, or am I doing somethign wrong? The BLOB data are jpegs I put into an sqlite3 database using Python 2.7.12. The schema for the table is CREATE TABLE data (md5sum TEXT PRIMARY KEY, data BLOB); import sqlite3 import hashlib def p_data(x): print [x] return x def p_md(x): print [x] return x db=sqlite3.connect('tagged.db') db.text_factory = str db.create_function('P_DATA', 1, p_data) db.create_function('P_MD', 1, p_md) r = db.execute('SELECT P_MD(md5sum),P_DATA(data),data FROM data LIMIT 1') for i in r: print # Don't want to print the thousands of bytes in i[-1] print i[:1] print hashlib.md5(i[-1]).hexdigest() python test.py [u'3040158ef2c323aaa63da499fc821d77'] [None] ('3040158ef2c323aaa63da499fc821d77', None) 3040158ef2c323aaa63da499fc821d77 Edit I boiled down my main program into the scripts below to make it easier to share an exact equivalent of what I am running. The test binary data (image) is my avatar image. Easy initializer for tagged.db PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; PRAGMA writable_schema=ON; INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)VALUES('table','files','files',0,'CREATE VIRTUAL TABLE "files" USING fts3(fname TEXT, orig_name TEXT, tags TEXT, md5sum TEXT)'); CREATE TABLE 'files_content'(docid INTEGER PRIMARY KEY, 'c0fname', 'c1orig_name', 'c2tags', 'c3md5sum'); CREATE TABLE 'files_segments'(blockid INTEGER PRIMARY KEY, block BLOB); CREATE TABLE 'files_segdir'(level INTEGER,idx INTEGER,start_block INTEGER,leaves_end_block INTEGER,end_block INTEGER,root BLOB,PRIMARY KEY(level, idx)); CREATE TABLE data (md5sum TEXT PRIMARY KEY, data BLOB); CREATE INDEX idx1 on data(md5sum); PRAGMA writable_schema=OFF; COMMIT; Contents of test.py import sqlite3 import hashlib def p_data(x): print 'inside p_data' print '\t', [x] return x def p_md(x): print 'inside p_md' print '\t', [x] return x db=sqlite3.connect…
favorite count: 0
tagged with: user-defined-functions
type: AnsweredQuestion

http://stackoverflow.com/a/47458284
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81894411
type: Answer
answers question: http://stackoverflow.com/q/47457983
has body: The easiest solution is indeed to plot n lines. import numpy as np import matplotlib.pyplot as plt xs =np.array([[ 555.59, 557.17], [ 867.64, 869. ], [ 581.95, 583.25], [ 822.08, 823.47], [ 198.46, 199.91], [ 887.29, 888.84], [ 308.68, 310.06], [ 340.1 , 341.52], [ 351.68, 353.21], [ 789.45, 790.89]]) ys = np.array([[ 737.55, 738.78], [ 404.7 , 406.17], [ 7.17, 8.69], [ 276.72, 278.16], [ 84.71, 86.1 ], [ 311.89, 313.14], [ 615.63, 617.08], [ 653.9 , 655.32], [ 76.33, 77.62], [ 858.54, 859.93]]) for (x,y) in zip(xs,ys): plt.plot(x,y, color="crimson") plt.show() If n is very large, a more efficient solution would be to use a single LineCollection to show all lines. The advantage is that this can be drawn faster, since only a single collection is used instead of n line plots. # data as above. seq = np.concatenate((xs[:,:,np.newaxis],ys[:,:,np.newaxis]), axis=2) c= matplotlib.collections.LineCollection(seq) plt.gca().add_collection(c) plt.gca().autoscale() plt.show()
has comment: http://stackoverflow.com/comment/81878733
has comment: http://stackoverflow.com/comment/81937492
has comment: http://stackoverflow.com/comment/81937401
score: 0
accepted answer of: http://stackoverflow.com/q/47457983
has comment: http://stackoverflow.com/comment/81895094

http://stackoverflow.com/comment/81944002
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47494385
has text: Stuff like `lambda x: x > 120` or `lambda x: 50 <= x < 100`.
type: Comment

http://stackoverflow.com/a/47503028
downvote count: 2
score: -2
type: Answer
answers question: http://stackoverflow.com/q/47502985
upvote count: 0
has comment: http://stackoverflow.com/comment/81961884
has body: The first code checks if the number is divisible by a factor twice: if x%i==0: ... and while x%i==0: ..., the first piece of code also creates multiple instances of x: x=x/i. A more efficient code would be: def prime(num): if num == 1 or num == 0: return False prime = True for i in range(2, num): if num % i == 0: prime = False return prime

http://stackoverflow.com/q/47512686
has comment: http://stackoverflow.com/comment/82512343
downvote count: 0
tagged with: caffe
has comment: http://stackoverflow.com/comment/82384327
has comment: http://stackoverflow.com/comment/82347570
has title: Loading custom Python Layer in Caffe-Import Error
upvote count: 1
has comment: http://stackoverflow.com/comment/81981738
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81981240
has comment: http://stackoverflow.com/comment/82440114
tagged with: pycaffe
has comment: http://stackoverflow.com/comment/81983944
has body: I've written my own Caffe layer in Python (maskextractor.py). When training the network from scratch, it worked well. But once I've tried finetuning from the saved network: ../caffe/build/tools/caffe train -solver solverFCN8s_MCN_newmodule.prototxt -snapshot snapshot/train8MCNs_borders_pascal_maskextractor_iter_1.solverstate the error I got is failed import of the new layer: I1127 09:38:40.254966 3102 layer_factory.hpp:77] Creating layer maskextractor ImportError: No module named mask_extractor terminate called after throwing an instance of 'boost::python::error_already_set' *** Aborted at 1511775520 (unix time) try "date -d @1511775520" if you are using GNU date *** Clearly Caffe can't find the new layer. I've added it to the Pythonpath via sys.path.insert and then copied to caffe/python/caffe/ an recompiled pycaffe, but it didn't help either. EDIT: this only happens when I finetune. If I start from solver: import numpy as np from PIL import Image import os, sys caffe_dir = "/home/ICTDOMAIN/453615/Downloads/caffe/python" sys.path.insert(0,caffe_dir) import caffe newmodule_dir = "../lib/mask_extractor" sys.path.insert(0, newmodule_dir) import mask_extractor # caffe.set_mode_gpu() caffe.set_device(0) # continue from the saved weights weights = 'snapshot/train8MCNs_borders_pascal_adadelta_maskextractor_new_iter_1.caffemodel' solver=caffe.get_solver('solverFCN8s_MCN_adadelta_maskextractor_new.prototxt') solver.net.copy_from(weights) solver.solve() everything works fine. But I want to continue training from he snapshot. In such case I get the error above. PythonPath looks like print sys.path ['/home/ICTDOMAIN/453615/Downloads/caffe/python', '../lib/mask_extractor', '/home/ICTDOMAIN/453615/Downloads/caffe/python', '/home/ICTDOMAIN/453615/Downloads/fcn.berkeleyvision.org/voc-fcn8s', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-pa…
tagged with: python
has answer: http://stackoverflow.com/a/47519954
has comment: http://stackoverflow.com/comment/82223436
has comment: http://stackoverflow.com/comment/82299566
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82512240
answer count: 1

http://stackoverflow.com/q/47462122
duplicate of: http://stackoverflow.com/q/152580
accepted answer: http://stackoverflow.com/a/47462149
upvote count: 0
has body: As you can tell, I am a fairly novice Python coder. As of current I am just making some little test programs and trying to ensure all my indentation and whatever is done properly before trying any large programs. So I am trying to ensure that if an input is not an integer, then the program outputs a message saying an integer must be inputted. However, with the current code I have (which I think should be correct) regardless of the answer the "please input an integer" message is outputted. What have I done wrong? Here is the code: a = input("What is your age?") b = 7 c = ((a-2) * 4) +25 if a == int: print "Your age in a small dog's years is:", ((a-2) * 4)+28 print "Your age in a medium sized dog's years is:", ((a-2) * 6)+27 print "Your age in a big dog's years is:", ((a-2) * 9)+22 print "Your age in cat years is:", c print "Your age in guinea pig years is:", a * 15 print "Your age in hamster years is:", a * 20 print "Your age in pig years is:", ((a-1) * 4)+18 print "Your age in goldfish years is:", ((a-1) * 8)+188 print "Your age in cow years is:", ((a-1) * 4)+14 print "Your age in horse years is:", a * 3 print "Your age in goat years is:", ((a-1) * 6)+18 print "Your age in rabbit years is:", ((a-1) * 8)+20 print "Your age in chinchilla years is:", ((a-1) * 7)+17 elif a != int: print "You must enter an integer!" It works otherwise, it's just this little end two lines that seem to ruin it. Thanks.
answer count: 1
has answer: http://stackoverflow.com/a/47462149
has comment: http://stackoverflow.com/comment/130099827
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3501382
has comment: http://stackoverflow.com/comment/81878954
tagged with: python
has comment: http://stackoverflow.com/comment/81878951
score: -1
has comment: http://stackoverflow.com/comment/81878978
has title: Why does this show as not an integer when I input an integer? (Python)
tagged with: python-2.7

http://stackoverflow.com/comment/81859410
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47452143
score: 0
has text: tried multiple .whl files and versions of paramiko all fail with the same error

http://stackoverflow.com/q/47454479
has comment: http://stackoverflow.com/comment/81863811
tagged with: append
favorite count: 0
type: Question
has body: I want to take the text of a file, each new value on a new line, for example hi /n this is my question /n can u answer it? My_list should look like this My_list[0] should be equal to hi, My_list[1] should be equal to this is my question and My_list[2] should be equal to can u answer it? I tried doing so using the following with open(r'path.docx',encoding="utf8") as f: content = f.readlines() content = [x.strip() for x in content] in an approach like the one i found in here How do I read a file line-by-line into a list? Then i got a Syntax error for unicode do i referred to this link Why do I get a SyntaxError for a Unicode escape in my file path? added r at first and solved it for the first iteration then got this error return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> that i referred to this link to solve UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> and added encoding="utf8". Still not working . EDIT: I changed the encoding to "Latin-1" but i didn't get the output i want from print (content) instead i got stuff like that ['PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x00\t$\x87\ , again what i want and expect is a list where each line of the .docx file is an element(seperated by /n).
upvote count: 0
linked to: http://stackoverflow.com/q/9233027
answer count: 2
has answer: http://stackoverflow.com/a/47454619
possible better answer: http://stackoverflow.com/a/47454619
linked to: http://stackoverflow.com/q/18084554
has comment: http://stackoverflow.com/comment/81864048
has answer: http://stackoverflow.com/a/47455322
linked to: http://stackoverflow.com/q/3277503
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81864903
has title: UnicodeDecodeError: 'charmap' codec can't decode
tagged with: list
accepted answer: http://stackoverflow.com/a/47455322
downvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81863949

http://stackoverflow.com/comment/81954286
type: QuestionComment
comment on: http://stackoverflow.com/q/47424751
score: 0
has text: @PM2Ring I'll try this out. On a different note, would I be able to get tweets as far back as I'd like, though?
type: Comment

http://stackoverflow.com/q/47391092
tagged with: twython
favorite count: 0
tagged with: social-networking
type: Question
possible better answer: http://stackoverflow.com/a/47391736
tagged with: python
tagged with: twitter
accepted answer: http://stackoverflow.com/a/47393913
type: AnsweredQuestion
has title: Twython with 140 character limitation of twitter
answer count: 2
has body: I am trying to search in twitter using Tython, but it seems that the library has a limitation on 140 characters. With the new feature of python, i.e. 280 characters length, what can one do?
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47391736
tagged with: web-scraping
has answer: http://stackoverflow.com/a/47393913

http://stackoverflow.com/a/47538580
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47535669
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47535669
has body: So it turns out that sample_weight can be used after all. As the sample weight can only have 2 dimensions (batch_size, no of predictions), the trick was to reshape the output from the model to be flat. The last 2 lines of my model definition: model.add(Reshape((-1, 1))) model.compile(loss='binary_crossentropy', optimizer='adam', sample_weight_mode='temporal', metrics=['binary_accuracy']) I use Reshape((-1,1)) because my input images have variable dimensions. When I train the model I then also have to use flattened labels and sample_weight. I found the answer here.

http://stackoverflow.com/comment/81952577
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47498667
type: QuestionComment
has text: never post images of the dataset. print your dataframe instead in this case. as the empty rows will be read as NAs, you can just `df.dropna(how='all')`

http://stackoverflow.com/comment/81739074
comment on: http://stackoverflow.com/q/47385053
type: Comment
type: QuestionComment
score: 0
has text: And looking at it some more, the app looks like it's looping through the records, just not pulling the data properly, I think my issue is somewhere between return render_template('mongoreqs.html', title="Reqs in Mongo DB", reqs=reqs) and the {% for req in reqs %} {{ req["Question"] }} Job Apply Link I just can't figure out why.

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/47415844
tags question: http://stackoverflow.com/q/47500449
tags question: http://stackoverflow.com/q/47497851
tags question: http://stackoverflow.com/q/47529290
tags question: http://stackoverflow.com/q/47513066
tags question: http://stackoverflow.com/q/47391347
tags question: http://stackoverflow.com/q/47460003
tags question: http://stackoverflow.com/q/47446494
tags question: http://stackoverflow.com/q/47469063
tags question: http://stackoverflow.com/q/47460593
tags question: http://stackoverflow.com/q/47477753
tags question: http://stackoverflow.com/q/47433061
tags question: http://stackoverflow.com/q/47450075
tags question: http://stackoverflow.com/q/47475024
tags question: http://stackoverflow.com/q/47413104
tags question: http://stackoverflow.com/q/47502079
tags question: http://stackoverflow.com/q/47457279
tags question: http://stackoverflow.com/q/47515025
tags question: http://stackoverflow.com/q/47413977
tags question: http://stackoverflow.com/q/47502849
tags question: http://stackoverflow.com/q/47441239
tags question: http://stackoverflow.com/q/47397800
tags question: http://stackoverflow.com/q/47508553
tags question: http://stackoverflow.com/q/47502382
tags question: http://stackoverflow.com/q/47512227
tags question: http://stackoverflow.com/q/47401311
tags question: http://stackoverflow.com/q/47408551
tags question: http://stackoverflow.com/q/47421708
tags question: http://stackoverflow.com/q/47487498
tags question: http://stackoverflow.com/q/47527443
tags question: http://stackoverflow.com/q/47532710
tags question: http://stackoverflow.com/q/47434292
tags question: http://stackoverflow.com/q/47492533
tags question: http://stackoverflow.com/q/47445157
tags question: http://stackoverflow.com/q/47442632
tags question: http://stackoverflow.com/q/47536176
tags question: http://stackoverflow.com/q/47397809
tags question: http://stackoverflow.com/q/47447155
type: Tag
tags question: http://stackoverflow.com/q/47464900
tags question: http://stackoverflow.com/q/47507144
tags question: http://stackoverflow.com/q/47448560
tag name: html
tags question: http://stackoverflow.com/q/47386098
tags question: http://stackoverflow.com/q/47518719
tags question: http://stackoverflow.com/q/47510544
tags question: http://stackoverflow.com/q/47506812
tags question: http://stackoverflow.com/q/47521206
tags question: http://stackoverflow.com/q/47535356
tags question: http://stackoverflow.com/q/47466722
tags question: http://stackoverflow.com/q/47441408
tags question: http://stackoverflow.com/q/47386378
tags question: http://stackoverflow.com/q/47536858
tags question: http://stackoverflow.com/q/47514886
tags question: http://stackoverflow.com/q/47480741
tags question: http://stackoverflow.com/q/47449035
tags question: http://stackoverflow.com/q/47393670
tags question: http://stackoverflow.com/q/47532632
tags question: http://stackoverflow.com/q/47508168
tags question: http://stackoverflow.com/q/47464406
tags question: http://stackoverflow.com/q/47449354
tags question: http://stackoverflow.com/q/47487376
tags question: http://stackoverflow.com/q/47521451

http://stackoverflow.com/q/47481540
favorite count: 0
has comment: http://stackoverflow.com/comment/81922136
type: Question
has answer: http://stackoverflow.com/a/47484375
score: 6
tagged with: python
tagged with: kivy
upvote count: 6
tagged with: animated-gif
has comment: http://stackoverflow.com/comment/81918611
type: AnsweredQuestion
has body: I have this toggle button in kivy and I want it to animate on when pressed (it's a power on button gif) but without looping. I can't seem to find any useful information about this. Any help is appreciated, thanks!
tagged with: kivy-language
has comment: http://stackoverflow.com/comment/81917957
has title: How can I use an animated gif that will play when pressed as a button in kivy?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47484375

http://stackoverflow.com/q/47449741
tagged with: python
has answer: http://stackoverflow.com/a/47450246
tagged with: linechart
duplicate of: http://stackoverflow.com/q/7358118
has body: I am new in Python and I want to plot multiple lines in one graph like in the figure below. I have tried write simple plotting code like this: I know these parameters # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') But I have a lot of lines such in the first figure, what kind of parameters which I can use to plotting like the first figure. Thank you
score: 2
type: AnsweredQuestion
upvote count: 3
tagged with: plotly
duplicate of: http://stackoverflow.com/q/33936134
downvote count: 1
tagged with: plot
favorite count: 0
accepted answer: http://stackoverflow.com/a/47450185
has title: Plotting multiple lines in python
type: Question
linked to: http://stackoverflow.com/q/7358118
has answer: http://stackoverflow.com/a/47450185
possible better answer: http://stackoverflow.com/a/47450246
answer count: 2
tagged with: matplotlib

http://stackoverflow.com/comment/81856309
comment on: http://stackoverflow.com/q/47450744
has text: Show what you mean by "But if I change the dict in child process, the change will not affect the dict in parent process."
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47539227
has answer: http://stackoverflow.com/a/47539333
has body: So I'm trying to create a while loop so the user can choose whether they want to continue the program or not. Any suggestions? import random while True: print ("--------------------------------------------------------------------\n") name = input("Please enter your name: ") pack = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21] random.shuffle(pack) print ("Welcome {0}! Hope you have fun playing! \n".format(name)) print("Original deck:", pack, "\n") print ("--------------------------------------------------------------------\n") for i in range(3): pack1 = pack[::3] pack2 = pack[1::3] pack3 = pack[2::3] print("1: ", pack1, "\n") print("2: ", pack2, "\n") print("3: ", pack3, "\n") user = input("Pick a number and enter the row it is in: ") while not (user == "1" or user == "2" or user == "3"): print(user, " is not a valid answer. Please try again \n") user = input("Pick a number and enter the row it is in: ") if user == "1": pack = pack3 + pack1 + pack2 elif user == "2": pack = pack1 + pack2 + pack3 elif user == "3": pack = pack2 + pack3 + pack1 print("The number you are thinking of is:", pack[10], "\n") answer = input("Would you like to play again (y/n)? ") if answer != "y" or answer != "n": break print ("Please press 'y' or 'n' and then Enter... ") if answer == "y": continue else: print ("Thank you for playing!") break Just to bring in some context about what this is about, this is a 21 Cards Trick program. Try it out if you want. Edit: Also what's happening when the question at the end is asked is that it's not really restarting the program when you type 'y'.
possible better answer: http://stackoverflow.com/a/47539748
accepted answer: http://stackoverflow.com/a/47539333
has comment: http://stackoverflow.com/comment/82035428
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82036279
has comment: http://stackoverflow.com/comment/82035425
tagged with: python
has title: I need help in while loop for this program
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47539748

http://stackoverflow.com/comment/81799057
comment on: http://stackoverflow.com/a/47417227
type: Comment
has text: Investigate why the process gets killed :)
score: 0
type: AnswerComment

http://stackoverflow.com/a/47402410
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47402357
has comment: http://stackoverflow.com/comment/81758986
type: AcceptedAnswer
downvote count: 0
has body: You could use sort_values + drop_duplicates: df.sort_values(['Date']).drop_duplicates('Category', keep='first') Category Color Date 2 triangle blue 2017-02-10 3 circle yellow 2017-07-10 1 square yellow 2017-11-10 If you want to preserve the original order of Category, you'll need to sort on a groupby call: df.groupby('Category', group_keys=False, sort=False)\ .apply(lambda x: x.sort_values('Date'))\ .drop_duplicates('Category', keep='first') Category Color Date 2 triangle blue 2017-02-10 1 square yellow 2017-11-10 3 circle yellow 2017-07-10
type: Answer
has comment: http://stackoverflow.com/comment/81759208
accepted answer of: http://stackoverflow.com/q/47402357

http://stackoverflow.com/a/47472986
accepted answer of: http://stackoverflow.com/q/47472878
type: AcceptedAnswer
downvote count: 0
has body: df = pd.DataFrame({'date':['00:02.0','00:05:0','00:08.1']}) print (df) date 0 00:02.0 1 00:05:0 2 00:08.1 It is possible convert to datetime: df['date'] = pd.to_datetime(df['date'], format='%M:%S.%f') print (df) date 0 1900-01-01 00:00:02.000 1 1900-01-01 00:00:05.000 2 1900-01-01 00:00:08.100 Or to timedeltas: df['date'] = pd.to_timedelta(df['date'].radd('00:')) print (df) date 0 00:00:02 1 00:00:05 2 00:00:08.100000 EDIT: For custom date use: date = '2015-01-04' td = pd.to_datetime(date) - pd.to_datetime('1900-01-01') df['date'] = pd.to_datetime(df['date'], format='%M:%S.%f') + td print (df) date 0 2015-01-04 00:00:02.000 1 2015-01-04 00:00:05.000 2 2015-01-04 00:00:08.100
answers question: http://stackoverflow.com/q/47472878
has comment: http://stackoverflow.com/comment/81900880
has comment: http://stackoverflow.com/comment/81901328
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/81901473
upvote count: 4
has comment: http://stackoverflow.com/comment/81901184

http://stackoverflow.com/q/47482115
has comment: http://stackoverflow.com/comment/81919129
has answer: http://stackoverflow.com/a/47482147
accepted answer: http://stackoverflow.com/a/47482147
answer count: 1
type: Question
tagged with: python-3.x
has body: class Drinks: def __init__(self): self.drink = ['Coke'] self.count = 0 self.alcohol_level = [1] def main(): Drinks().alcohol_level.append(89) I want to append to the level list, not quite sure how to go about it. What I've tried is: Drinks().alcohol_level.append(89) But that's obviously not correct. Any help is appreciated. Thanks!
has comment: http://stackoverflow.com/comment/81919113
has comment: http://stackoverflow.com/comment/81919082
has comment: http://stackoverflow.com/comment/81919142
has comment: http://stackoverflow.com/comment/81919103
tagged with: python
has comment: http://stackoverflow.com/comment/81919102
type: AnsweredQuestion
has title: Appending Item to list in a Class
score: 0

http://stackoverflow.com/q/47443880
type: AnsweredQuestion
tagged with: keras-layer
has answer: http://stackoverflow.com/a/47517447
answer count: 1
downvote count: 0
upvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
score: 1
tagged with: python
tagged with: keras-2
has body: I have a weighted sparse_categorical_crossentropy loss which is not working after updating to Keras 2.1.1. The previous version I was using was 2.0.6, and it was working fine then. There are 2 classes (0 and 1) in the Output Layer. I pass the flattened 1D array with an extra dimension as the label. label = label.flatten().astype(np.int16) label = np.expand_dims(label, axis=-1) If I call sparse_categorical_crossentropy directly then there are no errors shown and the training starts. To verify that there was nothing wrong in the way custom weighted loss function should be called, I copied the sparse_categorical_crossentropy from keras/backend/tensorflow_backend.py, renamed it to scc and assigned it to the loss function. // default net.model.compile(optimizer=Adam(lr=0.001), loss=sparse_categorical_crossentropy) // scc is just a copy of sparse_categorical_crossentropy from tensorflow_backend net.model.compile(optimizer=Adam(lr=0.001), loss=scc) This gives the following error: ValueError: Error when checking target: expected mask to have shape (None, 4096, 2) but got array with shape (8, 4096, 1) If I change the label to One-Hot encoding format to correspond to the 2 labels, then tensorflow throws an error as shown below: label = np.hstack((label, (~label.astype(bool)).astype(int))) W tensorflow/core/framework/op_kernel.cc:1192] Invalid argument: logits and labels must have the same first dimension, got logits shape [32768,2] and labels shape [65536] Any idea what I am doing wrong ?
has title: Dimension error with sparse_categorical_crossentropy
accepted answer: http://stackoverflow.com/a/47517447

instrumentation
type: Tag
tags question: http://stackoverflow.com/q/47537565
tag name: instrumentation

http://stackoverflow.com/comment/81850421
has text: as suggested, mean of accuracy is a good metric or as it is called, k-fold cross-validation. More on it [here](http://scikit-learn.org/stable/modules/cross_validation.html).
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47437478

http://stackoverflow.com/comment/102870653
type: Comment
has text: Instead of overriding the whole template, you can override just the `{% block object-tools-items %}`, although it has the "absolute url" part also.
type: AnswerComment
comment on: http://stackoverflow.com/a/47496191
score: 0

http://stackoverflow.com/comment/96963948
has text: `if getch() in [KEY_BACKSPACE, ord('\b')]` works for me
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47482113
type: Comment

http://stackoverflow.com/q/47403874
score: 2
has answer: http://stackoverflow.com/a/47403955
answer count: 3
has body: I'm new to Python and programming and am having trouble installing zlib through pip, I keep having the issue below: pip install zlib Collecting zlib Could not find a version that satisfies the requirement zlib (from versions: ) No matching distribution found for zlib
downvote count: 0
favorite count: 0
type: Question
tagged with: zlib
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63668845
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/74648721
has title: Pip error when trying to install zlib
has comment: http://stackoverflow.com/comment/81761522

http://stackoverflow.com/q/47407478
tagged with: class
type: AnsweredQuestion
tagged with: oop
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47409425
upvote count: 1
has title: I am learning objects and classes in python and i've tried to write a program which requires me print features of animals at different ladder rungs
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: object
has body: There is a ladder. On the 3rd rung of the ladder is a monkey, the 5th rung has a squirrel, the 8th rung has a pigeon, the 15th rung has an eagle, the 17th rung has another monkey. The monkey has 2 eyes, 2 hands, 2 legs. The squirrel has 2 eyes, 4 legs. The pigeon has 2 eyes, 2 wings, 2 legs and can fly. The eagle has 2 eyes, 2 wings, 2 legs and can fly. I have divided the code into two modules ladder-user and ladderutils ladder-user.py To print animal features from ladderutils import ladder l = ladder() print (l.animal_at_rung(3)) print (l.animal_at_rung(5)) print (l.animal_at_rung(8)) print (l.animal_at_rung(15)) print (l.animal_at_rung(10)) print (l.get_animals_count()) print (l.animal_at_rung(3) == l.animal_at_rung(17)) print (type(l.animal_at_rung(3)) == type(l.animal_at_rung(17))) print (l.animal_at_rung(8).fly()) print (l.animal_at_rung(3).fly()) print (l.hop(3)) print (l.animal_at_rung(3)) print (l.animal_at_rung(4)) print (l.hop(4)) print (l.animal_at_rung(4)) ladderutils.py class Animal(object): features= {} def __init__(self,eyes,legs,hands,wings,fly): self.features['eyes'] = eyes self.features['legs'] = legs self.features['hands'] = hands self.features['wings'] = wings self.features['fly'] = fly def fly(self): return self.features['fly'] class Monkey(Animal): def __init__(self,eyes,legs,hands): self.name = 'Monkey' Animal.__init__(self,eyes,legs,hands,0,False) def __repr__(self): temp = {} for key in self.features: if(self.features[key]&gt;0 and self.features[key]!=False): temp[key] = self.features[key] return str({self.name:temp}) class Squirrel(Animal): def __init__(self,eyes,legs): self.name = 'Squirrel' Animal.__init__(self,eyes,legs,0,0,False) def __repr__(self): temp = {} for key in self.features: if(self.features[key]&gt;0 or self.features[key]!=False): temp[key] = self.features[key] return str({self.name:temp}) class Pigeon(Animal): def __init__(self,eyes,legs,wings): self.name = 'Pigeon' Animal.__init__(self,eyes,legs,0,wings,True) def __repr__(s…
accepted answer: http://stackoverflow.com/a/47409425
tagged with: python
score: -1

http://stackoverflow.com/comment/81870149
type: QuestionComment
has text: should I just put all the code back in then?
comment on: http://stackoverflow.com/q/47457768
score: 0
type: Comment

http://stackoverflow.com/q/47498863
has comment: http://stackoverflow.com/comment/81953139
favorite count: 0
tagged with: unit-testing
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81952919
has comment: http://stackoverflow.com/comment/81953028
has comment: http://stackoverflow.com/comment/81953389
tagged with: python
has title: python unittests on string form functions
answer count: 0
has comment: http://stackoverflow.com/comment/81952972
score: 1
has comment: http://stackoverflow.com/comment/81953377
downvote count: 0
tagged with: python-unittest
upvote count: 1
has body: In my case, I'm getting the function the student submitted through an online course website in text form. for example, my input will get payload['content'] = ''' def my_func(a): return a + 1 ''' in normal scenario, I would run import my_func assert 2, my_func(1) how would go about solving this?

resolution
tag name: resolution
tags question: http://stackoverflow.com/q/47493042
type: Tag

http://stackoverflow.com/q/47537614
has answer: http://stackoverflow.com/a/47537926
score: 0
answer count: 2
tagged with: pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82032095
upvote count: 1
has body: I am trying to find a shortcut to assigning a pandas series from elements in a list. My code: import pandas as pd df=pd.DataFrame([[1,2,2183],[1,4,2235],[2,3,6123],[3,4,4213]],columns=['month','staff','sales']) goals=[1346,4456,4574] df['goals']=goals[df['month']-1] The last line throws an error: TypeError: list indices must be integers or slices, not Series Desired output looks like this: month staff sales goals 0 1 2 2183 1346 1 1 4 2235 1346 2 2 3 6123 4456 3 3 3 4213 4574 This is a general case, and in the future, the goals array might actually be multidimensional.
favorite count: 0
type: Question
has title: Using Pandas series values as index for assigning values to another series
has comment: http://stackoverflow.com/comment/93507584
has answer: http://stackoverflow.com/a/47537710
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/82032149

http://stackoverflow.com/comment/81916967
has text: @Abdou ValueError: DataFrame constructor not properly called!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47480961

http://stackoverflow.com/comment/81803689
type: Comment
has text: Can you provide a sample input of `word` and a sample input of `lines`?
type: QuestionComment
comment on: http://stackoverflow.com/q/47423582
score: 0

http://stackoverflow.com/a/47539575
accepted answer of: http://stackoverflow.com/q/47538974
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47538974
score: 1
type: Answer
has body: There is few problem with this page element is inside &lt;iframe&gt; so you have to find &lt;iframe&gt; and switch_to_frame() before you can search element &lt;iframe&gt; is in external &lt;iframe&gt; so first you have to find external &lt;iframe&gt; and switch_to_frame() before you start to searching internal &lt;iframe&gt; on small monitor element is invisible so Selenium can click it. You have to scroll page to element and then you can click it. . from selenium import webdriver browser = webdriver.Chrome() #'/usr/local/bin/chromedriver') browser.get('https://www.facebook.com/SparColruytGroup/app/300001396778554?app_data=DD722A43-C774-FC01-8823-8016BFF8F0D0') browser.implicitly_wait(5) iframe = browser.find_element_by_css_selector('#pagelet_app_runner iframe') browser.switch_to_frame(iframe) iframe = browser.find_element_by_css_selector('#qualifio_insert_place iframe') browser.switch_to_frame(iframe) button = browser.find_element_by_css_selector('#softGateBox &gt; div.button_softgate &gt; a') browser.execute_script("arguments[0].scrollIntoView(true);", button) button.click() BTW: There can be other &lt;iframe&gt; on page so you can't direclty do selector('iframe'). Internal frame have id but it changes every time you load page so you can't do selector('iframe#some_uniqe_id')

http://stackoverflow.com/q/47405813
tagged with: python
has comment: http://stackoverflow.com/comment/81765610
favorite count: 0
has comment: http://stackoverflow.com/comment/81766224
has comment: http://stackoverflow.com/comment/81768029
score: 0
has comment: http://stackoverflow.com/comment/81765105
has comment: http://stackoverflow.com/comment/81766256
answer count: 0
tagged with: alpine-linux
upvote count: 1
tagged with: pip
has title: Alpine OS 'pip install cryptography' was hanging several minutes and gave me nothing in return
type: UnansweredQuestion
downvote count: 1
linked to: http://stackoverflow.com/q/22073516
tagged with: linux
has comment: http://stackoverflow.com/comment/81765426
type: Question
has body: When I try to run &gt;&gt;&gt; pip install cryptography It hanging for several minutes so as I can go though setup.py is actually missing so how do i get it back? Thanks!
has comment: http://stackoverflow.com/comment/81766011
has comment: http://stackoverflow.com/comment/81767565

http://stackoverflow.com/a/47445634
has body: You can use itertext() to iterate over all text fields, even those inside nested elements (or on the tail of an enclosed element, as here): for l in root.iter('l'): file.write(''.join(l.itertext()) + "\n")
score: 0
answers question: http://stackoverflow.com/q/47445236
has comment: http://stackoverflow.com/comment/81848993
type: Answer
accepted answer of: http://stackoverflow.com/q/47445236
type: AcceptedAnswer

http://stackoverflow.com/q/47405191
has body: I am trying to make an MD5 password cracker using a wordlist. The MD5 hashes I am comparing with have been obtained from the HTML of a website that I have been tasked to gather information from. So far I have successfully gathered the MD5 hashes and I have obtained a word list that I loop through and successfully create hashes of. However, when trying to compare it with the hashes that I currently have it only finds one results (even though I know it is four). I could be doing something incredibly stupid, but would like some suggestions. def FindandCrackHash(content): # Find hashes attempt = 0 contentHash = content hashList = [] crackedHashes = [] contentHash = re.findall(r'[A-Fa-f0-9]{32}', contentHash.decode()) for h in contentHash: h = h.lower() hashList.append(h) print('') print(f'[+] {len(hashList)} MD5 Hashes Found:') for hashes in hashList: print(f'"{hashes}"') with open("C:\\Users\\Rory Gracey\\Desktop\\Napier CourseWork 2\\rockyou1.txt", 'r') as wordList: for line in wordList: md5Hash = hashlib.md5(line.encode('utf-8')) hashToCompare = md5Hash.hexdigest() compHash = str(hashToCompare) print(line) if compHash in hashList else None [+] 4 MD5 Hashes Found: "fea0f1f6fede90bd0a925b4194deac11" "d1133275ee2118be63a577af759fc052" "5badcaf789d3d1d09794d8f021f40f0e" "5fcfd41e547a12215b173ff47fdd3739" trustno1 This is what I have currently got. Any help would be much appreciated. CHEERS!
upvote count: 1
tagged with: passwords
has comment: http://stackoverflow.com/comment/81764188
score: 1
tagged with: python
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81764258
has title: Python File Read Error
tagged with: md5
downvote count: 0

http://stackoverflow.com/q/47496557
tagged with: addition
answer count: 1
tagged with: file
has body: I am trying to add two matrices from a text file that contains this: [[0,1,2],[9,8,7]] [[6,5,4],[3,4,5]] I have this code: def addition(filename): a=[] b=[] with open(filename, 'r') as myfile: data=myfile.read().split() a=data[0].split() b=data[1].split() a=a[0] b=b[0] print (a) sum = [] for i in range(len(a)): print (i) c = [] for j in range(len(a[0])): c.append(a[i][j]+b[i][j]) sum.append(c) return sum But it outputs: [['[['], ['[['], ['06'], [',,'], ['15'], [',,'], ['24'], [']]'], [',,'], ['[['], ['93'], [',,'], ['84'], [',,'], ['75'], [']]'], [']]']] Instead of: [[6,6,6],[12,12,12]] Any idea how I can fix this? Thanks!
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47496738
accepted answer: http://stackoverflow.com/a/47496738
type: AnsweredQuestion
tagged with: matrix
tagged with: python
has title: Add Two Matrix From A Text File (Python w/o Modules)
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/81918852
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47464112
type: AnswerComment
has text: So I have list of object type tuples as (a,b) where 'a' is float32 type 2D array(782,1) and 'b' is int type 2D array (10,1) where b[5] = 1 if the number is 5 in mnist. How do I preprocess this data type?

http://stackoverflow.com/comment/81889989
type: QuestionComment
has text: You need to first create a `Canvas` `window` object to put in it. [Here's](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_window.html) a little documentation.
score: 0
comment on: http://stackoverflow.com/q/47466995
type: Comment

key
tags question: http://stackoverflow.com/q/47438468
tags question: http://stackoverflow.com/q/47402759
tags question: http://stackoverflow.com/q/47411649
type: Tag
tags question: http://stackoverflow.com/q/47492688
tag name: key

http://stackoverflow.com/comment/81920125
has text: And shame on them for presenting tabular data as ` ` text.
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47482620
type: Comment

http://stackoverflow.com/comment/83137692
score: 0
has text: Thank you for trying @ryguy72
type: AnswerComment
comment on: http://stackoverflow.com/a/47838532
type: Comment

http://stackoverflow.com/a/47460410
score: 0
has body: You cant import A from A because you don't have A. if A is in Derived use: from Derived import A
type: Answer
answers question: http://stackoverflow.com/q/47460326

http://stackoverflow.com/q/47392589
has body: I have written a python code using opencv to detect a rectangle (displaying height, and width) also determine the distance from camera to the object but when i run the code i get this error(can be found below) i don't know what am doing wrong please i would appreciate it if anyone could help me out i have tried every possible solution that i could find but still can't rid of the error. ERROR yuv_red = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV) error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\imgproc\src\color.cpp:8059: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor import sys sys.path.append('C:\Python27\Lib\site-packages') import cv2 import numpy as np import argparse import math ############################# Capturing Video Through Camera ######################## cap = cv2.VideoCapture(0) ############# Distance to Camera initial value set to zero ########################## Distance_to_Camera=0 while(True): ################################# Capture frame-by-frame ########################### ret, frame = cap.read() ############################ Converting frame(img i.e BGR to YUV) ################### yuv_red = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV) red_color = np.uint8([[[0,0,255]]]) yuv_color = cv2.cvtColor(red_color,cv2.COLOR_BGR2YUV) print yuv_color ############################### Processing of Image ############################## ##################### Defining the Range of Red Colour ########################### red_lower = np.array([136,87,111],np.uint8) red_upper = np.array([180,255,255],np.uint8) ##################### Finding the Range of Red Colour in the image ################### mask = cv2.inRange(yuv_red, red_lower,red_upper) ####################### Morphological Transformation, Dilation ####################### res = cv2.bitwise_and(frame, frame, mask = mask) ##################################################################################### gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY) #Converting the BGR res to Gray blurred…
tagged with: opencv
has comment: http://stackoverflow.com/comment/81738530
score: 0
answer count: 1
has title: using Opencv python2.7 to detect a rectangle
type: Question
has answer: http://stackoverflow.com/a/47403541
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81750635
tagged with: python

http://stackoverflow.com/comment/82028186
comment on: http://stackoverflow.com/a/47535485
has text: you did it, absolutely beautiful solution and it worked perfectly. cheers
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47390071
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47388580
downvote count: 0
has comment: http://stackoverflow.com/comment/81764472
type: Answer
has body: You're using the grouping operator in the first example, it is the parenthesis. $ python -c 's=(""" hello world """ "Addendum: Long " "Line Here Is Broken Yet Continued.") print(s)' hello world Addendum: Long Line Here Is Broken Yet Continued.
accepted answer of: http://stackoverflow.com/q/47388580
score: 2

http://stackoverflow.com/comment/81946947
score: 0
has text: better in what aspect? how are you thinking to improve?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47494314

http://stackoverflow.com/comment/81910653
type: AnswerComment
comment on: http://stackoverflow.com/a/47476865
has text: It indeed worked fine, and including this last step it took 0.0020 seconds on the example. However I will keep @gboffi 's suggestion in the EDIT as it was twice faster. Still a very interesting solution, I learned something new, so thanks again!
type: Comment
score: 0

http://stackoverflow.com/comment/82031364
comment on: http://stackoverflow.com/q/47537014
has text: Each record is obtained from a stream of data that contains 10s of millions of records.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47408409
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47407537
accepted answer of: http://stackoverflow.com/q/47407537
type: Answer
has body: MongoDB returns a BSON (not a JSON) document, so actually you want to convert a BSON document into JSON document. Try to take a look into this artickle: https://technobeans.com/2012/09/10/mongodb-convert-bson-to-json/

http://stackoverflow.com/a/47457931
has comment: http://stackoverflow.com/comment/81870821
has comment: http://stackoverflow.com/comment/81893070
accepted answer of: http://stackoverflow.com/q/47457886
has body: I believe you need filter by masks and assign back: data = pd.DataFrame({'a':list('aaaddd'), 'Sex':['female','female','male','female','female','male'], 'Pclass':[1,2,1,2,1,1], 'Age':[40,20,30,20,np.nan,np.nan]}) print (data) Age Pclass Sex a 0 40.0 1 female a 1 20.0 2 female a 2 30.0 1 male a 3 20.0 2 female d 4 NaN 1 female d 5 NaN 1 male d #boolean mask mask1 = (data['Sex'] == 'female')&amp;(data['Pclass'] == 1) #get median by mask without NaNs med = data.loc[mask1, 'Age'].median() print (med) 40.0 #repalce NaNs data.loc[mask1, 'Age'] = data.loc[mask1, 'Age'].fillna(med) print (data) Age Pclass Sex a 0 40.0 1 female a 1 20.0 2 female a 2 30.0 1 male a 3 20.0 2 female d 4 40.0 1 female d 5 NaN 1 male d What is same as: mask2 = mask1 &amp;(data['Age'].isnull()) data.loc[mask2, 'Age'] = med print (data) Age Pclass Sex a 0 40.0 1 female a 1 20.0 2 female a 2 30.0 1 male a 3 20.0 2 female d 4 40.0 1 female d 5 NaN 1 male d EDIT: If need replace all groups NaNs by median: data['Age'] = data.groupby(["Sex","Pclass"])["Age"].apply(lambda x: x.fillna(x.median())) print (data) Age Pclass Sex a 0 40.0 1 female a 1 20.0 2 female a 2 30.0 1 male a 3 20.0 2 female d 4 40.0 1 female d 5 30.0 1 male d
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/81871206
type: Answer
answers question: http://stackoverflow.com/q/47457886
upvote count: 6

http://stackoverflow.com/comment/81939062
has text: yes , same size always and the pixel color will be the differentiator
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47491861
score: 0

http://stackoverflow.com/comment/81887549
score: 0
comment on: http://stackoverflow.com/a/47466500
type: AnswerComment
has text: itertools.count is kind of overpowered here -- wouldn't `enumerate` work too? My first thought was something like `dict(enumerate((v for d in dd for k,v in sorted(d.items())), 1))`.
type: Comment

http://stackoverflow.com/q/47450259
accepted answer: http://stackoverflow.com/a/47450314
has answer: http://stackoverflow.com/a/47450314
type: AnsweredQuestion
score: 4
possible better answer: http://stackoverflow.com/a/47450436
has title: merge row with next row in dataframe pandas
tagged with: pandas
has body: I have a dataframe in pandas which contains multiple columns. I want to merge every row with the next row. Example: input dataframe: A B C a1 a2 a3 b1 b2 b3 c1 c1 c3 d1 d2 d3 output dataframe: A1 B1 C1 A2 B2 C2 a1 a2 a3 b1 b2 b3 b1 b2 b3 c1 c2 c3 c1 c2 c3 d1 d2 d3 d1 d2 d3 NaN NaN NaN The solusion I came up with was copying the original dataframe, changing the index to be index - 1, and then merging the two data frames by index. Is there any other solution?
tagged with: dataframe
tagged with: rows
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/47450436
downvote count: 0
tagged with: python
tagged with: merge

http://stackoverflow.com/comment/81963758
type: AnswerComment
score: 0
has text: sorry i forgot to mention that my version 3.6
type: Comment
comment on: http://stackoverflow.com/a/47503970

http://stackoverflow.com/comment/81906038
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47457276
has text: Okay I'm stuck, I want to put the information in Columns in an excel file, so fileAssetId Filename Id the found FileAssettID in one column. the filename in another column and id in the next in order... etc I've also discovered Id shows up on other objects so i need Id only to show up AFTER filename has been found, any ideas?

http://stackoverflow.com/q/47478800
tagged with: seaborn
has answer: http://stackoverflow.com/a/47480250
accepted answer: http://stackoverflow.com/a/47480250
answer count: 1
downvote count: 0
tagged with: python
has title: How to retrieve error bar in seaborn
type: AnsweredQuestion
upvote count: 3
score: 3
has body: I've plot a barplot in seaborn using the follow function: ax = sns.barplot(x='Year', y='Value', data=df) Now I'd like to color each bar according to the following rule: percentages = [] for bar, yerr_ in zip(bars, yerr): low = bar.get_height() - yerr_ high = bar.get_height() + yerr_ percentage = (high-threshold)/(high-low) if percentage&gt;1: percentage = 1 if percentage&lt;0: percentage = 0 percentages.append(percentage) I believe I can access the bars through ax.patches, which returns a set of rectangles: for p in ax.patches: height = p.get_height() print(p) &gt;&gt; Rectangle(-0.4,0;0.8x33312.1) &gt;&gt; Rectangle(0.6,0;0.8x41861.9) &gt;&gt; Rectangle(1.6,0;0.8x39493.3) &gt;&gt; Rectangle(2.6,0;0.8x47743.6) However, I don't know how to retrieve the yerr data calculated by seaborn/matplotlib.
tagged with: matplotlib
favorite count: 0
type: Question

http://stackoverflow.com/q/47491750
has comment: http://stackoverflow.com/comment/81941109
tagged with: ubuntu
tagged with: flask
score: 0
has title: Python Flask not working properly on Bash on Ubuntu on Windows
has comment: http://stackoverflow.com/comment/81939644
tagged with: windows
has body: I am trying to run a flask app on my Windows 10 laptop through Bash on Ubunutu on Windows, but I am getting the following error: None Traceback (most recent call last): File "app.py", line 126, in app.run(debug=True) #Deubug is set to true File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 841, in run run_simple(host, port, self, **options) File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 720, in run_simple s.bind((hostname, port)) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 13] Permission denied I am not trying to run a restricted port. It should be on port 5000. Here are the commands I ran: sudo apt-get install python-pip sudo pip install Flask sudo pip install flask-bootstrap sudo pip install bokeh python app.py Whenever Flask was installed, I got back a warning: The directory '/home/User/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/User/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Also, running sudo python app.py does not help either. Any thoughts on what is happening?
tagged with: python
tagged with: windows-subsystem-for-linux
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47517979
has body: I have written code for two string combinations by one letter at the time: def stringCombination( string1, string2, fillValue = filler): filler = string2[-1] if len(string1) &gt; len(string2) else string[-1] return "".join(i for j in itertools.zip_longest(string1, string2, fillValue = filler) for i in j) I get error filler is not defined. Tried every possible solution but I cannot make it work. Help would be very nice. Working code should do: Input: home, car Output: hcoamre If one string is longer= car+home=ch ao rme
has comment: http://stackoverflow.com/comment/81992940
has comment: http://stackoverflow.com/comment/81992852
has title: Combining two string by one letter at the time
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81992221
upvote count: 0
has comment: http://stackoverflow.com/comment/81992370
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/47519195
has comment: http://stackoverflow.com/comment/81992692
favorite count: 0
tagged with: python-3.x
type: Question
possible better answer: http://stackoverflow.com/a/47519195
has comment: http://stackoverflow.com/comment/81992349
accepted answer: http://stackoverflow.com/a/47518412
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/47518412

http://stackoverflow.com/a/47512932
has body: You don't need to teach NERDCommenter about Python; it already knows that the comment prefix is # (and if it didn't, it falls back to Vim's 'commentstring' option, which also knows about Python). If that does not work, it looks as if your plugin installation is broken. The remapping is described under :help NERDComMappings. That remapping would be: map &lt;Leader&gt;c &lt;Plug&gt;NERDCommenterComment As the other NERDCommenter mappings start with &lt;Leader&gt;c, I would advise against this. As Vim cannot tell whether the mapping is done or you'll keep typing, there will be a delay until the mapping applies. Only way to get rid of that is remapping / deleting all other NERDCommenter mappings. Because of the timeout, the default &lt;Leader&gt;cc is actually faster to execute than what you have in mind.
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47484428

http://stackoverflow.com/q/47509233
tagged with: python
tagged with: sorting
has body: I have a given Array: A = [9, 8, 7, 6, 5, 4] I am implementing count-sort algorithm to sort this array in Python. The numbers in the array are always in the range N. I got the count of each element and sorting of the list. count = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1] sorted = [4, 5, 6, 7, 8, 9] Now, I want to output the count of each element: For eg: 4 1 5 1 6 1 7 1 8 1 9 1 How do I compare those to lists [count &amp; array]? Code: N = int(input()) A = list(map(int, input().split(" "))) print(A) m = N + 1 count = [0] * m for a in A: # count occurences count[a] += 1 print(count) i = 0 for a in range(m): for c in range(count[a]): A[i] = a i += 1 print(A, count) print([i,j for i,j in zip(A,count)]) I tried to zip, but it didn't work out well. How should I do it?
has comment: http://stackoverflow.com/comment/81974360
duplicate of: http://stackoverflow.com/q/2161752
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: compare
has title: Python: returning a pair of each number and its frequency in given array using count-sorting algorithm
answer count: 1
has comment: http://stackoverflow.com/comment/81974467
type: Question
accepted answer: http://stackoverflow.com/a/47509337
linked to: http://stackoverflow.com/q/2161752
has answer: http://stackoverflow.com/a/47509337

http://stackoverflow.com/comment/81751180
score: 0
type: Comment
type: QuestionComment
has text: @RobbieMilejczak right, well, my point is that the OP should be *precise*, since taken at face value, that is not what they are asking. I made the comment about `numpy` because this doesn't seem like a good use case for `numpy`, i.e. the use of strings.
comment on: http://stackoverflow.com/q/47398885

http://stackoverflow.com/comment/81832772
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47438971
score: 0
has text: Thanks for your tips, Ajith. The loaded dataset actually was split into training and test. As a result, I would like to load a new dataset and let the program predicts the news category.

google-chrome-extension
tags question: http://stackoverflow.com/q/47414575
tag name: google-chrome-extension
type: Tag
tags question: http://stackoverflow.com/q/47450002

http://stackoverflow.com/q/47518944
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81994781
has comment: http://stackoverflow.com/comment/81994143
upvote count: 9
possible better answer: http://stackoverflow.com/a/53136725
has body: I'm trying to write a script that opens a new terminal then runs a separate python script from that terminal. I've tried: os.system("gnome-terminal 'python f.py'") and p = Popen("/usr/bin/gnome-terminal", stdin=PIPE) p.communicate("python f.py") but both methods only open a new terminal and do not run f.py. How would I go about opening the terminal AND running a separate script? Edit: I would like to open a new terminal window because f.py is a simply server that is running serve_forever(). I'd like the original terminal window to stay "free" to run other commands.
has answer: http://stackoverflow.com/a/53136725
linked to: http://stackoverflow.com/q/89228
has answer: http://stackoverflow.com/a/69875728
has comment: http://stackoverflow.com/comment/81994092
favorite count: 0
score: 9
type: Question
has comment: http://stackoverflow.com/comment/81994395
has answer: http://stackoverflow.com/a/49587570
has title: Open new gnome-terminal and run command
accepted answer: http://stackoverflow.com/a/47519018
downvote count: 0
has comment: http://stackoverflow.com/comment/81994484
has answer: http://stackoverflow.com/a/47519018
has answer: http://stackoverflow.com/a/47519082
has comment: http://stackoverflow.com/comment/81994110
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/78603903

http://stackoverflow.com/comment/82209201
comment on: http://stackoverflow.com/a/47503462
score: 0
type: AnswerComment
has text: Create a question by showing your code and pointing out your error or error message, please make the code comply with be [mcve]
type: Comment

http://stackoverflow.com/a/47467023
has body: If Python is interpreted, what are .pyc files? Pyc files will be created when you import (and use) a python module. You might want to add an entry into .gitignore to ignore these files, while clearing all pyc files from your project.
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47466982
type: Answer

http://stackoverflow.com/q/47434724
has answer: http://stackoverflow.com/a/47434793
has comment: http://stackoverflow.com/comment/81824540
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81824400
has comment: http://stackoverflow.com/comment/81824685
has comment: http://stackoverflow.com/comment/81823611
has comment: http://stackoverflow.com/comment/81824907
has answer: http://stackoverflow.com/a/47434862
has comment: http://stackoverflow.com/comment/81824731
tagged with: python
downvote count: 1
score: 15
upvote count: 16
has comment: http://stackoverflow.com/comment/81824367
has body: Is there a python built-in (or just optimized) function to get the floor division and remainder at the same time in two separate variables? Example: a, b = 10 divided by 4 Desired results: a = 2 b = 2 I need this to be an optimized solution. Performance results: First piece of code: for i in range(10000000): a, b = divmod(i, 5) took 3.99 seconds to run Second piece of code: for i in range(10000000): a = i // 5 b = i % 5 took 2.56 seconds to run Remarks: Read @casevh answer for a more detailed explanation. tldr: divmod() works better if numbers are big.
tagged with: optimization
possible better answer: http://stackoverflow.com/a/47443579
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81824500
answer count: 3
has answer: http://stackoverflow.com/a/47443579
has comment: http://stackoverflow.com/comment/81824883
has comment: http://stackoverflow.com/comment/81825012
has comment: http://stackoverflow.com/comment/81824303
has comment: http://stackoverflow.com/comment/81823796
accepted answer: http://stackoverflow.com/a/47434793
has comment: http://stackoverflow.com/comment/81824301
has comment: http://stackoverflow.com/comment/81824964
has comment: http://stackoverflow.com/comment/81824435
has title: Getting Floor Division and Remainder at same time in 2 separate variables

http://stackoverflow.com/q/47385646
answer count: 2
has answer: http://stackoverflow.com/a/47385715
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/81724272
has answer: http://stackoverflow.com/a/47385693
favorite count: 0
linked to: http://stackoverflow.com/q/42271279
has comment: http://stackoverflow.com/comment/81724283
type: Question
has body: If I have a list, say list = [abc are all letters, elephants, bananas are yellow, apples are fruits] or something of that sort, how would I count the number of times the word 'are' shows up in this list?
type: UnansweredQuestion
has title: Python- How to count the number of occurrences of a partial string in a list of strings
duplicate of: http://stackoverflow.com/q/42271279
tagged with: python
score: -1

http://stackoverflow.com/q/47393251
has answer: http://stackoverflow.com/a/47394082
accepted answer: http://stackoverflow.com/a/47394082
tagged with: python
has body: Could someone explain why the following code generates the output of array([ 0.59813887, 0.69314718], dtype=float32) ? For example, numpy.log(0.5) = 0.69314718, but how does the 0.598138 come from ? import tensorflow as tf res1 = tf.nn.sparse_softmax_cross_entropy_with_logits(_sentinel=None, labels=[1, 0], logits=[[0.4, 0.6], [0.5, 0.5]], name=None) res2 = tf.nn.sparse_softmax_cross_entropy_with_logits(_sentinel=None, labels=[0, 1], logits=[[0.4, 0.6], [0.5, 0.5]], name=None) res3 = tf.nn.sparse_softmax_cross_entropy_with_logits(_sentinel=None, labels=[1, 0], logits=[[0.6, 0.4], [0.5, 0.5]], name=None) sess = tf.Session() sess.run(res1)
type: AnsweredQuestion
score: 0
tagged with: cross-entropy
tagged with: deep-learning
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/47394544
has title: understanding tensor flow function output
answer count: 2
possible better answer: http://stackoverflow.com/a/47394544

http://stackoverflow.com/comment/81733081
comment on: http://stackoverflow.com/a/47389858
type: Comment
type: AnswerComment
has text: @Eypros: I state at the top of my answer: *The library simply generates the exact same destination name*
score: 0

http://stackoverflow.com/comment/81755549
type: AnswerComment
has text: @COLDSPEED, Where is yours?
type: Comment
comment on: http://stackoverflow.com/a/47400962
score: 0

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/47397323

http://stackoverflow.com/q/47538974
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47539575
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/82035148
has comment: http://stackoverflow.com/comment/82035037
type: AnsweredQuestion
has title: Python: Unable to locate element: selector
has comment: http://stackoverflow.com/comment/82035065
has comment: http://stackoverflow.com/comment/82034920
tagged with: python
has body: I try to open a browser and click on a button by using a python script My code: from selenium import webdriver browser = webdriver.Chrome('/usr/local/bin/chromedriver') browser.get('xxx') browser.implicitly_wait(5) button = browser.find_element_by_css_selector('#softGateBox &gt; div.button_softgate &gt; a') button.click() The website opens. It waits 5 seconds and then I see the error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#softGateBox &gt; div.button_softgate &gt; a"} What can be wrong? I use chrome to inspect the button and I perform a right click and click copy selector.
type: Question
has comment: http://stackoverflow.com/comment/82035358
accepted answer: http://stackoverflow.com/a/47539575
has comment: http://stackoverflow.com/comment/82034866

http://stackoverflow.com/q/47391421
has comment: http://stackoverflow.com/comment/81750731
has body: UPDATE (TO SHOW FINAL CODE) Since this seemed hard to explain, I shared the project. For those that come to this question, you can see the full project here: https://github.com/jeffnyman/pacumen Calling out the files that were problematic for me: graphical_pacman https://github.com/jeffnyman/pacumen/blob/master/displays/graphical_pacman.py layout https://github.com/jeffnyman/pacumen/blob/master/mechanics/layout.py With the __init__.py and setup.py files in place, I'm now able to run commands like these: python displays/graphical_pacman.py python mechanics/layout.py All imports now resolve correctly when those commands are executed. You can see all the import statements I use in each file and the placement of the various __init__.py files. ORIGINAL QUESTION I cannot get what seems to be a simple thing to work: importing modules between directories. This is all in Python 3 so I don't want to have __init__.py files all over the place if I can help it, which many of the answers here suggest is the "right" way. I have a structure like this: project displays graphical_pacman.py mechanics layout.py The layout.py file has a top level function called get_layout() that I want to call from graphical_pacman.py. Going to the minimum code necessary, in graphical_pacman.py I have: import layout if __name__ == '__main__': board = layout.get_layout("test_maze.lay") Shows up fine in IDE, even autocompletes it for me. Running graphical_pacman.py gets me this: File "displays/graphical_pacman.py", line 3, in &lt;module&gt; import layout ModuleNotFoundError: No module named 'layout' Then I tried this: from mechanics.layout import get_layout if __name__ == '__main__': board = mechanics.layout.get_layout("test_maze.lay") Can't do that either: File "displays/graphical_pacman.py", line 3, in &lt;module&gt; from mechanics.layout import get_layout ModuleNotFoundError: No module named 'mechanics' I tried this: from mechanics import layout if __name__ == '__main__': board = layout.get_layout("te…
has comment: http://stackoverflow.com/comment/81735888
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47392317
answer count: 2
has comment: http://stackoverflow.com/comment/81772507
has title: Importing Module Between Directories
has answer: http://stackoverflow.com/a/47392317
score: 0
type: Question
tagged with: python-3.x
tagged with: python-import
possible better answer: http://stackoverflow.com/a/47400239
linked to: http://stackoverflow.com/q/46525674
has answer: http://stackoverflow.com/a/47400239
tagged with: python

http://stackoverflow.com/a/47463791
has comment: http://stackoverflow.com/comment/81882691
has comment: http://stackoverflow.com/comment/81882862
has body: If the file is guaranteed untainted, you could eval each line: with open('File.json', "r") as f: asins = [eval(line)['asin'] for line in f] Here is the same code, using @Ajax1234's ast.literal_eval(), to avoid issue with tainted files, but using my list comprehension, which evaluates each line individually, and so doesn't store the whole dataset as a temporary. import ast with open('File.json', "r") as f: asins = [ast.literal_eval(line)['asin'] for line in f] For your comment-based bonus question, getting a list of all "also_bought" items, including duplicates: import ast also_bought = [] asins = [] with open('File.json', "r") as f: for line in f: item = ast.literal_eval(line) asins.append(item['asin']) if 'related' in item: related = item['related'] if 'also_bought' in related: also_bought.extend(related['also_bought'])
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81882518
accepted answer of: http://stackoverflow.com/q/47463730
type: Answer
has comment: http://stackoverflow.com/comment/81883179
has comment: http://stackoverflow.com/comment/81882559
answers question: http://stackoverflow.com/q/47463730
score: 2
has comment: http://stackoverflow.com/comment/81882460
has comment: http://stackoverflow.com/comment/81882980
downvote count: 0

http://stackoverflow.com/q/47456104
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47456310
has title: Strip /n from line and simultaneously do a replace in that line in Python
type: Question
has body: I'm trying to quickly create a list of DITA keydefs from a list of document titles. If the title is "Device User Guide", I want to create a keydef like this: Device User Guide The titles are extracted from titles.txt file, where each of them is a new line. This causes the key (Device_User_Guide) to contain a \n at the end, so my output is this: Device User Guide I managed to replace the spaces with underscores and use rstrip for the keyword, but how can I strip the newline character at the same time that I'm doing the replace operation? Here is my code: title = open('titles.txt', 'r') keydefs = open('keydefs.txt', 'w') for line in title: keydefs.write(' \n \n \n %s \n \n \n ' % (line.replace(" ","_"), line.rstrip()))
score: 0
tagged with: dita

http://stackoverflow.com/comment/82253663
type: Comment
has text: How are you trying to install it? I recommend using easy_install
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47505569

http://stackoverflow.com/comment/83037644
type: Comment
comment on: http://stackoverflow.com/a/47644664
score: 0
type: AnswerComment
has text: @NarinderVerma, when you say deployed in the portal, you mean using the Cloud terminal, or creating the resources in the portal?

http://stackoverflow.com/comment/81778762
type: AnswerComment
comment on: http://stackoverflow.com/a/47412037
score: 0
type: Comment
has text: Thank you all for your help, now it works. I didn't know 'len' would work here.

sensors
type: Tag
tags question: http://stackoverflow.com/q/47441946
tag name: sensors

http://stackoverflow.com/q/47502182
type: Question
has body: I tried to run this code, this code generate epoch but why my data is not readable? def test(learning_rate=0.1, training_epochs=15, n_hidden=500, delay=6, k=1): print ('... loading data') data_path = "./data.csv" DataFrame = pd.read_csv(data_path) df = pd.DataFrame(np.random.randn(261, 2)) msk = np.random.rand(len(df)) &lt; 0.8 train_X, train_y= df[msk] test_X, test_y= df[~msk] print ('... modeling') rng = numpy.random.RandomState(123) rbm = RBM(input=train_X, n_visible=28 * 28, n_hidden=500, numpy_rng=rng) start_time = time.clock() mean_cost_list = [] for epoch in range(training_epochs): mean_cost = [] cost = rbm.get_cost_updates(lr=learning_rate, k=k) print ('Training epoch %d, cost is ' % epoch, cost) cost_plot(mean_cost_list) end_time = time.clock() pretraining_time = (end_time - start_time) print(('Training took %f minutes' % (pretraining_time / 60.))) return rbm what causes unreadable data at run epoch? I also tried to running without entering the dataframe, and epoch still running ...
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/81960362
has comment: http://stackoverflow.com/comment/81960661
tagged with: python
has comment: http://stackoverflow.com/comment/81960424
has comment: http://stackoverflow.com/comment/81960618
has title: data not read in pandas, into runing epoch
tagged with: split
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81960431
has comment: http://stackoverflow.com/comment/81960645
has comment: http://stackoverflow.com/comment/81960214

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/47387857
tags question: http://stackoverflow.com/q/47440481
tags question: http://stackoverflow.com/q/47476912
tags question: http://stackoverflow.com/q/47493299
tags question: http://stackoverflow.com/q/47435537
tags question: http://stackoverflow.com/q/47494720
tags question: http://stackoverflow.com/q/47446644
tags question: http://stackoverflow.com/q/47528125
tags question: http://stackoverflow.com/q/47483480
type: Tag

openpyxl
tags question: http://stackoverflow.com/q/47443839
tags question: http://stackoverflow.com/q/47527630
tags question: http://stackoverflow.com/q/47489498
tags question: http://stackoverflow.com/q/47442631
tags question: http://stackoverflow.com/q/47492343
tags question: http://stackoverflow.com/q/47404793
type: Tag
tags question: http://stackoverflow.com/q/47456368
tags question: http://stackoverflow.com/q/47507655
tags question: http://stackoverflow.com/q/47432988
tag name: openpyxl

http://stackoverflow.com/comment/82024408
score: 0
type: Comment
type: QuestionComment
has text: Concerning your question, I would recommend using a package manager like [conda](https://conda.io/miniconda.html) to handle your Python packages. This makes installing packages a lot easier, since conda handles most dependency issues for you. If you are interested in this you can find a tutorial [here](https://conda.io/docs/user-guide/getting-started.html).
comment on: http://stackoverflow.com/q/47508868

http://stackoverflow.com/a/47408894
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47405394
has body: selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH The message states that the directory containing chromedriver.exe needs to be in path, that means that it can´t find the executable in any of the directories in the PATH variable, you can add the directory containing the .exe to the path variable with the OS settings: The other option is to set up a environment before running python from CMD: path = %PATH%;C:/dir/to/your/chromedriverdir python What this does is sets the variable named path to the value of the previous variable %PATH% and adds another dir to the end. This is only set locally in the sesion of your cmd window, if you close it, it goes away. This method and the method a2mky sugested are the preferred methods over the system settings. Personally I use driver = webdriver.Chrome(executable_path=r"C:\Chrome\chromedriver.exe") I wanted to add this answer to clarify the error message and the next time you see it, makes sense to you. Your best friend in case of errors, are the error messages.
downvote count: 0
score: 5

http://stackoverflow.com/comment/81788695
type: Comment
has text: For me a row is each element of the list. For example row1:[{'bu':'01-DAM-XNXX'}, 45, 60]
type: QuestionComment
comment on: http://stackoverflow.com/q/47417364
score: 0

http://stackoverflow.com/comment/95869916
score: 0
comment on: http://stackoverflow.com/q/47397667
type: Comment
type: QuestionComment
has text: Ah that's annoying - I've managed to get a Python Client / C# Server working if you're still interested using the library linked below. Anyway - obrigado for the reply https://github.com/slazarov/python-signalr-client

http://stackoverflow.com/q/47422147
tagged with: tkinter
has body: from tkinter import * import tkinter as tk class dashboard(Frame): def __init__(self, master): super(dashboard, self).__init__(master) self.grid() self.buttons() def buttons(self): #student dashboard button bttn1 = Button(self, text = "Student", command=self.student, height = 2, width= 15) bttn1.grid() #teacher dashboard button bttn2 = Button(self, text = "Teacher", height = 2, width= 15) bttn2.grid() #exit button bttn3 = Button(self, text = "Exit", command=root.destroy, height = 2, width= 15) bttn3.grid() def student(self): #view highscores button bttn1 = Button(self, text = "Highscores", height = 2, width= 15) bttn1.grid() #print score button bttn2 = Button(self, text = "Print Score", height = 2, width= 15) bttn2.grid() #exit button bttn3 = Button(self, text = "Main Menu", command=root.destroy, height = 2, width= 15) bttn3.grid() #main root = Tk() root.title("Dashboard") root.geometry("300x170") app = dashboard(root) root.mainloop() Wondered if someone could help me basically, with this GUI I am creating I want to be able to access a new page on the same frame but the buttons from the main menu stay once I go to another page, does anyone know how I can hide/forget the buttons and go back to them at a later stage? Thanks.
accepted answer: http://stackoverflow.com/a/47422736
has comment: http://stackoverflow.com/comment/81799013
tagged with: user-interface
answer count: 1
has answer: http://stackoverflow.com/a/47422736
has comment: http://stackoverflow.com/comment/81799465
type: Question
linked to: http://stackoverflow.com/q/7546050
has comment: http://stackoverflow.com/comment/81799559
has title: GUI - hiding buttons
tagged with: python
has comment: http://stackoverflow.com/comment/81799225
has comment: http://stackoverflow.com/comment/81799674
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81759216
score: 0
has text: @GrzegorzOledzki My end goal is to plot a signal (for example a sine wave) and then have the ability to insert additional signals into that main signal at whichever location I choose. So I wanted to append these signals into lists, manipulate them by adding additional signals, and then plot.
type: QuestionComment
comment on: http://stackoverflow.com/q/47401701
type: Comment

http://stackoverflow.com/comment/81829894
type: Comment
comment on: http://stackoverflow.com/a/47437498
has text: Use of pd.concat([df]*len(init_df) is nice. If my initial_df contained columns that I wanted to remove from the final_df is there a way to do that without a separate statement to drop them?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81853434
comment on: http://stackoverflow.com/a/47448813
score: 0
type: Comment
type: AnswerComment
has text: @PatrickArtner hmmm, right. but I have added it to find occurrences of comments.

http://stackoverflow.com/q/47482824
tagged with: python
tagged with: amazon-web-services
score: 0
has comment: http://stackoverflow.com/comment/81995575
answer count: 0
tagged with: sql
has title: Prohibitively slow insert performance on aws RDS micro
type: Question
has body: I'm running a free RDS instance on AWS and I'm trying to run some very simple query to insert about 10000 rows. I followed this guide http://docs.sqlalchemy.org/en/latest/faq/performance.html to do the insert properly and not use the ORM (use Core), but it is incredibly slow. Here is my very simple code inserting dummy data: from models import Transaction from sqlalchemy import create_engine import time db_string = 'connection_string' engine = create_engine(db_string) all_txs_flat = [] for i in range(0, 10000): all_txs_flat.append( Transaction(token='test', block_number=1000, from_address='qfieieoqfieqnfioeqnfioqenfiodnvd', to_address='cqkwiofjeqiojqnvoienvioeqnvvnksvvwe', amount=5000)) t0 = time.time() engine.execute( Transaction.__table__.insert(), [{"token": tx.token, "block_number": tx.block_number, "from_address": tx.from_address, "to_address": tx.to_address, "amount": tx.amount} for tx in all_txs_flat] ) print( "SQLAlchemy Core: Total time for " + str(10000) + " records " + str(time.time() - t0) + " secs") It is a straight out of the box config for the RDS. Just followed the wizard and opened up 5432 to my IP so I could connect on my local machine. The output is alarming... SQLAlchemy Core: Total time for 10000 records 360.06809306144714 secs Am I missing something obvious? What can I do to profile this? I don't believe I am running into the t2.micro limits here. Thanks
tagged with: postgresql
has comment: http://stackoverflow.com/comment/81932232
type: UnansweredQuestion

http://stackoverflow.com/q/47493880
has body: I have 95 small CSV files downloaded from web. Their schemas are supposed to be very similar. I am trying to concatenate them with Python pandas, but when calling pd.read_csv, the various encoding of those files are causing problems, and I am not sure what's the best way to transform them into consistent encoding, e.g. utf-8. The encodings include ASCII text, with CRLF line terminators Little-endian UTF-16 Unicode English text, with CRLF line terminators Little-endian UTF-16 Unicode text, with CRLF line terminators Little-endian UTF-16 Unicode text, with CRLF, CR line terminators UTF-8 Unicode (with BOM) English text, with CRLF line terminators UTF-8 Unicode (with BOM) text, with CRLF line terminators The above list is generated with file -b *.csv | sort | uniq
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81943086
tagged with: utf-8
has comment: http://stackoverflow.com/comment/81942970
tagged with: encoding
type: Question
has title: how to transform csv files of various encoding into utf-8
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47495053
tagged with: python
answer count: 1

http://stackoverflow.com/comment/81997343
type: Comment
has text: Alright, thanks for the advice. I'll take a look at the second idea and see if it works. It should since I can return multiple values with the function still. Also, thanks for catching the error. I'm a college student and my honors writing professor would have killed me, ha.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47520306

http://stackoverflow.com/q/47458085
has body: I am just trying to learn to use BeautifulSoup to parse and modify html files. I wonder whether it is possible to print out an html file exactly as it was before being parsed (including empty lines, line indentation etc.) except for the elements I explicitly want to change? Note: my request is not only that spaces are left unchanged; what I'm asking is that no changes are introduced at all in the html file, except in the specified elements.
has comment: http://stackoverflow.com/comment/81870677
has comment: http://stackoverflow.com/comment/81870717
tagged with: beautifulsoup
score: 0
linked to: http://stackoverflow.com/q/33788047
has comment: http://stackoverflow.com/comment/81871542
has title: How (not to) reformat html with BeautifulSoup
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81896675
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/33788047

http://stackoverflow.com/comment/81956176
type: Comment
comment on: http://stackoverflow.com/q/47500006
has text: Presumably you're doing this in a loop, many times? (Else I wonder where the need for an optimised solution comes from.) Does the size `N` change each time, or do you need many example arrays for each `N`? If the latter, you don't need to worry about the cost of setting up `arr` in the first place; only the cost of the shuffling is important.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82042351
type: AnswerComment
comment on: http://stackoverflow.com/a/47493804
has text: The only other method I have in mind is to have two iterators on the same dataset, where one is a step ahead of the other.
score: 0
type: Comment

http://stackoverflow.com/comment/81739917
comment on: http://stackoverflow.com/q/47393026
score: 1
type: Comment
type: QuestionComment
has text: (Not exactly the same, as I don't get the interpreter header. But the traceback is the same.)

http://stackoverflow.com/comment/81988818
type: Comment
has text: You need to pay closer attention to the [answers to the question you linked](https://stackoverflow.com/a/17649901/10077). `random.shuffle()` **does not return anything**. It shuffles the list in-place.
score: 4
comment on: http://stackoverflow.com/q/47516428
type: QuestionComment

conv-neural-network
tags question: http://stackoverflow.com/q/47518131
tags question: http://stackoverflow.com/q/47428336
tags question: http://stackoverflow.com/q/47398009
tags question: http://stackoverflow.com/q/47494698
tags question: http://stackoverflow.com/q/47406652
tags question: http://stackoverflow.com/q/47403634
tags question: http://stackoverflow.com/q/47535940
tags question: http://stackoverflow.com/q/47426002
type: Tag
tags question: http://stackoverflow.com/q/47459225
tags question: http://stackoverflow.com/q/47530722
tags question: http://stackoverflow.com/q/47529721
tags question: http://stackoverflow.com/q/47408424
tags question: http://stackoverflow.com/q/47488598
tags question: http://stackoverflow.com/q/47430467
tags question: http://stackoverflow.com/q/47472833
tags question: http://stackoverflow.com/q/47536405
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/47469947
tags question: http://stackoverflow.com/q/47477371

http://stackoverflow.com/a/47540569
score: 0
has body: You should use return values and parameters in your functions. For example you could rewrite your script as follows: #!/usr/bin/env python import time # Create a useful time stamp for logging to the log file timestamp = time.strftime("%d/%m/%Y %H:%M:%S") def define_and_collect_1_wire_data(): tfile = open("/sys/bus/w1/devices/28-0000052c29e1/w1_slave") text = tfile.read() tfile.close() temperature_data = text.split()[-1] temperature = float(temperature_data[2:]) temperature1 = round(temperature / 1000,1) #for the purposes of testing. Temperature1 will be pulled from the Dallas 1-wire bus temperature1=13.1 # Create data_stream_logfile string data_stream_logfile = str(temperature1) + "," + str(timestamp) # Print output to a terminal print "Raw temperature data as written to log file:" print data_stream_logfile print " " return data_stream_logfile def log(message): # Open the text log datafile datafile_temperature_log = open("log_cron_temperature_data.log", "a", 1) datafile_temperature_log.write(message + "\n") datafile_temperature_log.close() def main(): log_file(define_and_collect_1_wire_data()) main()
has comment: http://stackoverflow.com/comment/82038187
type: Answer
answers question: http://stackoverflow.com/q/47540395

http://stackoverflow.com/comment/81761253
has text: @Barmar the expression is followed by BONUS though, so it should only match all characters up to "BONUS" -- which is "6\n\n\n\n"
score: 0
comment on: http://stackoverflow.com/q/47403566
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81910022
comment on: http://stackoverflow.com/a/47477378
score: 0
has text: @thewhitetie, my code actual for your link provided in the code. For doing the same with `news`, you should open the "news" page before. So if my answer was helpful -- check a tick near my answer, please.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81922783
type: AnswerComment
has text: "Fancy indexing" is a numpy term, not a python one.
type: Comment
comment on: http://stackoverflow.com/a/47483632
score: 0

http://stackoverflow.com/q/47509934
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25055712
has answer: http://stackoverflow.com/a/47510024
answer count: 3
tagged with: pandas
has body: Say I have the following table: +----+---------+--------+---------+---------+---------+---------+-----------+-----------+-----------+----------+-----------+------------+------------+---------+---+ | 1 | 0.72694 | 1.4742 | 0.32396 | 0.98535 | 1 | 0.83592 | 0.0046566 | 0.0039465 | 0.04779 | 0.12795 | 0.016108 | 0.0052323 | 0.00027477 | 1.1756 | 1 | | 2 | 0.74173 | 1.5257 | 0.36116 | 0.98152 | 0.99825 | 0.79867 | 0.0052423 | 0.0050016 | 0.02416 | 0.090476 | 0.0081195 | 0.002708 | 7.48E-05 | 0.69659 | 1 | | 3 | 0.76722 | 1.5725 | 0.38998 | 0.97755 | 1 | 0.80812 | 0.0074573 | 0.010121 | 0.011897 | 0.057445 | 0.0032891 | 0.00092068 | 3.79E-05 | 0.44348 | 1 | | 4 | 0.73797 | 1.4597 | 0.35376 | 0.97566 | 1 | 0.81697 | 0.0068768 | 0.0086068 | 0.01595 | 0.065491 | 0.0042707 | 0.0011544 | 6.63E-05 | 0.58785 | 1 | | 5 | 0.82301 | 1.7707 | 0.44462 | 0.97698 | 1 | 0.75493 | 0.007428 | 0.010042 | 0.0079379 | 0.045339 | 0.0020514 | 0.00055986 | 2.35E-05 | 0.34214 | 1 | | 7 | 0.82063 | 1.7529 | 0.44458 | 0.97964 | 0.99649 | 0.7677 | 0.0059279 | 0.0063954 | 0.018375 | 0.080587 | 0.0064523 | 0.0022713 | 4.15E-05 | 0.53904 | 1 | | 8 | 0.77982 | 1.6215 | 0.39222 | 0.98512 | 0.99825 | 0.80816 | 0.0050987 | 0.0047314 | 0.024875 | 0.089686 | 0.0079794 | 0.0024664 | 0.00014676 | 0.66975 | 1 | | 9 | 0.83089 | 1.8199 | 0.45693 | 0.9824 | 1 | 0.77106 | 0.0060055 | 0.006564 | 0.0072447 | 0.040616 | 0.0016469 | 0.00038812 | 3.29E-05 | 0.33696 | 1 | | 11 | 0.7459 | 1.4927 | 0.34116 | 0.98296 | 1 | 0.83088 | 0.0055665 | 0.0056395 | 0.0057679 | 0.036511 | 0.0013313 | 0.00030872 | 3.18E-05 | 0.25026 | 1 | | 12 | 0.79606 | 1.6934 | 0.43387 | 0.98181 | 1 | 0.76985 | 0.0077992 | 0.011071 | 0.013677 | 0.057832 | 0.0033334 | 0.00081648 | 0.00013855 | 0.49751 | 1 | +----+---------+--------+---------+---------+---------+---------+-----------+-----------+-----------+----------+-----------+------------+------------+---------+---+ I have two sets of row indices : set1 = [1,3,5,8,9] set2 = [2,4,7,10,10] Note :…
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81975512
accepted answer: http://stackoverflow.com/a/47510095
possible better answer: http://stackoverflow.com/a/47510086
has answer: http://stackoverflow.com/a/47510095
type: Question
has title: calculate difference of column values for sets of row indices which are not successive in pandas
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47510086

http://stackoverflow.com/a/47385196
answers question: http://stackoverflow.com/q/47383413
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: Clone python-for-android somewhere manually Install dependencies your cloned version would need (can be done just installing python-for-android with pip) Change your buildozer.spec file adding option p4a.source_dir pointing to cloned directory (for example p4a.source_dir = /home/ken/python-for-android) Done! Now buildozer will use your local python-for-android.
score: 1
accepted answer of: http://stackoverflow.com/q/47383413

http://stackoverflow.com/comment/81858435
has text: I am a little bit confused with indexes and arguments. Thanks for help.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47446080

http://stackoverflow.com/comment/126069387
type: Comment
score: 0
type: AnswerComment
has text: @Meet I expect weird things to happen that way. You could instead spawn your browser with the debug port open, and connect your webdriver to it.
comment on: http://stackoverflow.com/a/47509389

http://stackoverflow.com/comment/81949707
comment on: http://stackoverflow.com/a/47497162
type: AnswerComment
score: 0
type: Comment
has text: Thanks it worked like a charm. Also thanks very much for the link. Love to learn python. Links like this will definitely help me.

http://stackoverflow.com/q/47386554
has comment: http://stackoverflow.com/comment/81726286
score: 1
tagged with: python
tagged with: search
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81726157
has comment: http://stackoverflow.com/comment/81726056
accepted answer: http://stackoverflow.com/a/47387005
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81730794
has answer: http://stackoverflow.com/a/47387005
has body: import os, sys text = [file_search for file_search in os.listdir() if file_search.endswith('.txt') or file_search.endswith('.py')] search = input() print (text) for files in text: lines_list = open(files).read().lower().splitlines() bool1 = False for words in lines_list: if bool1 == True: break elif words == search: print (files) bool1 = True else: bool1 = False Can some tell me where I am going wrong?
upvote count: 1
favorite count: 0
type: Question
has title: searching a word in list of files(current directory) and returning all the files containg the word python

http://stackoverflow.com/comment/81998249
comment on: http://stackoverflow.com/a/47518564
type: AnswerComment
has text: You would have to put commas in between each one. I don't know how the data looks without looking at it.
score: 0
type: Comment

http://stackoverflow.com/comment/81912310
type: QuestionComment
has text: BTW, you can make your random character selection code a lot simpler by using `random.choice`.
score: 0
comment on: http://stackoverflow.com/q/47478628
type: Comment

http://stackoverflow.com/q/47440505
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81836186
answer count: 1
tagged with: python
has title: Python script not downloading files
has answer: http://stackoverflow.com/a/47440974
has body: I have the code below. It prints out the URL in the console. I'm having trouble figuring out how to get it to just download it instead of displaying it. I also want to be able to search for .mov file type. I'd rather have information on how to do this rather than it done for me. Any help is appreciated! import urllib def is_download_allowed(): f = urllib.urlopen("http://10.1.1.27/config?action=get&amp;paramid=eParamID_MediaState") response = f.read() if (response.find('"value":"1"') &gt; -1): return True f = urllib.urlopen("http://10.1.1.27/config?action=set&amp;paramid=eParamID_MediaState&amp;value=1") def download_clip(): url = "http://10.1.1.27/media/SC1ATK26" print url def is_not_download_allowed(): f = urllib.urlopen("http://10.1.1.27/config?action=get&amp;paramid=eParamID_MediaState") response = f.read() if (response.find('"value":"-1"') &gt; 1): return True f = urllib.urlopen("http://10.1.1.27/config?action=set&amp;paramid=eParamID_MediaState&amp;value=1") is_download_allowed() download_clip() is_not_download_allowed()
has comment: http://stackoverflow.com/comment/81837508
downvote count: 1
score: -1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82032259
comment on: http://stackoverflow.com/a/47537450
type: AnswerComment
score: 1
type: Comment
has text: This solution is valid but the "brute force" part makes it run in a time complexity of `O(n!)`...

http://stackoverflow.com/comment/82035184
score: 1
type: Comment
type: QuestionComment
has text: Because you are on Python 2, and `range` will create a `list` object. This list-object will require, *just for the pointers in the underlying array*, something like `9000000030 * 8 * 1e-9 == 72` gigabytes. You can add at least another 28 bytes per actual `int` object contained in the list, bringing you to `297` gigabytes
comment on: http://stackoverflow.com/q/47539087

http://stackoverflow.com/a/47419701
has comment: http://stackoverflow.com/comment/81795420
has comment: http://stackoverflow.com/comment/81795287
has comment: http://stackoverflow.com/comment/81794709
has comment: http://stackoverflow.com/comment/81795011
answers question: http://stackoverflow.com/q/47419251
score: 0
has body: python my_scripts\test.py should work. More generally, you run a python script using the interpreter with: python PATH_TO_SCRIPT
type: Answer

ubuntu-14.04
tags question: http://stackoverflow.com/q/47449512
tags question: http://stackoverflow.com/q/47460860
type: Tag
tags question: http://stackoverflow.com/q/47451166
tags question: http://stackoverflow.com/q/47440140
tag name: ubuntu-14.04

http://stackoverflow.com/a/47515063
answers question: http://stackoverflow.com/q/47514858
has body: the method of dataframe, 'apply' will be good. the code is below. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC')) # To create df df.apply(lambda x: np.mean(x), axis=0)
type: Answer
score: 0

http://stackoverflow.com/a/47443528
has comment: http://stackoverflow.com/comment/81853705
type: Answer
accepted answer of: http://stackoverflow.com/q/47443332
has comment: http://stackoverflow.com/comment/81858012
has comment: http://stackoverflow.com/comment/81856634
has comment: http://stackoverflow.com/comment/85186066
has body: If the lists are very long, repeatedly calling insert might not be very efficient. Alternatively, you could create two iterators from the lists and construct a list by getting the next element from either of the iterators depending on whether the current index is in ypos (or a set thereof): &gt;&gt;&gt; ity = iter(y) &gt;&gt;&gt; itz = iter(z) &gt;&gt;&gt; syp = set(ypos) &gt;&gt;&gt; [next(ity if i+1 in syp else itz) for i in range(len(y)+len(z))] [11, 12, 13, 14, 15] Note: this will insert the elements from y in the order they appear in y itself, i.e. the first element of y is inserted at the lowest index in ypos, not necessarily at the first index in ypos. If the elements of y should be inserted at the index of the corresponding element of ypos, then either ypos has to be in ascending order (i.e. the first index of ypos is also the lowest), or the iterator of y has to be sorted by the same order as the indices in ypos (afterwards, ypos itself does not have to be sorted, as we are turning it into a set anyway). &gt;&gt;&gt; ypos = [5,3,1] # y and z being same as above &gt;&gt;&gt; ity = iter(e for i, e in sorted(zip(ypos, y))) &gt;&gt;&gt; [next(ity if i+1 in syp else itz) for i in range(len(y)+len(z))] [15, 12, 13, 14, 11]
has comment: http://stackoverflow.com/comment/81857362
upvote count: 35
score: 35
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81848295
has comment: http://stackoverflow.com/comment/81844517
answers question: http://stackoverflow.com/q/47443332

http://stackoverflow.com/comment/81971912
type: Comment
comment on: http://stackoverflow.com/q/47507763
score: 0
type: QuestionComment
has text: No, I haven't. How do I pipe in the contents of variable `sourceCode` in that case?

http://stackoverflow.com/q/47409573
has answer: http://stackoverflow.com/a/47409630
tagged with: multithreading
downvote count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/18114285
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81772831
has body: I am trying to create different threads to work with 8 cores. However I see the code creates 8 threads but only uses around on 100% on my macos. Why? def runner(i): # do random stuff for a in range(0,1000000): i+=1 5000 / 34 * i i + 400 i / 20000 i * 24440 i+=1 5000 / 34 * i i + 400 i / 20000 q = queue.Queue() threads = list() for x in range(0,80): th = threading.Thread(target=runner,args=(x,)) threads.append(th) for th in threads: th.start() for th in threads: th.join()
score: 1
accepted answer: http://stackoverflow.com/a/47409630
answer count: 1
linked to: http://stackoverflow.com/q/3044580
linked to: http://stackoverflow.com/q/4496680
favorite count: 0
has title: Python multithreading works only a single CPU
type: Question
duplicate of: http://stackoverflow.com/q/4496680

http://stackoverflow.com/q/47388570
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/47388979
score: 4
has comment: http://stackoverflow.com/comment/81730620
has answer: http://stackoverflow.com/a/47388947
type: AnsweredQuestion
has body: I try to print my large dataframe to csv file but the tab separation sep='\t' does not work. I then test with newline sep='\n', it seems work ok, break all the elements by newline. What are possibly wrong here? The code is so simple like df_M.to_csv('report'+filename, header=True, sep='\t', index=False) The example of data (the protein column is very long), I mark where to separate by | "protein | cl | pept | [M] | [M+1H+]1+ | [M+2H+]2+" "ALBU_HUMAN_UPS Serum albumin (Chain 26-609) - Homo sapiens (Human)| 0| AWAVAR| 672.37072| 673.378| out-of-range" "ALBU_HUMAN_UPS Serum albumin (Chain 26-609) - Homo sapiens (Human)| 0| TPVSDR| 673.3394900000002| 674.3467700000002| out-of-range" "ALBU_HUMAN_UPS Serum albumin (Chain 26-609) - Homo sapiens (Human)| 0| NYAEAK| 694.3285900000001| 695.3358700000001| out-of-range" "
tagged with: python-2.7
has title: pandas dataframe to_csv works with sep='\n' but not sep='\t'
answer count: 3
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/81730393
possible better answer: http://stackoverflow.com/a/47388979
has comment: http://stackoverflow.com/comment/81730542
linked to: http://stackoverflow.com/q/45983286
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47389515
accepted answer: http://stackoverflow.com/a/47389515
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/47426914
tagged with: linux
tagged with: bash
has comment: http://stackoverflow.com/comment/81812164
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11710552
tagged with: build-automation
score: 0
has title: Bash/Python to gather several paths to one and replacing the file name by '*' character
accepted answer: http://stackoverflow.com/a/47429322
has body: I'm coding a bash script in order to generate .spec file (building RPM) automatically. I read all the files in the directory (which I hope to convert it into rpm package) and write all the paths of files needed to install in .spec file, I realize that I need to shorten them. An example: /tmp/a/1.jpg /tmp/a/2.conf /tmp/a/b/srf.cfg /tmp/a/b/ssp.cfg /tmp/a/conf_web_16.2/c/.htaccess /tmp/a/conf_web_16.2/c/.htaccess.WebProv /tmp/a/conf_web_16.2/c/.htprofiles => What I want to get: /tmp/a/*.jpg /tmp/a/*.conf /tmp/a/b/*.cfg /tmp/a/conf_web_16.2/c/* /tmp/a/conf_web_16.2/c/*.WebProv You guys please give me some advice about my problem. I hope you guys can suggest your idea in bash shell, python or C. Thank you in advance.
has answer: http://stackoverflow.com/a/47429322
has comment: http://stackoverflow.com/comment/81814205
type: Question
tagged with: python
answer count: 1
tagged with: filepath

http://stackoverflow.com/q/47521452
tagged with: pandas
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47521796
has body: I have a dataframe that looks like this. I need a subplot for each unique Item (book, Table and Chair). The plots should be sorted by Year (Year is also the x-axis). I need to make use of twiny to have Price on the left and Quantity plotted on the right of each subplot. I can do this manually for each Item by creating a individual dataframe. So I created a dataframe for Book, then sorted by Year and set Year as index. then create the plot with secondary_y. But obviously this is long winded. Is there a way to do this from the original dataframe without all the manual processing? Item Year Price Quantity 0 Book 2000 $2 50 1 Table 2000 $33 44 2 Chair 2000 $21 31 3 Book 2001 $3 77 4 Table 2001 $20 500 5 Chair 2001 $2 50 6 Book 2002 $36 7 7 Table 2002 $200 50 8 Chair 2002 $44 5
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47522226
score: 0
has comment: http://stackoverflow.com/comment/82011573
upvote count: 1
tagged with: python
downvote count: 1
tagged with: plot
has title: Pandas subplots plotting multiple y-axis
favorite count: 0
has comment: http://stackoverflow.com/comment/82000076
possible better answer: http://stackoverflow.com/a/47522226
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47521796

http://stackoverflow.com/comment/82008706
comment on: http://stackoverflow.com/q/47523544
score: 0
type: Comment
type: QuestionComment
has text: On further thought, I think I can come up with a custom `type` function and `Action` class that does what you want, even replacing default values piecemeal. But it will be just as easy to do that conversion after parsing. Why don't you do that, and I can then suggest how to make it a part of the parser?

http://stackoverflow.com/q/47494720
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68607949
upvote count: 3
tagged with: pivot-table
downvote count: 0
favorite count: 0
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/47494789
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/81944521
possible better answer: http://stackoverflow.com/a/72427624
tagged with: group-by
has answer: http://stackoverflow.com/a/47494789
tagged with: python
has answer: http://stackoverflow.com/a/72427624
has title: Python - Pandas subtotals on groupby
has body: here's a sample of the data i m using : SCENARIO DATE POD AREA IDOC STATUS TYPE AAA 02.06.2015 JKJKJKJKJKK 4210 713375 51 1 AAA 02.06.2015 JWERWERE 4210 713375 51 1 AAA 02.06.2015 JAFDFDFDFD 4210 713375 51 9 BBB 02.06.2015 AAAAAAAA 5400 713504 51 43 CCC 05.06.2015 BBBBBBBBBB 4100 756443 51 187 AAA 05.06.2015 EEEEEEEE 4100 756457 53 228 I have written the following code in pandas to groupby: import pandas as pd import numpy as np xl = pd.ExcelFile("MRD.xlsx") df = xl.parse("Sheet3") #print (df.column.values) # The following gave ValueError: Cannot label index with a null key # dfi = df.pivot('SCENARIO) # Here i do not actually need it to count every column, just a specific one table = df.groupby(["SCENARIO", "STATUS", "TYPE"]).agg(['count']) writer = pd.ExcelWriter('pandas.out.xlsx', engine='xlsxwriter') table.to_excel(writer, sheet_name='Sheet1') writer.save() table2 = pd.DataFrame(df.groupby(["SCENARIO", "STATUS", "TYPE"])['TYPE'].count()) print (table2) writer2 = pd.ExcelWriter('pandas2.out.xlsx', engine='xlsxwriter') table2.to_excel(writer2, sheet_name='Sheet1') writer2.save() this yields a result : SCENARIO STATUS TYPE TYPE AAA 51 1 2 9 1 53 228 1 BBB 51 43 1 CCC 51 187 1 Name: TYPE, dtype: int64 How could i add subtotals per group? Ideally i would want to achieve something like: SCENARIO STATUS TYPE TYPE AAA 51 1 2 9 1 Total 3 53 228 1 Total 1 BBB 51 43 1 Total 1 CCC 51 187 1 Total 1 Name: TYPE, dtype: int64 Is this possible?

http://stackoverflow.com/q/47432418
upvote count: 15
has comment: http://stackoverflow.com/comment/82574885
has answer: http://stackoverflow.com/a/47806854
favorite count: 0
possible better answer: http://stackoverflow.com/a/47806854
type: Question
tagged with: terminal
answer count: 2
accepted answer: http://stackoverflow.com/a/47889990
tagged with: python
tagged with: ansi-colors
score: 15
has comment: http://stackoverflow.com/comment/82574909
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47889990
downvote count: 0
has body: I am trying to print coloured text with colorama but when I compile an exe and run following... from colorama import Fore, Back, Style print(Fore.RED + 'text') print(Back.GREEN + 'and with a green background') print(Style.DIM + 'and in dim text') print(Style.RESET_ALL) print('back to normal now') I get output of:: Output: [31mtext [0m back to normal now Is it possible to print colors when compiling to pyinstaller exe or is this simply not possible?
has title: output of [31m text instead of color

http://stackoverflow.com/comment/81961233
score: 0
has text: @user1767754 That's seems to help a little. Thank you.
type: QuestionComment
comment on: http://stackoverflow.com/q/47502679
type: Comment

http://stackoverflow.com/q/47485023
accepted answer: http://stackoverflow.com/a/47493804
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47493804
tagged with: python
type: AnsweredQuestion
score: 3
has body: Recently, I want to implement GAN model and use tf.Dataset and Iterator to read face images as the training data. the dataset and iterator object's code is: self.dataset = tf.data.Dataset.from_tensor_slices(convert_to_tensor(self.data_ob.train_data_list, dtype=tf.string)) self.dataset = self.dataset.map(self._parse_function) #self.dataset = self.dataset.shuffle(buffer_size=10000) self.dataset = self.dataset.apply(tf.contrib.data.batch_and_drop_remainder(batch_size)) self.iterator = tf.data.Iterator.from_structure(self.dataset.output_types, self.dataset.output_shapes) self.next_x = self.iterator.get_next() My new GAN model is: self.z_mean, self.z_sigm = self.Encode(self.next_x) self.z_x = tf.add(self.z_mean, tf.sqrt(tf.exp(self.z_sigm))*self.ep) self.x_tilde = self.generate(self.z_x, reuse=False) #the feature self.l_x_tilde, self.De_pro_tilde = self.discriminate(self.x_tilde) #for Gan generator self.x_p = self.generate(self.zp, reuse=True) # the loss of dis network self.l_x, self.D_pro_logits = self.discriminate(self.next_x, True) So, the problem is that I use the self.next_x as the input tensor twice. The dataset for every time is different. So, how to solve this problem to keep the first batch for reusing?
upvote count: 3
tagged with: tensorboard
answer count: 1
downvote count: 0
has title: How to get the preivous batch after running Iteration.get_next() in tensorflow?

http://stackoverflow.com/comment/81748873
score: 0
type: QuestionComment
has text: If I understand what you're asking (and if by `surface[0]` you mean `surfaces[0]`), then it should be doing what you want already.
comment on: http://stackoverflow.com/q/47397734
type: Comment

http://stackoverflow.com/comment/81870552
score: 0
comment on: http://stackoverflow.com/q/47424751
type: Comment
has text: @MooingRawr in which case, however, I would have to first extract ALL tweets (which is impossible). Also, I don't think the Twitter API allows searching for tweets that only contain symbols.
type: QuestionComment

http://stackoverflow.com/comment/81810046
type: QuestionComment
comment on: http://stackoverflow.com/q/47426810
score: 0
has text: Sorry but I can't reproduce this. Everything works fine as expected on my machine. Maybe sth wrong with your system, like oom?
type: Comment

http://stackoverflow.com/q/47455234
type: Question
answer count: 2
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/47455413
possible better answer: http://stackoverflow.com/a/47455983
linked to: http://stackoverflow.com/q/45407616
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47455983
has title: Can't write to QTextBrowser when calling function from another file
has body: I have a python plugin where the main.py file displays a QTextBrowser and writes some text. This works fine. I wrote a second file anotherFile.py which identifies the same QTextBrowser but cannot write any text to it. Perhaps it needs to take ownership, I'm not sure? Here is the code used: # main.py # from Example_dockwidget import ExampleDockWidget from anotherFile import anotherClass class Example: def __init__(self, iface): self.iface = iface def function(self): self.dockwidget = ExampleDockWidget() self.dockwidget.show() textBrowser = self.dockwidget.textBrowser #textBrowser.setText('This works!') a = anotherClass(self) a.anotherFunction() # anotherFile.py # from Example_dockwidget import ExampleDockWidget class anotherClass: def __init__(self, iface): self.iface = iface self.dockwidget = ExampleDockWidget() def anotherFunction(self): textBrowser = self.dockwidget.textBrowser textBrowser.setText('This does not work!') print 'Why?' # Example_dockwidget.py # FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'Example_dockwidget_base.ui')) class ExampleDockWidget(QtGui.QDockWidget, FORM_CLASS): def __init__(self, parent=None): super(ExampleDockWidget, self).__init__(parent) self.setupUi(self)
tagged with: python
has comment: http://stackoverflow.com/comment/81864756
has answer: http://stackoverflow.com/a/47455413

http://stackoverflow.com/comment/81721670
type: Comment
has text: @KaiserDandangi so it gives me the following error Traceback (most recent call last): File "<ipython-input-39-3bb6f8df7336>", line 8, in <module> p = u.load() File "C:\Users\tende\Anaconda3\lib\pickle.py", line 1050, in load dispatch[key[0]](self) KeyError: 31
type: QuestionComment
comment on: http://stackoverflow.com/q/47384218
score: 0

http://stackoverflow.com/comment/81768009
type: Comment
comment on: http://stackoverflow.com/q/47402765
type: QuestionComment
score: 0
has text: what does `system("which python")` return?

http://stackoverflow.com/q/47445249
has body: I have been staring at this and Googling stuff for hours now, and I need another pair of eyes. I am learning Python and Flask. My problem: Flask is not visibly changing the page after the returned redirect(), but it is "working": The printed messages "Successfully redirected to the homepage." and "User has a valid session." are being outputted to the console after login. Additionally, navigating to "/home" directly works as expected. I am using jQuery to POST data to Flask. from flask import Flask, request, redirect, jsonify, render_template, session from google.oauth2 import id_token from google.auth.transport import requests import sys, collections import db app = Flask(__name__) app.secret_key = 'some-key' db.connect('users.sqlite') @app.route('/') def index(): return render_template('index.html') @app.route('/collect', methods=['POST']) def collect(): if request.method == 'POST': google_credential_package = {} google_credential_package['google_credential'] = request.json['google_credential'] google_credential_package['verified'] = request.json['verified'] try: idinfo = id_token.verify_oauth2_token(google_credential_package['google_credential'], requests.Request(), 'my-client-id') if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') if idinfo['aud'] == 'my-client-id': userid = idinfo['sub'] email = idinfo['email'] name = idinfo['name'] pfp = idinfo['picture'] user_type = 'normie' retrieved_user = db.user('users.sqlite', userid, email, name, pfp, user_type) if retrieved_user[3] == 'alpha': print('User ' + name + ' is an Alpha Tester.') session['user'] = 'yes' return redirect('/home') # THE URL DOES NOT CHANGE HERE. (REDIRECT DOES NOT VISUALLY CHANGE ANYTHING.) else: return 'Success.' except ValueError: print('Invalid token!') pass @app.route('/home') def generateHome(): print('Successfully redirected to the homepage.') if session.get('user'): print('User has a valid session.') return render_template('hom…
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81845903
accepted answer: http://stackoverflow.com/a/47445355
has comment: http://stackoverflow.com/comment/81845941
downvote count: 0
has answer: http://stackoverflow.com/a/47445355
tagged with: python
tagged with: jquery
tagged with: flask
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/47445353
upvote count: 3
has title: Flask Not Redirecting after POST?
has answer: http://stackoverflow.com/a/47445353

http://stackoverflow.com/comment/81894130
comment on: http://stackoverflow.com/a/47467372
has text: Yes, I agree, but I think there is a better way hidden in this approach: If we go the road of identifying points in each region, which is far easier that defining what a region is, we can likely (although I have no proof) scan this in `O(num_points * num_partitions * log(max(num_points, num_partitions)))`. In any event, if you are going to enumerate the regions, which the OP intends to do, you have no choice but to go through every one of them.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81813869
has text: You should try to find the cause of your exit. Simply restarting the script may not be enough for robust operation. You are likely to be failing to process the email that causes the script to exit.
score: 0
comment on: http://stackoverflow.com/q/47429532
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47456033
accepted answer of: http://stackoverflow.com/q/47455874
score: 0
has body: I would recommend using the threading module to run multiple threads simultaneously. You would need to modify your class to take a URL argument in the init. import threading sites = ['URL1','URL2','URL3'] def create_instance(): global sites CompanyInfoGrabberSpider(scrapy.Spider,sites[0]) sites.remove[sites[0]] for site in sites: threading.Thread(target=create_instance).start() # Create and start thread
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47455874
type: Answer

http://stackoverflow.com/comment/81836597
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47424492
has text: im still getting a weird error. I'll try working on it tonight. "only integer scalars can be converted to index" or something along those lines

http://stackoverflow.com/q/47483411
upvote count: 4
accepted answer: http://stackoverflow.com/a/47483538
tagged with: image
linked to: http://stackoverflow.com/q/45968617
linked to: http://stackoverflow.com/q/46036172
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81921949
has comment: http://stackoverflow.com/comment/81921812
answer count: 1
has answer: http://stackoverflow.com/a/47483538
favorite count: 0
type: Question
has body: I created the following image (image 3) using a threshold mask (image 2) on image 1. I am trying to convert all the pixels outside of the central image of image 3 (of lungs) to one colour (for example black) using opencv. Basically so that I am left with just the image of the lungs against a uniform background (or even transparent). My problem has been the similarity of the very outer pixels to those inside the lungs on image 3. Is this possible to do using opencv?
tagged with: opencv
score: 3
has comment: http://stackoverflow.com/comment/81921599
has title: Python and opencv: how do I convert the ALL of the background of this image to one colour or transparent
downvote count: 1
tagged with: python

http://stackoverflow.com/a/47407665
has comment: http://stackoverflow.com/comment/81768698
accepted answer of: http://stackoverflow.com/q/47407576
type: Answer
has comment: http://stackoverflow.com/comment/81768631
answers question: http://stackoverflow.com/q/47407576
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81770074
type: AcceptedAnswer
downvote count: 0
has body: Use: d = df.set_index('id').iloc[:, -3:].stack().groupby(level=0).apply(tuple).to_dict() print (d) {'bee': (7.4, 12.4, 1.3, 6.9, 0.8), 'cat': (5.2,), 'ant': (10.2, 3.5, 4.7, 5.7, 10.2)} Detail: print (df.set_index('id').iloc[:, -3:].stack()) id ant value_1 10.2 value_2 3.5 value_3 4.7 value_1 5.7 value_2 10.2 bee value_1 7.4 value_1 12.4 value_2 1.3 value_3 6.9 value_1 0.8 cat value_3 5.2 dtype: float64 If ordering is necesary and use pandas 0.21.0 is possible generate OrderedDict: from collections import OrderedDict d = (df.set_index('id') .iloc[:, -3:] .stack() .groupby(level=0) .apply(tuple) .to_dict(into=OrderedDict)) print (d) OrderedDict([('ant', (10.2, 3.5, 4.7, 5.7, 10.2)), ('bee', (7.4, 12.4, 1.3, 6.9, 0.8)), ('cat', (5.2,))])
has comment: http://stackoverflow.com/comment/81770143

http://stackoverflow.com/q/47499986
has title: HTTP request via proxy on AWS server fails with 407
has body: I'm running this brief script locally as well on an AWS EC2 intance in an ECS cluster: import requests proxies = {'http':'http://user:pw@host:port','https':'http://user:pw@host:port'} r = requests.get('http://quotes.toscrape.com/', proxies=proxies) print r.status_code When I run the script locally, I get a 200 status code, indicating that I successfully am able to connect to access the website via the proxy. When I run the script on the AWS instance, I get a 407 proxy authentication error. This is a common error that others have experienced (e.g. see here). I'm looking for a solution that allows me to authenticate the proxies WITHOUT having to whitelist the instance. The reason being is that every time I run a new instance, I'd have to whitelist that instance too. I would rather just pass in the credentials to requests and authenticate the proxy directly. Is this possible?
type: Question
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47503570
tagged with: python-requests
tagged with: amazon-web-services
answer count: 1
tagged with: proxy
tagged with: proxy-authentication
score: 1
favorite count: 0

mfcc
type: Tag
tags question: http://stackoverflow.com/q/47512800
tag name: mfcc

ant-colony
tag name: ant-colony
tags question: http://stackoverflow.com/q/47444967
type: Tag

http://stackoverflow.com/q/47539014
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84038611
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/105254406
has comment: http://stackoverflow.com/comment/82035248
tagged with: python-behave
has comment: http://stackoverflow.com/comment/105407720
tagged with: python
has title: Generate static HTML results report with Python Behave
has body: I use behave to run a set of e2e tests for my software, eg: behave ./tests/ --tags=set123 --tags=-skip When the process ends, a tests/results/ directory is created, plenty of results in the form of .xml files which root element is &lt;testsuite&gt;. I'd like to have an static HTML report with the result. PyCharm have a nice button to get such report directly, but I wonder about how to get it from the command line. I mean, some way of processing the resulting .xml files to render the HTML or (even better) to do it as result of the behave command itself. Any help, please? This seems to be conceptually easy but I haven't found any straighfoward solution googling out there... EDIT: I know the Allure tool. However, it doesn't fit my purpose as it starts a web server to serve the report and I need an static HTML. I have adjusted the wording of the question to make it clearer.
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/40763066
score: 1
has answer: http://stackoverflow.com/a/57070639
answer count: 1
has comment: http://stackoverflow.com/comment/82038948
has comment: http://stackoverflow.com/comment/105397890

http://stackoverflow.com/comment/81962977
type: Comment
has text: Hello, this is a software dev site, so your question might be best in other support forums. However, you should identify what OS you are running, how you installed the python package, and what you ran to uninstall it. Likely Pip, but this would help.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47503547

http://stackoverflow.com/comment/82030194
type: Comment
has text: You don't need weights (well, the entire model needs weights somewhere, but not every layer). But for keeping the (automatic) backpropagation intact, you need keras backend functions (or tensorflow/theano functions) directly on the tensors. Using numpy will break the connection.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47536066

http://stackoverflow.com/comment/82097855
type: Comment
type: QuestionComment
has text: If you are referring to a question you asked online previously, it would be good to add a link to it in your current post.
comment on: http://stackoverflow.com/q/47523760
score: 0

http://stackoverflow.com/a/47489233
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: You can also subclass int: class A(int): def multiply(self, *args): r = self for arg in args: r *= arg return r &gt;&gt;&gt; x = A(3) &gt;&gt;&gt; x.multiply(4,5) 60 &gt;&gt;&gt; x.multiply(2,3,4) 72 This will then also behave like an int in other situations: &gt;&gt;&gt; x + 5 8 &gt;&gt;&gt; x * 5 15
answers question: http://stackoverflow.com/q/47489152

http://stackoverflow.com/a/49608227
downvote count: 0
has body: There is only one rule when it comes to importing files in a Python project. You have to import the package relative to the directory from where the project is run. For example in the question main.py should have something like this: from dir.frontend import * from dir.dir2.backend import * But then you'll have to have something like main.py under dir/ which imports dir/dir1/main.py and then run python main.py. So, try to keep the main.py always in the head directory so you don't have to worry about such a situation as above. ONLY ONE RULE: Everything has to be imported relatively to the directory from where the project is run.
answers question: http://stackoverflow.com/q/47530191
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47530191
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48155373
type: Answer
score: 2
has body: The problem was with the import at the beginning of setup.py. The import in line 2 (from dicamsdk.control import __version__) forced the code check of the module. When removed, the install or build of the packages runs correctly.
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47511947

http://stackoverflow.com/q/47449545
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81854034
has answer: http://stackoverflow.com/a/47449616
score: 2
has title: how to split values in a datacolumn and adding it to a new column with a condition in pandas
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have a df, name Value Sri is a cricketer Sri,is Ram player Ram Ravi is a singer is cricket and foot is ball and,is,foot and a list, my_list=["is", "foot"] I am trying to split df["value"] by (,) and adding the value to a new column if the value exists in my_list. My expected output is name Value my_list Sri is a cricketer Sri is Ram player Ram Ravi is a singer is cricket and foot is ball and is,foot please help to achieve this, thanks in advance
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81853998
tagged with: data-analysis
upvote count: 2

http://stackoverflow.com/a/47443180
has body: I found it out, had to add this on top of the other import statements (all lines are important): #!/usr/bin/python -S import sys reload(sys) sys.setdefaultencoding("cp1252") import site cp1252 is the encoding reported to me by import locale print locale.getpreferredencoding() However the encoding of my "name" parameter was not cp1252 when I got it, had to find out with chardet lib (pip install chardet)that it was actually ISO-8859-9. So since I wanted to create a folder with this argument I encoded it back to cp1252: #!/usr/bin/python -S import sys reload(sys) sys.setdefaultencoding("cp1252") import site import click from click_shell import shell import os import locale import chardet @shell(prompt='Tool &gt; ', intro='some test...', hist_file=os.path.dirname(os.path.realpath(__file__))) def stRec(): pass @stRec.command() @click.argument('name', required=True, type=click.STRING) def set(name): # Create folder in the folder running this script folderPath = os.path.join(os.path.split(os.path.abspath(__file__))[0], name) folderPath = folderPath.decode(str(chardet.detect(bytes(folderPath))['encoding'])).encode(locale.getpreferredencoding()) if not os.path.exists(folderPath): os.makedirs(folderPath) if __name__ == '__main__': stRec()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47440247

http://stackoverflow.com/a/47398886
has body: you will need to assign values to the variables in your main function, since you are declaring these as global variables. Zombie = 'zombie' Zambie = 'zAmbie' Giant_Worm = 'big worm' Headless_Horseman = 'horseman without head' Also, consider using random.choice() choices = ( Zombie, Zambie, Giant_Worm, Headless_Horseman, Skeleton, Ghost, Ghoul, Baby_Sister, Little_Sister, Big_Sister, ) return random.choice(choices)
has comment: http://stackoverflow.com/comment/81751572
has comment: http://stackoverflow.com/comment/81751198
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/47398644
type: Answer
answers question: http://stackoverflow.com/q/47398644

http://stackoverflow.com/a/47462250
score: 0
has comment: http://stackoverflow.com/comment/81879516
upvote count: 1
has comment: http://stackoverflow.com/comment/81880338
downvote count: 1
has body: You can do this with a generator expression and the split() method: D = dict(i.split(":", 1) for i in Listing) If there are some items that don't have the x:y format and you want to ignore them, you can add a conditional: D = dict(i.split(":", 1) for i in Listing if ":" in i)
has comment: http://stackoverflow.com/comment/82246885
answers question: http://stackoverflow.com/q/47462233
has comment: http://stackoverflow.com/comment/81879408
type: Answer
has comment: http://stackoverflow.com/comment/81879462
has comment: http://stackoverflow.com/comment/81979831

http://stackoverflow.com/q/47403683
accepted answer: http://stackoverflow.com/a/47404042
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47404042
score: 1
tagged with: matplotlib
has title: Plot 2D histogram data with pcolormesh
tagged with: python
type: Question
has body: I need to plot a binned statistic, as one would get from scipy.stats.binned_statistic_2d. Basically, that means I have edge values and within-bin data. This also means I cannot (to my knowledge) use plt.hist2d. Here's a code snippet to generate the sort of data I might need to plot: import numpy as np x_edges = np.arange(6) y_edges = np.arange(6) bin_values = np.random.randn(5, 5) One would imagine that I could use pcolormesh for this, but the issue is that pcolormesh does not allow for bin edge values. The following will only plot the values in bins 1 through 4. The 5th value is excluded, since while pcolormesh "knows" that the value at 4.0 is some value, there is no later value to plot, so the width of the 5th bin is zero. import matplotlib.pyplot as plt X, Y = np.broadcast_arrays(x_edges[:5, None], y_edges[None, :5]) plt.figure() plt.pcolormesh(X, Y, bin_values) plt.show() I can get around this with an ugly hack by adding an additional set of values equal to the last values: import matplotlib.pyplot as plt X, Y = np.broadcast_arrays(x_edges[:, None], y_edges[None, :]) dummy_bin_values = np.zeros([6, 6]) dummy_bin_values[:5, :5] = bin_values dummy_bin_values[5, :] = dummy_bin_values[4, :] dummy_bin_values[:, 5] = dummy_bin_values[:, 4] plt.figure() plt.pcolormesh(X, Y, dummy_bin_values) plt.show() However, this is an ugly hack. Is there any cleaner way to plot 2D histogram data with bin edge values? "No" is possibly the correct answer, but convince me that's the case if it is.
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81809424
score: 1
type: Comment
type: QuestionComment
has text: In what ways is your code not working? What results do you expect? How do they coompare to what you're getting?
comment on: http://stackoverflow.com/q/47427386

http://stackoverflow.com/q/47390787
tagged with: optimization
tagged with: opencv
tagged with: webcam
has comment: http://stackoverflow.com/comment/81776121
has comment: http://stackoverflow.com/comment/81749890
score: 0
has body: I got a BRIO 4k Logitech Webcam for a research project deducing car velocity through pictures taken of traffic. It is working fine, I am currently trying to optimize the speed of taking pics with the highest possible resolution. I am using Logitech software to disable autofocus &amp; set it to as far as possible (focus not changeable through cv2 as far as I know). I put my current 3 program files here: https://1drv.ms/f/s!AvdFsPpMX-gYrA9zo-r_W340B7b8 take_photos.py is the script you need to run, just put all three in a folder and create a subfolder "pics" and it should work. func_cam.py includes functions that the main program is calling, params_cam.py some parameters like resolution (set to max throuch the 5k/5k input). The output will be the time taken to yield each image. Here are some typical outputs I get: 1.657 1.587 1.033 0.927 0.719 0.573 0.689 0.508 1.097 1.516 1.409 1.767 So you see quite a difference (no change in position, light condition, no moving objects in the imaging area) in times. How can I imporve image speeds, it is still to slow for my purposes (without reducing resolution) The second challenge I am currently facing is the big differences of image rates within a run despite almost no changes in image area or setup. Maybe there is an idea on how to stabilize this (time differences above)? I am looking forward to your help with these challenges I am facing! Thanks for this and all the best!
type: Question
answer count: 0
tagged with: python
tagged with: computer-vision
type: UnansweredQuestion
has title: Optimizing webcam picture rate python/cv2

http://stackoverflow.com/q/47480649
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: Multiple Inheritance and Multi-Level Inheritance
answer count: 1
has comment: http://stackoverflow.com/comment/81943122
has comment: http://stackoverflow.com/comment/81916460
linked to: http://stackoverflow.com/q/3277367
has body: Right, so I have to create this inheritance hierarchy for a school project, so ignoring certain redundancies (like how Square really doesn't need 2 parents), I've come across a strange way Python handles super calls. When initializing a square in the following code, it calls its super, which executes the Rectangle's initialization method. This makes sense. The rectangle then calls its super, which should go to the Parallelogram's initialization method; however, after some debugging, I've found that when it makes its super call, it is actually calling the Rhombus's initialization method. Can someone explain what is happening here and, if possible, a way to implement this properly without explicitly using class names? Relevant code is below. class Parallelogram: def __init__(self, base, side, theta): self.base = base self.side = side self.theta = theta class Rectangle(Parallelogram): def __init__(self, base, side): super(Rectangle, self).__init__(base, side, 90) class Rhombus(Parallelogram): def __init__(self, side, theta): super(Rhombus, self).__init__(side, side, theta) class Square(Rectangle, Rhombus): def __init__(self, side): super(Square, self).__init__(side, side)
score: 0
has comment: http://stackoverflow.com/comment/81916453
tagged with: python
has answer: http://stackoverflow.com/a/47481069

http://stackoverflow.com/q/47439871
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47439956
has comment: http://stackoverflow.com/comment/81834622
has answer: http://stackoverflow.com/a/47439962
has title: Get All Unique Values in a Row
score: 10
has body: I have a DataFrame df1 that looks like this: A B C ----------------- 1 1 2 2 2 3 5 4 9 I want to get all the unique values in a row. For example 1 and 2 in the first row. 2, 3 in the second row. And 4, 5 and 9 in the third row. Result can vary, I can imagine a new column that contains a list with unique values or replacing duplicates with None would be also okay (or something else, maybe there is something more pythonic for this case).
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47439956
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47440066
accepted answer: http://stackoverflow.com/a/47439962
upvote count: 10

http://stackoverflow.com/q/47507851
tagged with: deep-copy
tagged with: numba
has answer: http://stackoverflow.com/a/47515660
has body: How can I make a copy of a numba jitclass instance (whose variables are numpy scalars and arrays)? Is there a better way other than making a new instance and copying all variables in a loop? I also tried copy.copy and copy.deepcopy, but both fail with TypeError: can't pickle MyJitClassName objects
tagged with: python
tagged with: copy
type: Question
score: 2
answer count: 2
upvote count: 2
type: UnansweredQuestion
has title: Numba - copy of a jitclass instance
downvote count: 0
favorite count: 0
tagged with: jit
has answer: http://stackoverflow.com/a/78850435

http://stackoverflow.com/q/47461653
accepted answer: http://stackoverflow.com/a/47462105
has answer: http://stackoverflow.com/a/47462076
score: 0
tagged with: loops
has body: What I am trying to do, is to loop every time the user inputs 'no' for ''Is it 6 am?''or ''Is it 9 am?'' to ''Is it 9 am'' or ''Is it 6 am'', respectively. The code is supposed to set the temperature to 19 degrees when 9 am and 22 degrees when 6 am `start = 'yes' temp = 'yes' print('Start') if start == 'yes': if temp == 'yes': temp_input = input('Is it 6 am?') temp = 'no' if temp_input == 'yes': print('Checking temperature == 22 degrees') temp_input = 'no' if temp_input == 'no': input2 = input('Is it 9 am?')` This is my program.
type: Question
has comment: http://stackoverflow.com/comment/81878133
possible better answer: http://stackoverflow.com/a/47462076
has answer: http://stackoverflow.com/a/47462105
tagged with: python
has title: How can you loop to another different input command, everytime the same response is inputted in Python?
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/81875891
has text: yes indeed, although having multiple Python interpreters is not a hassle
comment on: http://stackoverflow.com/a/47459173
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81847687
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47446137
has text: @COLDSPEED Thanks! Just in case you didn't see my edit (sorry) what exactly does "if re.match(r"(\s|^)run(\s|$)",runny,flags=re.I):" do if I were to use regex?

http://stackoverflow.com/comment/81966169
type: QuestionComment
has text: Did you implement the [Registry Setting](https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration) as well? Additionally, how are you running your tests? Locally or via a terminal? If the latter, have a look at this [Selenium User Group](https://groups.google.com/d/msg/selenium-users/EXrE5uATK1o/_6Yp40kpAgAJ) post where the suggestion was to run `psexec \\localhost -i 0`
score: 0
comment on: http://stackoverflow.com/q/47497708
type: Comment

http://stackoverflow.com/q/47520590
type: AnsweredQuestion
score: 2
has title: Python - optimizing code ( looping through arrays )
has answer: http://stackoverflow.com/a/47520826
answer count: 2
upvote count: 2
tagged with: arrays
downvote count: 0
has body: I have two arrays, A and B. Based on a function, I create a subset C from A and a subset D from B. Now, I want to join them together ( I want to keep those items that are in C and D with the same index in A and B). A = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) B = np.array([20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]) C = np.array([3,7,13]) D = np.array([18,8]) fvl1 = list() fvl2 = list() for i in C: index = np.where(A == i) if B[index] in D: fvl1.append(A[index]) fvl2.append(B[index]) print(fvl1) print(fvl2) Output: [array([3]), array([13])] [array([18]), array([8])] This is what I've done until now, but it's really slow. Is there any way to optimize this for it to go faster? LE: You can see that the element 3 in A has the same index as element 18 in B(index = 3), same with element 13 from A and 8 from B.
accepted answer: http://stackoverflow.com/a/47520865
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81997762
has answer: http://stackoverflow.com/a/47520865
has comment: http://stackoverflow.com/comment/81998035
has comment: http://stackoverflow.com/comment/81998233
tagged with: python
has comment: http://stackoverflow.com/comment/81997728
possible better answer: http://stackoverflow.com/a/47520826
tagged with: numpy

http://stackoverflow.com/comment/81767565
score: 0
comment on: http://stackoverflow.com/q/47405813
has text: @hoefling build/temp.linux-x86_64-3.5/_openssl.c:53885:14: warning: conversion to 'long unsigned int' from 'long int' may change the sign of the result [-Wsign-conversion] . this came up.
type: Comment
type: QuestionComment

python-2.7
tags question: http://stackoverflow.com/q/47466491
tags question: http://stackoverflow.com/q/47487749
tags question: http://stackoverflow.com/q/47433067
tags question: http://stackoverflow.com/q/47522072
tags question: http://stackoverflow.com/q/47540146
tags question: http://stackoverflow.com/q/47497383
tags question: http://stackoverflow.com/q/47407576
tags question: http://stackoverflow.com/q/47447559
tags question: http://stackoverflow.com/q/47515103
tags question: http://stackoverflow.com/q/47423745
tags question: http://stackoverflow.com/q/47416625
tags question: http://stackoverflow.com/q/47528539
tags question: http://stackoverflow.com/q/47387699
tags question: http://stackoverflow.com/q/47526503
tags question: http://stackoverflow.com/q/47514695
tags question: http://stackoverflow.com/q/47466281
tags question: http://stackoverflow.com/q/47465730
tags question: http://stackoverflow.com/q/47422112
tags question: http://stackoverflow.com/q/47390107
tags question: http://stackoverflow.com/q/47502679
tags question: http://stackoverflow.com/q/47491733
tags question: http://stackoverflow.com/q/47514099
tags question: http://stackoverflow.com/q/47509857
tags question: http://stackoverflow.com/q/47400957
tags question: http://stackoverflow.com/q/47436776
tags question: http://stackoverflow.com/q/47492406
tags question: http://stackoverflow.com/q/47399143
tags question: http://stackoverflow.com/q/47518609
tags question: http://stackoverflow.com/q/47537226
tags question: http://stackoverflow.com/q/47421776
tags question: http://stackoverflow.com/q/47447033
tags question: http://stackoverflow.com/q/47451868
tags question: http://stackoverflow.com/q/47444695
tags question: http://stackoverflow.com/q/47447836
tags question: http://stackoverflow.com/q/47450032
tags question: http://stackoverflow.com/q/47391001
tags question: http://stackoverflow.com/q/47432401
tags question: http://stackoverflow.com/q/47405680
tags question: http://stackoverflow.com/q/47393018
tags question: http://stackoverflow.com/q/47534476
tags question: http://stackoverflow.com/q/47481361
tags question: http://stackoverflow.com/q/47462122
tags question: http://stackoverflow.com/q/47437988
tags question: http://stackoverflow.com/q/47384440
tags question: http://stackoverflow.com/q/47444727
tags question: http://stackoverflow.com/q/47495732
tags question: http://stackoverflow.com/q/47535672
tags question: http://stackoverflow.com/q/47423101
tags question: http://stackoverflow.com/q/47505000
tags question: http://stackoverflow.com/q/47469332
tags question: http://stackoverflow.com/q/47495596
type: Tag
tags question: http://stackoverflow.com/q/47434544
tags question: http://stackoverflow.com/q/47397461
tags question: http://stackoverflow.com/q/47441191
tags question: http://stackoverflow.com/q/47443660
tags question: http://stackoverflow.com/q/47531637
tags question: http://stackoverflow.com/q/47512599
tags question: http://stackoverflow.com/q/47402881
tags question: http://stackoverflow.com/q/47465922
tags question: http://stackoverflow.com/q/47385250
tags question: http://stackoverflow.com/q/47427386
tags question: http://stackoverflow.com/q/47443685
tags question: http://stackoverflow.com/q/47401829
tags question: http://stackoverflow.com/q/47399486
tags question: http://stackoverflow.com/q/47452723
tags question: http://stackoverflow.com/q/47438306
tags question: http://stackoverflow.com/q/47390846
tags question: http://stackoverflow.com/q/47515994
tags question: http://stackoverflow.com/q/47383691
tags question: http://stackoverflow.com/q/47526332
tags question: http://stackoverflow.com/q/47426435
tags question: http://stackoverflow.com/q/47471234
tags question: http://stackoverflow.com/q/47535373
tags question: http://stackoverflow.com/q/47503883
tags question: http://stackoverflow.com/q/47391673
tags question: http://stackoverflow.com/q/47501207
tags question: http://stackoverflow.com/q/47413437
tags question: http://stackoverflow.com/q/47425585
tags question: http://stackoverflow.com/q/47432965

http://stackoverflow.com/comment/81962262
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47503123
has text: I don't know what you were trying to do with that `quiver` call, but that doesn't look anything like [how `quiver` is supposed to take arguments](https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.quiver.html).

http://stackoverflow.com/q/47519350
has answer: http://stackoverflow.com/a/47519440
score: 1
has comment: http://stackoverflow.com/comment/81996645
tagged with: windows
tagged with: python
tagged with: exe
has title: Exe file created using pyinstaller shuts immediately when executing
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81996676
downvote count: 0
upvote count: 1
has body: I've tried to create an executable file using pyinstaller (python 3.6) I've tried to to do this on windows 10 using(also python 3.5) py2exe, and freeze(something), but only pyinstaller was "brave" enough to create an exe file. When I was opening the file.py through command prompt - no problem occured. But when I was trying to execute the file.exe - there is showing up a black window like a command prompt, and suddenly it disappears, while the file.exe is not executing. While creating an exe.file I had few warnings in command prompt: 12914 WARNING: lib not found: api-ms-win-crt-convert-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tk86t.dll 12986 WARNING: lib not found: api-ms-win-crt-utility-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tk86t.dll 13141 WARNING: lib not found: api-ms-win-crt-string-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll 13210 WARNING: lib not found: api-ms-win-crt-time-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll 13284 WARNING: lib not found: api-ms-win-crt-math-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll 13357 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll 13432 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll 13505 WARNING: lib not found: api-ms-win-crt-heap-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll 13576 WARNING: lib not found: api-ms-win-crt-environment-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll 13646 WARNING: lib not found: api-ms-win-crt-convert-l1-1-0.dll dependency of c:\users\krzys\appdata\local\progr…
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47642831
tagged with: pyinstaller

http://stackoverflow.com/comment/81856451
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47438533
has text: Thanks for the explanation ( loved it ) and the solution, worked perfectly !!.

http://stackoverflow.com/comment/82135585
comment on: http://stackoverflow.com/a/47555252
has text: That is not the input, it is a picture of the input. The reason pictures of your code are not allowed is that we cannot run them. And a picture of the input isn't any use for the same reason. Your program is expecting ascii data, not a picture. As I indicated, the problem you report is almost certainly in the data and not in the code. Post your input as code, your output as code, and report the entire error message you get including the stack trace. Otherwise it's not possible to reproduce your problem.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81756737
score: 0
type: Comment
type: QuestionComment
has text: First of all, your accuracy is always either 100% or 0%. Is that average loss for an epoch?
comment on: http://stackoverflow.com/q/47401556

http://stackoverflow.com/q/47391948
upvote count: 7
score: 7
tagged with: matplotlib
answer count: 1
tagged with: python
has body: I like using the background_gradient as it helps me look at my dataframes in an excel way. But I'm wondering if I there is a way I could map the colors to the figures in another dataframe. For example, something I am keen to do is to color the dataframe using a dataframe of zscores so i can see quickly the value of outliers. A = pd.DataFrame(np.random.randn(6, 3), columns=['a', 'b', 'c']) B = pd.DataFrame(np.random.randn(6, 3), columns=['a', 'b', 'c']) A.style.background_gradient(???) I'm wondering how to use background_gradient so that it uses the values in the dataframe B to style A.
has comment: http://stackoverflow.com/comment/81739272
favorite count: 0
type: Question
tagged with: pandas-styles
has title: Pandas - Style - Background Gradient using other dataframe
has comment: http://stackoverflow.com/comment/81736937
has answer: http://stackoverflow.com/a/47393167
accepted answer: http://stackoverflow.com/a/47393167
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81737074
downvote count: 0
tagged with: pandas

http://stackoverflow.com/a/47504187
type: Answer
has body: The echo function returns another function, that has n set to whatever you pass it. When you call inner_echo (ie, the return of echo) it keeps the scope that it was given when created. In your example, twice is created using echo(2) which returns the inner_echo function which, in it's scope, n is set to 2. Likewise, thrice, created by echo(3) creates a new version of inner_echo, where n is set to 3. Remember how echo returns a function? When you call twice or thrice you are calling the function that echo returned - ie, you are not calling echo at all. Therefore calling twice is calling inner_echo and that is how word is being populated.
answers question: http://stackoverflow.com/q/47504144
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47429983
has comment: http://stackoverflow.com/comment/81822723
answers question: http://stackoverflow.com/q/47428786
score: 1
has comment: http://stackoverflow.com/comment/81822438
type: Answer
has comment: http://stackoverflow.com/comment/81822943
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81823601
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47428786
has body: You may use ^[_a-zA-Z]\w*\[(?! *\]) *-? *\d*(?: *: *-? *\d*){0,2} *\]$ See the regex demo. The spaces may be replaced with [[:blank:]] or [ \t] to match horizontal whitespace. Pattern details ^ - start of string [_a-zA-Z] - a _ or an ASCII letter \w* - ASCII letters/digits/_ \[ - a [ (?! *\]) - there cannot be 0+ spaces followed with ] *-? * - 0+ spaces, an optional -, 0+ spaces \d* (?: *: *-? *\d*){0,2} - zero, one or two occurrenes of: *: *-? * - 0+ spaces, an optional -, 0+ spaces \d* - 0+ digits *] - 0+ spaces and ] $ - end of string. See the C++ demo (note that with regex_match, the ^ and $ become redundant and may be omitted): #include &lt;iostream&gt; #include &lt;regex&gt; using namespace std; int main() { std::vector&lt;std::string&gt; strings; strings.push_back("a[0]"); strings.push_back("a[:]"); strings.push_back("a[::]"); strings.push_back("a[0:]"); strings.push_back("a[-1::]"); strings.push_back("a[ 2 : 1:2]"); strings.push_back("a[: -1:]"); strings.push_back("a[::- 1]"); strings.push_back("a[1:10:2]"); strings.push_back("a[]"); std::regex rex1(R"([_a-zA-Z]\w*\[(?! *\]) *-? *\d*(?: *: *-? *\d*){0,2} *\])"); for (auto s : strings) { std::cout &lt;&lt; "Next string: " &lt;&lt; s; if (regex_match(s, rex1)) { std::cout &lt;&lt; "&lt;= Matched" &lt;&lt; std::endl; } else { std::cout &lt;&lt; "&lt;= Not Matched" &lt;&lt; std::endl; } } return 0; } Output: Next string: a[0]&lt;= Matched Next string: a[:]&lt;= Matched Next string: a[::]&lt;= Matched Next string: a[0:]&lt;= Matched Next string: a[-1::]&lt;= Matched Next string: a[ 2 : 1:2]&lt;= Matched Next string: a[: -1:]&lt;= Matched Next string: a[::- 1]&lt;= Matched Next string: a[1:10:2]&lt;= Matched Next string: a[]&lt;= Not Matched

http://stackoverflow.com/a/51030528
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47508518
upvote count: 4
downvote count: 0
has body: This is somewhat old, but the answers on here didn't solve the issue. A little googling got me here http://chromedriver.chromium.org/getting-started The test code here uses sleep to keep the browser open. I'm not sure if there are better options, so I will update this as I learn. import time from selenium import webdriver driver = webdriver.Chrome('/path/to/chromedriver') # Optional argument, if not specified will search path. driver.get('http://www.google.com/xhtml'); time.sleep(5) # Let the user actually see something! search_box = driver.find_element_by_name('q') search_box.send_keys('ChromeDriver') search_box.submit() time.sleep(5) # Let the user actually see something! driver.quit()

http://stackoverflow.com/a/47436045
type: Answer
has comment: http://stackoverflow.com/comment/81826630
answers question: http://stackoverflow.com/q/47435152
score: 1
has body: Method T does return super(DataFrame, self).transpose(1, 0, **kwargs). It will create another DataFrame.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81827024

http://stackoverflow.com/comment/81845209
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47440162
type: Comment
has text: but im shure the compress()-method is the only problem now.

http://stackoverflow.com/comment/81724176
type: QuestionComment
has text: Must be the third question for this today. Who gave you that homework?
type: Comment
comment on: http://stackoverflow.com/q/47385401
score: 1

http://stackoverflow.com/comment/81901148
comment on: http://stackoverflow.com/q/47473043
type: Comment
has text: You should add whole code sample - not just data.
type: QuestionComment
score: 0

django-apps
tags question: http://stackoverflow.com/q/47475385
tag name: django-apps
type: Tag

http://stackoverflow.com/a/47411454
downvote count: 0
answers question: http://stackoverflow.com/q/47403634
has comment: http://stackoverflow.com/comment/81798294
upvote count: 5
has body: Your network is too deep for the size of images you are using (60x60). As you know, the CNN layers do produce smaller and smaller feature maps as the input image propagate through the layers. This is because you are not using padding. The error you have simply says that the next layer is expecting 512 feature maps with a size of 2 pixels by 2 pixels. The actual feature map produced from the forward pass was 512 maps of size 0x0. This mismatch is what triggered the error. Generally, all stock networks, such as RESNET-18, Inception, etc, require the input images to be of the size 224x224 (at least). You can do this easier using the torchvision transforms[1]. You can also use larger image sizes with one exception for the AlexNet which has the size of feature vector hardcoded as explained in my answer in [2]. Bonus Tip: If you are using the network in pre-tained mode, you will need to whiten the data using the parameters in the pytorch documentation at [3]. Links http://pytorch.org/docs/master/torchvision/transforms.html https://stackoverflow.com/a/46865203/7387369 http://pytorch.org/docs/master/torchvision/models.html
type: Answer
has comment: http://stackoverflow.com/comment/81776223
has comment: http://stackoverflow.com/comment/81776472
score: 5
accepted answer of: http://stackoverflow.com/q/47403634
has comment: http://stackoverflow.com/comment/81777049
type: AcceptedAnswer

http://stackoverflow.com/comment/81938690
has text: Thanks for the advice. I'm new to Python and Stackoverflow so I am not familiar to convention. I will keep that in mind for next time. By the way any thoughts on what's causing the problem with my plots?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47491303

http://stackoverflow.com/comment/81816189
comment on: http://stackoverflow.com/a/47427466
type: AnswerComment
score: 1
type: Comment
has text: it seems that the SourceFroge repo doesn't have the latest binary. is it true?

http://stackoverflow.com/comment/81767830
comment on: http://stackoverflow.com/q/47389672
type: Comment
type: QuestionComment
score: 0
has text: Yeah, indeed. It seem that the first defined gets the variable in that case.

http://stackoverflow.com/q/47528938
tagged with: python
has answer: http://stackoverflow.com/a/47532350
accepted answer: http://stackoverflow.com/a/47532350
type: AnsweredQuestion
has title: filtering issue with a django template with two querysets - django
score: 0
tagged with: django-templates
has comment: http://stackoverflow.com/comment/82018403
answer count: 1
tagged with: django-forms
type: Question
has body: I have a django template that I want to use to filter objects in a query sets. I have a group that I want to add new members to. I have a list of member objects that are used to keep track of the groups members that were added when the group was created. The members were added by displaying a list of users friends with a checkbox next to their names. I now want to display a list of friends that are not already members of the group and then add them to the group if they are selected. I am getting an issue with the html template filtering system that I have created to just show the list of friends that are not already members... can anyone help me figure this out. I have all the code below: here is the queries that were passed: # grab the group members members = Member.objects.filter(group = group).all() # grab all of the friends fo the logged in user friender = Friend.objects.filter(user = user.username).all() friended = Friend.objects.filter(friend = user).all() friends = friender | friended # the required parameters for this form parameters = { 'friends':friends, 'members':members, 'group':group, 'message':message, } return render(request, 'groups/add_members.html', parameters) Now here is the html template : {% extends "general/header.html" %} {% block content %} Create Group {{ message }} {% csrf_token %} {% for friend in friends %} {% for member in members %} {% if member.user.username != friend.friend.username %} {% if member.user.username != friend.user %} {% if friend.user == user.username %} {{ friend.friend.username }} {% endif %} {% if friend.friend == user %} {{ friend.user }} {% endif %} {% endif %} {% endif %} {% endfor %} {% endfor %} {% endblock %} Here is the list of friends and members that exist right now logged in user omar friends: hani, assad, rana, amer members: hani, assad here is what is displaying: Here are the models: # the following are models for accepted friend requests class Friend(models.Model): user = models.CharField(max_length=22, d…
tagged with: django

http://stackoverflow.com/q/47538718
has comment: http://stackoverflow.com/comment/82035650
has comment: http://stackoverflow.com/comment/82035519
type: Question
type: UnansweredQuestion
has title: histogram plotting matplotlib
has comment: http://stackoverflow.com/comment/82034691
has comment: http://stackoverflow.com/comment/82035851
has body: I have an array of numbers and i have an array which has the value of how many time element of numbers is used. I have to create histogram plot which show how many times element from numbers list is used. I know that histogram plot shows distribution but i didnt get the logic of bining. import sys, tkinter import matplotlib.pyplot as plt numbers=['23.7', '23.718', '23.73', '23.7225', '23.754', '23.76', '23.736', '23.745', '23.6','23.64','23.65','23.625','23.6166666666667','23.6666666666667', '23.575', '23.54', '23.525', '23.5', '23.445', '23.39', '23.37', '23.3733333333333', '23.3233333333333', '23.365', '23.29', '23.3066666666667', '23.272', '23.2', '23.23', '23.215', '23.14', '23.15', '23.18', '23.1166666666667', '23.1', '23.06', '23.02', '23.01', '23', '22.9816666666667', '22.945', '22.956', '22.9725', '22.912', '22.89', '22.865', '22.8733333333333', '22.815', '22.84', '22.79', '22.772', '22.76''] how_many_times=[2, 1, 2, 2, 1, 3, 1, 2, 1, 1, 3, 1, 2, 1, 1, 1, 3, 1, 4, 2, 3, 1, 5, 1, 1, 1, 1, 10, 1, 1, 2, 1, 2, 1, 1, 19, 4, 2, 2, 2, 3, 1, 32, 2, 2, 6, 1, 2, 1, 1, 17, 3, 4, 6, 2, 3, 7, 44, 1, 5, 3, 1, 6, 3, 2, 3, 3, 2, 56, 1, 7, 6, 1, 16, 6, 18, 3, 4, 75, 1, 7, 6, 10, 1, 3,] numbers=[float(x) for x in numbers] plt.hist(numbers,bins, histtype='bar',rwidth=0.08) plt.xlabel('Numbers') plt.legend() plt.show() This code doesn't show the correct bins and numbers.How can I fix this?
has comment: http://stackoverflow.com/comment/82034978
has comment: http://stackoverflow.com/comment/82035895
tagged with: python
tagged with: plot
tagged with: bins
has comment: http://stackoverflow.com/comment/82035734
has comment: http://stackoverflow.com/comment/82035285
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82038186
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82034824

http://stackoverflow.com/a/47465420
upvote count: 2
has body: As other people have pointed out this happens because in python strings, as all of the other types I am aware of, are objects. Strings specifically are objects of the str class. You may look here for more on this. Also methods usually refer to functions bound to objects. This excellent post about how methods work on python may interest you.
type: Answer
answers question: http://stackoverflow.com/q/47465305
score: 2
downvote count: 0

http://stackoverflow.com/q/47393658
type: AnsweredQuestion
tagged with: time-series
has answer: http://stackoverflow.com/a/47393777
has title: Pandas generate missing dates & hours with 0 values
tagged with: dataframe
tagged with: python
has body: I have this dataframe : date station count 2015-01-01 13:00:00 A 4 2015-01-01 14:00:00 B 2 2015-01-02 15:00:00 A 7 For simplicity, pretend that the station only have 2 values : A &amp; B My goal is to generate 0 count for each date, each hour, and each station. For example, the code will generate : date station count 2015-01-01 00:00:00 A 0 2015-01-01 00:00:00 B 0 This is what I tried : # generate 0 values (no transaction) for each hour at each station df_trans = df_trans.set_index(['date', 'station']) (date_index, station_index) = df_trans.index.levels # generate a range of all dates &amp; hours all_dates = pd.date_range('2014-01-09', '2015-12-08', freq='H') new_index = pd.MultiIndex.from_product([all_dates, station_index]) df_trans = df_trans.reindex(new_index) df_trans = df_trans['net_rate'].fillna(0) However the result dataframe is not hourly. The output (no hour in date) : net_rate 2014-01-09 2 0.0 3 0.0 4 0.0
accepted answer: http://stackoverflow.com/a/47393777
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

multi-gpu
type: Tag
tag name: multi-gpu
tags question: http://stackoverflow.com/q/47530313

http://stackoverflow.com/comment/81732726
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47389858
type: AnswerComment
has text: Additional info: If the arguments have default values, but none is specified, the first wins (even if its default value is None).

http://stackoverflow.com/a/47506454
has body: Here is a link for string concatenation. What you want to archieve is something like this: from selenium import webdriver proxylist = open("proxylist.txt", "r+") proxy = proxylist.readlines() service_args = [ '--proxy='+proxy[18]+':'+proxy[19], '--proxy-type=socks5', ]
score: 0
answers question: http://stackoverflow.com/q/47496039
type: Answer

http://stackoverflow.com/a/47537824
score: 17
has comment: http://stackoverflow.com/comment/94253224
accepted answer of: http://stackoverflow.com/q/47537823
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91343568
upvote count: 17
answers question: http://stackoverflow.com/q/47537823
has body: The CategoricalDtype mentioned in the warning is available as pd.api.types.CategoricalDtype. So, you can write pd.Series(["a", "b", "b"]).astype(pd.api.types.CategoricalDtype(categories = ["a", "b", "c"])).
type: Answer

http://stackoverflow.com/comment/81992562
comment on: http://stackoverflow.com/q/47518131
type: Comment
type: QuestionComment
score: 0
has text: @silgon: Some (https://en.wikipedia.org/wiki/Convolutional_neural_network#ReLU_layer) would argue that ReLU itself constitutes a layer.

http://stackoverflow.com/comment/82017683
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47530574
has text: <urlopen error [Errno 101] Network is unreachable>
type: Comment

http://stackoverflow.com/q/47433169
has title: Replace values of one column for each value of another column in pandas
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
has body: I have a csv file shown below: ID,Number,Value 61745,three,11 61745,one,11 61745,one &amp; two,12 61745,two,13 61743,one,41 61743,two,42 61741,one,21 61741,one &amp; two,22 61715,one,31 61715,two,32 61715,three,33 What I am trying to achieve: For each ID, if the Number column contains "one &amp; two", I want all the Number column fields that contain "two" or "one" to be replaced with the "one &amp; two" value. For example, for the "61745" ID I can see the "one &amp; two" value at least once. But for the "61743" ID I cannot see this value. So, I want to return the following: ID,Number,Value 61745,three,11 61745,one &amp; two,11 61745,one &amp; two,12 61745,one &amp; two,13 61743,one,41 61743,two,42 61741,one &amp; two,21 61741,one &amp; two,22 61715,one,31 61715,two,32 61715,three,33 So far, I have tried this: import pandas as pd import os import csv import time import dateutil.parser as dparser import datetime df = pd.read_csv("slack.csv") for row in df.itertuples(): if row[2] == "one &amp; two": df.ix[df.Number.isin(['one &amp; two','one','two']), 'Number'] = 'one &amp; two' and the result is that the script replaces all the "two" and "one" values in the Number column for every ID: ID Number Value 0 61745 three 11 1 61745 one &amp; two 11 2 61745 one &amp; two 12 3 61745 one &amp; two 13 4 61743 one &amp; two 41 5 61743 one &amp; two 42 6 61741 one &amp; two 21 7 61741 one &amp; two 22 8 61715 one &amp; two 31 9 61715 one &amp; two 32 10 61715 pinterest 33
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47433396
type: Question
possible better answer: http://stackoverflow.com/a/47433353
has answer: http://stackoverflow.com/a/47433396
has answer: http://stackoverflow.com/a/47433353

http://stackoverflow.com/q/47526570
score: 0
has answer: http://stackoverflow.com/a/49630425
has title: Check Google In App Subscription Renewal Status
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: android-inapp-purchase
tagged with: in-app-purchase
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/36591498
has body: I have to implement Google In App susbscription in my app. In server side, I want to validate subscription status of user. The response of subscription is as follow { "kind": "androidpublisher#subscriptionPurchase", "startTimeMillis": long, "expiryTimeMillis": long, "autoRenewing": boolean, "priceCurrencyCode": string, "priceAmountMicros": long, "countryCode": string, "developerPayload": string, "paymentState": integer, "cancelReason": integer, "userCancellationTimeMillis": long, "orderId": string } Google has api to validate subscription status. Its response is as follow. { "kind": "androidpublisher#subscriptionPurchase", "startTimeMillis": long, "expiryTimeMillis": long, "autoRenewing": boolean, "priceCurrencyCode": string, "priceAmountMicros": long, "countryCode": string, "developerPayload": string, "paymentState": integer, "cancelReason": integer, "userCancellationTimeMillis": long, "orderId": string } I want to check user subscription status by using this API. The question I want to ask how will I know that user subscription has been renewed by this response. If user get subscription for one month and after one month, subscription will be renewed automatically. I have receipt for old subscription in my database and I will be using same OrderId to check subscription status. How will I new that subscription has been renewed for that particular orderId.

http://stackoverflow.com/comment/82116481
type: AnswerComment
score: 1
has text: My point is that this solution relies on the same data type that it pretends to avoid. It is a hack that obscures the distinction between variable names and data... and to what benefit? It doesn't even avoid the data type that _should_ have been used, in a perfectly straightforward way, from the start.
comment on: http://stackoverflow.com/a/47496649
type: Comment

http://stackoverflow.com/comment/82028938
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47535920
type: QuestionComment
has text: what is the dimension of each patch?

http://stackoverflow.com/a/47425745
has body: This suggests just what the error message says: some of your variables are collinear. In other words, the elements of one vector are a linear function of the elements of another, such as 0, 1, 2, 3 3, 5, 7, 9 In this case, LDA can't differentiate their influences on the rest of the world. I can't diagnose anything specific, since you failed to provide the suggested MCVE.
score: 7
type: Answer
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/47425694

http://stackoverflow.com/a/47466817
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47465586
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47465586
has body: using Javascript. Refer to the snippet : from selenium import webdriver wd = webdriver.Firefox() wd.execute_script("var list = document.getElementsByName('layer_from'); list[1].value='something'; var anotherList = document.getElementsByName('user_pwd'); anotherList[1].value='password';")

http://stackoverflow.com/comment/81879516
score: 0
type: AnswerComment
type: Comment
has text: @MooingRawr Isn't it better to just downvote the question? If the answer is good (like this one is), it just discourages answerers to answer questions, IMHO.
comment on: http://stackoverflow.com/a/47462250

http://stackoverflow.com/comment/81914100
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47479584
has text: it's a little more complicated than the dupe proposal. For instance, using `heapq` doesn't qualify here, because you have to associate the index, not only the value.

http://stackoverflow.com/comment/81922097
comment on: http://stackoverflow.com/q/47483215
type: Comment
has text: By the way what if same word is in both the bags? Why not just join the two columns as one and then take bag of words.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81932152
type: AnswerComment
has text: It seams your code expect variable `xx` but you didn't create it. You have to read data from file and assign to variable `xx` - ie. `xx = data['xx']` .
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47487883

http://stackoverflow.com/comment/81953321
comment on: http://stackoverflow.com/a/47499055
has text: @furas Oh I see, he was trying to convert a string representation of a float to an int
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49587570
score: 1
type: Answer
has body: The following code will open a new terminal and execute the process: process = subprocess.Popen( "sudo gnome-terminal -x python f.py", stdout=subprocess.PIPE, stderr=None, shell=True )
downvote count: 0
answers question: http://stackoverflow.com/q/47518944
upvote count: 1

http://stackoverflow.com/comment/81976768
score: 0
has text: I don't know if you can assume that, since I didn't see OP mention it anywhere... am I mistaken?
type: AnswerComment
comment on: http://stackoverflow.com/a/47510242
type: Comment

http://stackoverflow.com/q/47436718
type: AnsweredQuestion
has body: I have a list which consists of lines as lines = ['The query complexity'] I need to select each word in a separate line every time I start loop lines = ['The'] lines = ['query'] lines = ['complexity'] Please help me to obtain it as a list of seperate words. for i in array: print(array[0].split())
has comment: http://stackoverflow.com/comment/81827691
tagged with: python
score: -1
has title: splitting a list of sentences into seperate words in a array
type: Question
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81827763
has comment: http://stackoverflow.com/comment/81827776
has comment: http://stackoverflow.com/comment/81827823
has answer: http://stackoverflow.com/a/47436810
possible better answer: http://stackoverflow.com/a/47436810
has answer: http://stackoverflow.com/a/47436820
downvote count: 1
accepted answer: http://stackoverflow.com/a/47436820
favorite count: 0

http://stackoverflow.com/comment/81749845
type: Comment
type: QuestionComment
score: 0
has text: I just need to get the expected output.
comment on: http://stackoverflow.com/q/47398242

http://stackoverflow.com/q/47477338
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81918010
tagged with: opencv
score: 0
tagged with: python
tagged with: eclipse
has comment: http://stackoverflow.com/comment/81915864
type: Question
has body: I have the code below that I use to find if there is any dicontinuity on railways. The idea is to create bounding box and if there are 2 boxes, it means that everything is okay. Otherwise, if I have more than 2 boxes, it means that there is a discontinuity. So, at the end of my code, I put a function print len(contours). The problem is that when I have my final image (with blue rectangles), we can see those I need (those that cover the railways), but also some really little rectangles I don't want. It means that the function print len(contours) send me back a message telling me that there are 19 rectangles for example. My idea is to make a little function, asking the programme to count the number of rectangles with a minimal length or width (so it would count only the rectangles that cover the railways). I am a beginner in coding with Python and I have no idea about how to code this, does anyone can help me please? Thank you in advance for your help. Here is my code: import numpy as np import argparse import cv2 image = cv2.imread('..\img.jpg') frame = cv2.resize(image,(500,500)) """boundaries = [ ([17, 15, 100], [50, 56, 200]), ([86, 31, 4], [220, 88, 50]), ([25, 146, 190], [62, 174, 250]), ([103, 86, 65], [145, 133, 128])]""" boundaries = [([100, 100, 100], [255, 255, 255])] for (lower, upper) in boundaries: # create NumPy arrays from the boundaries lower = np.array(lower, dtype = "uint8") upper = np.array(upper, dtype = "uint8") # find the colors within the specified boundaries and apply # the mask mask = cv2.inRange(frame, lower, upper) output = cv2.bitwise_and(frame, frame, mask = mask) # show the images cv2.namedWindow("images", cv2.WINDOW_NORMAL) cv2.resizeWindow("images", 1000, 500) cv2.imshow("images", np.hstack([frame, output])) cv2.waitKey(0) gray=cv2.cvtColor(output,cv2.COLOR_BGR2GRAY) ret,th1 = cv2.threshold(gray,25,255,cv2.THRESH_BINARY) contours,hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: x,y,w,h =…
has title: How can I count the number of rectangles with a minimal length?
has answer: http://stackoverflow.com/a/47482958

http://stackoverflow.com/comment/82014151
comment on: http://stackoverflow.com/q/47528415
type: Comment
type: QuestionComment
score: 0
has text: Ok let us make it insane, but i need to be ready for this and not to loose anything (order or content): Host: abc.com, User-Agent: Mozilla, Host:123.com, TE: chunked, User-Agent: Safari. I am asking for experience in regards to ease of both storage and later lookup, preferably lookup by name.

http://stackoverflow.com/a/51705800
upvote count: 6
answers question: http://stackoverflow.com/q/47397711
has body: Might not be perfect but it worked great for me. import os import uncompyle6 your_directory = '' for dirpath, b, filenames in os.walk(your_directory): for filename in filenames: if not filename.endswith('.pyc'): continue filepath = dirpath + '/' + filename original_filename = filename.split('.')[0] original_filepath = dirpath + '/' + original_filename + '.py' with open(original_filepath, 'w') as f: uncompyle6.decompile_file(filepath, f)
type: Answer
downvote count: 0
score: 6

http://stackoverflow.com/q/47521206
has answer: http://stackoverflow.com/a/47521302
has comment: http://stackoverflow.com/comment/81999270
type: Question
has comment: http://stackoverflow.com/comment/81999016
answer count: 2
has comment: http://stackoverflow.com/comment/81999133
type: UnansweredQuestion
has title: Python Selenium Clicking Buttons
has answer: http://stackoverflow.com/a/47522726
tagged with: python
tagged with: jquery
tagged with: css
score: 0
has comment: http://stackoverflow.com/comment/81999079
tagged with: http://stackoverflow.com/tag/html
has body: I'm getting an error when asking Selenium to click a tab (or button) in my web app. Please see the code and the CSS selectors below: Error: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: #tab-item-1090 > md-icon:nth-child(1) CSS Selector for button Patient page button: #tab-item-1090 > md-icon:nth-child(1) Code for the script. It breaks at the 'patientPage' variable. def createPatient(): browser = webdriver.Firefox() browser.get(confidential) emailElem = browser.find_element_by_css_selector('#input_0') emailElem.send_keys('bconfidential') passElem = browser.find_element_by_css_selector('#input_1') passElem.send_keys('confidential') loginElem = browser.find_element_by_css_selector('button.md-raised:nth-child(4)').click() patientPage = browser.find_element_by_css_selector('#tab-item-1090 &gt; md-icon:nth-child(1)').click() patientOptions = browser.find_element_by_css_selector('.md-fab &gt; button:nth-child(1)').click() patientOption_Create = browser.find_element_by_css_selector('#menu_container_981 &gt; md-menu-content:nth-child(1) &gt; md-menu-item:nth-child(1) &gt; button:nth-child(1)').click() patientCreate_Firstname = browser.find_element_by_css_selector('#input_1072') patientCreate_Firstname.send_keys('Test') patientCreate_Lastname = browser.find_element_by_css_selector('#input_1073').click() patientCreate_Lastname.send_keys('Script') patientCreate_SSN = browser.find_element_by_css_selector('#input_1074') patientCreate_SSN.send_keys('9812') patientCreate_DOB = browser.find_element_by_css_selector('.md-datepicker-triangle-button').click() patientCreate_DOB_Month = browser.find_element_by_css_selector('#md-0-year-2015-8-1 &gt; span:nth-child(1)').click() patientCreate_DOB_Day = browser.find_element_by_css_selector('#md-0-month-2015-8-16 &gt; span:nth-child(1)').click() patientCreate_Submit = browser.find_element_by_css_selector('button.md-raised:nth-child(2)').click() createPatient() I'm not sure why this CSS element can't be …
tagged with: selenium

http://stackoverflow.com/a/47503462
answers question: http://stackoverflow.com/q/47503169
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: You must connect the clicked signal, this returns the item and the column pressed, we will use the item and the setChecked method self.tree.itemClicked.connect(self.onItemClicked) def onItemClicked(self, item, column): item.setCheckState(0, QtCore.Qt.Unchecked if item.checkState(0) == QtCore.Qt.Checked else QtCore.Qt.Checked )
has comment: http://stackoverflow.com/comment/82210348
has comment: http://stackoverflow.com/comment/82209217
has comment: http://stackoverflow.com/comment/82209201
has comment: http://stackoverflow.com/comment/82209140
type: Answer
accepted answer of: http://stackoverflow.com/q/47503169
has comment: http://stackoverflow.com/comment/82210386
has comment: http://stackoverflow.com/comment/82376912
has comment: http://stackoverflow.com/comment/82211191

http://stackoverflow.com/q/47437936
has comment: http://stackoverflow.com/comment/81832191
type: UnansweredQuestion
has title: How to preserve all leading white spaces when splitting the content of a FileReader in JavaScript?
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/81830374
score: 0
tagged with: whitespace
has body: I am trying to read in a python file and split the lines into elements of an array. I am able to read and split the file content, however sometimes the leading white space for some of the elements gets removed. Is there a way to split the file while making sure to retain all of the white spaces? Here is my code to read in the file: reader = new FileReader(); reader.onload = function (progressEvent) var lines = file.split("\n"); Here is an example input: def main(): print(1) print(2) def main2(): print(3) #test Here is the expected output: 0: "def main():" 1: " print(1)" 2: " print(2)" 3: "def main2():" 4: " print(3)" 5: " #test" Here is the real output: 0: "def main():" 1: "print(1)" 2: "print(2)" 3: "def main2():" 4: "print(3)" 5: "#test"
tagged with: regex
has comment: http://stackoverflow.com/comment/81830344
has comment: http://stackoverflow.com/comment/81830450
type: Question
linked to: http://stackoverflow.com/q/6156501
tagged with: split
answer count: 0

http://stackoverflow.com/comment/81805664
type: Comment
has text: Just load the python interpreter - it prints the version number when it starts up. Or you could start IDLE - the version # prints on the first line.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47424972

http://stackoverflow.com/comment/81876131
score: 0
type: Comment
has text: Also I believe the crash function doesn't work either, don't worry about that though. Thanks :)
type: QuestionComment
comment on: http://stackoverflow.com/q/47460794

http://stackoverflow.com/comment/81886039
score: 0
type: AnswerComment
has text: I'm not sure how that's a problem =/ Why would you have concerns about importing glob and using it once?
type: Comment
comment on: http://stackoverflow.com/a/47464938

http://stackoverflow.com/comment/114406165
has text: I have a similar question here https://stackoverflow.com/questions/64704015/nlp-classification-labels-have-many-similarirites-replace-to-only-have-one
score: 0
comment on: http://stackoverflow.com/a/47502290
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47463781
has body: I have to return the middle part of string. When the string has odd number of elements, the middle part is one letter and when the string has even number of elements, the middle part is two letters. If string is empty, return empty string "help" -&gt; "el" "hi" -&gt; "hi" "hey" -&gt; "e" I wrote a code: if len(s) % 2 != 0: return s[len(s)//2] elif len(s) % 2 == 0: return s[len(s)//2 - 1] + s[len(s)//2] With this I got a neede output but also an error that index is out of range. Where is mistake?
possible better answer: http://stackoverflow.com/a/47463842
accepted answer: http://stackoverflow.com/a/47463824
downvote count: 1
has answer: http://stackoverflow.com/a/47463824
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81882494
score: 1
has comment: http://stackoverflow.com/comment/81882436
tagged with: python
has answer: http://stackoverflow.com/a/47463842
has title: Return middle part of string
has comment: http://stackoverflow.com/comment/81882428
type: Question
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/81959048
type: AnswerComment
score: 1
has text: Thank you, this helped as well, I was confused by dictionaries and lists so this helps me understand what I'm working with better.
comment on: http://stackoverflow.com/a/47501579
type: Comment

http://stackoverflow.com/a/47480033
has body: The only reason that I could think is that you want to change from from spam import * to import spam as sp. If you would just replace those lines, it would instantly break the code, you would have to prefix everything with sp.. If you want to do this change at a slower pace, you can do this. Then you can slowely add the sp. where needed and eventually remove the from spam import *.
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/47479965
score: 3

http://stackoverflow.com/comment/82068923
has text: re: overlap : Of course. MFCCs are calculated over `winlen`, and each `winstep`. So number of windows depends on `winstep`. Quality of features depend on 'winlen'. For different applications you use different windows sizes.
type: Comment
comment on: http://stackoverflow.com/a/47555651
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82000611
type: Comment
comment on: http://stackoverflow.com/q/47522072
type: QuestionComment
has text: Apart of course for indentation being wrong, there is nothing in your current code that could cause this behaviour. Please see https://stackoverflow.com/help/mcve
score: 3

http://stackoverflow.com/a/47407845
upvote count: 25
has comment: http://stackoverflow.com/comment/81769127
score: 25
downvote count: 0
has comment: http://stackoverflow.com/comment/81769240
has body: You need to take into account you mocked the whole class. You can mock individual methods too: @mock.patch('library.library.Library.query_fun') def test_get_response(self, mock_query_fun): mock_query_fun.return_value = { 'text': 'Hi', 'entities': 'value' } } response = MockBotter.get_response() self.assertIsNotNone(response) Only Library.query_fun has been replaced, everything else in the class is still in place. Simplified demo: &gt;&gt;&gt; from unittest import mock &gt;&gt;&gt; class Library(object): ... def query_fun(self): ... pass ... def get_response(self): ... return self.query_fun() ... &gt;&gt;&gt; with mock.patch('__main__.Library.query_fun') as mock_query_fun: ... mock_query_fun.return_value = {'foo': 'bar'} ... print(Library().get_response()) ... {'foo': 'bar'}
answers question: http://stackoverflow.com/q/47407741
has comment: http://stackoverflow.com/comment/81769182
has comment: http://stackoverflow.com/comment/138101458
type: Answer
has comment: http://stackoverflow.com/comment/81769097

http://stackoverflow.com/q/47391702
upvote count: 39
answer count: 2
tagged with: colors
accepted answer: http://stackoverflow.com/a/47392973
has comment: http://stackoverflow.com/comment/81738655
has answer: http://stackoverflow.com/a/47395401
has answer: http://stackoverflow.com/a/47392973
tagged with: matplotlib
has title: How to make a colored markers legend from scratch
downvote count: 0
tagged with: markers
has body: In Matplotlib, I'm trying to make a legend with colored "markers" like this one : this one has been made using the scatter function, but is not adapted to my plot. I'd like to produce a legend "from scratch", without associated data. The color is important, and therefore should be an attribute of each marker. I've tried import matplotlib.markers as mmark list_mak = [mmark.MarkerStyle('.'),mmark.MarkerStyle(','),mmark.MarkerStyle('o')] list_lab = ['Marker 1','Marker 2','Marker 3'] plt.legend(list_mak,list_lab) But : The MarkerStyle class doesn't support color information I get the warning : UserWarning: Legend does not support <matplotlib.markers.MarkerStyle object at 0x7fca640c44d0> instances. A proxy artist may be used instead. But how can I define a proxy artist based on a marker ?
has comment: http://stackoverflow.com/comment/81738178
favorite count: 0
type: Question
score: 39
has comment: http://stackoverflow.com/comment/81737802
tagged with: legend
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47395401

http://stackoverflow.com/comment/81875067
type: Comment
comment on: http://stackoverflow.com/q/47460240
type: QuestionComment
score: 5
has text: A raw binary file. Each double is fixed 8 bytes length.

http://stackoverflow.com/a/47470787
has comment: http://stackoverflow.com/comment/81896030
has comment: http://stackoverflow.com/comment/81896115
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47470645
accepted answer of: http://stackoverflow.com/q/47470645
has comment: http://stackoverflow.com/comment/81896640
score: 3
has body: You were not far off: result = func(a) needs to be result = func(*args, **kwargs). This prints to screen. Writing to file is almost the same: def log_message(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) print(result) return result return wrapper @log_message def a_function_that_returns_a_string(): return "a string" @log_message def a_function_that_returns_a_strings_with_a_newline(s): return "{}\n".format(s) a = a_function_that_returns_a_string() b = a_function_that_returns_a_strings_with_a_newline('abc')
type: Answer
has comment: http://stackoverflow.com/comment/81896681

http://stackoverflow.com/a/47506981
has body: General purpose: import numpy as np from numpy.lib.stride_tricks import as_strided def moving_slice(a, k): a = a.ravel() return as_strided(a, (a.size - k + 1, k), 2 * a.strides) Moving avg better: def moving_avg(a, k): ps = np.cumsum(a) return (ps[k-1:] - np.r_[0, ps[:-k]]) / k Example: a = np.arange(10) moving_avg(a, 4) # array([ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]) ms = moving_slice(a, 4) ms # array([[0, 1, 2, 3], # [1, 2, 3, 4], # [2, 3, 4, 5], # [3, 4, 5, 6], # [4, 5, 6, 7], # [5, 6, 7, 8], # [6, 7, 8, 9]]) # no data are copied: a[4] = 0 ms # array([[0, 1, 2, 3], # [1, 2, 3, 0], # [2, 3, 0, 5], # [3, 0, 5, 6], # [0, 5, 6, 7], # [5, 6, 7, 8], # [6, 7, 8, 9]])
has comment: http://stackoverflow.com/comment/81970365
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81969853
accepted answer of: http://stackoverflow.com/q/47506663
answers question: http://stackoverflow.com/q/47506663
score: 1
type: Answer

http://stackoverflow.com/q/47499098
answer count: 2
upvote count: 0
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47499219
type: AnsweredQuestion
has body: I'm trying to animate a set of points that move around in a 2D space using matplotlib. It currently sort of works in that it the code does produce an animation of the points but it isn't how I was thinking it would work. Instead of plotting the points at each moment in time it plots them at all points in time instead. For example if the code is run with twenty points I would like it to show the twenty points at one frame and then those same points at the next frame and so on. Instead it keeps the previous frames points instead of just showing the new ones. Can someone please tell me where I have gone wrong? Also, I've found from my research that it would be best to enable blitting for the animation to optimise the problem but when I add blit=True as an argument for the FuncAnimation the console spits out a huge traceback ending in : File "C:\Users\Anaconda3\lib\site-packages\matplotlib\animation.py", line 1568, in _draw_frame a.set_animated(self._blit) AttributeError: 'numpy.ndarray' object has no attribute 'set_animated' I also don't know why this happens and searching online has not been helpful. The code follows: import matplotlib.pyplot as plt #Import plotting library from matplotlib import animation import numpy as np #Import numpy library dim = 2 #Defines the dimensionality of the system n = 25 #Number of BOIDS tmax = 80 #Length of sim dmax = 5 #Distance boids can "see", determines what other boids interact with them o = np.zeros(dim) #Origin as vector r = np.random.rand(n,dim) #Places BOIDs randomly with co-ordinates (x,y,z) from 0 to 1. Has dimensions n and dim v = 2*np.random.rand(n,dim)-1#Sets initial velocity of each BOID from -1 to 1 in each cardinal direction rt = np.zeros((tmax,n,dim)) #This array contains the whole system's positions at each point in time x = np.empty(n) y = np.empty(n) d = np.zeros(n) vk = np.zeros((n,2)) vksum = np.zeros((n,2)) pltx = np.zeros((tmax,n)) plty = np.zeros((tmax,n)) """rt[a][b][0] is the x co-ordinate of boid n=b at t=a…
has answer: http://stackoverflow.com/a/47499219
has title: matplotlib animation plotting all the points instead of just the latest iteration
accepted answer: http://stackoverflow.com/a/47500824
tagged with: matplotlib
tagged with: animation
has answer: http://stackoverflow.com/a/47500824
tagged with: python
score: -1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81953586

http://stackoverflow.com/comment/81764000
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47390554
has text: No.. Its just date
score: 0

http://stackoverflow.com/q/47418485
tagged with: pyyaml
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/47441501
upvote count: 1
answer count: 1
has body: I have a YAML file, test.yaml: test: server_group_1: type: OS::Nova::ServerGroup properties: name: { get_param: [server_groups, 5] } policies: [ { get_param: [server_group_types, 5] } ] and when I use PyYAML to read and print the output it gives me below output, which is different from the input test: server_group_1: properties: name: get_param: - server_groups - 5 policies: - get_param: - server_group_types - 5 type: OS::Nova::ServerGroup code: import yaml print yaml.dump(yaml.load(open('/test.yaml')), default_flow_style=False) I want the output same as the input, here order is also getting changed
favorite count: 0
has answer: http://stackoverflow.com/a/47422388
type: Question
accepted answer: http://stackoverflow.com/a/47422388
tagged with: ruamel.yaml
score: 1
has title: improper output with pyyaml
tagged with: python

http://stackoverflow.com/comment/137830816
score: 0
has text: how are you using it?, I have a working bot which tags users this way and it works like a charm
type: Comment
comment on: http://stackoverflow.com/a/78047935
type: AnswerComment

http://stackoverflow.com/q/47402207
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: How to extract accelerometer column and the data between the words "start" and "stop" from a csv and write into new csv file
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47402337
has body: import numpy as np import matplotlib.pyplot as plt from matplotlib import style path= r'C:\Users\npatel\Documents\Coremotion Data\MotionData\data_file.csv' datafile = open(path) data = open(path,'r') reader = path.reader(datafile) interestingrows=[row for idx, row in enumerate(reader) if idx in (start,stop)] new_path = r'C:\Users\npatel\Documents\Coremotion Data\MotionData\new_data.csv' new_data = open(new_path,'w') title = 'trial' new_data.write(title) print(title) new_data.write(data) print(data) Error: 'str' object has no attribute 'reader' I am new to python , so just learnt to read and write files but how can I extract the data between the keywords "start" and "stop" and save it to a new file? There are more than 10 columns but I want to extract only 4 columns with specific title.

spotify
tags question: http://stackoverflow.com/q/47532728
tag name: spotify
type: Tag

http://stackoverflow.com/q/47485011
score: 1
has comment: http://stackoverflow.com/comment/81925009
downvote count: 1
has title: Python, opencv and PIL: Creating a thumbnail with minimal background around the edges based on a centred image
favorite count: 0
tagged with: opencv
type: Question
tagged with: python-imaging-library
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47457918
has body: I have trimmed an image like this... to minimise the black background around it using the PIL libary. As follows But I need the result to maintain its thumbnail dimensions and maintain the aspect ratio and centring of the image. So in my example, (image2) I would need a little more height. I have tried to use the thumbnail function in PIL, opencv resize and also the imutils library without success. Keep in mind that the I have many of these images and the image of the Lungs in the middle will vary slightly in size so my trim function is dynamic to take care of that.
upvote count: 2
answer count: 0

http://stackoverflow.com/comment/81722098
type: Comment
comment on: http://stackoverflow.com/a/47384608
type: AnswerComment
score: 0
has text: the overall problem I am trying to solve is to change a base 10 number from to any base, without the abc thing. The final answer I need to get is a number not in a list

http://stackoverflow.com/q/47517038
score: 1
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: odoo
accepted answer: http://stackoverflow.com/a/47519481
tagged with: python
has answer: http://stackoverflow.com/a/47519481
has body: what i'm trying to do here is "consolidate" similar lines with the same product_id,and append it to get one2many field in another view wizard I got to fill a sale_order_line in my wizard field uing this method; def default_get(self, cr, uid, fields, context=None): if context is None: context = {} res = super(sale_order_consolidation, self).default_get(cr, uid, fields, context=context) picking_ids = context.get('active_ids', []) active_model = context.get('active_model') if not picking_ids or len(picking_ids) != 1: return res assert active_model in ('sale.order'), picking_id, = picking_ids picking = self.pool.get('sale.order').browse(cr, uid, picking_id, context=context) items = [] packs = [] if not picking.order_line: picking.do_prepare_partial() for op in picking.order_line: item = { 'ref': op.ref, 'product_id': op.product_id.id, 'name': op.name, 'product_uom_qty': op.product_uom_qty, 'product_uom': op.product_uom.name, 'price_standard': op.price_standard, 'price_unit': op.price_unit, 'discount_2': op.discount_2, #'tax_id': op.tax_id.id, 'price_subtotal': op.price_subtotal, } #if op.product_id: items.append(item) for rec in items: key = d['product_id'] # the right instruction to add QTY with the same products and append it to packs in order to update my one2many field res.update(order_line_consolidation=items) return res and what I actually want is : d = [{'product_id': "x" , 'price': 1 , 'Qty': 2}, {'product_id': "y" , 'price': 5 , 'Qty': 4}, {'product_id': "x" , 'price': 1 , 'Qty': 1}, {'product_id': "z" , 'price': 9 , 'Qty': 1}, {'product_id': "y" , 'price': 5 , 'Qty': 5} ] result: d = [{'product_id': "x" , 'price': 1 , 'Qty': 3}, {'product_id': "y" , 'price': 5 , 'Qty': 9}, {'product_id': "z" , 'price': 9 , 'Qty': 1}, ] what I actually looking for is the right way to add QTY with the same products and append it to packs in order to update my one2many field thanks you for your help, Best regards.
has title: list of dictionary consolidation
type: AnsweredQuestion
answer count: 1

http://stackoverflow.com/comment/81841407
score: 0
comment on: http://stackoverflow.com/q/47442733
type: Comment
has text: @juanpa.arrivillaga thanks. I tried to explicitly call import gc and gc.collect().. the memory could be reduced somehow but still too high than expected as I tried then to set e.g. df=df.loc[0:3] and then call gc.collect() again - however this time the memory usage didn't change...
type: QuestionComment

deserialization
type: Tag
tags question: http://stackoverflow.com/q/47394836
tags question: http://stackoverflow.com/q/47388241
tags question: http://stackoverflow.com/q/47410864
tag name: deserialization

http://stackoverflow.com/comment/81916263
score: 0
type: AnswerComment
has text: @RobertoBassett thanks, I appreciate it, and I'm sorry you feel that way about the website. StackOverflow is pretty awesome, and has helped me an uncountable amount of times, I only recently started trying to contribute myself. It may seem that some people on here have an "attitude", but that's really because they just want to maintain a certain level of quality on the questions and answers on the site. That requires some active moderation, which by some could definitely construed in a non-amicable way (especially if someone shits on a question you ask). So, I get where you're coming from.
type: Comment
comment on: http://stackoverflow.com/a/47398609

http://stackoverflow.com/q/47418061
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47419770
has body: I'm using successfully pythonwhois (installed with pip install ...) to check the availability of .com domains: import pythonwhois for domain in ['aaa.com', 'bbb.com', ...]: details = pythonwhois.get_whois(domain) if 'No match for' in str(details): # simple but it works! print domain But: it is a little bit slow (2 requests per second on average) won't I be blacklisted by the whois server if I do 26*26*26 ~ 17000 requests? (I'm testing availability of ???mail.com with ? being a..z) Question: is there a better way to check availability than doing one whois request per domain? Edit: The job finished in 9572 seconds, and here is the full list of all domains available of the form ???mail.com, as of November 2017, if anyone is interested to start an email service!
has answer: http://stackoverflow.com/a/47419770
tagged with: python
tagged with: domain-name
tagged with: whois
score: 2
upvote count: 2
answer count: 1
has title: Testing domain-name availability with pythonwhois
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/120713882
score: 2
type: AnswerComment
has text: If you are using C#, use: `code`options.AddExcludedArgument("enable-logging");`code`
comment on: http://stackoverflow.com/a/56408800
type: Comment

http://stackoverflow.com/comment/81812593
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47409072
score: 0
has text: Hi Garr, sorry it was a typo. I did start checking from the 2nd element

http://stackoverflow.com/comment/81857737
has text: thx.But same error happens.I updated my question again.Could u check my code which is as same as ur intended code?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47447191

http://stackoverflow.com/a/47504603
type: Answer
answers question: http://stackoverflow.com/q/47473442
score: 0
has body: One thing you can do is use an untrainable variable instead of a constant: X = tf.Variable(scaled_housing_data_plus_bias, dtype=tf.float64, name="X", trainable=False) Setting trainable=False means that TensorFlow won't try to change it to minimize your cost function. Note that I needed to change the type to float64; you may not need to. However, it would probably be cleaner to normalize the values while they're still a Numpy array, and then use that to create the tf.constant.

http://stackoverflow.com/comment/82010747
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47459747
has text: aha .. The 32-bit version of pygame worked for me. Thanks
type: Comment

http://stackoverflow.com/comment/81833442
type: Comment
score: 0
has text: http://www.christies.com/lotfinder/searchresults.aspx
type: QuestionComment
comment on: http://stackoverflow.com/q/47439159

http://stackoverflow.com/q/47507252
has title: ValueError: invalid literal for int() with base 10: '' Can't I cast int to None?
downvote count: 1
has comment: http://stackoverflow.com/comment/81970295
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81970278
upvote count: 0
has answer: http://stackoverflow.com/a/47507288
tagged with: django
tagged with: python
score: -1
has body: I got an error,ValueError: invalid literal for int() with base 10: '' . I wrote def convert_json(request): id = None print(type(id)) json_body = json.loads(request.body) for index, content in json_body.items(): if index == "ans": id = content id = int(id) return id When json_body does not have "ans" key,id has None and the error happens in the code of id = int(id) .print(type(id)) print out class 'str' so I really cannot understand why I cannot convert str into int.Is None special kind of str?I wanna put empty value to id when json_body does not have "ans" key.How should I fix this?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81970315
accepted answer: http://stackoverflow.com/a/47507288
answer count: 1

http://stackoverflow.com/a/48624057
score: 2
has body: All the answers on Stack Overflow_ about it were obsolete, so I decided to add this. The path variable that needs to be added is, C:\Users\Username\AppData\Local\Programs\Python\Python36-32 Note that everyone may have a different Username.
has comment: http://stackoverflow.com/comment/88151273
has comment: http://stackoverflow.com/comment/101002733
answers question: http://stackoverflow.com/q/47539201
type: Answer
has comment: http://stackoverflow.com/comment/88120348
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89579097

http://stackoverflow.com/comment/81791422
has text: I did see this tutorial during my initial search. I tried modifying the examples for my usage, but BeautifulSoup gave an `IndexError: list index out of range` error.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47418322
type: Comment

http://stackoverflow.com/a/47484729
has comment: http://stackoverflow.com/comment/81924318
downvote count: 1
has comment: http://stackoverflow.com/comment/81924351
has comment: http://stackoverflow.com/comment/81924562
has comment: http://stackoverflow.com/comment/81926378
upvote count: 2
type: Answer
has body: What you are probably looking for is replace rather then strip is used to eliminate characters at the beginning or end of your text. By default it is removing spaces, but you can specify a character as well. data.replace("&amp;nbsp", "")
has comment: http://stackoverflow.com/comment/81924381
answers question: http://stackoverflow.com/q/47484680
has comment: http://stackoverflow.com/comment/81924383
score: 1

http://stackoverflow.com/q/47532710
has title: Scrapy: Select specific word due to search characters in HTML Text
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47544808
has answer: http://stackoverflow.com/a/47545394
has body: I have the following HTML script where I am searching for specific words. Berufsbezeichnung: ExampleName Anrede: Herrn Name: ExampleLastName Vorname: ExampleSurname … I want to have different variables "Berufsbezeichnung", "Anrede",... which have to be filled with the correct content. In same data sets for example "Berufsbezeichnung" is missing, so this variable has to be left empty. I tried a scrapy script that searches for the content but it isnt working: soup = BeautifulSoup(response.css('table').extract()[0],'lxml') for elem in soup.findAll('tr'): for eleme in elem.findAll('th'): if eleme.get_text()=='Berufsbezeichnung:': Berufsbezeichnung = elem.css('td.gray::text') if eleme.get_text()=='Anrede:': Anrede = elem.css('td.gray::text') ... Does somebody has an idea or maybe also an easier way? Thanks a lot!
has answer: http://stackoverflow.com/a/47544808
tagged with: http://stackoverflow.com/tag/html
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82029764
type: Question
accepted answer: http://stackoverflow.com/a/47545394
tagged with: beautifulsoup
tagged with: python
has comment: http://stackoverflow.com/comment/82042234
type: AnsweredQuestion

http://stackoverflow.com/q/47445814
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/6818091
has body: This was fine yesterday when I got it working. from ftplib import FTP ftp = FTP('files.000webhost.com') ftp.login(user='', passwd='') ftp.cwd('/public_html') def homeDrop(): filename = 'iframe.html' ftp.storbinary('STOR ' + filename, open(filename, 'rb')) ftp.rename(filename, "home.html") ftp.quit() homeDrop() Hypothesis: it might just be the ftp server being slow thats causing this issue because that is the only dynamic variable. There is no other apparent errors.
score: 1
tagged with: python
has title: Python EOF Error when ftp
tagged with: eof
has comment: http://stackoverflow.com/comment/81854846
tagged with: ftp
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81847421

search-engine
type: Tag
tag name: search-engine
tags question: http://stackoverflow.com/q/47426938

http://stackoverflow.com/q/47397717
type: AnsweredQuestion
score: 0
has body: I am trying to loop through a list to create a series of boxplots using Matplotlib. Each item in the list should print a plot that has 2 boxplots, 1 using df1 data and 1 using df2 data. I am successfully plotting x1, but x2 is blank and I don't know why. I am using jupyter notebook with Python 3. Any help is appreciated! df1 = df[df.order == 1] df2 = df[df.order == 0] lst = ['device', 'ship', 'bill'] i = 0 for item in lst: plt.figure(i) x1= df1[item].values x2 = df2[item].values plt.boxplot([x1, x2]) plt.title(item) i = i+1 The series that I'm trying to plot have the following format with several thousand observations each: df[order] == 1 df['device'] df['ship'] df['bill'] 0.0 0.0 0.0 19.0 5.0 0.0 237.0 237.0 237.0 df[order] == 0 df['device'] df['ship'] df['bill'] 1.0 21.0 0.0 75.0 31.0 100.0 5.0 18.0 71.0 The dataframe contains data for orders. The columns listed in lst is made up of dtype float64
has comment: http://stackoverflow.com/comment/81749136
has comment: http://stackoverflow.com/comment/81748840
answer count: 1
accepted answer: http://stackoverflow.com/a/47402197
has answer: http://stackoverflow.com/a/47402197
type: Question
has title: For Loop to create boxplots with Matplotlib
tagged with: matplotlib
tagged with: python
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/81749079

http://stackoverflow.com/comment/81871740
score: 0
type: Comment
has text: thank you so much.I am really sorry I can't vote because i have less than 15 reputation.When i cross 15 Reputation i will do vote.Thanks again
comment on: http://stackoverflow.com/a/47441817
type: AnswerComment

http://stackoverflow.com/comment/82034901
comment on: http://stackoverflow.com/q/47538776
type: Comment
has text: @stefreak The scripts are independent. They are only related in the fact that all the scripts connect to my broker's api and gather some data about individual stocks. Each script has a unique stock symbol.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47449978
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47446480
has body: You can use the Heroku Platform API to update Heroku env vars from within your app.
score: 0
upvote count: 1

http://stackoverflow.com/comment/81797005
type: QuestionComment
type: Comment
has text: That's not how assignment works in Python, and trying to change those kinds of language mechanics is unlikely to go well even for experts. [Here's a quick guide to what assignment actually does in Python.](https://nedbatchelder.com/text/names.html)
score: 0
comment on: http://stackoverflow.com/q/47421289

http://stackoverflow.com/comment/81871336
type: Comment
type: QuestionComment
has text: Is all you need the histogram? Or are you using fitter for other things?
comment on: http://stackoverflow.com/q/47455826
score: 0

http://stackoverflow.com/a/47411526
answers question: http://stackoverflow.com/q/47396954
score: 0
type: Answer
has body: this is the solution filename=dir_path+'train1.csv' def load(filename): # read file into a list of rows with open(filename, 'rU') as csvfile: lines = csv.reader(csvfile, delimiter=',') rows = list(lines) # create empty numpy arrays of the required size data = np.empty((len(rows), len(rows[0])-1), dtype=np.float64) expected = np.empty((len(rows),), dtype=np.int64) # fill array with data from the csv-rows for i, row in enumerate(rows): data[i,:] = row[1:] expected[i] = row[0] training_data = data, expected return training_data print load(filename)

http://stackoverflow.com/comment/81891728
has text: So maybe need `df_train.loc[train_mask, 'cat1'] = df_train.loc[train_mask, 'categories'][0][0]`, but not sure with last `[0][0]`.
type: QuestionComment
comment on: http://stackoverflow.com/q/47468715
type: Comment
score: 2

http://stackoverflow.com/a/47429945
score: 1
answers question: http://stackoverflow.com/q/47429817
accepted answer of: http://stackoverflow.com/q/47429817
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: Just use a class as a namespace: class AnimalChoices(object): RABBIT = "RABBIT" CAMEL = "CAMEL" print(AnimalChoices.RABBIT)

http://stackoverflow.com/comment/81959475
comment on: http://stackoverflow.com/q/47489855
has text: The original window is only the direct parent of the first child window. All the other child windows are actually grandchildren, great-grandchildren, etc. If you want the original window to be the direct parent of all the other windows, then spawn the new xterms in a loop instead of recursively.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82041950
comment on: http://stackoverflow.com/q/47496850
has text: `import discord` not `import discord.py`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47531940
answers question: http://stackoverflow.com/q/47531729
type: Answer
has comment: http://stackoverflow.com/comment/82061933
has comment: http://stackoverflow.com/comment/82021710
score: 3
upvote count: 3
downvote count: 0
has body: The problem in your code is that you're trying to get an attribute of a class rather than an instance of a class. You need to convert i to the actual instance of that class. You have the additional problem that you're passing 'self.wordLabel' rather than just 'wordLabel'. A simple fix is to look up the instance in self.frames def update_widgets(self, frame_list, widget_name, criteria, output): for i in frame_list: frame = self.frames[i] label = getattr(frame, widget_name) label[criteria] = output You also need to change the button command to look like this: self.changeTextEntryButton = tk.Button(... command=lambda: self.controller.update_widgets([A,B], 'wordLabel', 'text', self.changeTextEntry.get())) If you intend for update_widgets to always update all of the page classes, there's no reason to pass the list of frame classes in. Instead, you can just iterate over the known classes: def update_widgets(self, widget_name, criteria, output): for frame in self.frames.values(): label = getattr(frame, 'classLabel') label[criteria] = output You would then need to modify your buttons to remove the list of frame classes: self.changeTextEntryButton = tk.Button(..., command=lambda: self.controller.update_widgets('wordLabel', 'text', self.changeTextEntry.get()))
has comment: http://stackoverflow.com/comment/82022274
has comment: http://stackoverflow.com/comment/82066839
has comment: http://stackoverflow.com/comment/82059421
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47531729
has comment: http://stackoverflow.com/comment/82066070

http://stackoverflow.com/comment/133021104
comment on: http://stackoverflow.com/a/48479810
type: AnswerComment
score: 0
has text: I still didnt got the answer: I have the python code which overwrites the sqlite files every 1 minute - who can i solve this error?
type: Comment

http://stackoverflow.com/comment/81825090
type: QuestionComment
has text: Did you also call the same random seed before the second time you call Random Forest Classifier? Can you show your different results also?
comment on: http://stackoverflow.com/q/47433920
type: Comment
score: 0

http://stackoverflow.com/comment/81919225
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47481132
score: 0
has text: @JohnAnderson true indeed. The only exception is if it involved parallel IO, here's one [reference](https://www.ploggingdev.com/2017/01/multiprocessing-and-multithreading-in-python-3/), but there's more. In fact, in one of my programs that had some heavy data processing (data feed from files), the multithreading module helped a lot. It reduced the processing time considerably.

http://stackoverflow.com/comment/81914569
comment on: http://stackoverflow.com/a/47479627
type: Comment
score: 0
type: AnswerComment
has text: `list(list)`: that's not going to work :)

http://stackoverflow.com/a/57329186
upvote count: 2
downvote count: 0
has body: if you have the input as raw strings, you can use word_tokenize before pos_tag: import nltk is_noun = lambda pos: pos[:2] == 'NN' lines = 'You can never plan the future by the past' lines = lines.lower() tokenized = nltk.word_tokenize(lines) nouns = [word for (word, pos) in nltk.pos_tag(tokenized) if is_noun(pos)] print(nouns) # ['future', 'past']
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47519987

http://stackoverflow.com/a/47414727
score: 0
has body: First off all, i would merge xtrain and ytrain. For that we need to pivot your x frame: xtrain_old = pd.Series(np.random.random(10000)).to_frame() ytrain_old = pd.Series(np.random.randint(5, size=20)) xtrain_old['column_names'] = 'feature_'+ (xtrain_old.index%500).astype(str) xtrain_old.index = np.floor(xtrain_old.index/500).astype(int) xtrain_old = xtrain_old.pivot(columns='column_names') xtrain_old.columns = xtrain_old.columns.droplevel() Now we can merge the label: ytrain_old = ytrain_old.rename('label') df = pd.concat([xtrain_old, ytrain_old], axis=1) And select all rows with the label we care about: df_selected = df.loc[df['label'].isin([2,3])]
answers question: http://stackoverflow.com/q/47413540
type: Answer

system
tag name: system
tags question: http://stackoverflow.com/q/47425331
type: Tag
tags question: http://stackoverflow.com/q/47460580

http://stackoverflow.com/a/55179682
answers question: http://stackoverflow.com/q/47437488
type: Answer
score: 0
has body: Now, you can not extract 30 days old tweets using Twitter's streaming API. Twitter has made it payable. You can extract past 30 days tweets using search-30day subscription plan of Twitter premium API. Also, you can buy Twitter premium subscription only if you have approved Twitter's developer's account. To get an approval, you can see this link: https://developer.twitter.com/en/apply-for-access.html If you have one-time requirement of this, then I will suggest you to use third-party services such as TrackMyhashtag.com or Tweetreach.com

http://stackoverflow.com/comment/81918179
score: 0
type: AnswerComment
has text: %s if the format specifier for the string. When you write '%s' % variable it means that you will create a string with the value of the variable. It is useful when you need to use many variables: 'Here goes a string %s. Here goes an int %d. And here goes a float %f' % (str_var, int_var, float_var).
type: Comment
comment on: http://stackoverflow.com/a/47481591

http://stackoverflow.com/q/47422899
type: Question
possible better answer: http://stackoverflow.com/a/47422992
downvote count: 5
has answer: http://stackoverflow.com/a/47422992
has title: Lists and loops and changing elements
accepted answer: http://stackoverflow.com/a/47422966
tagged with: python
has answer: http://stackoverflow.com/a/47423020
has body: How would I loop through a list to find if a number is over 9, if any numbers are over 9 then subtract that number by 9. list = [2,2,12,14,18,9] newlist = [2,2,3,5,9,9]
type: AnsweredQuestion
upvote count: 0
score: -5
has comment: http://stackoverflow.com/comment/81800532
answer count: 3
has answer: http://stackoverflow.com/a/47422966
has comment: http://stackoverflow.com/comment/81800485
favorite count: 0

http://stackoverflow.com/comment/81946053
score: 0
comment on: http://stackoverflow.com/q/47495326
has text: Using the solution in that question gives me `['54776f204f6e65204e696e652054776f']`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47495643
has body: I would like to extract the market information from the following url and all of its subsequent pages: https://uk.reuters.com/investing/markets/index/.FTSE?sortBy=&amp;sortDir=&amp;pn=1 I have successfully parsed the data that I want from the first page using some code from the following url: https://impythonist.wordpress.com/2015/01/06/ultimate-guide-for-scraping-javascript-rendered-web-pages I have also been able to parse out the url for the next page to feed into a loop in order to grab data from the next page. The problem is it crashes before the next page loads for a reason I don't fully understand. I have a hunch that the class that I have borrowed from 'impythonist' may be causing the problem. I don't know enough object orientated programming to work out the problem. Here is my code, much of which is borrowed from the the url above: import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import * from lxml import html import re from bs4 import BeautifulSoup class Render(QWebPage): def __init__(self, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) self.mainFrame().load(QUrl(url)) self.app.exec_() def _loadFinished(self, result): self.frame = self.mainFrame() self.app.quit() base_url='https://uk.reuters.com' complete_next_page='https://uk.reuters.com/investing/markets/index/.FTSE?sortBy=&amp;sortDir=&amp;pn=1' #LOOP TO RENDER PAGES AND GRAB DATA while complete_next_page != '': print ('NEXT PAGE: ',complete_next_page, '\n') r = Render(complete_next_page) # USE THE CLASS TO RENDER JAVASCRIPT FROM PAGE result = r.frame.toHtml() # ERROR IS THROWN HERE ON 2nd PAGE # PARSE THE HTML soup = BeautifulSoup(result, 'lxml') row_data=soup.find('div', attrs={'class':'column1 gridPanel grid8'}) print (len(row_data)) # PARSE ALL ROW DATA stripe_rows=row_data.findAll('tr', attrs={'class':'stripe'}) non_stripe_rows=row_data.findAll('tr', attrs={'class':''}) print (len(stripe_rows)) print (l…
has comment: http://stackoverflow.com/comment/81946364
has comment: http://stackoverflow.com/comment/81946691
type: Question
has comment: http://stackoverflow.com/comment/81947168
has title: Parsing html from a javascript rendered url with python object
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/81946852
linked to: http://stackoverflow.com/q/37903536
has comment: http://stackoverflow.com/comment/81946920
has comment: http://stackoverflow.com/comment/81946719
type: AnsweredQuestion
score: 0
tagged with: web-scraping
tagged with: python-object
accepted answer: http://stackoverflow.com/a/47496352
answer count: 1
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47496352

http://stackoverflow.com/comment/81773138
score: 0
type: AnswerComment
has text: @ArtsiomPraneuski that's really not a good advice
type: Comment
comment on: http://stackoverflow.com/a/47409630

http://stackoverflow.com/comment/81815915
has text: @M.Jones : what is the input you are giving?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47430612

http://stackoverflow.com/q/47441379
has comment: http://stackoverflow.com/comment/81837744
has answer: http://stackoverflow.com/a/47441485
downvote count: 7
has answer: http://stackoverflow.com/a/47441492
tagged with: string
tagged with: integer
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81837760
has title: Typecasting in Python to Integer
has comment: http://stackoverflow.com/comment/81837806
tagged with: python
score: -7
tagged with: typecasting-operator
upvote count: 0
has body: L = int(input()) N = int(input()) W, H = int(input().split(" ")) for num in range(N): if (W &lt; L or H &lt; L): print("UPLOAD other")][1] https://i.sstatic.net/xgtoS.jpg
has comment: http://stackoverflow.com/comment/81837791

http://stackoverflow.com/q/47399789
has answer: http://stackoverflow.com/a/47399803
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/4785244
has title: I want to search a txt file for a specific word and print the whole line
type: UnansweredQuestion
upvote count: 1
has body: My code is currently: admin_username_choice = input("Enter the user's username: ") with open("data.txt") as f: line = f.read().split() for line in f: if admin_username_choice in line: print(line) else: print("Incorrect information") but this prints out - for line in f: ValueError: I/O operation on closed file. Can someone please tell me what I am doing wrong?
downvote count: 1
duplicate of: http://stackoverflow.com/q/4785244
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47399812
has answer: http://stackoverflow.com/a/47399848
tagged with: python

http://stackoverflow.com/comment/81853705
type: AnswerComment
comment on: http://stackoverflow.com/a/47443528
has text: It may be obvious, but one should ensure that `len(y) == len(ypos)` before running the list comprehension.
score: 0
type: Comment

http://stackoverflow.com/a/47512834
score: 8
accepted answer of: http://stackoverflow.com/q/47512037
has body: As suggested in comment, It should be session.read.format instead of session.read().format Silly Me!
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47512037
upvote count: 8
type: Answer

http://stackoverflow.com/a/47523994
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47445745
has body: To answer your questions in order: You are probably trying to search for data that goes in through your custom fields. One solution that exists similar to SOLR indexing for custom fields is to override the search ordering block by implementing /templates/package/search.html in your extension This allows SOLR to use your fields to order the SOLR search results. You may need to reload your development server for the changes to take effect. You can follow a guide here: http://docs.ckan.org/en/latest/extensions/adding-custom-fields.html#sorting-by-custom-fields-on-the-dataset-search-page Also, you could implement this function in your plugin.py ` def before_index(self, index_dict): #Implement some package level stuff here and put the value in the index_dict index_dict['your_choice_index_name'] = 'your proposed value' return index_dict In order to achieve this, you may need to override all the blocks in the current dataset meta data form by overriding them in templates/package. If that's what you refer to by meta-data fields on the UI. I hope this helps.
answers question: http://stackoverflow.com/q/47445745
score: 0

http://stackoverflow.com/comment/102035261
type: AnswerComment
has text: @PrakashPalnati if you trying to capture the TCP packets between client and Tornado server, you'll find that Tornado is pushing data to client every 10 seconds.
score: 0
comment on: http://stackoverflow.com/a/47718124
type: Comment

http://stackoverflow.com/comment/81962330
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47503213
has text: Or you could upgrade to Python 3.6 and use f-strings, Eg `f'{value1:02}'`

http://stackoverflow.com/q/47440539
score: 1
has comment: http://stackoverflow.com/comment/81836694
has body: I am trying to run following simple script on Debian Stable Linux: $ cat ./mytest.py #! /usr/bin/python3 print("Before importing sys.") import sys print("Before importing pandas.") import pandas as pd print("Before importing numpy.") import numpy as np But it is giving following error: $ ./mytest.py Before importing sys. Before importing pandas. time.struct_time(tm_year=2017, tm_mon=11, tm_mday=22, tm_hour=22, tm_min=43, tm_sec=50, tm_wday=2, tm_yday=326, tm_isdst=0) Date=22 Month=11 Year=2017 Hour=22 Minute=43 Second=50 Local current time : Wed Nov 22 22:43:50 2017 Traceback (most recent call last): File "./mytest.py", line 7, in &lt;module&gt; import pandas as pd File "/usr/lib/python3/dist-packages/pandas/__init__.py", line 13, in &lt;module&gt; __import__(dependency) File "/home/iuser/.local/lib/python3.5/site-packages/numpy/__init__.py", line 142, in &lt;module&gt; from . import add_newdocs File "/home/iuser/.local/lib/python3.5/site-packages/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/home/iuser/.local/lib/python3.5/site-packages/numpy/lib/__init__.py", line 8, in &lt;module&gt; from .type_check import * File "/home/iuser/.local/lib/python3.5/site-packages/numpy/lib/type_check.py", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "/home/iuser/.local/lib/python3.5/site-packages/numpy/core/__init__.py", line 16, in &lt;module&gt; from . import multiarray SystemError: initialization of multiarray raised unreported exception Following versions of pandas and numpy are installed through Debian Repositories: Package Installed Previous Now State =======================-===============-===============-===============-===== python3-pandas 0.19.2-5.1 0.19.2-5.1 0.19.2-5.1 install python3-pandas-lib 0.19.2-5.1 0.19.2-5.1 0.19.2-5.1 install python-numpy 1:1.12.1-3 1:1.12.1-3 1:1.12.1-3 install python3-numpy 1:1.12.1-3 1:1.12.1-3 1:1.12.1-3 install Where is the problem and how can it be solved? Edit: I find that …
tagged with: python
has title: Not able to import pandas and numpy
has comment: http://stackoverflow.com/comment/81836027
has comment: http://stackoverflow.com/comment/81836160
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81836405
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81836538
has answer: http://stackoverflow.com/a/47440615
possible better answer: http://stackoverflow.com/a/47440615
downvote count: 0
has answer: http://stackoverflow.com/a/47446085
accepted answer: http://stackoverflow.com/a/47446085
upvote count: 1
has comment: http://stackoverflow.com/comment/81836281
favorite count: 0
has comment: http://stackoverflow.com/comment/81836139
type: AnsweredQuestion
tagged with: linux
has comment: http://stackoverflow.com/comment/81836617
tagged with: pandas

openpgp
tags question: http://stackoverflow.com/q/47525580
tag name: openpgp
type: Tag

http://stackoverflow.com/comment/81902570
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47474013
has text: So your desired output would just remove the height="250" but leaves everything else? (in that one example that is)
score: 0

http://stackoverflow.com/q/47537209
has comment: http://stackoverflow.com/comment/82032938
has comment: http://stackoverflow.com/comment/82033751
has comment: http://stackoverflow.com/comment/82035075
type: Question
tagged with: python-3.x
answer count: 0
has body: I want to find the remainder of 23.153 when divided by 23 i.e. 23.153%23. The remainder should come 0.153 but its coming as 0.1529999999999987.
has comment: http://stackoverflow.com/comment/82033015
type: UnansweredQuestion
has title: How to get the exact remainder using modulus in python
tagged with: python
linked to: http://stackoverflow.com/q/588004
tagged with: modulus
duplicate of: http://stackoverflow.com/q/588004
score: 0

http://stackoverflow.com/q/47486563
upvote count: 3
has comment: http://stackoverflow.com/comment/81927970
downvote count: 1
has answer: http://stackoverflow.com/a/47488736
has comment: http://stackoverflow.com/comment/81927945
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47486621
accepted answer: http://stackoverflow.com/a/47486621
has comment: http://stackoverflow.com/comment/81927974
has comment: http://stackoverflow.com/comment/108802034
tagged with: python
has comment: http://stackoverflow.com/comment/81927904
has title: how can i get index of two of more duplicate characters in a string?
possible better answer: http://stackoverflow.com/a/47488736
favorite count: 0
has comment: http://stackoverflow.com/comment/81928100
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/991350
answer count: 2
has body: I want to store actual index of Two or more duplicate characters in a list. For that i used index() but it returns the same index of all the duplicate characters. Any other solution for this problem.
linked to: http://stackoverflow.com/q/11122291

http://stackoverflow.com/a/47494789
has body: Use: #if necessary convert TYPE column to string df['TYPE'] = df['TYPE'].astype(str) df = df.groupby(["SCENARIO", "STATUS", "TYPE"])['TYPE'].count() #aggregate sum by first 2 levels df1 = df.groupby(["SCENARIO", "STATUS"]).sum() #add 3 level of MultiIndex df1.index = [df1.index.get_level_values(0), df1.index.get_level_values(1), ['Total'] * len(df1)] #thanks MaxU for improving #df1 = df1.set_index(np.array(['Total'] * len(df1)), append=True) print (df1) SCENARIO STATUS AAA 51 Total 3 53 Total 1 BBB 51 Total 1 CCC 51 Total 1 Name: TYPE, dtype: int64 #join together and sorts df = pd.concat([df, df1]).sort_index(level=[0,1]) print (df) SCENARIO STATUS TYPE AAA 51 1 2 9 1 Total 3 53 228 1 Total 1 BBB 51 43 1 Total 1 CCC 51 187 1 Total 1 Name: TYPE, dtype: int64
has comment: http://stackoverflow.com/comment/130606110
accepted answer of: http://stackoverflow.com/q/47494720
type: Answer
has comment: http://stackoverflow.com/comment/130606084
has comment: http://stackoverflow.com/comment/130605231
score: 12
has comment: http://stackoverflow.com/comment/130606197
downvote count: 0
has comment: http://stackoverflow.com/comment/130606336
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47494720
has comment: http://stackoverflow.com/comment/130604260
upvote count: 12

http://stackoverflow.com/q/47393222
downvote count: 0
tagged with: file
tagged with: networkx
score: 2
has body: I am facing a little problem while trying to save my NetworkX graph on file through the "savefig" function. My graph looks like this: However, when I save on file, the resulting saved graph looks like this: As you can see, in the second graph the edges are drawn normally without considering the fact that I reduced their thickness. I'll post my code over here, maybe I'm doing something wrong: # Retrieving the GCC from the undirected version of the graph GCC = max(nx.connected_component_subgraphs(UG), key=len) pos = nx.spring_layout(GCC,k=0.30,iterations=70, scale=2) nx.draw_networkx_nodes(GCC, pos,node_color=color_map,with_labels=True, node_size=17) #node_color=color_map, with_labels=True, node_size=17) nx.draw_networkx_edges(GCC, pos, width=0.3) # Saving graph in the main folder of the project fig = plt.gcf() fig.set_size_inches(18.5, 10.5) fig.savefig('graph7.pdf', dpi=100) plt.show()
tagged with: python
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: layout
tagged with: save
has title: NetworkX - graph saved on file changes edges thickness

http://stackoverflow.com/q/47482705
has comment: http://stackoverflow.com/comment/81920296
has comment: http://stackoverflow.com/comment/81920398
has answer: http://stackoverflow.com/a/47487110
answer count: 1
has comment: http://stackoverflow.com/comment/81920396
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81923043
has comment: http://stackoverflow.com/comment/81920561
tagged with: for-loop
has comment: http://stackoverflow.com/comment/81920423
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81920334
has comment: http://stackoverflow.com/comment/81920419
tagged with: python
has comment: http://stackoverflow.com/comment/81923467
has title: for loop python the last value is not added in the list
has comment: http://stackoverflow.com/comment/81920406
has comment: http://stackoverflow.com/comment/81920363
has body: The last value is not added in the tab. So i create a program to test if a string is contains on other string. it works but the last value is not take in care. result: result: ['testing', 'toto', 'trete'] what expected: ['testing', 'toto', 'trete','apoi'] str= ("""test testing toto trete apoi""") tab = str.splitlines() tabmot = [] mot = "" for i in range(len(tab)): print(int(tab[i]) if mot in tab[i]: mot = tab[i] else: if mot != "": tabmot.append(mot) elif tab[i] == tab[-1]: tabmot.append(tab[i]) mot = tab[i]
score: 0
tagged with: list

http://stackoverflow.com/comment/82035143
comment on: http://stackoverflow.com/q/47539048
type: Comment
type: QuestionComment
score: 0
has text: I wanted to loop through each item in a nested list using a while loop.

http://stackoverflow.com/a/47534635
accepted answer of: http://stackoverflow.com/q/47523483
type: Answer
has body: Having formatted your data in order to make a MCVE: import pandas as pd data = { 'smonth': ['Apr', 'Jan', 'Jul', 'Oct'] ,'temp': [61, 32, 69, 43] } df = pd.DataFrame(data) We have the following DataFrame: smonth temp 0 Apr 61 1 Jan 32 2 Jul 69 3 Oct 43 Now we convert your String Month (using %b formatter, see list) column into a Date, then into an Index and we finally extract Month field: df['month'] = pd.DatetimeIndex(pd.to_datetime(df['smonth'], format='%b')).month Then reindex and sort: df = df.set_index('month').sort_index() It is done: smonth temp month 1 Jan 32 4 Apr 61 7 Jul 69 10 Oct 43 Update If I explicitly reproduce your input, using: df2 = pd.DataFrame( data['temp'] ,index=pd.Index(data['smonth'], name='Month') ,columns=['Temp'] ) Then it reduces to: df2.index = pd.to_datetime(df2.index, format='%b').month df2.sort_index(inplace=True) And returns: Temp Month 1 32 4 61 7 69 10 43
upvote count: 2
answers question: http://stackoverflow.com/q/47523483
score: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81891983
type: Comment
comment on: http://stackoverflow.com/q/47468605
has text: So I assume you have something like `app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'first-task': { 'task': 'tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, 'second-task': { 'task': 'tasks.add', 'schedule': crontab(hour=12, minute=30, day_of_week=1), 'args': (16, 16), } }` which should be a collection of dictionaries for each task.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81753302
score: 0
type: Comment
type: QuestionComment
has text: @user2357112, curious, if I run it directly from the commandline, it works. It might be something my bash script that launches it is doing... but seemingly it's just scriptToRun=/some/place/myApp.py, ${scriptToRun} &, nothing too fancy. Could there be some setting that affects children of scripts? Some hidden Linux Max Children dealie?
comment on: http://stackoverflow.com/q/47398489

http://stackoverflow.com/comment/81832576
score: 2
has text: You need to pass each element of the list as an argument to `__init__`; the string `"red"` is not, and cannot be, an instance of `Character`. `players = [Character(color) for color in ["red", "green", "blue", "yellow"]`.
type: Comment
comment on: http://stackoverflow.com/q/47438914
type: QuestionComment

http://stackoverflow.com/q/47510770
has title: Install fitter package in python
has comment: http://stackoverflow.com/comment/81977327
has comment: http://stackoverflow.com/comment/81980961
score: 0
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/82012794
tagged with: python
type: UnansweredQuestion
has body: I've been using python for some time now but I haven't installed any external packages that are not include in anaconda. Now I want to install fitter 1.0.8 package in python 2.7.10. I have anaconda 2.3.0 downloaded (64 bit) on windows and I'm working on spyder. So far I have tried to install it from the Anaconda command Prompt. I tried to right-click the tar.gz hyperlink and click "Copy Link Address" and I got https://pypi.python.org/packages/78/d8/6c41c8aa704994998564a41f2570b72f755431adab05f401908cab7c6de8/fitter-1.0.8.tar.gz. Then I typed in the anaconda command prompt: pip install https://pypi.python.org/packages/78/d8/6c41c8aa704994998564a41f2570b72f755431adab05f401908cab7c6de8/fitter-1.0.8.tar.gz and I got access denied for some of the folders of the package. Any help would be vary much appreciated.
has answer: http://stackoverflow.com/a/75865087

vertica
tag name: vertica
tags question: http://stackoverflow.com/q/47529906
type: Tag

http://stackoverflow.com/q/47527776
has body: I got a list of different events with mixed occurrences. For instance the event1 might occur three times, then another event and later on event1 will occur again. What I need is the intervals for each event and the number of occurrences of that event in those intervals. values = { '2017-11-28 11:00': 'event1', '2017-11-28 11:01': 'event1', '2017-11-28 11:02': 'event1', '2017-11-28 11:03': 'event2', '2017-11-28 11:04': 'event2', '2017-11-28 11:05': 'event1', '2017-11-28 11:06': 'event1', '2017-11-28 11:07': 'event1', '2017-11-28 11:08': 'event3', '2017-11-28 11:09': 'event3', '2017-11-28 11:10': 'event2', } import pandas as pd df = pd.DataFrame.from_dict(values, orient='index').reset_index() df.columns = ['time', 'event'] df['time'] = df['time'].apply(pd.to_datetime) df.set_index('time', inplace=True) df.sort_index(inplace=True) df.head() The expected result is: occurrences = [ {'start':'2017-11-28 11:00', 'end':'2017-11-28 11:02', 'event':'event1', 'count':3}, {'start':'2017-11-28 11:03', 'end':'2017-11-28 11:04', 'event':'event2', 'count':2}, {'start':'2017-11-28 11:05', 'end':'2017-11-28 11:07', 'event':'event1', 'count':3}, {'start':'2017-11-28 11:08', 'end':'2017-11-28 11:09', 'event':'event3', 'count':2}, {'start':'2017-11-28 11:10', 'end':'2017-11-28 11:10', 'event':'event2', 'count':1}, ] I was thinking to use pd.merge_asof to find the start/end times of the intervals and the use pd.cut (as explained here) for groupby and count. But somehow I'm stuck. Any help is appreciated.
tagged with: pandas
has comment: http://stackoverflow.com/comment/82014038
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82012882
has comment: http://stackoverflow.com/comment/82012386
has answer: http://stackoverflow.com/a/47529163
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47528967
possible better answer: http://stackoverflow.com/a/47529163
answer count: 2
tagged with: pandas-groupby
upvote count: 3
has comment: http://stackoverflow.com/comment/82013666
downvote count: 0
has title: Pandas Dataframe find intervals and count occurances
linked to: http://stackoverflow.com/q/26539646
has comment: http://stackoverflow.com/comment/82012209
linked to: http://stackoverflow.com/q/25119524
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/25010215
has answer: http://stackoverflow.com/a/47528967
score: 3

http://stackoverflow.com/comment/81883729
type: AnswerComment
has text: I see the logic. Thanks so much for the help!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47463599

http://stackoverflow.com/comment/81725248
type: QuestionComment
score: 0
has text: The error message is pretty helpful. Did you specify an encoding?
type: Comment
comment on: http://stackoverflow.com/q/47386143

http://stackoverflow.com/comment/116363049
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47571289
has text: @WisdomPill Thanks!

http://stackoverflow.com/comment/81736622
type: Comment
has text: @jezrael I understand your point about using `float`. The problem is the task itself is to make column with zero floating point numbers. So if i use float than it means i can actually remove the whole function :(
type: AnswerComment
comment on: http://stackoverflow.com/a/47391174
score: 0

http://stackoverflow.com/q/47478934
upvote count: 0
has title: Python Numpy DTYPE dynamic array
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81912841
favorite count: 0
tagged with: numpy
type: Question
has answer: http://stackoverflow.com/a/47481807
has comment: http://stackoverflow.com/comment/81913043
type: UnansweredQuestion
tagged with: python
has body: I have a code like this np.fromfile( f, dtype = np.dtype( [ ( 'f1', np.float16 ), ( 'f2', np.float16 ) ] ), count = -1 ) and I need to make a dtype dependent on variable ( instead of size=2 make size=var ). Tried to google it and tried to ask on IRC but no rescue. Thanks in advance!
score: -1

http://stackoverflow.com/q/47490816
upvote count: 2
score: 1
answer count: 1
downvote count: 1
tagged with: import
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47490877
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/47490877
has title: No module named 'x'; 'x' is not a package
tagged with: tkinter
has body: This is the error that appears when I try to import other tkinter files with the use of a button: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Feargus\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Users\Feargus\Documents\COMPUTING\games\BIG_MAIN_MENU.py", line 13, in settingsButton import SETTINGS.py ModuleNotFoundError: No module named 'SETTINGS.py'; 'SETTINGS' is not a package Here is the code which imports the files: def startGame(): import GAME.py def settingsButton(): import SETTINGS.py quit() def leaderBoard(): import Leaderboard.py quit() def endGame(): quit()

http://stackoverflow.com/comment/81750901
comment on: http://stackoverflow.com/a/47398279
type: AnswerComment
score: 0
type: Comment
has text: I'm using 2.3.1. I'm going to try what you posted and if doesn't work I'll revert back to a previous version and see if that works.

http://stackoverflow.com/q/47477744
has body: Hi i am stata user and now iam trying to pass my codes in stata to python/pandas. In this case i want to create a new variables size that assign the value 1 if the number of jobs is between 1 and 9, the value 2 if jobs is between 10 and 49, 3 between 50 and 199 and 4 for bigger than 200 jobs. And aftewards, if it is possible label them (1:'Micro', 2:'Small', 3:'Median', 4:'Big') id year entry cohort jobs 1 2009 0 NaN 3 1 2012 1 2012 3 1 2013 0 2012 4 1 2014 0 2012 11 2 2010 1 2010 11 2 2011 0 2010 12 2 2012 0 2010 13 3 2007 0 NaN 38 3 2008 0 NaN 58 3 2012 1 2012 58 3 2013 0 2012 70 4 2007 0 NaN 231 4 2008 0 NaN 241 I tried using this code but couldnt succed df['size'] = np.where((1 &lt;= df['jobs'] &lt;= 9),'Micro',np.where((10 &lt;= df['jobs'] &lt;= 49),'Small'),np.where((50 &lt;= df['jobs'] &lt;= 200),'Median'),np.where((200 &lt;= df['empleo']),'Big','NaN'))
has comment: http://stackoverflow.com/comment/81910992
type: Question
tagged with: python
has title: Create variable with multiple return of numpy where
has answer: http://stackoverflow.com/a/47478131
tagged with: pandas
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47478131
tagged with: numpy
tagged with: python-3.x

sqlite
tags question: http://stackoverflow.com/q/47517091
tags question: http://stackoverflow.com/q/47481047
tags question: http://stackoverflow.com/q/47458189
tags question: http://stackoverflow.com/q/47448063
tags question: http://stackoverflow.com/q/47519701
tags question: http://stackoverflow.com/q/47446524
tags question: http://stackoverflow.com/q/47490444
tags question: http://stackoverflow.com/q/47531456
type: Tag
tags question: http://stackoverflow.com/q/47453453
tags question: http://stackoverflow.com/q/47402032
tags question: http://stackoverflow.com/q/47515586
tags question: http://stackoverflow.com/q/47425271
tags question: http://stackoverflow.com/q/47409170
tags question: http://stackoverflow.com/q/47466871
tags question: http://stackoverflow.com/q/47483184
tags question: http://stackoverflow.com/q/47515014
tags question: http://stackoverflow.com/q/47540607
tags question: http://stackoverflow.com/q/47442902
tags question: http://stackoverflow.com/q/47470270
tags question: http://stackoverflow.com/q/47474254
tags question: http://stackoverflow.com/q/47384084
tag name: sqlite
tags question: http://stackoverflow.com/q/47507831
tags question: http://stackoverflow.com/q/47421513
tags question: http://stackoverflow.com/q/47438961
tags question: http://stackoverflow.com/q/47524720
tags question: http://stackoverflow.com/q/47422672

http://stackoverflow.com/comment/81943830
has text: Can you change `b` to be valid condition like `=20` or `in range(50,100)`?
comment on: http://stackoverflow.com/q/47494385
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47384271
type: Question
accepted answer: http://stackoverflow.com/a/47384478
has title: Python - Automatically print a value from json file if the updated value is bigger than its previous value
has comment: http://stackoverflow.com/comment/81721466
tagged with: python
score: -1
has body: Greeting, I'm trying to create a simple continuous function where I get a value from a json file and if that value is updated and bigger than before the update, it will print the new value, I'm not doing it quite right, can anyone help me with this? any help is much appreaciated thanks. import urllib.request, json with urllib.request.urlopen("https://free.currencyconverterapi.com/api/v4/convert?q=MYR_INR&amp;compact=y") as url: data = json.loads(url.read().decode()) myr_ind = data['MYR_INR'] val = myr_ind['val'] previous_value= [0] while True: if val &gt; previous_value[0]: previous_value.pop(0) previous_value.append(val) print(val)
has comment: http://stackoverflow.com/comment/81721421
has comment: http://stackoverflow.com/comment/81721424
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47384478
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81916117
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47480454
has text: Well, this particular one won't since the dataframes now contain values different from 0 and 1, meaning that the bitwise or operation no longer suffices. You could still combine it with MaxU's suggestion below and do something like `(df_a + df_c.loc[df_a.index, df_a.columns]).ne(0).astype(np.int8)` though.
type: Comment

http://stackoverflow.com/comment/81881412
has text: Thanks @hpaulj, that's helped me clear my thinking, I didn't realise I was creating 2d arrays by specifying the other was 1. In maths a nx1 array is just a column on n rows. theta = np.random(n)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47463066
score: 0

http://stackoverflow.com/comment/81980542
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47505050
has text: @BurhanKhalid How can you tell that it is running out of memory when trying to boot Raven? It seems to me like the issue occurs after unsuccessfully trying to boot up a gunicorn worker several times. What am I missing?

http://stackoverflow.com/a/47449594
answers question: http://stackoverflow.com/q/47449452
downvote count: 0
score: 1
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47449452
has body: Case 1 One time access It is perfectly alright to read your data and iterate over it, returning the first match found. def access(f, author): with open(file) as f: data = json.load(f) for d in data: if d['Author'] == author: return d else: return 'Not Found' Case 2 Repeated access In this instance, it would be wise to reshape your data in such a way that accessing objects by author names is much faster (think dictionaries!). For example, one possible option would be: with open(file) as f: data = json.load(f) newData = {} for d in data: newData[d['Author']] = d Now, define a function and pass your pre-loaded data along with a list of author names. def access(myData, author_list): for a in author_list: yield myData.get(a) The function is called like this: for i in access(newData, ['Paul', 'John', ...]): print(i) Alternatively, store the results in a list r. The list(...) is necessary, because yield returns a generator object which you must exhaust by iterating over. r = list(access(newData, [...]))
type: AcceptedAnswer

http://stackoverflow.com/q/47500969
has comment: http://stackoverflow.com/comment/81957650
tagged with: python
has comment: http://stackoverflow.com/comment/81957706
tagged with: windows-console
answer count: 0
has title: Take a snapshot of the contents of a Windows console
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81959393
has comment: http://stackoverflow.com/comment/81957577
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82056484
has body: I have a program that produces colored output on the console, and I want to write a test ensuring the output is correct. On Unix-like systems this is done using ANSI escape codes, so capturing the output stream is enough to check the rendered colors. On Windows, I'm using colorama to translate the ANSI codes to Win32 API calls. However, I'd still like to ensure the right colors are being produced. How do I programmatically capture the contents of a Windows console to compare it to the expected output? Any format is OK as long as the content doesn't spuriously change - HTML, an image, PDF, etc. The test in question needs to run on AppVeyor, so it probably does not have a graphical environment ready.

http://stackoverflow.com/comment/82035696
type: Comment
comment on: http://stackoverflow.com/q/47538776
type: QuestionComment
has text: @SteveJ bash -> batch. pretty much the exact same can be accomplished with `START "" "path-to-python" "path-to-script"`
score: 1

http://stackoverflow.com/q/47456405
has answer: http://stackoverflow.com/a/47456486
duplicate of: http://stackoverflow.com/q/3845018
upvote count: 2
score: 0
linked to: http://stackoverflow.com/q/36550588
downvote count: 2
has title: weird behaviour in python conditional operators for "and" and "&"
has body: Below are the different scenarios tried using '&amp;' and 'and' conditional operators and its result. (using Python 2.7) Using '&amp;' operator: Using 'and' operator: Wondering why both conditional operators showing different behaviour? Explanation with real scenarios would be helpful. Thanks in advance.
favorite count: 0
has answer: http://stackoverflow.com/a/47456599
has comment: http://stackoverflow.com/comment/81867277
has comment: http://stackoverflow.com/comment/81867434
has answer: http://stackoverflow.com/a/47456455
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/3845018
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81867689
has answer: http://stackoverflow.com/a/47456562
tagged with: python-2.7
answer count: 4

exception
tags question: http://stackoverflow.com/q/47423746
tags question: http://stackoverflow.com/q/47452824
tags question: http://stackoverflow.com/q/47435749
tags question: http://stackoverflow.com/q/47385354
tags question: http://stackoverflow.com/q/47390846
tags question: http://stackoverflow.com/q/47430091
tags question: http://stackoverflow.com/q/47495956
tag name: exception
tags question: http://stackoverflow.com/q/47491602
type: Tag

http://stackoverflow.com/comment/82026648
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47514304
score: 0
has text: @user3034958 Perhaps including the C++ STL (specifically `vector` and `map`) in the comparison would help. `map` is an associative container, but the iteration order is the order of the keys (different from both PHP (order added) and Python (arbitrary)). `vector` is pretty much the same as a Python list.

amazon-cognito
tags question: http://stackoverflow.com/q/47516202
tag name: amazon-cognito
type: Tag

http://stackoverflow.com/q/47430796
has title: How do I display attributes of table in oracle using python?
has body: I connected Python to Oracle. I am trying to display the attributes of the table using python i.e I want to display table schema. I am using 'describe' statement but while executing it gives me an error ' Invalid SQL Statement'. I have done the following: queryString = 'Describe Customer' onCursor.execute(queryString) "Customer" is the table name
has comment: http://stackoverflow.com/comment/81817227
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81817107
answer count: 3
tagged with: sql
score: 1
tagged with: cx-oracle
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47431623
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81817023
accepted answer: http://stackoverflow.com/a/52623270
has answer: http://stackoverflow.com/a/52623270
possible better answer: http://stackoverflow.com/a/47432321
tagged with: oracle-database
has answer: http://stackoverflow.com/a/47432321
tagged with: python

http://stackoverflow.com/a/47520306
has comment: http://stackoverflow.com/comment/81997343
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47520236
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: The solution per se is to change how your import works: import functions functions.setup() print(Welcome " + functions.name + ".") However I fear that if you pursue this approach, your multi-file program will be just as confusing as your single-file program was. The broader solution is to avoid global variables when you can. Perhaps setup can return whatever it creates and then its caller can decide what to do with it: def setup(): return input("What is your name? ").capitalize() and name = functions.setup() print("Welcome " + name + ".") Or, if setup() has more work to do than just discover the player's name, try this: # functions.py class Player: # Fill this in later as you refine your design pass def setup(): player = Player() player.name = input("What is your name? ").capitalize() # player.score = ... # player.charm = ... # etc return player and import functions player = functions.setup() print("Welcome " + player.name + ".")
accepted answer of: http://stackoverflow.com/q/47520236

http://stackoverflow.com/comment/81858912
type: Comment
type: QuestionComment
has text: try this : https://docs.python.org/2/library/wave.html#wave.Wave_read.readframes
score: 2
comment on: http://stackoverflow.com/q/47452034

http://stackoverflow.com/q/47384019
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has title: How do I apply .agg to the top n items in a dataframe
answer count: 1
has answer: http://stackoverflow.com/a/47384045
type: Question
upvote count: 2
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47384045
tagged with: python
has body: I'm trying to pull back a dataframe object computed from the top 4 items of a larger data set. To do this I've pulled the created a data frame census_df then written the following return (census_df.set_index('STNAME','COUNTY') .nlargest(4,'CENSUS2010POP') .groupby(level=0)['CENSUS2010POP'] .agg([{'Sum':np.sum}])) which returns the four largest counties rather than all states with their population estimated by the four largest counties inside those states. I tried using return (census_df.set_index('STNAME','COUNTY') .nlargest(4,'CENSUS2010POP') .groupby(level=0)['CENSUS2010POP'] .agg([{'Sum':np.argsort()[-3:].sum()}])) but argsort is missing a positional argument and I'm not sure what to put there -- what would argsort even reference?
favorite count: 0
score: 2

http://stackoverflow.com/a/47487169
has comment: http://stackoverflow.com/comment/81929470
has comment: http://stackoverflow.com/comment/81929339
has comment: http://stackoverflow.com/comment/81929447
has body: data = {} with open('zzz.txt') as fp: for line in fp: var, values = list(map(str.strip, line.split('='))) values = list(map(float, values.split(','))) data[var] = values
type: Answer
has comment: http://stackoverflow.com/comment/81929526
score: 0
answers question: http://stackoverflow.com/q/47486993

http://stackoverflow.com/comment/81837347
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47396470
has text: Unfortunately this is not true. I'm using font awesome for embedding icons in the text. Also the font size can be changed in the middlemof the text with the [size=30] markup.
type: Comment

http://stackoverflow.com/a/47502375
accepted answer of: http://stackoverflow.com/q/47502212
has comment: http://stackoverflow.com/comment/81961824
has comment: http://stackoverflow.com/comment/108916845
upvote count: 14
has comment: http://stackoverflow.com/comment/117538457
answers question: http://stackoverflow.com/q/47502212
type: Answer
has body: In this case, this is the solution: from tkinter import * def click(): MainTextBox.delete(0, END) OutputBox.delete('1.0', END) GUI = Tk() MainTextBox = Entry(GUI, width = 20, bg = "white") MainTextBox.grid(row = 0, column = 0, sticky = W) Button(GUI, text = "SUBMIT", width = 6, command = click).grid(row = 1, column = 0, sticky = W) OutputBox = Text(GUI, width = 100, height = 10, wrap = WORD, background = "orange") OutputBox.grid(row = 4, column = 0, sticky = W) OutputBox.insert(END, "Example text") GUI.mainloop()
has comment: http://stackoverflow.com/comment/127596412
score: 12
downvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/47509013
score: 0
linked to: http://stackoverflow.com/q/47347505
answer count: 1
has comment: http://stackoverflow.com/comment/81978104
has comment: http://stackoverflow.com/comment/81979238
tagged with: python-docx
has answer: http://stackoverflow.com/a/47518332
type: Question
has comment: http://stackoverflow.com/comment/81975159
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81992625
has body: I am planning to search the specific heading in the document, and then i have to strike out all the contents in that heading. The document has many headings, each heading may have paragraph, tables, images altogether or in any combinations. I have installed docx, i was able to search the specific heading, strike out paragraph, tables. Now next task to the access the images under that Heading and blur those images (instead of strikeout, we are planning to blur the image) I am able to get the resource id for the images which is under Specific Heading by using the code in the link Bluring the Image which is under specific Heading using Python docx Since there are no direct API supporting this features, I am trying to use the XML code as referenced in https://github.com/python-openxml/python-docx/issues/55#issuecomment-43914055.. I am having the XML Code without blur and with blur (by manually setting the Artistic Effect (for blur) of Image) XML Code for the Image without blur: &lt;pic:blipFill&gt; &lt;a:blip r:embed="rId11"&gt; &lt;a:extLst&gt; &lt;a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}"&gt; &lt;a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/&gt; &lt;/a:ext&gt; &lt;/a:extLst&gt; &lt;/a:blip&gt; &lt;a:srcRect/&gt; &lt;a:stretch&gt; &lt;a:fillRect/&gt; &lt;/a:stretch&gt; &lt;/pic:blipFill&gt;` XML Code for the image with blur: &lt;pic:blipFill&gt; &lt;a:blip r:embed="rId11"&gt; &lt;a:extLst&gt; &lt;a:ext uri="{BEBA8EAE-BF5A-486C-A8C5-ECC9F3942E4B}"&gt; &lt;a14:imgProps xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main"&gt; &lt;a14:imgLayer r:embed="rId12"&gt; &lt;a14:imgEffect&gt; &lt;a14:sharpenSoften amount="-50000"/&gt; &lt;/a14:imgEffect&gt; &lt;/a14:imgLayer&gt; &lt;/a14:imgProps&gt; &lt;/a:ext&gt; &lt;a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}"&gt; &lt;a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/&gt; &lt;/a:ext&gt; &lt;/a:extLst&gt; &lt;/a:blip&…
has comment: http://stackoverflow.com/comment/81976516
has title: access XML Content <a14:sharpenSoften> for image Blur using Python Docx

http://stackoverflow.com/q/47491386
has title: Add a QSrollArea on a group of widgets
tagged with: pyqt4
answer count: 1
has answer: http://stackoverflow.com/a/47492009
accepted answer: http://stackoverflow.com/a/47492009
type: Question
tagged with: python
tagged with: qscrollarea
has body: I am coding an interface with stackedwidgets and QGridLayout in which are some widgets which for some are added on the fly ... I'd like to add a QSrolledArea for each group of widgets (see the screenshot attached showing one of the groups of widgets that can be added on the fly) but I don't know how, can you help me ? ... def ajouter_ref_artistique(self) : ''' ''' # r = len(self.liste_ref_artistiques) #if r &gt;= 0 : self.label_annonce_vocab.hide() # Création des QTextEdit self.dico_chem_ref_art[r] = QTextEdit() self.dico_com_ref_art[r] = QTextEdit() self.dico_chem_ref_art[r].setMaximumWidth(170) self.dico_chem_ref_art[r].setMinimumWidth(170) self.dico_chem_ref_art[r].setMaximumHeight(84) self.dico_chem_ref_art[r].setMinimumHeight(84) self.dico_com_ref_art[r].setMaximumWidth(398) self.dico_com_ref_art[r].setMinimumWidth(398) self.dico_com_ref_art[r].setMaximumHeight(84) self.dico_com_ref_art[r].setMinimumHeight(84) # Création des boutons de chargement self.dico_bout_charg_ref_art[r] = QPushButton(u"Ouvrir ref {}".format(r+1)) ''' # Conditions de redimensionnement if r &gt; 5 : self.dico_vocab_mot[r].setMaximumHeight(34) self.dico_vocab_mot[r].setMinimumHeight(34) self.dico_vocab_def[r].setMaximumHeight(34) self.dico_vocab_def[r].setMinimumHeight(34) ''' # Répartition dans la grille self.grille_3_stack_5.addWidget(self.dico_chem_ref_art[r], r, 0) self.grille_3_stack_5.addWidget(self.dico_com_ref_art[r], r, 1) self.grille_3_stack_5.addWidget(self.dico_bout_charg_ref_art[r], r, 2) # Ecriture des n°s de lignes dans la partie mots de vocabulaire self.dico_chem_ref_art[r].setText(str(r+1)+'. ') # Les données sont introduites dans une liste self.liste_ref_artistiques.append([self.dico_chem_ref_art[r], self.dico_com_ref_art[r], self.dico_bout_charg_ref_art[r]]) # ===================================================== # Signaux # ---------- Récup des données textuelles self.dico_chem_ref_art[r].textChanged.connect(self.changements_phase_5) self.dico_com_ref_art[r].textChanged…
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: pyqt

http://stackoverflow.com/a/47422675
type: Answer
has body: As @swimmingduck said, so need to add hisc.close() to the end of your code, as without it, Python wouldn't realise that you have finished writing to the file.
has comment: http://stackoverflow.com/comment/81800957
score: 0
answers question: http://stackoverflow.com/q/47422570
has comment: http://stackoverflow.com/comment/81800000

http://stackoverflow.com/comment/81785037
score: 2
has text: Maybe because you have `csv` as a variable as well as a module?
comment on: http://stackoverflow.com/q/47415735
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47460971
tagged with: random
answer count: 0
has body: def FitnessSelection(population, relative_fitness): selected_chromosomes = [] selected1 = random.choices(population, weights = relative_fitness, k = 1) ind1 = selected1[0][1][0] del relative_fitness[ind1] del population[ind1] selected2 = random.choices(population, weights = relative_fitness, k = 1) ind2 = selected2[0][1][0] del relative_fitness[ind2] del population[ind1] selected = selected1, selected2 selected_chromosomes = [i[0] for i in selected] return (selected_chromosomes) I am trying to perform a random weighted selection from a list, however, I cant have the same item selected twice, therefore I am trying to exclude the selected items immediately after selection so it won't be in the population in the list for the next run of the function. The problem is that the program is running but I don't think the items are being excluded I have the items in the following structure population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]]] Where the last brackets of each string is an index counter. I am trying to isolate the counter and exclude the item in the same position, but when I check the population afterward, they were not excluded. Does anyone know what could be wrong with this approach? p.s. - I'm sorry for not posting a standalone program, I couldn't make it work in a small sample like this. Thanks!
type: Question
has title: Remove items from list sequentially based on variable index
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81877261
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81877133
score: 0
tagged with: list

http://stackoverflow.com/comment/82023437
score: 0
comment on: http://stackoverflow.com/q/47533128
type: QuestionComment
has text: Indorman thanks for a good hint. I work in jupyter notebook right now and somehow plotly was sort of "hidden" from him when installed in bash. I just made a new project in PyCharm with my "notebook" enviroment and added plotly to interpreter manually.It solved my problem.
type: Comment

http://stackoverflow.com/comment/81975999
type: AnswerComment
comment on: http://stackoverflow.com/a/47510095
has text: @Bharath Good point. While slower (if I'm not mistaken), that is safer.
score: 1
type: Comment

http://stackoverflow.com/q/47437109
has comment: http://stackoverflow.com/comment/81828571
tagged with: dataframe
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/47437408
tagged with: export-to-csv
has comment: http://stackoverflow.com/comment/81828672
type: AnsweredQuestion
has title: how to write dataframe data likes '0012' to csv by to_csv in pandas
downvote count: 3
accepted answer: http://stackoverflow.com/a/47437408
has body: the code is as following: a={'code':['0012'],'name':['jason']} DataFrame(a).to_csv('test.csv') it appears that the data '0012' changes to '12' in the test.csv file. How can I solve the problem? Thanks a lot :)
upvote count: 1
answer count: 1
tagged with: dataformat
favorite count: 0
type: Question
tagged with: pandas

http://stackoverflow.com/a/47489101
has comment: http://stackoverflow.com/comment/88150287
score: 1
has comment: http://stackoverflow.com/comment/88221276
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47461149
has body: Use: #create dictionary by scenaries d = {'scenario{}'.format(k):v for k, v in enumerate(scenario_descriptions, 1)} #unique id for reindex uniq_id = df['id'].unique() def f(x): #check if all description c = set(x['description']) &gt;= set(v) #check if 4,5 or 6 value d = x['status'].isin([4,5,6]).all() return (c &amp; d) d1 = {} for k, v in d.items(): #filter df by scenary first for remove not relevant rows a = df[df['description'].isin(v)] #call groupby with custom function b = a.groupby('id').apply(f) #add missing ids and fill by False #output to dictionary d1[k] = b.reindex(uniq_id, fill_value=False) print (d1) {'scenario1': id 1 False 2 False dtype: bool, 'scenario4': id 1 False 2 False dtype: bool, 'scenario5': id 1 True 2 False dtype: bool, 'scenario3': id 1 True 2 False dtype: bool, 'scenario2': id 1 True 2 False dtype: bool} #reduce dict to DataFrame and check at least one True per row m = pd.concat(d1, axis=1).any(axis=1) print (m) id 1 True 2 False #last filtering df = df[df['id'].isin(m.index[m])] print (df) id description status 0 1 world1 1 1 1 world2 4 2 1 world3 1 3 1 world4 4 4 1 world5 4 5 1 world6 4 6 1 world7 1 7 1 world8 4 8 1 world9 4 9 1 world10 4 10 1 world11 4 11 1 world12 4 12 1 world13 4 13 1 world14 4 14 1 world15 1
has comment: http://stackoverflow.com/comment/88150339
type: Answer
accepted answer of: http://stackoverflow.com/q/47461149
has comment: http://stackoverflow.com/comment/88220994

http://stackoverflow.com/comment/81965294
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47504748
has text: very useful answer！now everything is ok！ thank you mate！
type: Comment

http://stackoverflow.com/a/47387898
downvote count: 0
answers question: http://stackoverflow.com/q/47387887
type: Answer
has comment: http://stackoverflow.com/comment/81729949
score: 2
has comment: http://stackoverflow.com/comment/81730247
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47387887
type: AcceptedAnswer
has body: Convert column to sets and use &amp; for intersection with list converted to set also: cat_list = ['Cat1','Cat2', 'Cat4'] print (test_df['Category'].apply(set) &amp; set(cat_list)) 0 True 1 False 2 True Name: Category, dtype: bool Last filter by boolean indexing: test_df = test_df[test_df['Category'].apply(set) &amp; set(cat_list)] print (test_df) Title Category 0 Title1 [Cat1, Cat2] 2 Title2 [Cat3, Cat4]

http://stackoverflow.com/comment/81910106
type: QuestionComment
has text: Yes, with homebrew without sudo
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47429321

http://stackoverflow.com/a/47498964
has comment: http://stackoverflow.com/comment/81953508
upvote count: 23
score: 23
has comment: http://stackoverflow.com/comment/81972848
has comment: http://stackoverflow.com/comment/81961756
type: Answer
accepted answer of: http://stackoverflow.com/q/47498920
has comment: http://stackoverflow.com/comment/134341676
has comment: http://stackoverflow.com/comment/81973697
has comment: http://stackoverflow.com/comment/81961351
answers question: http://stackoverflow.com/q/47498920
downvote count: 0
has body: use np.add.outer(): In [65]: pd.DataFrame(np.add.outer(df['Size'], df['Size']), columns=df['ID'].values, index=df['ID'].values) Out[65]: a b c d e f g a 8 7 4 6 13 9 7 b 7 6 3 5 12 8 6 c 4 3 0 2 9 5 3 d 6 5 2 4 11 7 5 e 13 12 9 11 18 14 12 f 9 8 5 7 14 10 8 g 7 6 3 5 12 8 6 UPDATE: memory-saving (Pandas Multi-Index) approach (NOTE: this approach is much slower, compared to the previous one): In [33]: r = pd.DataFrame(np.array(list(combinations(df['Size'], 2))).sum(axis=1), ...: index=pd.MultiIndex.from_tuples(list(combinations(df['ID'], 2))), ...: columns=['TotalSize'] ...: ) In [34]: r Out[34]: TotalSize a b 7 c 4 d 6 e 13 f 9 g 7 b c 3 d 5 e 12 f 8 g 6 c d 2 e 9 f 5 g 3 d e 11 f 7 g 5 e f 14 g 12 f g 8 It can be accessed as follows: In [41]: r.loc[('a','b')] Out[41]: TotalSize 7 Name: (a, b), dtype: int32 In [42]: r.loc[('a','b'), 'TotalSize'] Out[42]: 7 In [44]: r.loc[[('a','b'), ('c','d')], 'TotalSize'] Out[44]: a b 7 c d 2 Name: TotalSize, dtype: int32 In [43]: r.at[('a','b'), 'TotalSize'] Out[43]: 7 Memory usage comparison (DF shape: 7000x3): In [65]: df = pd.concat([df] * 1000, ignore_index=True) In [66]: df.shape Out[66]: (7000, 2) In [67]: r1 = pd.DataFrame(np.add.outer(df['Size'], df['Size']), ...: columns=df['ID'].values, ...: index=df['ID'].values) ...: In [68]: r2 = pd.DataFrame(np.array(list(combinations(df['Size'], 2))).sum(axis=1), ...: index=pd.MultiIndex.from_tuples(list(combinations(df['ID'], 2))), ...: columns=['TotalSize']) ...: In [69]: r1.memory_usage().sum()/r2.memory_usage().sum() Out[69]: 2.6685407829018244 Speed comparison (DF shape: 7000x3): In [70]: %%timeit ...: r1 = pd.DataFrame(np.add.outer(df['Size'], df['Size']), ...: columns=df['ID'].values, ...: index=df['ID'].values) ...: 180 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [71]: %%timeit ...: r2 = pd.DataFrame(np.array(list(combinations(df['Size'], 2))).sum(axis=1), ...: index=pd.MultiIndex.from_tuples(list(combinations(df['ID'], 2))), ...: columns=['TotalSiz…
type: AcceptedAnswer

http://stackoverflow.com/q/47429673
score: 0
has comment: http://stackoverflow.com/comment/81819570
has comment: http://stackoverflow.com/comment/81819860
tagged with: python
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81821326
has body: I am trying to scrape a website using the python requests module and have needed to login to the site to retrieve the data I want. I have written a script which should work but is not. I am unsure as to wether this is because of the authentication method for the login of the site. This is the website i am trying to scrape: https://ashwoodvic.compass.education/login.aspx?sessionstate=disabled import requests import bs4 as bs login_url = "https://ashwoodvic.compass.education/login.aspx?sessionstate=disabled" target_url = "https://ashwoodvic.compass.education" login_data = { "username": "my_username", "password": "my_password"} with requests.Session() as s: page = s.get(login_url) page_login = s.post(login_url, data = login_data) page = s.get(target_url) final_page = bs.BeautifulSoup(page.content, 'lxml') print(final_page.title) This is the html of the password box: Password The script does not contain any errors but just fails to login to the website and the title returned at the end was Login. Any help is appreciated.
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python-requests
tagged with: beautifulsoup
has title: Web Scraping Python with Requests (Login)
has comment: http://stackoverflow.com/comment/81814046
has comment: http://stackoverflow.com/comment/81819979

http://stackoverflow.com/comment/81887853
has text: The list comprehension looks crazy. Either you want `filelist = [os.path.abspath(item) for item in ...]` or else `filelist = []; for item in ..: filelist.append(os.path.abspath(item))` but you have an unholy mixture of append inside a comprehension.
score: 0
comment on: http://stackoverflow.com/q/47464706
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81974024
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47501674
has text: Yeah I never thought of that now I understand that better thank you bro.
type: Comment

keras
tags question: http://stackoverflow.com/q/47473297
tags question: http://stackoverflow.com/q/47521003
tags question: http://stackoverflow.com/q/47476036
tags question: http://stackoverflow.com/q/47504501
tags question: http://stackoverflow.com/q/47490834
tags question: http://stackoverflow.com/q/47485216
tags question: http://stackoverflow.com/q/47484469
tags question: http://stackoverflow.com/q/47405091
tags question: http://stackoverflow.com/q/47535669
tags question: http://stackoverflow.com/q/47489955
tags question: http://stackoverflow.com/q/47470655
tags question: http://stackoverflow.com/q/47502126
tags question: http://stackoverflow.com/q/47433065
tags question: http://stackoverflow.com/q/47445732
tags question: http://stackoverflow.com/q/47514063
tags question: http://stackoverflow.com/q/47401556
tags question: http://stackoverflow.com/q/47383833
tags question: http://stackoverflow.com/q/47451919
tags question: http://stackoverflow.com/q/47485587
tags question: http://stackoverflow.com/q/47462114
tags question: http://stackoverflow.com/q/47417897
tags question: http://stackoverflow.com/q/47477371
tags question: http://stackoverflow.com/q/47440955
tags question: http://stackoverflow.com/q/47414371
tags question: http://stackoverflow.com/q/47463652
tags question: http://stackoverflow.com/q/47389536
tags question: http://stackoverflow.com/q/47474869
tags question: http://stackoverflow.com/q/47410239
tags question: http://stackoverflow.com/q/47445588
tags question: http://stackoverflow.com/q/47398009
tags question: http://stackoverflow.com/q/47443880
tags question: http://stackoverflow.com/q/47495190
tags question: http://stackoverflow.com/q/47418617
tags question: http://stackoverflow.com/q/47538391
tags question: http://stackoverflow.com/q/47416861
tags question: http://stackoverflow.com/q/47494896
tags question: http://stackoverflow.com/q/47423512
tags question: http://stackoverflow.com/q/47437750
tags question: http://stackoverflow.com/q/47480111
tags question: http://stackoverflow.com/q/47421951
tags question: http://stackoverflow.com/q/47406652
tags question: http://stackoverflow.com/q/47455397
tags question: http://stackoverflow.com/q/47394104
tags question: http://stackoverflow.com/q/47394572
tags question: http://stackoverflow.com/q/47490381
tags question: http://stackoverflow.com/q/47537576
tags question: http://stackoverflow.com/q/47532162
tags question: http://stackoverflow.com/q/47385700
tags question: http://stackoverflow.com/q/47523841
tag name: keras
tags question: http://stackoverflow.com/q/47527735
tags question: http://stackoverflow.com/q/47398769
tags question: http://stackoverflow.com/q/47525790
tags question: http://stackoverflow.com/q/47536066
tags question: http://stackoverflow.com/q/47465640
tags question: http://stackoverflow.com/q/47382952
tags question: http://stackoverflow.com/q/47411492
tags question: http://stackoverflow.com/q/47459299
type: Tag
tags question: http://stackoverflow.com/q/47519554
tags question: http://stackoverflow.com/q/47508874
tags question: http://stackoverflow.com/q/47470385
tags question: http://stackoverflow.com/q/47430437
tags question: http://stackoverflow.com/q/47493392
tags question: http://stackoverflow.com/q/47442792
tags question: http://stackoverflow.com/q/47530722
tags question: http://stackoverflow.com/q/47490393
tags question: http://stackoverflow.com/q/47513277
tags question: http://stackoverflow.com/q/47491098

http://stackoverflow.com/q/47451334
has comment: http://stackoverflow.com/comment/81858210
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47451359
accepted answer: http://stackoverflow.com/a/47451509
has title: How to find max() in a list and find its index value as well using max()?
has answer: http://stackoverflow.com/a/47451359
has answer: http://stackoverflow.com/a/47451509
has comment: http://stackoverflow.com/comment/81858413
tagged with: python
has body: Just wondering if someone could spot what i was doing wrong, i was under the impression that the following code would find the max number and the index of the max number. here is the code im using below. def select_winner(): print('The game scores are:') for i in range (4): print(Players[i], ' = ', score[i]) winner = max(enumerate(score)) print('----------------') print() print('The Winner is ', Players[winner[0]], ' with ', str(winner[1]),' points!') print(winner) The output: #The game scores are: #Jarrah = 86 #Reza = 121 #Marge = 72 #Homer = 91 #---------------- #The Winner is Homer with 91 points! #(3, 91) max should choose the highest value right? and enumerate should choose the value and its index if im not mistaken and when i print them together i should get the highest value and wheres its located in the list. well atleast thats what im trying to do. the index for the score that was chosen as the highest should share the same index with the player who got that score as well as thats how they were listed. any help would be great thanks Update: def select_winner(): print('The game scores are:') for i in range (4): print(Players[i], ' = ', score[i]) winner =(max(score)) print('----------------') print() print('The Winner is '+ Players[winner[0]]+ ' with '+ str(winner[1])+ ' points!') print(winner) output: #The game scores are: #Jarrah = 91 #Baldwin = 73 #Kepa = 112 #Long = 106 #---------------- #in select_winner #print('The Winner is '+ Players[winner[0]]+ ' with '+ str(winner[1])+ ' #points!') #TypeError: 'int' object is not subscriptable anyone know of a work around, and does the max() on its own pull the index of where the max number is located? if not, is there a way to do that? Fixed!: def select_winner(): k=0 print('The game scores are:') for i in range (4): print(Players[i], ' = ', score[i]) winner2=(score.index(max(score))) winner=str(max(score)) print('----------------') print() print('The Winner is '+ Players[winner2]+ ' with '+ winner + ' points!')
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81857522

http://stackoverflow.com/comment/82022943
comment on: http://stackoverflow.com/a/47520980
type: AnswerComment
has text: @FJ oh sorry data_dict is the full version of json_sample. So it has same structure but with the full data.
score: 0
type: Comment

http://stackoverflow.com/q/47407926
tagged with: python
tagged with: odoo
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: How to create default radio button website, I want to set default in radio button on morning in my website. Choose your shift delivery Morning Afternoon samebody help?
has title: How to create default radio button website
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47409569

http://stackoverflow.com/a/47460246
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47460105
type: Answer
has body: In the snippet you provided, every time when the line is not empty, data list is cleared. data_buf = [] data_tot = [] with open('file.txt', 'r') as infile: for line in infile: if line.rstrip() == '': data_tot.append(data_buf[:]) data_buf = [] else: data_buf.append(line.rstrip()) if len(data_buf) &gt; 0: data_tot.append(data_buf[:]) Note that data_buf[:] copies list object to avoid its modification in the next iteration. Also you should add the last buffer to the total list, if it is not followed by empty line. Here is the full standalone sample code with StringIO instead of the file import io f = io.StringIO("""1 2 3 23 33 55 1 2 4 """) data_buf = [] data_tot = [] with f as infile: for line in infile: if line.rstrip() == '': data_tot.append(data_buf[:]) data_buf = [] else: data_buf.append(line.rstrip()) data_tot.append(data_buf[:])
score: 2

http://stackoverflow.com/comment/82015445
comment on: http://stackoverflow.com/a/47525639
score: 0
type: AnswerComment
has text: I dit that. json file doesn't contains correct data. I still have ` D\u00e9couvrez toutes les recettes de couleur marron `
type: Comment

http://stackoverflow.com/a/47384376
has comment: http://stackoverflow.com/comment/81723999
has comment: http://stackoverflow.com/comment/81722541
has comment: http://stackoverflow.com/comment/81723132
has comment: http://stackoverflow.com/comment/81724214
score: 0
has comment: http://stackoverflow.com/comment/81722953
has comment: http://stackoverflow.com/comment/81721972
has comment: http://stackoverflow.com/comment/81722688
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81722669
has comment: http://stackoverflow.com/comment/81724347
has comment: http://stackoverflow.com/comment/81724370
has comment: http://stackoverflow.com/comment/81722762
has comment: http://stackoverflow.com/comment/81724245
has body: You do not have to use a QGraphicsView necessarily, you can use any widget, what you have to do is insert a layout and add the canvas to the layout. [...] t = arange(0.0, 3.0, 0.01) s = sin(2*pi*t) figure = Figure() self.axes = figure.gca() self..set_title("title") self..plot(t,s) self.canvas = FigureCanvas(figure) self.canvas.setGeometry(0, 0, 500, 500) lay = QtWidgets.QVBoxLayout(self.graphicsView) lay.addWidget(self.canvas) [...] def onActivated(self, text): print(text) self.axes.clear() t = arange(0.0, 3.0, 0.01) s = cos(2*pi*t) self.axes.plot(t,s) self.canvas.draw()
has comment: http://stackoverflow.com/comment/81722808
accepted answer of: http://stackoverflow.com/q/47384116
has comment: http://stackoverflow.com/comment/81724036
has comment: http://stackoverflow.com/comment/81722792
type: Answer
has comment: http://stackoverflow.com/comment/81722822
answers question: http://stackoverflow.com/q/47384116

http://stackoverflow.com/comment/82130011
score: 0
type: AnswerComment
has text: awesome, let me put that to work, and sorry for the delays, been wicked busy all of a sudden
type: Comment
comment on: http://stackoverflow.com/a/47503449

http://stackoverflow.com/a/47503108
accepted answer of: http://stackoverflow.com/q/47503071
type: AcceptedAnswer
has body: Fixing your code, I'd recommend iterating over each element directly, appending to a nested list - r = [[]] for i in temp: if i.strip(): r[-1].append(i) else: r.append([]) Note that if temp ends with a newline, r will have a trailing empty [] list. You can get rid of that though: if not r[-1]: del r[-1] Another option would be using itertools.groupby, which the other answerer has already mentioned. Although, your method is more performant.
type: Answer
answers question: http://stackoverflow.com/q/47503071
score: 0

http://stackoverflow.com/a/55139209
type: Answer
answers question: http://stackoverflow.com/q/47527330
has body: You did forget to import Mglearn. It can be installed in Ubuntu via pip install Mglearn . After that, Import mglearn it will start working, same happened with me!!
score: 0

http://stackoverflow.com/a/47537085
answers question: http://stackoverflow.com/q/47537055
score: 3
type: Answer
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47537055
type: AcceptedAnswer
has body: In [34]: df['chain'] += df.pop('pos').astype(str) In [35]: df Out[35]: chain 0 A1 1 B2 2 C3 renaming column: In [37]: df = df.rename(columns={'chain':'chain+pos'}) In [38]: df Out[38]: chain+pos 0 A1 1 B2 2 C3

file
tags question: http://stackoverflow.com/q/47393222
tags question: http://stackoverflow.com/q/47392526
type: Tag
tags question: http://stackoverflow.com/q/47535540
tags question: http://stackoverflow.com/q/47423481
tags question: http://stackoverflow.com/q/47446834
tags question: http://stackoverflow.com/q/47455562
tags question: http://stackoverflow.com/q/47496557
tags question: http://stackoverflow.com/q/47432043
tags question: http://stackoverflow.com/q/47422506
tags question: http://stackoverflow.com/q/47523319
tags question: http://stackoverflow.com/q/47537849
tags question: http://stackoverflow.com/q/47425695
tags question: http://stackoverflow.com/q/47459078
tag name: file
tags question: http://stackoverflow.com/q/47478050
tags question: http://stackoverflow.com/q/47462524
tags question: http://stackoverflow.com/q/47478404
tags question: http://stackoverflow.com/q/47460105
tags question: http://stackoverflow.com/q/47502360
tags question: http://stackoverflow.com/q/47433755
tags question: http://stackoverflow.com/q/47510091
tags question: http://stackoverflow.com/q/47499176
tags question: http://stackoverflow.com/q/47462282
tags question: http://stackoverflow.com/q/47531879
tags question: http://stackoverflow.com/q/47498481
tags question: http://stackoverflow.com/q/47520049
tags question: http://stackoverflow.com/q/47477809
tags question: http://stackoverflow.com/q/47493034
tags question: http://stackoverflow.com/q/47443445
tags question: http://stackoverflow.com/q/47512640

http://stackoverflow.com/comment/81736509
type: Comment
has text: I am using 2 option: `-m` meaning `--max_value` and `--max-value`. Where is 1 option only?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47389858

http://stackoverflow.com/comment/91214757
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47394941
score: 0
has text: hey man, could you up vote or select my answer as preferred if I answered your question.

http://stackoverflow.com/q/47469836
linked to: http://stackoverflow.com/q/9042542
has comment: http://stackoverflow.com/comment/81894205
favorite count: 0
has title: How to tell if a directory is a windows junction in python
type: Question
has comment: http://stackoverflow.com/comment/81899371
linked to: http://stackoverflow.com/q/15258506
has comment: http://stackoverflow.com/comment/85996868
linked to: http://stackoverflow.com/q/1143260
tagged with: windows
has body: I am running os.walk() on "C:\Users\confusedDev\Documents", I see ["My Music", "My Pictures"...] returned as subDirs but they are not actually being visited. After some research I found that they are actually junctions in Windows. My understanding is that junction is a symlink points to directory, which gets ignored by default during os.walk(), but the following test has failed me &gt;&gt;&gt; os.path.islink("C:\\Users\\confusedDev\\Documents\\My Pictures") False hmm...how did os.walk() know that "C:\Users\confusedDev\Documents\My Pictures" is a symlink to "C:\Users\confusedDev\Pictures" and needed to be skipped? I want to call the same api...For now, my workaround logic simply assumes that if a directory is skipped by os.walk(), it is a junction
tagged with: python
has answer: http://stackoverflow.com/a/59904873
upvote count: 6
tagged with: symlink
tagged with: filesystems
has answer: http://stackoverflow.com/a/54678399
has answer: http://stackoverflow.com/a/78185350
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49496649
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/77557230

http://stackoverflow.com/a/47551321
has comment: http://stackoverflow.com/comment/116374077
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47536253
accepted answer of: http://stackoverflow.com/q/47536253
has body: Going with the comment from @mdurant, it's not as easy as you'd expect to copy a dataframe maintaining types, but this seems to work. This wouldn't work if your first file errors out, of course. import dask.dataframe as dd import dask.delayed _default_record = None def _read(self, filename): global _default_record try: df = pd.read_csv(filename, sep=';', decimal=',', encoding='latin1', index_col=False) if _default_record is None: _default_record = pd.DataFrame.from_items([ (name, pd.Series(data=None, dtype=series.dtype)) for name, series in df.head(1).iteritems()]) return df except BaseException as e: return _default_record tasks = [] for root, dirs, files in os.walk(os.path.join(self._path, "files")): for file in files: tasks.append(dask.delayed(_read, pure=True)(os.path.join(root, file))) ddf = dd.from_delayed(tasks)
upvote count: 3

http://stackoverflow.com/a/47410070
upvote count: 4
score: 4
has body: You can't access path[count] and assign something to it if path[count] doesn't already exist. To create a new list, use .append(). You don't need to keep track of a counter at all (it's rarely necessary to do a C-style loop in Python; the pythonic way is to iterate over the elements of a list/tuple/dictionary directly): file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl'] path = [] for item in file_name: newpath = "D:\\Work\\" + item + ".csv" # or better: newpath = r"D:\Work\{}.csv".format(item) path.append(newpath) print(newpath)
answers question: http://stackoverflow.com/q/47409940
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82004629
type: Comment
has text: Sure, I added a simplified version of the status update JSON object. An exhaustive explanation can be found here: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/tweet-object
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47522258

http://stackoverflow.com/comment/81719404
type: Comment
has text: Again thanks, you have no idea how much time you have saved me!
comment on: http://stackoverflow.com/a/47383163
type: AnswerComment
score: 0

http://stackoverflow.com/q/47452543
type: AnsweredQuestion
score: 3
tagged with: python
has body: Installed VS Tools for AI and tried to run a python deep learning script. The script runs well on the Anaconda Interactive provided by the IDE. Problem is with the 'Variable Explorer'. It shows an error saying "Error retrieving environment list". The Default python environment is set to Anaconda 4.4.0. Any solution to get the prevailing variables in the executing script through the explorer?
type: Question
has comment: http://stackoverflow.com/comment/82097485
upvote count: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49179310
has title: Visual Studio Tools for AI - Variable Explorer not loading
favorite count: 0
tagged with: visual-studio
has answer: http://stackoverflow.com/a/49179310
tagged with: ptvs

http://stackoverflow.com/comment/81983696
has text: First, thanks for your answer: I'm not sure if I understood it correctly, did you mean this? changing it to **weights=[w.T]** or **w.shape[0],w.shape[1]** to **w.shape[1],w.shape[0]** got me different other errors. but even if not I think with transposing the embedding matrix it would also be problematic passing in the input as it need to be multiplied with the input vectors.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47489955
score: 0

http://stackoverflow.com/comment/81898518
type: AnswerComment
comment on: http://stackoverflow.com/a/47446550
score: 0
type: Comment
has text: @ImperishableNight - if you run the Batch File the Msdos Window Will also Appears, **if you do not want that second Window** you can try this Code, Example3.pyw - import pywinauto pywinauto.Application().start(r"C:\Python27\Pythonw.exe c:\test\my_app.py") ps - Look to my answer - I Hope you Will Like this.

http://stackoverflow.com/a/47500795
accepted answer of: http://stackoverflow.com/q/47500345
has comment: http://stackoverflow.com/comment/81958739
has body: You firstly need to check if user is authenticated, it not, then return every Item. Then to filter out Item objects if corresponding WalletItem objects exceeded its limit. from django.db.models import Count, F, Sum ... class ItemViewSet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): queryset = super().get_queryset() user = self.request.user if user.is_anonymous: return queryset queryset = queryset.annotate(user_wallet_items=Sum( Case( When(walletitem__wallet_id=user.wallet_id, then=1), default=0, output_field=IntegerField() )) \ .filter(user_wallet_items__lte=F('limit_usage')) return queryset I suggest you to move your filtration based on current time to the same get_queryset() method, since it's belong there. Note: i've not tested this approach.
answers question: http://stackoverflow.com/q/47500345
type: Answer
has comment: http://stackoverflow.com/comment/81963993
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81806699
type: AnswerComment
comment on: http://stackoverflow.com/a/47425855
has text: I guess it depends on your use case. For simple local development, I am okay with a restart policy. If you plan on using compose in production (not particularly common), you would want to be more careful and use `wait-for-it`.
type: Comment
score: 0

http://stackoverflow.com/a/47500187
has comment: http://stackoverflow.com/comment/81956917
has body: You can't create a DataFrame from a tuple. You can, however, create a Series from a tuple, and have the indicies be the columns of dFrame: dFrame.append(pd.Series(row, index=dfHeader.keys()), ignore_index=True)
answers question: http://stackoverflow.com/q/47500081
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81955831

http://stackoverflow.com/comment/81811429
score: 0
comment on: http://stackoverflow.com/q/47428299
type: Comment
type: QuestionComment
has text: Do you always want only the first two keys? If so you dont need to sort the dict

http://stackoverflow.com/q/47431458
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: image-extraction
has answer: http://stackoverflow.com/a/47438212
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82540276
tagged with: python
has comment: http://stackoverflow.com/comment/82506816
has body: I am trying to extract images from PDF and got a code from StackOverflow. It is working fine for some of the pdf but not for all. I saw a pattern that pdf which has a number of pages more than 8-10, it is not extracting anything.I think I am missing something minute here. Please help me figure out. This is the code I am using and here is the link to pdf resources import PyPDF2 import sys from PIL import Image import os import glob from PyPDF2 import PdfFileReader def ExtractImages(filename): print("\n---------------------------------------") print("This is the pdf processing",filename) fileObject = PyPDF2.PdfFileReader(open(filename, "rb")) print(fileObject) pages = fileObject.getNumPages() print("Total number of Pages is.....",pages) for i in range(2,pages): tempPage = fileObject.getPage(i) if '/XObject' in tempPage['/Resources']: xObject = tempPage['/Resources']['/XObject'].getObject() for obj in xObject: if xObject[obj]['/Subtype'] == '/Image': size = (xObject[obj]['/Width'], xObject[obj]['/Height']) data = xObject[obj].getData() if xObject[obj]['/ColorSpace'] == '/DeviceRGB': mode = "RGB" else: mode = "P" if '/Filter' in xObject[obj]: if xObject[obj]['/Filter'] == '/FlateDecode': img = Image.frombytes(mode, size, data) img.save(obj[1:] + ".png") elif xObject[obj]['/Filter'] == '/DCTDecode': img = open(obj[1:] + ".jpg", "wb") img.write(data) img.close() elif xObject[obj]['/Filter'] == '/JPXDecode': img = open(obj[1:] + ".jp2", "wb") img.write(data) img.close() elif xObject[obj]['/Filter'] == '/CCITTFaxDecode': img = open(obj[1:] + ".tiff", "wb") img.write(data) img.close() else: img = Image.frombytes(mode, size, data) img.save(obj[1:] + ".png") else: print("No image found for file.",filename) listOfFiles = glob.glob('./*.pdf') for file in listOfFiles: ExtractImages(file)
has comment: http://stackoverflow.com/comment/82507836
has title: Image extraction not working if PDF contains 8-10 or more pages
has comment: http://stackoverflow.com/comment/82527283
score: 0
tagged with: pypdf
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
has comment: http://stackoverflow.com/comment/81819482

http://stackoverflow.com/comment/81818030
comment on: http://stackoverflow.com/q/47430437
has text: Using info from https://www.tensorflow.org/api_guides/python/math_ops try something like from `keras import backend as K; def customLossFunction(y_true, y_pred): return K.mean(K.sign(y_pred) * y_true, axis=-1)`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47459226
score: 3
tagged with: pandas
upvote count: 3
tagged with: plotly
has answer: http://stackoverflow.com/a/47461139
answer count: 1
downvote count: 0
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
has title: Python: Plotly: Parallel Coordinates Opacity
has body: Im trying to do a parallel coordinate plot. I want the color of the lines black, but with an opacity so that lines which overlap are darker than the rest. Is it possible to set an opcaity to the color in the example of plotly parallel coordinates ? import plotly.plotly as py import plotly.graph_objs as go import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/parcoords_data.csv") data = [ go.Parcoords( line = dict(color = df['colorVal'], colorscale = 'Jet', showscale = True, reversescale = True, cmin = -4000, cmax = -100), dimensions = list([ dict(range = [32000,227900], constraintrange = [100000,150000], label = 'Block Height', values = df['blockHeight']), dict(range = [0,700000], label = 'Block Width', values = df['blockWidth']), dict(tickvals = [0,0.5,1,2,3], ticktext = ['A','AB','B','Y','Z'], label = 'Cyclinder Material', values = df['cycMaterial']), dict(range = [-1,4], tickvals = [0,1,2,3], label = 'Block Material', values = df['blockMaterial']), dict(range = [134,3154], visible = True, label = 'Total Weight', values = df['totalWeight']), dict(range = [9,19984], label = 'Assembly Penalty Weight', values = df['assemblyPW']), dict(range = [49000,568000], label = 'Height st Width', values = df['HstW']), dict(range = [-28000,196430], label = 'Min Height Width', values = df['minHW']), dict(range = [98453,501789], label = 'Min Width Diameter', values = df['minWD']), dict(range = [1417,107154], label = 'RF Block', values = df['rfBlock']) ]) ) ] py.offline.plot(data, filename = 'parcoords-advanced')

http://stackoverflow.com/a/47460544
has comment: http://stackoverflow.com/comment/82149344
answers question: http://stackoverflow.com/q/47459717
has comment: http://stackoverflow.com/comment/82167228
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47459717
has comment: http://stackoverflow.com/comment/82151713
score: 1
type: Answer
has body: OK, let's see: import urllib.parse globals() You will see an item: 'urllib': &lt;module 'urllib' from 'C:\\Users\\XXXX\\AppData\\Local\\Programs\\Python\\Python35\\lib\\urllib\\__init__.py'&gt; Then, try dir(urllib), you will see: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'parse'] So there is a parse in urllib, but not request or error. Because parse doesn't import them. Now let's go to urllib.request: import urllib.request globals() Get an item: 'urllib': &lt;module 'urllib' from 'C:\\Users\\XXXX\\AppData\\Local\\Programs\\Python\\Python35\\lib\\urllib\\__init__.py'&gt; It is the same as import urllib.parse. Then try dir(urllib) again: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'error', 'parse', 'request', 'response'] There are 'error', 'parse', 'request', 'response' in it. Why? Because urllib.request imports them. Let me try and explain it in more details. Importing urllib.request first imports urllib, then urllib.request. Importing urllib gives us urllib symbol in local scope, representing module having been imported. Importing urllib.request imports urllib.error among other things. Which adds error symbol to urllib module. And since we have reference to urllib, that makes us able to access urllib.error after importing urllib.request. Consider the following example: ./main.py #!/usr/bin/env python import a.b print(a.c.c) # 2 print(d.e.e) # NameError ./a/b.py import a.c import d.e b = 1 ./a/c.py c = 2 ./d/e.py: e = 3
has comment: http://stackoverflow.com/comment/82128358
has comment: http://stackoverflow.com/comment/82149405
has comment: http://stackoverflow.com/comment/82112838
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82145470
downvote count: 0

http://stackoverflow.com/comment/81995737
type: Comment
type: QuestionComment
has text: Vectorization is made hard in particular by the fact that the windows may become arbitrarily large. Had distances been integral and positive, we could assume that windows would always be of size at most 5 at which point precalculation may provide a passable solution. In any case, following @JohnE's comment, I added a few examples of how numba effectively solves the problem in the answer below.
comment on: http://stackoverflow.com/q/47480942
score: 1

http://stackoverflow.com/comment/82040183
has text: `csvfile.write('Your text \n')`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47540344

http://stackoverflow.com/a/51870885
downvote count: 3
upvote count: 80
answers question: http://stackoverflow.com/q/47425520
type: Answer
has body: You do not need to activate the virtual environment while running in .bat. All you need to do is to run the python.exe file in your virtual environment. {path to virtual environment directory}/Scripts/python.exe path/to/your/file.py In Windows Task Scheduler you can specify the path in which the command prompt will open. So when adding the action, use path to your python in the field Program/script, the name of the file to be run in Add arguments field, and the path to your file.py in Start in field. P.S if you are reading or writing files in your python file, note that your path will be relative to the one you specify in your start in field in the Action window
score: 77

http://stackoverflow.com/q/47400055
type: Question
tagged with: tuples
has answer: http://stackoverflow.com/a/47400194
has body: I am trying to write a basic store-front script that loops until the customer says no to the question. Each time there's input of an Item Number, I'm trying to store it and then eventually be able to match those numbers up with the Item Name and the Price (not quite yet, though)... I am just, now, trying to get it to add to the empty list "item_nums" instead of adding the last entry and over-writing the previous numbers. STOREKEEPER products = ['Notebook', 'Atari', 'TrapperKeeper', 'Jeans', 'Insects', 'Harbormaster', 'Lobotomy', 'PunkRock', 'HorseFeathers', 'Pants', 'Plants', 'Salami'] prices = ['$4.99', '$99.99', '$89.99', '$3.99', '$2.99', '$299.99', '$19.99', '$3.99', '$4.99', '$2.99', '$119.99', '$1.99'] SKUs = [1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12] item_nums = () quantity = [] response = '' #MORE VARIABLES AND FUNCTIONS WILL GO HERE print("Jay's House of Rip-Offs\n\n") titles = ['Item Number', 'Item Name', 'Price'] data = [titles] + list(zip(SKUs, products, prices)) for i, d in enumerate(data): line = '|'.join(str(x).ljust(16) for x in d) print(line) if i == 0: print('-' * len(line)) response = str(input("Order products [Y / N]?: ")) while response != 'N': item_nums = input("Enter an item number: ") SKUs.append(item_nums) response = str(input("Order products [Y / N]?: ")) if response == 'N': break print("Here is the list of items you ordered: ",item_nums[0])
tagged with: while-loop
tagged with: if-statement
has comment: http://stackoverflow.com/comment/81755543
tagged with: python
has title: Python3 - Adding User Response to a List Instead of Over-writing Existing Data
accepted answer: http://stackoverflow.com/a/47400194
tagged with: user-input
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81753834
answer count: 1

http://stackoverflow.com/q/47420957
has title: Create custom wait until condition in Python
tagged with: python
answer count: 4
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 20
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/53312121
has comment: http://stackoverflow.com/comment/81796996
has body: I tried to create a function with custom wait condition in Python. However, I get an error: TypeError: 'bool' object is not callable def waittest(driver, locator, attr, value): element = driver.find_element_by_xpath(locator) if element.get_attribute(attr) == value: return element else: return False wait = WebDriverWait(driver, 10) element = wait.until(waittest(driver, '//div[@id="text"]', "myCSSClass", "false"))
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81797003
accepted answer: http://stackoverflow.com/a/47516221
possible better answer: http://stackoverflow.com/a/53887433
has answer: http://stackoverflow.com/a/47422132
has answer: http://stackoverflow.com/a/47516221
upvote count: 20
has answer: http://stackoverflow.com/a/53887433

http://stackoverflow.com/q/47408081
tagged with: python
has comment: http://stackoverflow.com/comment/81769541
score: 0
has comment: http://stackoverflow.com/comment/81769507
has comment: http://stackoverflow.com/comment/81769469
has title: I am not able to use my models.py data in views.py that I want to display in as html
has comment: http://stackoverflow.com/comment/81771012
has comment: http://stackoverflow.com/comment/81769390
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81776968
has answer: http://stackoverflow.com/a/47409849
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81771801
has body: When I open the django app and view the site check is visible but nothing from my model is printed I want to display the data that I have stored in the customers model in the html file models.py from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=1000) Status =models.CharField(max_length=1000,blank=True, null=True) def __str__(self): return self.name views.py from django.shortcuts import render from django.template.response import TemplateResponse from Core.models import Customer def user_profile(request): data = Customer.objects.all() return render_to_response(request,"templates/home.html", {"data": data}) home.html {% extends 'base.html' %} {% block title %}Video Page {% endblock %} {% block content %} {% for customer in data %} {{ customer.name}} {% endfor %} check {% endblock %}
tagged with: django

http://stackoverflow.com/comment/81805118
score: 0
has text: I mean, i dont know what version of python im using. i think its 2.7 but im not sure.
type: QuestionComment
comment on: http://stackoverflow.com/q/47424972
type: Comment

http://stackoverflow.com/comment/81879432
has text: This script will form part of a cron job that will run at a set time and if it sees a modification in timestamp.... copy file again
comment on: http://stackoverflow.com/q/47460793
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47463756
has comment: http://stackoverflow.com/comment/81889689
has comment: http://stackoverflow.com/comment/81883783
has comment: http://stackoverflow.com/comment/81891588
accepted answer of: http://stackoverflow.com/q/47463587
has body: Here how you can do that. ops = {0 : "+", 1 : "-", 2 : "*", 3 : "/"} for i in range(4): print(eval("12"+ops[i]+"4")) i = int(input("What operator?")) print(eval("12"+ops[i]+"4"))
answers question: http://stackoverflow.com/q/47463587
type: Answer
has comment: http://stackoverflow.com/comment/81883402
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47476120
score: 0
answers question: http://stackoverflow.com/q/47474906
has body: That is a normal call. When the peer closes its socket (or simply shutdowns it with SH_WR) a read call returns immediately with 0 bytes. So your handle_read should be prepared for that end of file on the socket: def handle_read(self): ... if len(data) == 0: # EOF on input socket pass # or add disconnection processing... elif len(data) &lt; 2: #comandos digitais ...
type: Answer

http://stackoverflow.com/a/47486194
has comment: http://stackoverflow.com/comment/81928755
type: Answer
has comment: http://stackoverflow.com/comment/81929900
answers question: http://stackoverflow.com/q/47485587
score: 2
upvote count: 2
has body: The problem in your first code listing is that you first predict the output with your model and then use this result pred as the ground truth for the test, so that you will of course have an accuracy of 1.0 See the signature for the test_on_batch method: test_on_batch(self, x, y, sample_weight=None) So I can't test it myself for you because you only showed a part of your code (e.g. I don't know where your ground truth comes from) but try something like this, i.e. just remove the manual prediction step as it is done internally for you in test_on_batch: for patch in generator(): loss_val_partial,accuracy_val_partial = model.test_on_batch(np.array(patch, dtype=patch.dtype), ground_truth)
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47485587
has comment: http://stackoverflow.com/comment/81929379
has comment: http://stackoverflow.com/comment/81929420

http://stackoverflow.com/comment/82042593
has text: Thanks so much. This is great. I have made an edit to my question that I think will make this easier and more flexible. If you would not mind taking a look?
comment on: http://stackoverflow.com/a/47536292
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47444999
has comment: http://stackoverflow.com/comment/81845516
downvote count: 0
tagged with: dataset
accepted answer: http://stackoverflow.com/a/47445094
possible better answer: http://stackoverflow.com/a/47445173
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/47445094
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I have a huge dataset with thousands of rows and hundreds of columns. One of these columns contain a string because I am getting an error. I want to locate this string. All my columns are supposed to be float values, however one of these columns has a type str somewhere. How can I loop through a particular column using Pandas and print only the row that is of type str? I want to find out what the string(s) are so I can convert them to their numerical equivalent.
has title: Check if column contains type string (object)
has answer: http://stackoverflow.com/a/47445173
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 2

http://stackoverflow.com/comment/81874696
has text: Thanks for your help. Now It's work. I can put a file on the server side. ฺ But I'm confusing with 'quit' and 'lls' part can you fixed it for me. Thank you very much. @GilHamilton
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47440054
type: AnswerComment

http://stackoverflow.com/q/47447183
possible better answer: http://stackoverflow.com/a/47449700
accepted answer: http://stackoverflow.com/a/47447462
has answer: http://stackoverflow.com/a/47449700
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/47447462
upvote count: 3
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
has title: Remove a set of tensors from a tensor in Tensorflow
has body: I'm looking for an easy way to remove a set of tensors from a current tensor in Tensorflow and I'm having a difficult reasonable solution. For example, let's say that I have the below current tensor: a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') And that I want to remove, say, two items from this tensor (2.0 and 5.0). What would be the best way to transform this tensor into [1.0, 3.0, 4.0, 6.0] after it has been created? Many thanks in advance.
tagged with: python

http://stackoverflow.com/comment/82125455
type: AnswerComment
has text: I can't tell you how grateful I am for your continued attention to this
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47516549

http://stackoverflow.com/a/47405992
type: Answer
has body: This is a solution based on the idea of calculating the indices which should be kept. We use numpy.argmin and numpy.nonzero to find the start of the -1 or the end of the row, then use 2-dimensional addition/subtraction to build the indices of the 30 elements that need to be kept. First off, we create reproducible example data import numpy as np np.random.seed(0) a = np.random.randint(low=0, high=10, size=(3, 1000, 100)) for i in range(3): for j in range(1000): a[i, j, np.random.randint(low=30, high=a.shape[2]+1):] = -1 You can of course skip this step, I just added it to allow others to reproduce this solution. :) Now let's go through the code step-by-step: Change shape of a to simplify code a.shape = 3 * 1000, 100 Find index of -1 in each row of a i = np.argmin(a, axis=1) Replace any indices for rows of a with no -1 by a 100 i[np.nonzero(a[np.arange(a.shape[0]), i] != -1)] = a.shape[1] Translate indices to 1D i = i + a.shape[1] * np.arange(a.shape[0]) Calculate indices for all elements that should be kept. We make the indices two-dimensional so that we get the 30 indices before each -1 index. i = i.reshape(a.shape[0], 1) - 30 + np.arange(30).reshape(1, 30) a.shape = 3 * 1000 * 100 Perform filtering a = a[i] Return a to desired shape a.shape = 3, 1000, 30
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/47405541
upvote count: 6

http://stackoverflow.com/q/47424076
favorite count: 0
type: Question
tagged with: postgresql
score: 5
type: UnansweredQuestion
upvote count: 5
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81806070
has title: Raw query and row level access control over multiple models in Django
has answer: http://stackoverflow.com/a/47567846
answer count: 3
has answer: http://stackoverflow.com/a/47531396
has answer: http://stackoverflow.com/a/47541511
has body: I'm trying to provide an interface for the user to write custom queries over the database. I need to make sure they can only query the records they are allowed to. In order to do that, I decided to apply row based access control using django-guardian. Here is how my schemas look like class BaseClass(models.Model): somefield = models.TextField() class Meta: permissions = ( ('view_record', 'View record'), ) class ClassA(BaseClass): # some other fields here classb = models.ForeignKey(ClassB) class ClassB(BaseClass): # some fields here classc = models.ForeignKey(ClassC) class ClassC(BaseClass): # some fields here I would like to be able to use get_objects_for_group as follows: &gt;&gt;&gt; group = Group.objects.create('some group') &gt;&gt;&gt; class_c = ClassC.objects.create('ClassC') &gt;&gt;&gt; class_b = ClassB.objects.create('ClassB', classc=class_c) &gt;&gt;&gt; class_a = ClassA.objects.create('ClassA', classb=class_b) &gt;&gt;&gt; assign_perm('view_record', group, class_c) &gt;&gt;&gt; assign_perm('view_record', group, class_b) &gt;&gt;&gt; assign_perm('view_record', group, class_a) &gt;&gt;&gt; get_objects_for_group(group, 'view_record') This gives me a QuerySet. Can I use the BaseClass that I defined above and write a raw query over other related classes? &gt;&gt;&gt; qs.intersection(get_objects_for_group(group, 'view_record'), \ BaseClass.objects.raw('select * from table_a a' 'join table_b b on a.id=b.table_a_id ' 'join table_c c on b.id=c.table_b_id ' 'where some conditions here')) Does this approach make sense? Is there a better way to tackle this problem? Thanks! Edit: Another way to tackle the problem might be creating a separate table for each user. I understand the complexity this might add to my application but: The number of users will not be more than 100s for a long time. Not a consumer application. Per our use case, it's quite unlikely that I'll need to query across these tables. I won't write a query that needs to aggregate anything from table1, ta…
tagged with: django-guardian

http://stackoverflow.com/q/47476225
has comment: http://stackoverflow.com/comment/81975515
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/81907102
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
has title: Multiprocessing of data held by multiple objects
tagged with: parallel-processing
score: 0
has body: First question here ever so I hope I get it right... I have written a piece of code to handle multiple data sets in the following way: - a base class that holds the data arrays (numpy) and all the methods to manipulate this data (bk subtraction, normalization etc.). - a second class that holds all the different data objects which I use to both apply the different methods on each data set and to calculate average values. Now for the problem - if we take for example the normalization of the data, I'm currently iterating over the different objects and calling the normalization method for each one, however, since thees are separated data set, there is no restriction to calculate it in parallel, but, if I assign the normalization method call to a process once the process is finished I end up with the data set I started with. import numpy as np import multiprocessing as mp class Scan(object): """ Basic scan object """ def __init__(self): super(Scan, self).__init__() # Init the object with some numbers self.data = np.arange(0, 10) def normalize(self, low, nlow, high, nhigh): # Normalizes the scan self.data = (self.data - np.mean(self.data[low:(low + nlow)])) / \ (np.mean(self.data[(high - nhigh):high]) - np.mean(self.data[low:(low + nlow)])) def main(): data_obj_list = [] processes = [] # Generate a list of data objects for i in range(10): data_obj_list.append(Scan()) # Print an example print(data_obj_list[0].data) #[0, 1, ..., 10] # divides the normalization to separated processes for scans in data_obj_list: process = mp.Process(target=scans.normalize, args=(0, 1, 10, 1)) process.start() processes.append(process) for process in processes: process.join() # Print an example print(data_obj_list[0].data) #[0, 1, ..., 10] # normalizing the scans one by one for scans in data_obj_list: scans.normalize(0, 1, 10, 1) # Print an example print(data_obj_list[0].data) #[0, 0.111, 0.222, ..., 1] if __name__ == '__main__': main() If I understand the documentation correctly - Python is co…
tagged with: python

http://stackoverflow.com/comment/81882503
has text: Check out the various "word sense disambiguation" links in the related questions list on this page. (I'm not going to flag it as a duplicate of those questions, as maybe (hopefully!) someone will answer with something Hindi-specific.)
type: QuestionComment
comment on: http://stackoverflow.com/q/47387082
score: 0
type: Comment

http://stackoverflow.com/q/47417279
answer count: 1
linked to: http://stackoverflow.com/q/525247
score: 0
tagged with: linux
has body: I have a script written this way on shell script function test1(){ command1 }; function test2(){ command2 }; function test3(){ command3 }; I use the &amp; on shell script to run those functions daemonized writting test1 &amp; test2 &amp; test3 But I want to do the same thing on Python. Is there a way to do it using any of python built-in functions and not using the "daemonize" library? EDIT: I think I should have written it better. I can see now that "background" is the better word for the question. My intention was to join what I read here with the python command to make something daemonized-like. tripleee comment already answer it for me. Thank everybody who left a comment and sorry for the mistake. I can't give points or add a comment since I don't have enough reputation.
has title: What is the equivalent of "&" from shell script in python
tagged with: python
tagged with: shell
has comment: http://stackoverflow.com/comment/81788567
type: Question
has comment: http://stackoverflow.com/comment/81788489
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81790216
tagged with: function
has answer: http://stackoverflow.com/a/47421967

http://stackoverflow.com/q/47478978
has comment: http://stackoverflow.com/comment/81913472
type: AnsweredQuestion
score: 3
answer count: 2
linked to: http://stackoverflow.com/q/21157739
has title: Iterate through queue containing objects in python
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47479215
possible better answer: http://stackoverflow.com/a/47479215
favorite count: 0
has answer: http://stackoverflow.com/a/47479048
type: Question
has comment: http://stackoverflow.com/comment/81913410
tagged with: priority-queue
has comment: http://stackoverflow.com/comment/81913317
tagged with: python
has body: I'm new to python and just discovered a strange error when trying to iterate through a queue. Here's a code snippet: frontier = q.PriorityQueue() for goal in goals: portals = findPortals(maze) comb_value = heuristic(startX, startY, goal[0], goal[1]) frontier.put_nowait((comb_value, heuristic(startX, startY, goal[0], goal[1]), 0, startX, startY, startX, startY)) for portal in portals: heur = portalHeuristic(maze, startX, startY, goal[0], goal[1]) frontier.put_nowait((heur, heur, 0, startX, startY, startX, startY)) for elem in list(frontier): print(elem) When trying to print out the elements it says TypeError: 'PriorityQueue' object is not iterable. Can I fix this somehow? I tried to find some solutions on here, but I didn't really find anything I understood...
accepted answer: http://stackoverflow.com/a/47479048

http://stackoverflow.com/a/47452902
score: 0
has body: You can use RandomForestRegressor in python on your train data to fit a model. Then you can use feature_importance_ function to find the importance of each feature. And if you are interested in explanatory power of your model then you can also use the function treeinterpreter from the package treeinterpreter. Here are two links(link1, link2) that give more insight on treeinterpreter.
type: Answer
answers question: http://stackoverflow.com/q/47404605

directed-acyclic-graphs
type: Tag
tags question: http://stackoverflow.com/q/47470270
tag name: directed-acyclic-graphs

http://stackoverflow.com/a/54240245
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/129603648
has body: I found this to be useful df.index = pd.to_datetime(df.index, format='%Y').year
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/47531712

http://stackoverflow.com/q/47404203
has comment: http://stackoverflow.com/comment/81762810
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81763564
has comment: http://stackoverflow.com/comment/81762595
has comment: http://stackoverflow.com/comment/81762483
favorite count: 0
type: Question
has title: Allocating more memory in Python Spyder
has comment: http://stackoverflow.com/comment/81762453
has comment: http://stackoverflow.com/comment/81763581
tagged with: spyder
tagged with: python
tagged with: memory
answer count: 0
has body: I am running a Python 2.7 script in Spyder that can run as long as I need, but I am getting a MemoryError. Short runs of this script do not do this, and I have no reason to believe that the run is substantially different as the runtime grows arbitrarily long. I'd like to go into Spyder's settings to allow more memory to be consumed, but I cannot find where to go in the settings.
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/82007720
type: AnswerComment
has text: There is no problem with some firewall? Or some typo in url? Please check `pd.read_csv('https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv')`. It should works.
score: 0
comment on: http://stackoverflow.com/a/47392288
type: Comment

http://stackoverflow.com/a/47424779
has comment: http://stackoverflow.com/comment/81806240
has comment: http://stackoverflow.com/comment/81806108
has comment: http://stackoverflow.com/comment/81806247
has comment: http://stackoverflow.com/comment/81804793
upvote count: 2
has comment: http://stackoverflow.com/comment/81806199
type: AcceptedAnswer
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47424766
has comment: http://stackoverflow.com/comment/81805605
downvote count: 0
has body: df2.a.value_counts().reindex(df1.a) Out[369]: a 4 11 5 5 Name: a, dtype: int64 Add sum df2.a.value_counts().reindex(df1.a).sum() Out[370]: 16
answers question: http://stackoverflow.com/q/47424766

http://stackoverflow.com/a/49348570
upvote count: 1
has body: I resolved this issue in another way. I just created my own Web of Science Web Services client which can print out JSON. You can find it here: https://github.com/mdziezyc/WoSPythonClient
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47540354
accepted answer of: http://stackoverflow.com/q/47540354
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47486190
favorite count: 0
type: Question
has body: I have a dataframe df which looks like: date perf cumulative_perf 29/11/2005 36528.11368 36528.11368 30/11/2005 29034.77194 65562.88563 01/12/2005 47923.50416 113486.3898 02/12/2005 52740.69331 166227.0831 05/12/2005 -3185.762137 163041.0321 06/12/2005 -25084.55935 137956.7616 07/12/2005 3551.701267 141508.4629 08/12/2005 22039.83875 163548.3016 09/12/2005 58217.58428 221765.8859 12/12/2005 -2906.995835 218858.8901 13/12/2005 -31979.02878 186879.8613 I am trying to add a column called peak that will look at the cumulative_perf for the date and compare it to the peak value from yesterday and return to the peak column the max of the two. The result output would hopefully look like: date perf cumulative_perf peak 29/11/2005 36528.11368 36528.11368 36528.11368 30/11/2005 29034.77194 65562.88563 65562.88563 01/12/2005 47923.50416 113486.3898 113486.3898 02/12/2005 52740.69331 166227.0831 166227.0831 05/12/2005 -3185.762137 163041.0321 166227.0831 06/12/2005 -25084.55935 137956.7616 166227.0831 07/12/2005 3551.701267 141508.4629 166227.0831 08/12/2005 22039.83875 163548.3016 166227.0831 09/12/2005 58217.58428 221765.8859 221765.8859 12/12/2005 -2906.995835 218858.8901 221765.8859 13/12/2005 -31979.02878 186879.8613 221765.8859 How can I reference the the cumulative_perf column and the peak value for the day before to make a decision of which value to return to the peak column for the current day?
answer count: 2
upvote count: 2
downvote count: 0
tagged with: python
score: 2
possible better answer: http://stackoverflow.com/a/47488255
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/47488255
accepted answer: http://stackoverflow.com/a/47486484
has answer: http://stackoverflow.com/a/47486484
has title: Create a peak column in dataframe

http://stackoverflow.com/q/47440561
accepted answer: http://stackoverflow.com/a/47440934
has title: Verify BigQuery table existence
upvote count: 10
has answer: http://stackoverflow.com/a/47440934
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/61846168
score: 10
has body: I have a simple function to determine whether a table exists or not: def check_users_usersmetadata_existence(): """ Checks if the table Prod_UserUserMetadata exists """ app_id = get_app_id() bigquery_client = bigquery.Client(project=app_id) dataset_ref = bigquery_client.dataset('Backup') table_ref = dataset_ref.table('Prod_UserUserMetadata') try: table = bigquery_client.get_table(table_ref) if table: print('Table {}\'s existence sucessfully proved!'.format(table_ref)) return True except HttpError as error: raise print('Whoops! Table {} doesn\'t exist here! Ref: {}'.format(table_ref, error.resp.status)) return False Problem is, it throws a 404 on this line table = bigquery_client.get_table(table_ref) which is ok because the table shouldn't exist. But it won't continue to process the rest of the script. I'm trying to parse it inside a try except wrapper however it's not working. How would I parse this?
tagged with: python
has answer: http://stackoverflow.com/a/61846168
tagged with: google-bigquery
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47441488
downvote count: 0

http://stackoverflow.com/comment/81980363
type: QuestionComment
score: 0
has text: Do you have a file `serverlist_form.html` in the templates?
comment on: http://stackoverflow.com/q/47512227
type: Comment

overlapping-matches
tag name: overlapping-matches
type: Tag
tags question: http://stackoverflow.com/q/47536655

http://stackoverflow.com/a/47421736
answers question: http://stackoverflow.com/q/47421497
type: Answer
has body: This will do you homework for you: def MyMean(myList): rv = [] for n in myList[::-1] : # reverse list try: rv.append(int(n)) # convert element to int except: # 2.7: return float(sum(rv))/len(rv) # on first error, bail and return number # 3.6 # return sum(rv)/len(rv) # all numbers need to return as well # 2.7: return float(sum(rv))/len(rv) # on first error, bail and return number # 3.6 # return sum(rv)/len(rv) # all numbers need to return as well myLis = [1,2,4,'A',3,4] print(MyMean(myLis)) myLis = "1239A9391" print(MyMean(myLis)) myLis = "1020392" print(MyMean(myLis)) Output: # 2.7 3.5 5.5 2.42857142857 #3.6 3.5 5.5 2.4285714285714284
has comment: http://stackoverflow.com/comment/81816647
has comment: http://stackoverflow.com/comment/81814453
score: 0

http://stackoverflow.com/comment/82036264
comment on: http://stackoverflow.com/q/47535920
has text: It is 50 x 50 x 3. The total number of patches is 104720
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47423770
answers question: http://stackoverflow.com/q/47423687
upvote count: 2
downvote count: 0
type: Answer
has body: In Python 3.x and 2.7, you can simply do this: &gt;&gt;&gt; '${:,.2f}'.format(1234.5) '$1,234.50' The :, adds a comma as a thousands separator, and the .2f limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
score: 2
accepted answer of: http://stackoverflow.com/q/47423687
type: AcceptedAnswer

http://stackoverflow.com/a/47516298
answers question: http://stackoverflow.com/q/47494896
has body: The forth dimension is the number of samples in a batch. Look at https://keras.io/preprocessing/image/ at the data_format explanation
type: AcceptedAnswer
upvote count: 10
downvote count: 1
score: 9
accepted answer of: http://stackoverflow.com/q/47494896
type: Answer

http://stackoverflow.com/q/47421969
has comment: http://stackoverflow.com/comment/81798436
accepted answer: http://stackoverflow.com/a/47422479
has comment: http://stackoverflow.com/comment/81798405
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47422479
tagged with: python
has comment: http://stackoverflow.com/comment/81798347
score: -1
has answer: http://stackoverflow.com/a/47422343
possible better answer: http://stackoverflow.com/a/47422216
type: AnsweredQuestion
has body: So I have a CSV file that looks something like this: Username,Password,Name,DOB,Fav Artist,Fav Genre Den1994,Denis1994,Denis,01/02/1994,Eminem,Pop Joh1997,John1997,John,03/04/1997,Daft Punk,House What I need to be able to do is let the user edit and change their Fav Artist and Fav Genre so that their new values are saved to the file in place of the old ones. I'm not the very advanced when it comes to CSV so I'm not sure where to begin with it, therefore any help and pointers will be greatly appreciated. Thanks guys. EDIT: Adding the code I have so far so it doesn't seem like I'm just trying to get some easy way out of this, generally not sure what to do after this bit: def editProfile(): username = globalUsername file = open("users.csv", "r") for line in file: field = line.split(",") storedUsername = field[0] favArtist = field[4] favGenre = field[5] if username == storedUsername: print("Your current favourite artist is:", favArtist,"\n" + "Your current favourite genre is:",favGenre,"\n") wantNewFavArtist = input("If you want to change your favourite artist type in Y, if not N: ") wantNewFavGenre = input("If you want to change your favourite genre type in Y, if not N: ") if wantNewFavArtist == "Y": newFavArtist = input("Type in your new favourite artist: ") if wantNewFavGenre == "Y": newFavGenre = input("Type in your new favourite genre: ")
has answer: http://stackoverflow.com/a/47422216
answer count: 3
linked to: http://stackoverflow.com/q/39165533
has title: Python - Replacing a specific value in a CSV file while keeping the rest
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/81798533
favorite count: 0
type: Question

http://stackoverflow.com/comment/81781233
type: QuestionComment
score: 0
has text: @Jan : I do not want to split the paragraphs : I want to keep thr entire paragraphs containing the specified pattern, and those paragraphs only.
comment on: http://stackoverflow.com/q/47413572
type: Comment

http://stackoverflow.com/q/47466040
type: Question
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/81886668
tagged with: numpy
has comment: http://stackoverflow.com/comment/81886663
type: AnsweredQuestion
score: 0
has body: So I'm trying to sort an array like this by the third item in the array: [[591 756 3] [296 669 7] [752 560 2] [476 474 0] [214 459 1] [845 349 6] [122 145 4] [476 125 5] [766 110 8]] so it would look like [[476 474 0] [214 459 1] [752 560 2] [591 756 3] ....and so on] This is the code I'm currently using: sortedanswers = sorted(answithcpoints,key=lambda x:x[2]) but printing sortedanswers would output something like [array([476, 474, 0]), array([214, 459, 1]), array([752, 560, 2]), array([591, 756, 3]), array([122, 145, 4]), array([476, 125, 5]), array([845, 349, 6]), array([296, 669, 7]), array([766, 110, 8])] seems to be some sort of array inside the array? Does anyone know why it's doing this?
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47466066
answer count: 1
has answer: http://stackoverflow.com/a/47466066
has title: Sorting 2-D Array Python Outputing as array within an array

http://stackoverflow.com/comment/81959567
has text: It looks like version `1.13` is using a larger buffer (docs talk about changes in the in-place buffering). My `np.add(fib[:-2], fib[1:-1], out=fib[2:])` does not give any recursion, where as your's has full or partial recursion depending on dtype.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47427603

http://stackoverflow.com/a/47406857
accepted answer of: http://stackoverflow.com/q/47398769
upvote count: 1
has body: If you want 7th layer then: output_func_Layer_7 = K.function([autoencoder.layers[0].input, K.learning_phase()], [autoencoder.layers[7].output]) intermediate_output = output_func_Layer_7([X_train, False])
has comment: http://stackoverflow.com/comment/81776715
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47398769
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81833909
type: Comment
type: AnswerComment
has text: Thank you, that did the job!
comment on: http://stackoverflow.com/a/47439322
score: 1

http://stackoverflow.com/comment/81888287
has text: http://answers.opencv.org/question/32248/open-cv-30-findcontours-return-too-many-value-to-unpack/
score: 0
comment on: http://stackoverflow.com/q/47466583
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47420095
tagged with: factory
score: 0
tagged with: oop
tagged with: reflection
has comment: http://stackoverflow.com/comment/81794375
has body: I am trying to parametrize my objects with a json string provided at runtime through a rest API. I have come up with the following design. It works, but I feel like using class reflection and setattr are bad programming practices...but I don't know any other way of doing this in the fully generic way I want (I would like to be able to extend classes in the future which have new attributes, register more nested classes, etc) Is this JUST awful, is there a better way? class Factory: contains = {} @staticmethod def subclass(this, args): klass = next((cls for cls in this.__class__.__subclasses__(this) if cls.__name__ == args.get('type', None)), this.__class__) return klass() def __init__(self, d=None): for key, value in self.contains.items(): args = d.get(key, None) child = self.subclass(value, args) setattr(self, key, child) class Clock(Factory): def tick(self): print("base clock tick") class DigitalClock(Clock): def tick(self): print("digital clock tick") class House(Factory): contains = {'clock': Clock} def __init__(self, d): self.color = d.get('color','red') super().__init__(d) H = House({'clock': {'type': "DigitalClock"}, 'color': 'blue'}) H.clock.tick()
has title: parameterizing a python object with a generic factory
tagged with: python
favorite count: 0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81795136
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/81795165
tagged with: design-patterns
downvote count: 1

http://stackoverflow.com/comment/81853848
score: 0
has text: wait i disagree, this one deals with tuples
type: Comment
comment on: http://stackoverflow.com/q/47449438
type: QuestionComment

http://stackoverflow.com/comment/81991216
type: Comment
has text: Also note, `hstack` docs recommend: "This function continues to be supported for backward compatibility, but you should prefer ``np.concatenate`` or ``np.stack``"
type: AnswerComment
comment on: http://stackoverflow.com/a/47516381
score: 0

http://stackoverflow.com/q/47501953
has title: Python: Automatically reconnect IP camera
has comment: http://stackoverflow.com/comment/81960759
downvote count: 1
favorite count: 0
has body: My IP camera seems to be a little unstable and disconnects randomly. I'd like my script to be able to determine when its disconnected and attempt to reconnect a few times, probably waiting 5-10 seconds between attempts. I've tried a few things, but nothing is working. This is my basic script, when ret is false the script ends: #!/usr/local/bin/python3 import cv2 import time import datetime print("start time: " + datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p")) cap = cv2.VideoCapture('rtsp://&lt;ip&gt;&lt;port&gt;/live0.264') while(True): # Capture frame-by-frame ret, frame = cap.read() # Confirm we have a valid image returned if not ret: print("disconnected!") break # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) # Display the resulting frame cv2.imshow('frame', gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break print("end time: " + time.strftime("%X")) # When everything is done, release the capture cap.release() cv2.destroyAllWindows() Edit: I would also like the script to try to reconnect to the camera in the event that my network goes down temporarily or anything like that as well.
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/62853843
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/62853843
has comment: http://stackoverflow.com/comment/81959691
has comment: http://stackoverflow.com/comment/81959666
score: 1
tagged with: surveillance
tagged with: python
has comment: http://stackoverflow.com/comment/81959773
type: Question
accepted answer: http://stackoverflow.com/a/47614392
answer count: 2
has comment: http://stackoverflow.com/comment/81960500
upvote count: 2
has answer: http://stackoverflow.com/a/47614392

http://stackoverflow.com/comment/81835256
type: QuestionComment
comment on: http://stackoverflow.com/q/47439594
score: 0
has text: In the very likely case that it is not possible, what would you suggest for making that `change_docstring` available to the decorator? Essentially it is a setting that should default to False. I was just looking to have the setting as an attribute on the class to make it easy to set.
type: Comment

http://stackoverflow.com/comment/81956977
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47500628
has text: Hey willem Van Onsem.. bear with me what two categories?

http://stackoverflow.com/comment/81781960
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47414078
has text: Minor suggestion: make the lambda accept `*x` instead of `x` to make it generic for the case of multiple inputs (e.g. data and labels). Aside from this, one problem I have with your suggestion is that the `prefetch` is before the `flat_map`. Is that really needed? Because now the buffer-size is not the actual buffer-size, but the amount of inputs (which might result in a variable number of items in the buffer finally). Is there a way around this?

http://stackoverflow.com/comment/81875471
has text: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 307: invalid start byte Jamils-MacBook-Air:downloads jamilaldani$ python try.py Traceback (most recent call last): File "try.py", line 23, in <module> f=j.read() File "/Users/jamilaldani/miniconda3/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 0x96 in position 307: invalid start byte
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47459078

http://stackoverflow.com/q/47457466
has answer: http://stackoverflow.com/a/47457890
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47457968
tagged with: imread
score: -2
has body: I want read 100 colour images and use them for further processing. Suppose one image size is 256x 256 by reading it in python openCV its size is (256,256,3). I now want to read 100 images and after reading I have to get the size as (100,256,256,3).
tagged with: python
tagged with: image
has comment: http://stackoverflow.com/comment/81869408
has title: How to read multiple images in python
answer count: 2
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81869586

http://stackoverflow.com/comment/81789559
comment on: http://stackoverflow.com/a/47417207
type: AnswerComment
has text: This worked! I'll have to test out a change to account for the second title in use case #3, but this gets me going in the right direction `[Michael Feldstein and Ms. Alexandra Milstein] [Benjamin Hochberger and Ms. Melissa Goldstein]`
score: 0
type: Comment

http://stackoverflow.com/comment/81902631
type: QuestionComment
has text: ＠Beyhan Gül no.. it seems it can only be installed by pip, so how to add the package installed by pip into conda install package list?
score: 0
comment on: http://stackoverflow.com/q/47473458
type: Comment

http://stackoverflow.com/comment/81998395
score: 0
type: AnswerComment
type: Comment
has text: My example above may be poor. The more general problem I am trying to solve is that the paths can potentially branch in zero or more places, right now your example will cover for one level of branching.
comment on: http://stackoverflow.com/a/47520165

rtsp
tags question: http://stackoverflow.com/q/47523708
tags question: http://stackoverflow.com/q/47475130
tags question: http://stackoverflow.com/q/47396372
type: Tag
tag name: rtsp

http://stackoverflow.com/q/47465072
type: UnansweredQuestion
has title: Using xlwt to print xls to paper
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47481679
score: 0
has body: So, I am using the xlwt and xlrd modules in python to write to a XLS document. What I am trying to do now, is to have this useless file be printed out on paper, old school style, but searching for "print out on paper" (or the like) just gives you the wrong results. Can anyone help me? here is the code: import xlwt import xlrd from xlutils.copy import copy from tkinter import * def test(): print(ent.get()) rb = xlrd.open_workbook("test.xls") wb = copy(rb) w_sheet = wb.get_sheet(0) w_sheet.write(0,1,ent.get()) fr = w_sheet.col(0) fr.width = 256 * 20 wb.save("test.xls") vindue = Tk() but = Button(vindue, text="Click", command=test) but.pack() ent = Entry(vindue) ent.pack() vindue.mainloop()
type: Question
tagged with: xlwt

http://stackoverflow.com/q/47518707
upvote count: 5
tagged with: python
has title: Check if an object is a file in Python 2 and 3
has answer: http://stackoverflow.com/a/48082549
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
linked to: http://stackoverflow.com/q/18880948
has answer: http://stackoverflow.com/a/47518865
has answer: http://stackoverflow.com/a/47518744
has body: Is there a Python 2/3-compatible way of checking whether an object is a file? I need to check if an object filehandler is actually a file object. This code needs to run in both Python 2 and 3. In Python 2 I could do isinstance(filehandler, file) However file is not part of Python 3, so this code raises a NameError when run with Python 3. According to this answer, in Python 3 io.IOBase should be used to check if an object is a file, but Python 2's file doesn't subclass io.IOBase, so isinstance(filehandler, io.IOBase) won't work. I thought about doing isinstance(filehandler, (io.IOBase, file)), but that still gives a NameError when I run it with Python 3. Is there a way to do this that is compatible with both Python 2.7 and 3?
downvote count: 0
possible better answer: http://stackoverflow.com/a/48082549
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47518865
score: 5
tagged with: compatibility

http://stackoverflow.com/q/47388431
type: UnansweredQuestion
tagged with: windows
tagged with: python
has body: Using the Python HookManager, is it possible to get some distinction as to which device is giving me the input? Like if I had two keyboards, or a QR scanner for instance? How could I find out where the input is coming from? import pyHook import pythoncom chars = "" def pressed_chars(event): global chars if event.Ascii: char = chr(event.Ascii) if event.Ascii == 3: quit() else: chars += char print chars proc = pyHook.HookManager() proc.KeyDown = pressed_chars proc.HookKeyboard() pythoncom.PumpMessages() The code above simply uses HookManager to detect keyboard input. But I can't find anything in the event variable that tells me where the input came from?
answer count: 0
score: 1
tagged with: pyhook
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Python HookManager: Get Device ID

http://stackoverflow.com/comment/81991943
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47517899
type: QuestionComment
has text: What approaches did u try, so we don't give you the same approach.

http://stackoverflow.com/comment/82033421
has text: You mean running foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE) foo_proc.communicate('y\n') When i do this it seems to just skip the command. It never executes
comment on: http://stackoverflow.com/q/47538080
type: Comment
type: QuestionComment
score: 0

fibonacci
tags question: http://stackoverflow.com/q/47386647
tag name: fibonacci
type: Tag
tags question: http://stackoverflow.com/q/47512442

http://stackoverflow.com/comment/81765838
score: 0
comment on: http://stackoverflow.com/a/47387253
type: Comment
has text: Thanks, the first algorithm worked. I had to swap the 1 and 2 on lines 3 and 4 to get the right order, but it seemed to work.
type: AnswerComment

http://stackoverflow.com/comment/81913343
comment on: http://stackoverflow.com/a/47479029
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the code, Its well organised and looks better. I will try it out and let you know.

http://stackoverflow.com/q/47536272
has answer: http://stackoverflow.com/a/47536534
tagged with: python
type: AnsweredQuestion
has body: print("What is this for?:") z = input(str()) print("Username:") x = input(str()) print("Password:") y = input(str()) f = open("UserandPass.txt", 'a') f.write('\n') f.write('\n' + 'Domain:') f.write('\n' + z) f.write('\n' + 'Username:') f.write('\n' + x) f.write('\n' + 'Password:') f.write('\n' + y) f.close() g = open("UserandPassbackup.txt", 'a') g.write('\n') g.write('\n' + 'Domain:') g.write('\n' + z) g.write('\n' + 'Username:') g.write('\n' + x) g.write('\n' + 'Password:') g.write('\n' + y) g.close() print(z) print(x) print(y) So I'm running a program in pycharm that can write text to a .txt file fine. The issue comes along when I run the .py script in the cmd prompt... doesn't write to the file. There are no errors, in the cmd prompt after running either. Not sure what is going on.
has title: CMD windows running .py scrip not writing to txt file, but running in pycharm does write to the file
score: 2
tagged with: windows
answer count: 1
downvote count: 0
tagged with: cmd
favorite count: 0
has comment: http://stackoverflow.com/comment/82030063
type: Question
has comment: http://stackoverflow.com/comment/82029613
accepted answer: http://stackoverflow.com/a/47536534
tagged with: pycharm
upvote count: 2

http://stackoverflow.com/q/47505790
accepted answer: http://stackoverflow.com/a/47505881
tagged with: pandas
has body: A dataframe (df) contain two columns as below: A B 46 0 45 1 46 1 51 1 47 1 46 1 45 0 48 0 47 0 45 1 49 1 I need to design a sliding window kind of grouping for each three rows, such that: 1) Take first three rows, transpose column(A) and append third entry of column(B), so we get a row of four columns as below: 46 45 46 1 2) Then move down by one row (i.e. start from row 2 in original df), repeat step-1 so we get the second output as below. 45 46 51 1 3) At each iteration, we get the successive output as below: 46 51 47 1 51 47 46 1 47 46 45 0 ... In summary, the desired output is - 46 45 46 1 45 46 51 1 46 51 47 1 51 47 46 1 47 46 45 0 ...
score: 1
has answer: http://stackoverflow.com/a/47505881
has title: Grouping using Sliding Window and Transpose
upvote count: 1
possible better answer: http://stackoverflow.com/a/47508429
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47508429
downvote count: 0
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81967607
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/82033582
comment on: http://stackoverflow.com/a/47537770
has text: Sorry, mistake in urls. Should be like this: `url(r'^cholera/', include('SeqData.urls', namespace='seqdata'))`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47539457
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82036315
has comment: http://stackoverflow.com/comment/82036198
upvote count: 1
has comment: http://stackoverflow.com/comment/82036312
answer count: 1
has comment: http://stackoverflow.com/comment/82036287
has comment: http://stackoverflow.com/comment/82036245
has comment: http://stackoverflow.com/comment/82035969
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82036025
has comment: http://stackoverflow.com/comment/82036179
has comment: http://stackoverflow.com/comment/82036122
has comment: http://stackoverflow.com/comment/82036069
has title: How to use random to print integers whose sum is less than or equal to another integer in Python?
has comment: http://stackoverflow.com/comment/82036182
has comment: http://stackoverflow.com/comment/82036135
score: -3
has body: I have a list of integers and I would like to print all integers whose sum is less than than or equal to a variable. My sum is 38 below, how do I randomly return the values in the list below where my sum is less than or equal to 15? I have tried to adapt the function below, but it doesn't work. j=[4,5,6,7,1,3,7,5] x = 15 jSum = sum(j) def decomposition(i): while i &lt;= x: n = random.randint(j, i) yield n i -= n print i decomposition(jSum)
has comment: http://stackoverflow.com/comment/82036045
tagged with: python
has comment: http://stackoverflow.com/comment/82036378
has answer: http://stackoverflow.com/a/47539722
downvote count: 4
accepted answer: http://stackoverflow.com/a/47539722

http://stackoverflow.com/q/47419036
tagged with: precision
has title: How to sum very large numbers to 1 in python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81792177
has comment: http://stackoverflow.com/comment/81792244
answer count: 3
has comment: http://stackoverflow.com/comment/81792294
type: UnansweredQuestion
score: 5
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47419231
upvote count: 5
has answer: http://stackoverflow.com/a/47419095
has body: So imagine I have &gt;&gt;&gt; a = 725692137865927813642341235.00 If I do &gt;&gt;&gt; sum = a + 1 and afterwards &gt;&gt;&gt; sum == a True This is because a is bigger than a certain threshold. Is there any trick like the logsumexp to perform this? PS: a is an np.float64.
tagged with: python
has answer: http://stackoverflow.com/a/47419241
has comment: http://stackoverflow.com/comment/81792436
has comment: http://stackoverflow.com/comment/81792385

http://stackoverflow.com/q/47410967
answer count: 2
has body: I'm pretty new to python and maybe this is a very silly/stupid question, but I've got a tremendous headache from thinking about this problem. I got a set of data, for example integers, from which I want to extract a random subset, but every object has a different probability. How can I extract the subset in a way that respect the probability distribution of the data? I suppose that np.random_sample gives to all samples the same priority, so its not what I'm looking for...
tagged with: python
has title: Random Sampling with different probabilities
accepted answer: http://stackoverflow.com/a/47412714
has comment: http://stackoverflow.com/comment/81775522
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75496941
tagged with: random
downvote count: 0
possible better answer: http://stackoverflow.com/a/75496941
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/81808492
has comment: http://stackoverflow.com/comment/81775847
has answer: http://stackoverflow.com/a/47412714
favorite count: 0
type: Question

http://stackoverflow.com/q/47494410
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/44372046
has body: I am trying to make a timer count with a stopper. I found some code here. Tkinter timer to start at 0 on button click by PM 2 Ring. I was wondering how to add another function to this code so that when no buttons on the keyboard are pressed the time will automatically keep adding up. However, when either the right arrow or the left arrow is pressed the timer will stop. Thanks here is the link to the github https://github.com/a210082/I2P-Summative It is the timerbutton code thanks
has comment: http://stackoverflow.com/comment/81947730
type: Question
tagged with: timer
has answer: http://stackoverflow.com/a/47494545
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47494545
tagged with: tkinter
has title: How do I make a timer stop when a key is pressed in python?
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81944065
tagged with: github

http://stackoverflow.com/comment/81868490
type: Comment
comment on: http://stackoverflow.com/a/47445292
score: 0
type: AnswerComment
has text: use `np.where` on the matrix. `np.where(images==6, 1, images)`

http://stackoverflow.com/q/47514431
answer count: 2
has title: Placing multiple images centered and fixed spacing with Kivy
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47520375
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47520375
possible better answer: http://stackoverflow.com/a/47514835
score: 1
has answer: http://stackoverflow.com/a/47514835
tagged with: kivy
has body: I want to place multiple (varies from 0 to 8) images centered and fixed spacing (as the screenshots following), but I have no idea how to do. when 8 images are in the layout(what I want to do) when 2 images are in the layout(what I want to do) This is what I see with this code when 2 images are in the layout BoxLayout: Image: source: "yellow.png" Image: source: "red.png" Image: source: "yellow.png Image: ... Is there any way to do this?
type: Question
tagged with: python-3.x
tagged with: kivy-language

http://stackoverflow.com/comment/82035860
has text: sure does. Looks like e= df[df[SelLst].any(1)] is what I'm looking for. Thanks!
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47539271
type: Comment

http://stackoverflow.com/q/47426068
answer count: 1
has title: create extension postgis in Python
has answer: http://stackoverflow.com/a/47440121
type: Question
has body: Python 2.7 if __name__ == '__main__': import os app = Flask(__name__) os.system("dropdb biobreak") os.system("createdb biobreak") os.system("CREATE EXTENSION postgis") On the last line I get this error: (env) vagrant@vagrant:biobreak$ python seed.py sh: 1: CREATE: not found I tried importing subprocess by the syntax was driving me crazy. EDIT: I tried the following command: import subprocess cr_ext = "create extension postgis;" try: subprocess.check_call([ 'psql', '-q', '-U', 'vagrant', '-f', 'cr_ext', 'biobreak' ]) except subprocess.CalledProcessError, ex: print "Failed to invoke psql: {}".format(ex) Got this error: cr_ext: No such file or directory Failed to invoke psql: Command '['psql', '-q', '-U', 'vagrant', '-f', 'cr_ext', 'biobreak']' returned non-zero exit status 1
type: UnansweredQuestion
tagged with: python
tagged with: postgis
score: 0

http://stackoverflow.com/comment/82030092
has text: i run the same code i posted here.
score: 0
comment on: http://stackoverflow.com/q/47533609
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47507426
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86466434
answer count: 1
accepted answer: http://stackoverflow.com/a/47507626
has title: pandas dataframe filter by dateform that doesn't have dtype
has answer: http://stackoverflow.com/a/47507626
type: Question
has body: I'm making some project to sort orders from many channels. the problem is, I have to add note for dispatch date depending on customers needs. the date will be put by me, through google spread sheet and its date form. I'm using gspread_pandas module. import gspread_pandas import Spread s = Spread('myid', 'sheetname') s.sheets temp_df = s.sheet_to_df(index=False, headers=1, start_row=2, sheet='data') temp_df is like below. name item quantity dispatch_due 0 james shoes 1 2017-11-27 1 john shirts 1 2017-11-28 2 jack pants 2 please add dispatch_due 3 lambo gun 3 2017-11-143 I want to make a dataframe filtered only with dispatch_due is filled with right form of date. in case of lambo(index3), I want to change it back to 'please add dispatch_due. print(temp_df.dtypes) the problem is, if I do like above, there is no dtype that I can deal with. all of the columns are 'object'. name object item object quantity object dispatch_due object What can I would do with it?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47391056
has comment: http://stackoverflow.com/comment/81735979
has comment: http://stackoverflow.com/comment/81735682
tagged with: selenium
has comment: http://stackoverflow.com/comment/81736494
has title: Why does a page keep loading in the loop?
type: Question
has answer: http://stackoverflow.com/a/47398567
type: UnansweredQuestion
has body: In python(Selenium) driver = webdriver.Chrome() driver.get("https://www.baidu.com") for keywords in open('klist','r'): driver.get("https://www.baidu.com") driver.find_element_by_class_name('...').click() .... Although the whole page appears, it just hangs and keeps loading. So a lot of time is wasted. Not every time it freezes. But once it freezes, it can hang for several minutes before the next step.
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81735431
has comment: http://stackoverflow.com/comment/81741794
has comment: http://stackoverflow.com/comment/81735468
score: 0
has comment: http://stackoverflow.com/comment/81736312

http://stackoverflow.com/comment/81975877
type: Comment
comment on: http://stackoverflow.com/q/47510098
type: QuestionComment
has text: @roganjosh I have to have it as a numpy array input later on in my code, do you think I could sort it as a list here and then convert it to a numpy array later?
score: 0

http://stackoverflow.com/a/47543574
upvote count: 1
answers question: http://stackoverflow.com/q/47539028
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82044282
has body: So... I've decided I've posted enough in comments and I might as well post a real answer. I see three ways to do this: push, pull, and indexing. Push Recall the HTTP protocol. The client asks for a file, the server locates it, and sends it. So get a list of all the files in a directory and send them all together. Better yet, tar them all together, zip them with some compression algorithm, and send that ONE file. This method is actually pretty much industry standard among Linux users. Pull I identifed this in the comments, but it works like this: Client asks for directory Server returns a text file containing the names of all the files. Client asks for each file. Index This technique is the least mutable of the three. Keep an index of all the files in the directory, named INDEX.xml (funny enough, you could model the entire directory tree in xml.) your client will request the xml file, then walk the tree requesting other files.
downvote count: 0

http://stackoverflow.com/comment/81737070
has text: type `python3 -V`
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47392040
type: Comment

http://stackoverflow.com/comment/81722476
type: AnswerComment
has text: I edited my answer, but I am still rather unclear what exactly you want
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47384608

http://stackoverflow.com/q/47435092
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81824417
has comment: http://stackoverflow.com/comment/81824254
has comment: http://stackoverflow.com/comment/81824308
has comment: http://stackoverflow.com/comment/81824485
answer count: 1
has comment: http://stackoverflow.com/comment/81824727
type: Question
accepted answer: http://stackoverflow.com/a/47435376
has title: How to add bubble sort to my boxes in the code?
has comment: http://stackoverflow.com/comment/81824348
has answer: http://stackoverflow.com/a/47435376
has comment: http://stackoverflow.com/comment/81824785
has comment: http://stackoverflow.com/comment/81824628
tagged with: python
tagged with: bubble-sort
tagged with: sorting
has body: So first here is my code: import pygame, sys, random from pygame.locals import * # Create the constants (go ahead and experiment with different values) BOARDWIDTH = 4 # number of columns in the board BOARDHEIGHT = 4 # number of rows in the board TILESIZE = 80 WINDOWWIDTH = 640 WINDOWHEIGHT = 480 FPS = 30 BLANK = None # R G B BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BRIGHTBLUE = ( 0, 50, 255) DARKTURQUOISE = ( 3, 54, 73) GREEN = ( 0, 204, 0) BGCOLOR = DARKTURQUOISE TILECOLOR = GREEN TEXTCOLOR = WHITE BORDERCOLOR = BRIGHTBLUE BASICFONTSIZE = 20 BUTTONCOLOR = WHITE BUTTONTEXTCOLOR = BLACK MESSAGECOLOR = WHITE XMARGIN = int((WINDOWWIDTH - (TILESIZE * BOARDWIDTH + (BOARDWIDTH - 1))) / 2) YMARGIN = int((WINDOWHEIGHT - (TILESIZE * BOARDHEIGHT + (BOARDHEIGHT - 1))) / 2) UP = 'up' DOWN = 'down' LEFT = 'left' RIGHT = 'right' def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, RESET_SURF, RESET_RECT, NEW_SURF, NEW_RECT, SOLVE_SURF, SOLVE_RECT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Slide Puzzle') BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE) # Store the option buttons and their rectangles in OPTIONS. RESET_SURF, RESET_RECT = makeText('Reset', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120, WINDOWHEIGHT - 90) NEW_SURF, NEW_RECT = makeText('New Game', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120, WINDOWHEIGHT - 60) SOLVE_SURF, SOLVE_RECT = makeText('Solve', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120, WINDOWHEIGHT - 30) mainBoard, solutionSeq = generateNewPuzzle(80) SOLVEDBOARD = getStartingBoard() # a solved board is the same as the board in a start state. allMoves = [] # list of moves made from the solved configuration while True: # main game loop slideTo = None # the direction, if any, a tile should slide msg = 'Click tile or press arrow keys to slide.' # contains the message to show in the upper left corner. if mainBoard == SOLVEDBOARD: msg = 'Solved!' drawBoard(mainBoard…

http://stackoverflow.com/q/47482009
has body: Here is a sample code. df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB')) df['C'] = df.B.rolling(window=3) Output: A B C 0 -0.108897 1.877987 Rolling [window=3,center=False,axis=0] 1 -1.276055 -0.424382 Rolling [window=3,center=False,axis=0] 2 1.578561 -1.094649 Rolling [window=3,center=False,axis=0] 3 -0.443294 1.683261 Rolling [window=3,center=False,axis=0] 4 0.674124 0.281077 Rolling [window=3,center=False,axis=0] 5 0.587773 0.697557 Rolling [window=3,center=False,axis=0] 6 -0.258038 -1.230902 Rolling [window=3,center=False,axis=0] 7 -0.443269 0.647107 Rolling [window=3,center=False,axis=0] 8 0.347187 0.753585 Rolling [window=3,center=False,axis=0] 9 -0.369179 0.975155 Rolling [window=3,center=False,axis=0] I want my 'C' column to be an array like [0.1231, -1.132, 0.8766]. I tried using rolling apply but in vain. Expected Output: A B C 0 -0.108897 1.877987 [] 1 -1.276055 -0.424382 [] 2 1.578561 -1.094649 [-1.094649, -0.424382, 1.877987] 3 -0.443294 1.683261 [1.683261, -1.094649, -0.424382] 4 0.674124 0.281077 [0.281077, 1.683261, -1.094649] 5 0.587773 0.697557 [0.697557, 0.281077, 1.683261] 6 -0.258038 -1.230902 [-1.230902, 0.697557, 0.281077] 7 -0.443269 0.647107 [0.647107, -1.230902, 0.697557] 8 0.347187 0.753585 [0.753585, 0.647107, -1.230902] 9 -0.369179 0.975155 [0.975155, 0.753585, 0.647107]
has comment: http://stackoverflow.com/comment/81920405
has comment: http://stackoverflow.com/comment/115420030
has comment: http://stackoverflow.com/comment/81919936
has answer: http://stackoverflow.com/a/74753705
has comment: http://stackoverflow.com/comment/81920655
downvote count: 0
has answer: http://stackoverflow.com/a/47483671
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/15722324
has answer: http://stackoverflow.com/a/67992476
has answer: http://stackoverflow.com/a/54443012
score: 25
has title: Pandas rolling window to return an array
has answer: http://stackoverflow.com/a/65216213
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81921157
tagged with: pandas
has comment: http://stackoverflow.com/comment/81920388
linked to: http://stackoverflow.com/q/47483579
answer count: 7
has comment: http://stackoverflow.com/comment/81918887
possible better answer: http://stackoverflow.com/a/65216213
has answer: http://stackoverflow.com/a/67992777
has comment: http://stackoverflow.com/comment/81920713
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81919979
upvote count: 25
has answer: http://stackoverflow.com/a/47483774
accepted answer: http://stackoverflow.com/a/47483671

http://stackoverflow.com/comment/81928697
score: 1
has text: What was your attempt and where did it fail? Please provide the code and read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)
comment on: http://stackoverflow.com/q/47486930
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47427603
has answer: http://stackoverflow.com/a/47429565
has comment: http://stackoverflow.com/comment/81810556
tagged with: python
has comment: http://stackoverflow.com/comment/81810305
answer count: 4
has comment: http://stackoverflow.com/comment/81959567
possible better answer: http://stackoverflow.com/a/47444215
has comment: http://stackoverflow.com/comment/81821844
score: 2
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81810358
has answer: http://stackoverflow.com/a/47444215
upvote count: 2
has comment: http://stackoverflow.com/comment/81809659
has answer: http://stackoverflow.com/a/47428472
downvote count: 0
has comment: http://stackoverflow.com/comment/81809779
has answer: http://stackoverflow.com/a/47435909
has comment: http://stackoverflow.com/comment/81810056
favorite count: 0
linked to: http://stackoverflow.com/q/41890448
type: Question
has body: Is there any way to make recurrence without using for's in numpy? Using np.add with out keyword do the trick with dtype="int" import numpy as np N = 100 fib = np.zeros(N, dtype=np.int) fib[:2] = 1. np.add(fib[:-2], fib[1:-1], out=fib[2:]) print(fib[:10]) output: [ 1 1 2 3 5 8 13 21 34 55] However, if dtype is changed to np.float import numpy as np N = 100 fib = np.zeros(N, dtype=np.float) fib[:2] = 1. np.add(fib[:-2], fib[1:-1], out=fib[2:]) print(fib[:10]) output: [ 1. 1. 2. 1. 3. 1. 4. 1. 5. 1.] Could someone tell me why? or any other way to make recursion?
has title: Recurrence with numpy
has comment: http://stackoverflow.com/comment/81810180
accepted answer: http://stackoverflow.com/a/47429565
has comment: http://stackoverflow.com/comment/81813551
has comment: http://stackoverflow.com/comment/81811234

http://stackoverflow.com/q/47397341
score: 3
has title: How to prevent LDAP-injection in ldap3 for python3
tagged with: python
tagged with: code-injection
type: AnsweredQuestion
upvote count: 3
answer count: 2
tagged with: python-ldap
tagged with: ldap3
downvote count: 0
has answer: http://stackoverflow.com/a/48290733
possible better answer: http://stackoverflow.com/a/48290733
has answer: http://stackoverflow.com/a/56593412
accepted answer: http://stackoverflow.com/a/56593412
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81981879
has comment: http://stackoverflow.com/comment/81765264
has body: I'm writing some python3 code using the ldap3 library and I'm trying to prevent LDAP-injection. The OWASP injection-prevention cheat sheet recommends using a safe/parameterized API(among other things). However, I can't find a safe API or safe method for composing search queries in the ldap3 docs. Most of the search queries in the docs use hard-coded strings, like this: conn.search('dc=demo1,dc=freeipa,dc=org', '(objectclass=person)') and I'm trying to avoid the need to compose queries in a manner similar to this: conn.search(search, '(accAttrib=' + accName + ')') Additionally, there seems to be no mention of 'injection' or 'escaping' or similar concepts in the docs. Does anyone know if this is missing in this library altogether or if there is a similar library for Python that provides a safe/parameterized API? Or has anyone encountered and solved this problem before? A final point: I've seen the other StackOverflow questions that point out how to use whitelist validation or escaping as a way to prevent LDAP-injection and I plan to implement them. But I'd prefer to use all three methods if possible.
tagged with: ldap

http://stackoverflow.com/q/47458616
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: whoosh
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has title: Deep NLP pipeline with Whoosh
has body: I am very new to NLP and IR programs. I am trying to implement a deep NLP pipeline i.e. adding Lemmatizing, Dependency parsing features to the indexing of sentences. Following is my schema and searcher. my_analyzer = RegexTokenizer()| StopFilter()| LowercaseFilter() | StemFilter() | Lemmatizer() pos_analyser = RegexTokenizer() | StopFilter()| LowercaseFilter() | PosTagger() schema = Schema(id=ID(stored=True, unique=True), stem_text=TEXT(stored= True, analyzer=my_analyzer), pos_tag= pos_analyser) for sentence in sent_tokenize_list1: writer.add_document(stem_text = sentence, pos_tag = sentence) for sentence in sent_tokenize_list2: writer.add_document(stem_text = sentence, pos_tag = sentence) writer.commit() with ix.searcher() as searcher: og = qparser.OrGroup.factory(0.9) query_text = MultifieldParser(["stem_text","pos_tag"], schema = ix.schema, group= og).parse( "who is controlling the threat of locusts?") results = searcher.search(query_text, sortedby= scores, limit = 10 ) This is the custom analyzer. class PosTagger(Filter): def __eq__(self, other): return (other and self.__class__ is other.__class__ and self.__dict__ == other.__dict__) def __ne__(self, other): return not self == other def __init__(self): self.cache = {} def __call__(self, tokens): assert hasattr(tokens, "__iter__") words = [] tokens1, tokens2 = itertools.tee(tokens) for t in tokens1: words.append(t.text) tags = pos_tag(words) i=0 for t in tokens2: t.text = tags[i][0] + " "+ tags[i][1] i += 1 yield t I am getting the following error. whoosh.fields.FieldConfigurationError: CompositeAnalyzer(RegexTokenizer(expression=re.compile('\w+(\.?\w+)*'), gaps=False), StopFilter(stops=frozenset({'for', 'will', 'tbd', 'with', 'and', 'the', 'if', 'it', 'by', 'is', 'are', 'this', 'as', 'when', 'us', 'or', 'from', 'yet', 'you', 'have', 'can', 'be', 'we', 'of', 'to', 'on', 'a', 'an', 'your', 'at', 'in', 'may', 'not', 'that'}), min=2, max=None, renumber=True), LowercaseFilter(), PosTagger(cache={})) is not a FieldTyp…
tagged with: information-retrieval
tagged with: python
has answer: http://stackoverflow.com/a/47464016
accepted answer: http://stackoverflow.com/a/47464016
tagged with: nlp

http://stackoverflow.com/comment/81981070
type: AnswerComment
comment on: http://stackoverflow.com/a/47506205
score: 3
type: Comment
has text: @roganjosh: It could be the site administrators saw a specific Python script abuse the site and wanted to block that one script, quickly. It could be they implemented a naive blacklist, and will make it more sophisticated as the need arises. Etc. Just because the blockade is simple today, won't mean it won't become harder to bypass as abusers bypass it.

http://stackoverflow.com/comment/82059271
has text: @Wen thx for the reply again. I got that, so that code is setting the df2['new_value'] column to a dict. But how did the replace work? The code is saying replace the 'original' column by using the dict we just defined?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47524153
score: 0

http://stackoverflow.com/comment/81917482
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47467656
type: Comment
has text: ahhh, I see what you did there with `keepdims`; awesome :)

http://stackoverflow.com/q/47446613
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: subdirectory
accepted answer: http://stackoverflow.com/a/47446647
type: AnsweredQuestion
has title: Python os.walk, working with files in subdirectories
has comment: http://stackoverflow.com/comment/81848551
answer count: 1
has body: Learning Python as part of my thesis, and I'm completely self taught/don't know what I'm doing; apologies if this is trivial. Been scouring the net for a while, and cannot find a "plain english" answer to this, nor can I figure out how to do this on my own. I've gleaned many tidbits on knowledge from this site via lurking, so I hope ya'll can help. I have a folder that contains folders named after years (2001, 2002, 2003, etc), and inside each is a numbered folder for each month (01, 02, 03, etc). Inside each of those are my csv files that I'm working with. I've already set up a program to load them in and analyze them, but it only works when there are no subdirectories involved. Otherwise it tells me the file does not exist. Simply trying to get python to see the csv files in those subdirectories and run them through the program. For example, this works just fine: top = r'C:\Users\Brock\Desktop\Masters_Python&amp;Data\WRF_data\ctl\2006\01' os.chdir(top) #change current directory to 'top' object for root,dirs,files in os.walk(top, topdown = True): for file in files: #blah blah program goes here However when I try to run this: top = r'C:\Users\Brock\Desktop\Masters_Python&amp;Data\WRF_data\ctl' os.chdir(top) for root,dirs,files in os.walk(top, topdown = True): for file in files: #blah blah program goes here It tells me that the first file in the first folder (01) does not exist. Also throws a random "b" in there after the word "File": FileNotFoundError: File b'1136072700_KSUN_wrf6x6.csv' does not exist This occurs if top is something like "r'C:\Users\Brock\Desktop\Masters_Python&amp;Data\WRF_data\ctl\2006' as well. Again, I apologize if this is a stupid question, but I'd rather ask someone who knows rather than me fiddling with it for a week to get somewhere. Cheers
has answer: http://stackoverflow.com/a/47446647
tagged with: os.walk
type: Question

http://stackoverflow.com/q/47467582
score: 0
has comment: http://stackoverflow.com/comment/81889733
answer count: 1
tagged with: django
tagged with: javascript
has title: Check user permissions not working in template after AJAX refresh?
tagged with: jquery
has comment: http://stackoverflow.com/comment/81889554
tagged with: ajax
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81889684
has body: I have strange behavior. In template I show list of objects as in the picture below. When user add/edit/delete any data by form I update list of users by AJAX. Problem is that after refresh by AJAX buttons disappear in list. It seems like {% if perms.foo.do_something %} don't work with AJAX. What's wrong and how to fix this problem? P.S. In the same time if I refresh page by browser {% if perms.foo.do_something %} works perfect. Show permissions correct. I am confused. At start: After refresh list by AJAX: Below example of code: javascript: // Submit Form $(function () { var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#users").html(data.html_users); $("#user-modal").modal("hide"); } else { $("#user-modal .modal-content").html(data.html_form); } } }); return false; }; // Update User Data $("#users").on("click", ".user-edit-btn", loadForm); $("#user-modal").on("submit", ".user-edit-form", saveForm); }); views.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserEditForm model = User permission_required = ('auth.change_user') def form_valid(self, form): form.save() data = dict() data['form_is_valid'] = True context = {'users': User.objects.order_by('username')} data['html_users'] = render_to_string('users/users.html', context) return JsonResponse(data) *** users.html: {% for user in users %} {{ user.username }} ({{ user.email }}) {% if perms.auth.change_user_password %} {% endif %} {% if perms.auth.delete_user %} {% endif %} {% if perms.auth.change_user %} {% endif %} {% endfor %}
accepted answer: http://stackoverflow.com/a/47467985
tagged with: python
has answer: http://stackoverflow.com/a/47467985
has comment: http://stackoverflow.com/comment/81889903
type: Question
has comment: http://stackoverflow.com/comment/81889594

http://stackoverflow.com/comment/81903150
has text: Now it handles `NaN`, `-inf`, `inf`, and scientific notation, thanks for demanding more.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47473730

http://stackoverflow.com/comment/81970676
score: 0
has text: That said, the instructions seem clear; it wants you to use the setters in your `__init__` method, and you aren't.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47507272

http://stackoverflow.com/q/47403920
possible better answer: http://stackoverflow.com/a/47404301
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47404079
score: 0
answer count: 2
tagged with: operating-system
has comment: http://stackoverflow.com/comment/81761919
has title: How to convert lower case file path to actual
has comment: http://stackoverflow.com/comment/81761626
has answer: http://stackoverflow.com/a/47404301
has body: The variable file_path uses only the lowercase characters: file_path = '/users/username/documents/my_doc.txt' while the actual file path contains both: the upper and lower case characters: /Users/UserName/Documents/My_Doc.txt Interesting, that os.path.exists(file_path) returns True making me believe that I can ignore the letter-casing since Python and the OS the process is running on is not case sensative. But the letter case becomes incredibly important if the file path starts with /Volumes/ (why it is happening deserves a separate discussion). How can we turn the all lower case file path to the the actual file path that correctly displays both the upper and lower cases?
type: Question
has comment: http://stackoverflow.com/comment/81761610
has answer: http://stackoverflow.com/a/47404079
has comment: http://stackoverflow.com/comment/81761849
tagged with: sys
tagged with: python
has comment: http://stackoverflow.com/comment/81761708

http://stackoverflow.com/q/47458491
has comment: http://stackoverflow.com/comment/81871835
score: 0
has answer: http://stackoverflow.com/a/47459930
answer count: 1
tagged with: object
has comment: http://stackoverflow.com/comment/81871961
type: Question
has comment: http://stackoverflow.com/comment/81872156
has comment: http://stackoverflow.com/comment/81874326
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81872100
tagged with: instances
has body: Im trying to write a python method that looks at Rarity and counts the different types and then returns what the smallest count is but i keep getting: 'MagicCard' object is not subscriptable. Im also wanting to check which colors are associated with the least rare cards. Any help would be appreciated: Here is where the Json can be obtained from for testing: http://mtgjson.com/json/DTK.json Card Object: class MagicCard(object): def __init__ (self, jsonCard): self.name=jsonCard["name"] if jsonCard.get("colors",""): self.colors=jsonCard["colors"] else: self.colors=None if jsonCard["rarity"]: self.rarity=jsonCard["rarity"] else: self.rarity=None def get_name(self): """Return the name of the card""" return self.name def get_colors(self): """Return the colors of the card""" return self.colors def get_rarity(self): """Return the rarity of the card""" return self.rarity Card Deck Object: class MagicCardSet(object): def __init__(self, DeckDict): self.cardlist = [MagicCard(eachCard) for eachCard in DeckDict["cards"]] def get_card_list(self): Card_name_list=[] for newCard in self.cardlist: Card_name_list.append(newCard.get_name()) return(Card_name_list) def get_card_color(self): color_list=[] for newCard in self.cardlist: color_list.append(newCard.get_color()) return(color_list) def get_card_rarity(self): rarity_list=[] for newCard in self.cardlist: rarity_list.append(newCard.get_rarity()) return(rarity_list) def get_rarest_card(self): for eachCard in self.cardlist: if eachCard["rarity"]=="Uncommon": uncommon_counter = uncommon_counter + 1 elif eachCard["rarity"]=="Common": common_counter=common_counter + 1 elif eachCard["rarity"]=="Rare": rare_counter = rare_counter + 1 elif eachCard["rarity"]=="Mythic Rare": mythic_rare_counter = mythic_rare_counter + 1 return(mythic_rare_counter) error:
has title: Finding min of different counts in object

http://stackoverflow.com/q/47539628
tagged with: matplotlib
score: 0
has body: I'm working on a program that allows users to put a different number of plots onto an axis. I need to show the legend, and the plot labels are long so I think it is best to show this under the plot. When I've done this before, I've always just shrunk the plot a bit and put the legend under the plot. Now that there are a varying number of plots this isn't as simple since I cannot find a nice formula for determining how much to shrink the plot and how far down to put the legend so it is not being cut off or overlapping the axis. I've written a an example code to demonstrate what I currently am doing, which is ugly. I currently am checking how many items are in the plot and tried to manually optimize the axis shrink and legend offset parameters then did a big if loop to use the manually optimized values. They are not optimized for this example code, but I think it demonstrates what I am doing. import matplotlib.pyplot as plt import numpy as np def find_scales(legendData): leg_len = len(legendData) if leg_len == 0: height_scale = 1 legend_offset = 0 elif leg_len == 1: height_scale = 0.96 legend_offset = -0.18 elif leg_len == 2: height_scale = 0.95 legend_offset = -0.25 elif leg_len == 3: height_scale = 0.94 legend_offset = -0.35 elif leg_len == 4: height_scale = 0.93 legend_offset = -0.45 elif leg_len == 5: height_scale = 0.93 legend_offset = -0.57 elif leg_len == 6: height_scale = 0.93 legend_offset = -0.68 elif leg_len == 7: height_scale = 0.93 legend_offset = -0.82 elif leg_len == 8: height_scale = 0.93 legend_offset = -0.98 elif leg_len == 9: height_scale = 0.92 legend_offset = -1.3 elif leg_len == 10: height_scale = 0.92 legend_offset = -1.53 else: height_scale = 0.92 legend_offset = -1.8 return height_scale, legend_offset num_plots = 3 x_range = np.arange(10) fig,ax = plt.subplots() for i in range(num_plots): ax.plot(x_range, np.random.rand(10)) legend_labels = ['a','b','c','d','e','f','g','h','i','j'][:num_plots] box = ax.get_position() height_scale, legend_offse…
has answer: http://stackoverflow.com/a/47540409
has comment: http://stackoverflow.com/comment/82036588
has title: Showing legend under matplotlib plot with varying number of plots
linked to: http://stackoverflow.com/q/42994338
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/82036663
has comment: http://stackoverflow.com/comment/82036914
has comment: http://stackoverflow.com/comment/82036646
answer count: 1
linked to: http://stackoverflow.com/q/4700614
has comment: http://stackoverflow.com/comment/82036415
has comment: http://stackoverflow.com/comment/82036470
has comment: http://stackoverflow.com/comment/82036842
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82036316
accepted answer: http://stackoverflow.com/a/47540409

http://stackoverflow.com/q/47461386
type: AnsweredQuestion
has title: Fastest way to extract all bands from raster at once (python/gdal)
score: 0
answer count: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/47471935
type: Question
tagged with: python
has body: I have some hyperspectral imagery with a large number of bands, which I want to do analysis on. My script needs to be able to access all the bands at once. Currently, I'm achieving this with the following: bands = np.asarray([dataset.GetRasterBand(n+1) for n in range(dataset.RasterCount)]) This works fine, but it seems that this step is taking up a significant amount of time in my processing workflow, and I suspect there is a better way to do it. Also, I am under the impression that it is poor practice to use list comprehensions with numpy in this way (?). Do numpy or gdal have any built-in methods that can make this faster?
accepted answer: http://stackoverflow.com/a/47471935
tagged with: gdal

http://stackoverflow.com/a/47517582
has body: I suggest a different approach to this problem. Rather than use tkinter underpinnings to find the color of inactive objects (from turtle's perspective), I recommend you work completely within turtle and make the drawn objects active. We can do this by making each drawing a turtle cursor so that we're clicking on turtles, and interrogating their color, which is a simpler problem: import turtle def rectangle(height): length = height * 2 turtle.begin_poly() for _ in range(2): turtle.forward(length) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.end_poly() return turtle.get_poly() def star(vertices, steps, length): angle = steps * 360.0 / vertices turtle.begin_poly() for _ in range(vertices): turtle.forward(length) turtle.right(angle) turtle.end_poly() return turtle.get_poly() def circle(radius): turtle.begin_poly() turtle.circle(radius) turtle.end_poly() return turtle.get_poly() def display_color(turtle): print(turtle.fillcolor()) def main(): # Use the "default" turtle to draw the others turtle.penup() turtle.hideturtle() turtle.setheading(90) turtle.speed('fastest') screen.register_shape('rectangle', rectangle(150)) screen.register_shape('star', star(5, 2, 50)) screen.register_shape('circle', circle(50)) rectangle_turtle = turtle.Turtle('rectangle') rectangle_turtle.penup() rectangle_turtle.color('purple') rectangle_turtle.onclick(lambda x, y: display_color(rectangle_turtle)) star_turtle = turtle.Turtle('star') star_turtle.penup() star_turtle.setposition(150, 3) star_turtle.color('red') star_turtle.onclick(lambda x, y: display_color(star_turtle)) circle_turtle = turtle.Turtle('circle') circle_turtle.penup() circle_turtle.setposition(70, -107) circle_turtle.color('orange') circle_turtle.onclick(lambda x, y: display_color(circle_turtle)) screen = turtle.Screen() main() screen.mainloop() Now you should be able to click on any of the filled colored areas and you'll see the name of the color printed in the console window. (After you click on the window its…
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47502624
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47502624

http://stackoverflow.com/a/47510683
type: Answer
answers question: http://stackoverflow.com/q/47510098
score: 0
has body: You could do it in numpy using a structured array import numpy as np labels = list(map(''.join, zip(*3*((chr(ord('a')+(19*i)%24) for i in range(24)),)))) numbers = np.arange(8) dt = np.dtype([('label', object), ('value', int)]) table = np.empty((8,), dtype = dt) table['label'] = labels table['value'] = numbers print(table) table.sort() print(table) Output: #[('ato', 0) ('jex', 1) ('sni', 2) ('dwr', 3) ('mhc', 4) ('vql', 5) # ('gbu', 6) ('pkf', 7)] #[('ato', 0) ('dwr', 3) ('gbu', 6) ('jex', 1) ('mhc', 4) ('pkf', 7) # ('sni', 2) ('vql', 5)] Edit: How to access individual records: table[2] = 'new label', 1000 table # array([('ato', 0), ('dwr', 3), ('new label', 1000), ('jex', 1), # ('mhc', 4), ('pkf', 7), ('sni', 2), ('vql', 5)], # dtype=[('label', 'O'), ('value', '&lt;i8')])

http://stackoverflow.com/q/47438313
has answer: http://stackoverflow.com/a/47439155
accepted answer: http://stackoverflow.com/a/47439155
favorite count: 0
type: Question
answer count: 2
has body: I have got a dataset which contains just two useful columns for training my model, first is news heading and the second is category of news. So, I got the following training command running successfully using python: import re import numpy as np import pandas as pd # the Naive Bayes model from sklearn.naive_bayes import MultinomialNB # function to split the data for cross-validation from sklearn.model_selection import train_test_split # function for transforming documents into counts from sklearn.feature_extraction.text import CountVectorizer # function for encoding categories from sklearn.preprocessing import LabelEncoder # grab the data news = pd.read_csv("/Users/helloworld/Downloads/NewsAggregatorDataset/newsCorpora.csv",encoding='latin-1') news.head() def normalize_text(s): s = s.lower() # remove punctuation that is not word-internal (e.g., hyphens, apostrophes) s = re.sub('\s\W',' ',s) s = re.sub('\W\s',' ',s) # make sure we didn't introduce any double spaces s = re.sub('\s+',' ',s) return s news['TEXT'] = [normalize_text(s) for s in news['TITLE']] # pull the data into vectors vectorizer = CountVectorizer() x = vectorizer.fit_transform(news['TEXT']) encoder = LabelEncoder() y = encoder.fit_transform(news['CATEGORY']) # split into train and test sets x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) nb = MultinomialNB() nb.fit(x_train, y_train) So my question is, how can I give a new set of data (e.g. Just news heading) and tell the program to predict the news category using python sklearn command? P.S. My training data is like:
has title: How to predict after training data using naive bayes with python?
tagged with: naivebayes
has comment: http://stackoverflow.com/comment/81832926
tagged with: scikit-learn
tagged with: python
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/47438971
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47438971
has comment: http://stackoverflow.com/comment/81831559

http://stackoverflow.com/comment/81743733
has text: Just updated with a link to the data.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47394969
type: Comment

http://stackoverflow.com/q/47446626
has title: How to output only the string in list data?
downvote count: 0
score: 1
upvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/81848599
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47446661
type: UnansweredQuestion
has body: My file reads the teamNames.txt file which is: Collingwood Essendon Hawthorn Richmond Code: file2 = input("Enter the team-names file: ") ## E.g. teamNames.txt bob = open(file2) teamname = [] for line1 in bob: ##loop statement until no more line in file teamname.append(line1) print(teamname) The output is: ['Collingwood\n', 'Essendon\n', 'Hawthorn\n', 'Richmond\n'] I want to make it so the output will be: Collingwood, Essendon, Hawthorn, Richmond
tagged with: python
has answer: http://stackoverflow.com/a/47446659
tagged with: append
tagged with: list
tagged with: split
answer count: 3
has answer: http://stackoverflow.com/a/47446869

http://stackoverflow.com/q/47435854
has comment: http://stackoverflow.com/comment/81826265
tagged with: pandas
tagged with: python
tagged with: utf-8
has title: Why UTF-8 takes more time in processing
score: 2
has comment: http://stackoverflow.com/comment/81826049
has comment: http://stackoverflow.com/comment/81827143
tagged with: encoding
answer count: 0
has body: What is the reason of slow performance when dealing with utf-8 I had a Pandas code where I read from csv in chunk do some data transformation. My benchmark before assigning encoding='utf-8' was 29s per 250k rows. After I implemented enconding to utf-8 to read_csv and to_csv it take double time i.e 60s per 250k rows. for df in pd.read_csv(downloaded_file, chunksize=chunksize, compression='gzip', low_memory=False, skipinitialspace=True, encoding='utf-8'): # do some handling df.to_csv(outfile_name, index=False, compression='gzip', sep='\t', quoting=1, encoding='utf-8') My data processing is mainly renaming columns, detecting and removing blacklisted words, rounding the price etc.
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81826488
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/81923269
type: QuestionComment
has text: Keep in mind that this will lead to a LOT of data duplication, if you decide to have them as separate rows, so bear the fact in mind.
comment on: http://stackoverflow.com/q/47484166
score: 0
type: Comment

http://stackoverflow.com/tag/c
tags question: http://stackoverflow.com/q/47490929
tags question: http://stackoverflow.com/q/47517323
tags question: http://stackoverflow.com/q/47511947
tags question: http://stackoverflow.com/q/47435650
tags question: http://stackoverflow.com/q/47431704
tag name: c
tags question: http://stackoverflow.com/q/47481160
tags question: http://stackoverflow.com/q/47489515
tags question: http://stackoverflow.com/q/47460240
tags question: http://stackoverflow.com/q/47401997
type: Tag
tags question: http://stackoverflow.com/q/47520712
tags question: http://stackoverflow.com/q/47451169
tags question: http://stackoverflow.com/q/47424637
tags question: http://stackoverflow.com/q/47503566
tags question: http://stackoverflow.com/q/47456055

http://stackoverflow.com/comment/81779185
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47411800
has text: IMO, `Firefox Quantum (Released)` version is **`57.0`** Are you using `Mozilla Firefox Quantum v58.0` from **`Nightly`** / **`Beta`** / **`Developers`** ?
type: Comment

http://stackoverflow.com/comment/81820911
type: Comment
has text: There could be other methods like 'PUT' so providing functionality for GET inside else wouldn't be okay.
comment on: http://stackoverflow.com/a/47433253
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81974836
comment on: http://stackoverflow.com/q/47508891
type: Comment
type: QuestionComment
has text: @M.Carreira You, and did get through though. The last time you did `ls` you see the `settings.py` right there. What are you trying to do with the `settings.py`? Edit it? Run your Django application as debug with `python manage.py runserver`? What are you expecting to happen, and what are you trying?
score: 0

http://stackoverflow.com/q/47408683
has answer: http://stackoverflow.com/a/47409001
tagged with: scrapy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47449169
has title: How to crawl from base url to another url in scrapy using request library
has comment: http://stackoverflow.com/comment/81772364
has comment: http://stackoverflow.com/comment/81771127
has comment: http://stackoverflow.com/comment/81771008
tagged with: python
score: 4
possible better answer: http://stackoverflow.com/a/47449169
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81770958
has body: import scrapy from scrapy.selector import Selector from scrapy.contrib.spiders import CrawlSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request class NextlinkSpider(scrapy.Spider): name = 'nextlink' allowed_domains = ['www.shanazrafiq.com/'] start_urls = ['https://www.shanazrafiq.com/'] def parse(self, response): yield Request(url='https://www.shanazrafiq.com/p/recipes.html',callback = self.parse_dir_contents) Error :AttributeError: 'NextlinkSpider' object has no attribute 'parse_dir_contents' trying to crawl to another url from base url I wanted to get the recipes page tag content by navigating from first page but unable to call the callback function which say me attribute not found error while doing so. Help me in fixing this . Thanks in advance def parse_dir_contents(self, response): # second function to be called. sel = Selector(response) title_name=sel.css("div.widget HTML h2::text").extract() print title_name
answer count: 2
accepted answer: http://stackoverflow.com/a/47409001
downvote count: 0
has comment: http://stackoverflow.com/comment/81770736

c++
tags question: http://stackoverflow.com/q/47486442
tags question: http://stackoverflow.com/q/47454108
tags question: http://stackoverflow.com/q/47441877
tags question: http://stackoverflow.com/q/47523708
tags question: http://stackoverflow.com/q/47386149
tags question: http://stackoverflow.com/q/47489515
tags question: http://stackoverflow.com/q/47444783
tags question: http://stackoverflow.com/q/47491371
tags question: http://stackoverflow.com/q/47517351
type: Tag
tags question: http://stackoverflow.com/q/47474961
tags question: http://stackoverflow.com/q/47428786
tags question: http://stackoverflow.com/q/47450516
tag name: c++
tags question: http://stackoverflow.com/q/47524685
tags question: http://stackoverflow.com/q/47404984
tags question: http://stackoverflow.com/q/47402429
tags question: http://stackoverflow.com/q/47408154

http://stackoverflow.com/comment/81828394
has text: Oh, surely! This function is not differentiable (regarding the weights), because it depends only on `yTrue` in the end. The function must depend on `yPred`. (There aren't `yPred` values in this function, only a condition that uses them, and the condition is not differentiable).
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47432758

http://stackoverflow.com/q/47440317
answer count: 0
tagged with: http://stackoverflow.com/tag/csv
has body: I'm trying to import a CSV file to my PostgreSQL (which is set to utf-8 encoding). I'm using Python 2.76 and the Pandas read_csv module. I'm using the following libraries to interact with the database - sqlalchemy and psycopg2. In order to parse the file i've set the following encoding due to the fact that there are German characters in the file as well: df = pd.read_csv(full_path, encoding='windows-1252', sep=';', header=0) Upon the insert statement to the database I see the following error: csv file not loaded into database: (&lt;class 'sqlalchemy.exc.DataError'&gt;, DataError('(psycopg2.DataError) invalid input syntax for type double precision: "2.670,40" Currently in the database the formatting of integers and float is in the format XXXX.XX while in the CSV X.XXX,XXX (seems like the German number formatting style). What is the appropriate way to convert the format in the CSV file to the one in the database? It appears that this is conflict causing the error. I've tried several other encodings including utf-8-sig, 'utf-8andlatin-1`, either work. I also had an approach to replace the dots with an empty character and the commas with a dot but this seems backwards and inefficient. Thanks!
has comment: http://stackoverflow.com/comment/81868064
type: Question
has comment: http://stackoverflow.com/comment/81835671
tagged with: encoding
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81835564
tagged with: python
tagged with: number-formatting
has title: Import CSV data to PostgreSQL - Encoding is invalid
tagged with: postgresql
score: 0

http://stackoverflow.com/a/68986146
has body: random implements a pseudo random number generator. Knowing the algorithm and the parameters we can predict the generated sequence. At the end of the text is a possible implementation of a linear pseudo random generator in Python, that shows the generator can be a simple linear function. os.urandom uses system entropy sources to have better random generation. Entropy sources are something that we cannot predict, like asynchronous events. For instance the frequency that we hit the keyboard keys cannot be predicted. Interrupts from other devices can also be unpredictable. In the random module there is a class: SystemRandom which uses os.urandom() to generate random numbers. Actually, it cannot be proven if a given sequence is Random or NOT. Andrey Kolmogorov work this out extensively around 1960s. One can think that a sequence is random when the rules to obtain the sequence, in any given language, are larger than the sequence itself. Take for instance the following sequence, which seems random: 264338327950288419716939937510 However we can represent it also as: pi digits 21 to 50 Since we found a way to represent the sequence smaller than the sequence itself, the sequence is not random. We could even think of a more compact language to represent it, say: pi[21,50] or yet another. But the smaller rules, in the most compact language (or the smaller algorithm, if you will), to generate the sequence may never be found, even if it exists. This finding depends only on human intelligence which is not absolute. There might be a definitive way to prove if a sequence is random, but we will only know it when someone finds it. Or maybe there is no way to prove if randomness even exists. An implementation of a LCG (Linear congruent generator) in Python can be: from datetime import datetime class LCG: defaultSeed = 0 defaultMultiplier = 1664525 defaultIncrement = 1013904223 defaultModulus = 0x100000000 def __init__(self, seed, a, c, m): self._x0 = seed #seed self._a = a #multiplier…
answers question: http://stackoverflow.com/q/47514695
score: 1
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82119809
score: 0
has text: I have a harder time following this -- but that's on me as a noob -- but it does deliver something like the desired answer. Given the input above, this outputs a list of lists: `[(1, 'S1', '4'), [2, 'S1', '6'], [1, 'S2', '11sf'], [2, 'S3', '6'], [1, 'S3', '12'], [3, 'S3', '7'], [1, 'S4', '11cws'], [3, 'S5', '7'], [1, 'S6', '4'], [2, 'S6', '2'], [3, 'S6', '11nf'], [3, 'S7', '7'], [2, 'S8', '6'], [1, 'S8', '10'], [1, 'S9', '5'], [1, 'S10', '3'], [1, 'S11', '11sl'], [3, 'S12', '7'], [1, 'S13', '11sl'], [2, 'S14', '6']]`. I can imagine re-organizing to make the day-test combination the priority.
type: Comment
comment on: http://stackoverflow.com/a/47554334
type: AnswerComment

http://stackoverflow.com/comment/82069157
score: 0
comment on: http://stackoverflow.com/q/47534449
type: Comment
type: QuestionComment
has text: The idea by @AndreyF worked perfectly, but still keeping the indentation of the inner class, otherwise it won't work. Why do you say that it is better to have not nested classes?

http://stackoverflow.com/q/47492516
upvote count: 4
score: 4
answer count: 4
type: AnsweredQuestion
tagged with: django-templates
has answer: http://stackoverflow.com/a/47493656
tagged with: django-views
downvote count: 0
has body: Let's say my sql table looks like this.. products table -------------------------------- | id | Model| Manufacturer | -------------------------------- | 1 | ABC | Samsung | | 2 | XYZ | LG | | 3 | ZYX | Sony | -------------------------------- in django view i fetched all records from this table and passed it to template.. def compare(request): product_ids = request.GET.get('product_ids') products = Product.objects.filter(id__in=product_ids) return render(request, 'compare.html', {'products': products}) as query_set result records comes like one after the other we can say it is following row wise but for this case in template i wanted to create an html table and the result should come like this .. -------------------------------------------- |id | 1 | 2 | 3 | |Model | ABC | XYZ | ZYX | |Manufacturer | Samsung | LG | Sony | -------------------------------------------- By looking at above example you can see data is rendered as column wise. so please suggest me a better method in Django by which i can achieve this and also please correct me if i'm wrong as i'm beginner in Django. Thanks in advance
has answer: http://stackoverflow.com/a/47494014
favorite count: 0
has answer: http://stackoverflow.com/a/47492846
type: Question
tagged with: html-table
has answer: http://stackoverflow.com/a/56964004
possible better answer: http://stackoverflow.com/a/56964004
tagged with: django
accepted answer: http://stackoverflow.com/a/47494014
tagged with: python
has title: How to render Django query set as column wise into html table?

http://stackoverflow.com/comment/81964554
comment on: http://stackoverflow.com/q/47504266
score: 2
type: Comment
type: QuestionComment
has text: @AruneshSingh: dictionary keys are in an _arbitrary_ order, one stable unless the dictionary is mutated; that's not the same as random.

http://stackoverflow.com/q/47509074
tagged with: deep-learning
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47510518
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
has body: I was reading this paper describing the various pros and cons of different metrics for time series forecasting. I want to combine MAPE (Mean Absolute Percentage Error): with SMSE (Signed Mean Squared Error): Where e_t is the difference between the actual value and the forecasting error . So I wanted to know how to implement this in Tensorflow. The formula should be: My Try If we immagine I have already written up the rest of the neural network then: error = y - prediction cost = tf.reduce_mean(tf.divide(error, y) * 100) + tf.reduce_mean(tf.divide(error, tf.abs(error)) * tf.square(error) I am quite unsure about how I have used * instead of tf.multiply. I know they perform different operations, but I can't quite figure out which one should I use here. Assume that y is a tf.placeholder(tf.float32, [None, #future_predictions]) and that predition is the output of the neural network and should have the same shape as y. Here None is the batch_size.
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47510518
has title: Tensorflow: Combining metrics to improve cost function
type: Question
tagged with: neural-network
tagged with: python

http://stackoverflow.com/comment/82031756
comment on: http://stackoverflow.com/q/47537463
type: Comment
has text: The interface is just what the user of the function sees: the signature. Someone calling `circle` doesn't need to know the internal structure; they just need to know that it takes two arguments `t` and `r`, and that there should be a global(?) variable named `n` defined in the calling scope.
score: 1
type: QuestionComment

http://stackoverflow.com/a/47414817
answers question: http://stackoverflow.com/q/47404653
downvote count: 0
has comment: http://stackoverflow.com/comment/103525079
has comment: http://stackoverflow.com/comment/81805842
has comment: http://stackoverflow.com/comment/98865573
upvote count: 27
has comment: http://stackoverflow.com/comment/103516314
has body: There is an issue with pandas datetimes and matplotlib coming from the recent release of pandas 0.21, which does not register its converters any more at import. Once you use those converters once (within pandas) they'll be registered and automatically used by matplotlib as well. A workaround would be to register them manually, import pandas.plotting._converter as pandacnv pandacnv.register() In any case the issue is well known at both pandas and matplotlib side, so there will be some kind of fix for the next releases. Pandas is thinking about readding the register in an upcomming release. So this issue may be there only temporarily. An option is also to revert to pandas 0.20.x where this should not occur. Update: this is no longer an issue with current versions of matplotlib (2.2.2)/pandas(0.23.1), and likely many that have been released since roughly December 2017, when this was fixed. Update 2: As of pandas 0.24 or higher the recommended way to register the converters is from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() or if pandas is already imported as pd, pd.plotting.register_matplotlib_converters()
type: Answer
has comment: http://stackoverflow.com/comment/81823133
score: 27
has comment: http://stackoverflow.com/comment/114706219
has comment: http://stackoverflow.com/comment/81818754

http://stackoverflow.com/comment/81788748
score: 0
has text: And what is the ´01´ at the start of ´01-DAM-XNXX´ when you are looking for the key without the leading numbers?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47417364

http://stackoverflow.com/q/47478475
has body: Here is a small quote from this answer: import requests import json data = {"data" : "24.3"} data_json = json.dumps(data) headers = {'Content-type': 'application/json'} response = requests.post(url, data=data_json, headers=headers) Does anyone know for sure whether it matters whether you have data = {"data" : "24.3"} or data = {"data" : 24.3} ?
downvote count: 3
has comment: http://stackoverflow.com/comment/81911934
accepted answer: http://stackoverflow.com/a/47478583
tagged with: python-requests
possible better answer: http://stackoverflow.com/a/47480985
favorite count: 0
has title: Does Python Requests POST need numerical data to be a string rather than a float?
has comment: http://stackoverflow.com/comment/81911918
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47480985
has comment: http://stackoverflow.com/comment/81911861
tagged with: python
has comment: http://stackoverflow.com/comment/81951989
linked to: http://stackoverflow.com/q/13941742
has comment: http://stackoverflow.com/comment/81955848
has answer: http://stackoverflow.com/a/47478583
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81916819
answer count: 2
has comment: http://stackoverflow.com/comment/81911916
upvote count: 3

http://stackoverflow.com/a/47473152
answers question: http://stackoverflow.com/q/47473084
has comment: http://stackoverflow.com/comment/81900827
has comment: http://stackoverflow.com/comment/81900850
accepted answer of: http://stackoverflow.com/q/47473084
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/81900768
has body: what you need is not zip which doesn't combine your lists but rather itertools.product in a dict comprehension: import itertools a = [0.001,0.01,0.1,1] h = [2,4,8,16,32,64] d = {z:[] for z in itertools.product(a,h)} print(d) result: {(0.01, 2): [], (0.1, 64): [], (0.001, 64): [], (0.01, 64): [], (0.001, 2): [], (1, 4): [], (0.01, 4): [], (1, 64): [], (0.1, 8): [], (0.01, 8): [], (1, 2): [], (0.1, 32): [], (0.001, 32): [], (0.01, 32): [], (1, 16): [], (0.001, 8): [], (1, 8): [], (0.1, 16): [], (0.001, 16): [], (0.01, 16): [], (0.001, 4): [], (1, 32): [], (0.1, 4): [], (0.1, 2): []}
upvote count: 7
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47565728
has body: OK, finally I decided use the method of nx.compose and It' worked After the line pos2 in the command, add those: D_1=G2.nodes() G3=nx.compose(G1,G2) pos3= nx.spring_layout(G3) for k, v in pos3.items(): if k in D_1: v[0] = v[0] +10 nx.draw_networkx_nodes(G3,pos3,nodelist=G1.nodes(),node_color='b') nx.draw_networkx_nodes(G3,pos3,nodelist=G2.nodes()) nx.draw_networkx_edges(G3,pos3,edgelist=G1.edges()) nx.draw_networkx_edges(G3,pos3,edgelist=G2.edges()) nx.draw_networkx_labels(G3,pos3) The image will became this
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47466354

http://stackoverflow.com/comment/81833832
has text: Nop, not the answer to my question
type: Comment
comment on: http://stackoverflow.com/q/47439205
type: QuestionComment
score: 0

http://stackoverflow.com/q/47406740
tagged with: django-migrations
tagged with: django-orm
tagged with: django
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/47406814
type: AnsweredQuestion
score: 0
has body: I want to make a schema migration, just add 1 field to Model and to ModelAdmin. class MyModel(models.Model): some_field = models.ForeignKey(SomeModel) my_new_field = models.CharField(max_length=20, blank=True, null=True, choices=[(b'1', b'1'), (b'2', b'2')]) class MyModelAdmin(admin.ModelAdmin): list_display = ['some_field', 'my_new_field'] raw_id_fields = ('some_field', 'my_new_field',) And I got : (admin.E003) The value of 'raw_id_fields[1]' must be a ForeignKey or ManyToManyField. How can I fix that? I write an app with Python 2.7, Django 1.8 and PostgreSQL. I also use Docker containers for backend and PostgreSQL.
answer count: 1
accepted answer: http://stackoverflow.com/a/47406814
has title: Why I am getting an "(admin.E003) The value of 'raw_id_fields[N]' must be a ForeignKey or ManyToManyField." error in Django app?
type: Question

http://stackoverflow.com/q/47476347
type: UnansweredQuestion
score: 1
tagged with: python
has title: How to create a websocket wrapper using python
tagged with: api
has answer: http://stackoverflow.com/a/48054457
answer count: 1
downvote count: 0
tagged with: websocket
upvote count: 1
has body: I'm currently working on my project to create a python wrapper for the gemini api (https://docs.gemini.com/rest-api/). I'm in the process of working on the order events websocket (https://docs.gemini.com/websocket-api/#order-events) and having difficulty using the websocket client for python. This is how my code right now: import json import hmac import hashlib import base64 import time from websocket import create_connection import requests public_key = 'asdfkjdfdfk' private_key = 'asdfkjdfdfk' url = "https://api.sandbox.gemini.com/v1/order/status" def header(method, payload=None): if payload is None: payload = {} payload['request'] = method payload['nonce'] = int(time.time() * 1000) payload['order_id'] = '86499545' b64_payload = base64.b64encode(json.dumps(payload).encode('utf-8')) signature = hmac.new(private_key.encode('utf-8'), b64_payload, hashlib.sha384).hexdigest() headers = { 'X-GEMINI-APIKEY': public_key, 'X-GEMINI-PAYLOAD': b64_payload, 'X-GEMINI-SIGNATURE': signature, } return headers r = requests.post(url, headers=header('/v1/order/status')) print(r.json()) ws = create_connection("wss://api.sandbox.gemini.com/v1/order/events", header=header('/v1/order/events')) when i run script i get the following error : {'order_id': '86499545', 'id': '86499545', 'symbol': 'btcusd', 'exchange': 'gemini', 'avg_execution_price': '0.00', 'side': 'buy', 'type': 'exchange limit', 'timestamp': '1511299791', 'timestampms': 1511299791519, 'is_live': False, 'is_cancelled': True, 'is_hidden': False, 'was_forced': False, 'executed_amount': '0', 'remaining_amount': '0.1', 'options': ['maker-or-cancel'], 'price': '7900.00', 'original_amount': '0.1'} Traceback (most recent call last): File "C:\Users\uzman\Documents\Python\Gemini- Python API Wrapper\gemini\testing.py", line 35, in &lt;module&gt; header=header('/v1/status/order')) File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\websocket\_core.py", line 487, in create_connection websock.connect(url, **op…
favorite count: 0
type: Question

google-oauth
type: Tag
tag name: google-oauth
tags question: http://stackoverflow.com/q/47506698

http://stackoverflow.com/q/47476928
score: 0
answer count: 2
has body: I'm storing values in a dict in this way: def fname(): return max({(x): x**2 for x in range(1, 20)}) The problem is this returns the value of max key, and i need the value of that key. How the get the value or rewrite this so that i do get the value of the max key? Preferably without the use of itertools. EDIT: I forgot to mention, i would need this written in a single line.
has answer: http://stackoverflow.com/a/47479483
downvote count: 2
has comment: http://stackoverflow.com/comment/81908632
has answer: http://stackoverflow.com/a/47479699
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81908643
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has title: get value using max(dict comprehension)

http://stackoverflow.com/comment/82021089
has text: @khelwood how? like I just clear drive C or something?
score: 0
comment on: http://stackoverflow.com/q/47532330
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81975937
comment on: http://stackoverflow.com/q/47510098
type: Comment
type: QuestionComment
has text: You absolutely could do that. Just build a list and convert it to an array. You're not getting any speed benefits from using numpy the way you are, it's running in Python time because of the `for` loop. Not sure whether it's faster to sort in numpy or python for your list, you'd have to test and convert before/after sorting as appropriate.
score: 1

http://stackoverflow.com/a/47393000
has body: That's pretty much how SQL works. But: you can leverage SQLAlchemy's ORM relationships here and let SQLA handle the "deduplicating" for you: students = db.session.query(Child).\ options(joinedload("parents", innerjoin=True)).\ all() which will fetch the Child objects and prepopulate the parents relationship in the same query. To understand the difference between an explicit join and a joined load, read the zen of joined eager loading. The innerjoin=True is there since your original query performed one as well. Then you could simply: students_json = { "children": [ { "name": s.name, "id": s.id, "parent_id": [p.id for p in s.parents] } for s in students ] } If you're worried about the width of the returned rows, you can provide a suitable load_only() as options as well: options(load_only("id", "name"), joinedload("parents", innerjoin=True).load_only("id"))
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47391715
score: 1
answers question: http://stackoverflow.com/q/47391715
type: Answer
upvote count: 1

http://stackoverflow.com/comment/81756189
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47401186
score: 0
has text: again, update your question with all input filenames that need to be requested, avoid confusing

http://stackoverflow.com/q/47501670
answer count: 2
tagged with: python
tagged with: pygame
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47501891
has title: Python pong game against computer player
has comment: http://stackoverflow.com/comment/81959365
has comment: http://stackoverflow.com/comment/81959284
tagged with: pycharm
score: 0
has answer: http://stackoverflow.com/a/47501875
has body: I made a 2 player version of Pong recently. But I want the game a bit different it should be Player 1 vs. CPU. Does anybody have tips how to program the CPU player in my Pong game? The CPU player should replace the role of Player 2 (Human player). The Player 2 object is defined as (P2) in my code it should be replaced by a computer player. The CPU should randomly go up and down. Thanks in advance :) import pygame ### initialize game pygame.init() ### setup display DISPLAY_SIZE = DISPLAY_WIDTH, DISPLAY_HEIGHT = 800, 600 screen = pygame.display.set_mode(DISPLAY_SIZE) ### set window caption pygame.display.set_caption("Future Game by Kevin Narain") ### clock clock = pygame.time.Clock() ### hide cursor pygame.mouse.set_visible(False) ### game constants # buttons P1_UP = pygame.K_w P1_DOWN = pygame.K_s P2_UP = pygame.K_UP P2_DOWN = pygame.K_DOWN # other constants PLAYER_PAD_LENGTH = 100 PLAYER_PAD_SPEED = 10 PLAYER_PAD_WIDTH = 10 BALL_RADIUS = 6 ### game variables ## player scores p1_score = 0 p2_score = 0 ## ball speed is split into x and y axes ball_speed_x = 5 ball_speed_y = 5 ## ball coordinates ball_x = 400 ball_y = 300 ## player pad y's p1_pad_y = 300 p2_pad_y = 300 ## player move flags p1_move_up = False p1_move_down = False p2_move_up = False p2_move_down = False ### main game loop while (True): ## detect and process key events # keydowns and keyups raise and lower player move flags for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == P1_UP: p1_move_up = True p1_move_down = False elif event.key == P1_DOWN: p1_move_down = True p1_move_up = False elif event.key == P2_UP: p2_move_up = True p2_move_down = False elif event.key == P2_DOWN: p2_move_down = True p2_move_up = False elif event.type == pygame.KEYUP: if event.key == P1_UP: p1_move_up = False elif event.key == P1_DOWN: p1_move_down = False elif event.key == P2_UP: p2_move_up = False elif event.key == P2_DOWN: p2_move_down = False elif event.type == pygame.QUIT: exit() ## move player…
type: Question

http://stackoverflow.com/comment/81860080
comment on: http://stackoverflow.com/a/47444959
has text: It doesn't plot the last few days it seems as it only seems to cover full weeks. Also, how do you get the y axis range to be the same for each graph? I tried adding `plt.ylim([0,10])` in the loop but that didn't work well.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47475419
has comment: http://stackoverflow.com/comment/81908747
accepted answer of: http://stackoverflow.com/q/47475331
has comment: http://stackoverflow.com/comment/81909414
has body: Using broadcasting and some masking - def extract_rows(arr, first, second, fillval=0): # Define the extent of output array L = (second.clip(max=arr.shape[1]-1) - first).max() # Get the ranged indices to cover the extent of cols for all rows idx = first[:,None] + range(L) # Now, the inices that are bounded by the limit of second values are to be # set as fillval. Similarly, the indices that go beoyn the extent of column # length of the input array are invalid as well. So, get the combined mask. invalid_mask = (idx &gt;= arr.shape[1]) | ((second - first)[:,None] &lt;= range(L)) # Set invalid places in idx as zeros or just any value, but make sure those # are indexable into input array idx[invalid_mask] = 0 # Finally index into input array with those and set the invalid ones in it # with fillval. return np.where(invalid_mask, fillval, arr[np.arange(len(idx))[:,None], idx]) Sample run - 1] Input array : In [639]: arr Out[639]: array([[87, 83, 36, 30, 58, 35, 85, 87], [17, 58, 51, 39, 56, 27, 97, 26], [33, 45, 1, 90, 87, 49, 30, 37], [92, 29, 17, 9, 81, 35, 47, 33], [61, 87, 22, 44, 97, 43, 96, 66], [47, 67, 28, 74, 50, 93, 22, 19], [77, 82, 35, 51, 25, 29, 25, 29], [95, 24, 70, 70, 34, 35, 50, 53], [53, 64, 84, 46, 21, 89, 44, 52], [92, 78, 21, 53, 53, 39, 7, 59]]) 2] Input start, stop indices per row : In [640]: np.c_[first, second] Out[640]: array([[ 0, 1], [ 0, 6], [ 2, 3], [ 3, 12], [ 2, 8], [ 2, 4], [ 4, 12], [ 0, 0], [ 2, 7], [ 4, 6]]) 3] Output array : In [652]: extract_rows(arr, first, second) Out[652]: array([[87, 0, 0, 0, 0, 0], [17, 58, 51, 39, 56, 27], [ 1, 0, 0, 0, 0, 0], [ 9, 81, 35, 47, 33, 0], [22, 44, 97, 43, 96, 66], [28, 74, 0, 0, 0, 0], [25, 29, 25, 29, 0, 0], [ 0, 0, 0, 0, 0, 0], [84, 46, 21, 89, 44, 0], [53, 39, 0, 0, 0, 0]])
has comment: http://stackoverflow.com/comment/81905777
score: 3
answers question: http://stackoverflow.com/q/47475331
upvote count: 3
has comment: http://stackoverflow.com/comment/81905688
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81908802
has comment: http://stackoverflow.com/comment/81906006
has comment: http://stackoverflow.com/comment/81908297
has comment: http://stackoverflow.com/comment/81909283
has comment: http://stackoverflow.com/comment/81905551
has comment: http://stackoverflow.com/comment/81908669
type: Answer

http://stackoverflow.com/a/47429621
has body: To 1) Yes, obviously there is "Go to definition" functionality. Otherwise the menu entry wouldn't make any sense, would it? If no definition was found that means vscode does not have any information about this part, which can have several reasons (e.g. the source code or at least a typings file for that is not available). It seems obvious but for completeness let me say: "Go to definition" functionality must be provided by an extension for that language. Hence you need one that generates that info for vscode. To 2) No, we cannot recommend any software here. This is off-topic for Stackoverflow. Use the extension search in vscode and see what's available. Often there is more than one extension for a given language and you can try out what works best for you.
type: Answer
answers question: http://stackoverflow.com/q/47400816
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81842911

http://stackoverflow.com/comment/81808737
has text: I'd ask a new question for that.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47426033

http://stackoverflow.com/comment/82019388
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47529066
score: 0
has text: Could be due to the small number of input data may be.

http://stackoverflow.com/comment/81817627
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47431544
has text: OP said samething about regular expressions, so it's probably more like `[re.matches(k, v) for ...]` but the idea is the same.
type: Comment

http://stackoverflow.com/q/47452107
tagged with: heroku
score: 0
answer count: 1
tagged with: selenium
tagged with: google-chrome
type: Question
has answer: http://stackoverflow.com/a/47467112
type: UnansweredQuestion
has body: I added the following heroku-buildpack: google-chrome an heroku-buildpack-chromedriver Then I set the environment variables GOOGLE_CHROME_BIN = /app/.apt/opt/google/chrome/chrome GOOGLE_CHROME_SHIM = /app/.apt/usr/bin/google-chrome-stable And I get the folowing message: Exception Type: WebDriverException Exception Value: Message: unknown error: cannot find Chrome binary (Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 3.13.0-133-generic x86_64) Exception Location: /app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py in check_response, line 194 I am struggle with it and dont know what am I doing wrong? And how do I know if I set the path of the variable correctly?
tagged with: python
has title: Heroku unknown error: cannot find Chrome binary

http://stackoverflow.com/comment/81966637
comment on: http://stackoverflow.com/a/47503395
type: Comment
has text: If you answer my key question "How to set learning rate in log scale", I will accept this as an answer. I had a look on the API and believe there is no such function in Tensorflow, so is it possible to define something like math functions to have our custom learning rate? If so, how?
score: 0
type: AnswerComment

http://stackoverflow.com/q/47406700
tagged with: rating
tagged with: ranking
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91446028
downvote count: 0
has body: why is it that a random population with random winners, the scores slowly drift to 0. I get that the scores might be random, but why always drift negatively? import trueskill as ts from random import choice r = [] for i in range(10): r.append(ts.Rating()) def avg(r): ratings = [(a.mu, a.sigma) for a in r] mus = list(zip(*ratings))[0] sigmas = list(zip(*ratings))[1] avg_mu = sum(mus) / float(len(mus)) avg_sigma = sum(sigmas) / float(len(sigmas)) return avg_mu, avg_sigma for j in range(20000): p1_ix = choice(range(len(r))) p2_ix = choice(range(len(r))) p1 = r[p1_ix] p2 = r[p2_ix] r[p1_ix], r[p2_ix] = ts.rate_1vs1(p1, p2) if not j % 1000: print(avg(r))
answer count: 1
accepted answer: http://stackoverflow.com/a/47603022
has title: Python Trueskill (ELO) scores drift down
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47603022

http://stackoverflow.com/comment/81740120
type: QuestionComment
has text: It works the same with / or without defaults. :( DateTime.now sets automatically after Getting checking completes.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47393433

http://stackoverflow.com/a/47532856
has body: Here's a vectorized output - def unique_pairs(von_knoten, zu_knoten): s = np.max([von_knoten, zu_knoten])+1 p1 = zu_knoten*s + von_knoten p2 = von_knoten*s + zu_knoten p = np.maximum(p1,p2) sidx = p.argsort(kind='mergesort') ps = p[sidx] m = np.concatenate(([True],ps[1:] != ps[:-1])) sm = sidx[m] return von_knoten[sm],zu_knoten[sm] Sample run - In [417]: von_knoten = np.array([0, 0, 1, 1, 1, 2, 2, 2, 3, 4]) ...: zu_knoten = np.array([1, 2, 0, 2, 3, 0, 1, 4, 1, 2]) In [418]: unique_pairs(von_knoten, zu_knoten) Out[418]: (array([0, 0, 1, 1, 2]), array([1, 2, 2, 3, 4]))
answers question: http://stackoverflow.com/q/47531532
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/81841916
comment on: http://stackoverflow.com/a/47443327
type: AnswerComment
has text: @chribis : You should be careful while writing the questions and you shouldn't be changing the *basic requirement* of the question once you have the answers to it. It marks existing answers invalid answer. For example: I just got two down-votes because you changed your question :/ PS: I have updated the answer to match your desired result
type: Comment
score: 2

http://stackoverflow.com/comment/81804236
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47424593
has text: Thanks i get the right shape after that but i have another error TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles.

http://stackoverflow.com/q/47439310
tagged with: nao-robot
score: 1
has answer: http://stackoverflow.com/a/47543056
upvote count: 1
favorite count: 0
type: Question
answer count: 2
has title: Getting data value from ALMemory using JS
accepted answer: http://stackoverflow.com/a/47543056
has answer: http://stackoverflow.com/a/47452872
possible better answer: http://stackoverflow.com/a/47452872
downvote count: 0
tagged with: javascript
tagged with: python
type: AnsweredQuestion
has body: When I try to get data from ALMemory with the following code: session.service("ALMemory").done(function (ALMemory) { var value = ALMemory.getData("ALTextToSpeech/TextDone"); }); This value is of type AL::ALValue. How can I cast it to int, because in this case it is expected to be 0 for currently speaking and 1 for currently not speaking. I have tried to cast it to int or to number or to string with different methods, but with no success. When I am using this functionality with python SDK: def onLoad(self): self.memory = ALProxy("ALMemory") def onUnload(self): self.memory = None def onInput_checkIfSpeaking(self, p): value = self.memory.getData("ALTextToSpeech/TextDone") this value is of type int, not AL::ALValue. Is that possible to be achieved with JavaScript?
tagged with: pepper

http://stackoverflow.com/comment/81875380
type: AnswerComment
has text: I guess you mean `np.loadtxt("file.txt").reshape(-1,3)`
comment on: http://stackoverflow.com/a/47460351
score: 1
type: Comment

http://stackoverflow.com/comment/81830373
type: AnswerComment
has text: It worked! Had to change "items" to table name.. Many thanks man!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47437133

http://stackoverflow.com/q/47390161
upvote count: 1
tagged with: python
has body: I have been trying to write a program to automate my work. My task has series of steps but I am stuck at one point. I am constantly getting NoSuchElementException. I have tried to use id, class, name methods of Selenium but nothing seems to work. My present code is this: from selenium import webdriver from selenium.webdriver.common.by import By browser = webdriver.Chrome('C:\\Users\\abc\\AppData\\Local\\Programs\\Python\\Python36\\chromedriver.exe') browser.get("http://example.com/login.aspx") usernameElem = browser.find_element_by_id('txtuser') usernameElem.send_keys('admin') passwordElem = browser.find_element_by_id('txtpassword') passwordElem.send_keys('password') loginElem = browser.find_element_by_id('btn_login') loginElem.click() # follows the "Read It Online" link browser.get("http://example.com/Reports.aspx") subscriberslistElem = browser.find_element_by_id('ContentPlaceHolder1_rptDC_lnk_0') subscriberslistElem.click() browser.implicitly_wait(3) entityElem = browser.find_element_by_id("report_Entity_ClientState") print("Test") entityElem.send_keys('Entity1') browser.implicitly_wait(3) reportElem = browser.find_element_by_class_name('selectbox') print("Test 2") reportElem.click() showdataElem = browser.find_element_by_id('btn_new') showdataElem.click() excelElem = browser.find_element_by_id('imgExport') excelElem.click() print('All is well') Link to webpage, complete files. It's strange that when I opened HTML file online as code and searched 'report_Entity_ClientState' there were no results. Images of elements I am trying to access: First element. Second element. Both the entity and report element are not found. Following parts of code return error. entityElem = browser.find_element_by_id("report_Entity_ClientState") reportElem = browser.find_element_by_class_name('selectbox') entityElem.send_keys('Entity1') browser.implicitly_wait(3) HTML code of elements: select ALL SPCG0033 Report Type Total Subscriber List Subscriber List with Active Package
has comment: http://stackoverflow.com/comment/81736096
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/47394364
has comment: http://stackoverflow.com/comment/81734074
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47394364
has comment: http://stackoverflow.com/comment/81734236
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/81733452
favorite count: 0
possible better answer: http://stackoverflow.com/a/47427801
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47427801
has title: Using Selenium to find elements related to drop down list from another frame -- Python
downvote count: 0

http://stackoverflow.com/q/47484639
type: Question
has title: pyparsing how to SkipTo end of indented block?
has comment: http://stackoverflow.com/comment/81984365
has answer: http://stackoverflow.com/a/47492383
downvote count: 0
has body: I am trying to parse a structure like this with pyparsing: identifier: some description text here which will wrap on to the next line. the follow-on text should be indented. it may contain identifier: and any text at all is allowed next_identifier: more description, short this time last_identifier: blah blah I need something like: import pyparsing as pp colon = pp.Suppress(':') term = pp.Word(pp.alphanums + "_") description = pp.SkipTo(next_identifier) definition = term + colon + description grammar = pp.OneOrMore(definition) But I am struggling to define the next_identifier of the SkipTo clause since the identifiers may appear freely in the description text. It seems that I need to include the indentation in the grammar, so that I can SkipTo the next non-indented line. I tried: description = pp.Combine( pp.SkipTo(pp.LineEnd()) + pp.indentedBlock( pp.ZeroOrMore( pp.SkipTo(pp.LineEnd()) ), indent_stack ) ) But I get the error: ParseException: not a subentry (at char 55), (line:2, col:1) Char 55 is at the very beginning of the run-on line: ...will wrap\n on to the next line... ^ Which seems a bit odd, because that char position is clearly followed by the whitespace which makes it an indented subentry. My traceback in ipdb looks like: 5311 def checkSubIndent(s,l,t): 5312 curCol = col(l,s) 5313 if curCol &gt; indentStack[-1]: 5314 indentStack.append( curCol ) 5315 else: -&gt; 5316 raise ParseException(s,l,"not a subentry") 5317 ipdb&gt; indentStack [1] ipdb&gt; curCol 1 I should add that the whole structure above that I'm matching may also be indented (by an unknown amount), so a solution like: description = pp.Combine( pp.SkipTo(pp.LineEnd()) + pp.LineEnd() + pp.ZeroOrMore( pp.White(' ') + pp.SkipTo(pp.LineEnd()) + pp.LineEnd() ) ) ...which works for the example as presented will not work in my case as it will consume the subsequent definitions.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81981816
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/2940489
tagged with: pyparsing
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81935912
has comment: http://stackoverflow.com/comment/81934587
has comment: http://stackoverflow.com/comment/81992169
tagged with: python
has comment: http://stackoverflow.com/comment/81937688
has comment: http://stackoverflow.com/comment/81937664

http://stackoverflow.com/q/47485638
has comment: http://stackoverflow.com/comment/81926078
has comment: http://stackoverflow.com/comment/82047167
accepted answer: http://stackoverflow.com/a/47485944
has comment: http://stackoverflow.com/comment/81926154
answer count: 1
has title: Similarities between both strings
has answer: http://stackoverflow.com/a/47485944
tagged with: string
linked to: http://stackoverflow.com/q/2460177
has comment: http://stackoverflow.com/comment/81927092
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81926116
upvote count: 2
has comment: http://stackoverflow.com/comment/82025474
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82023951
has body: I am trying to compare the similarities between 2 strings. I did it successfully by import SequenceMatcher The result should only return 3 possibilities, i) Good which means second string contains in the first string. Eg: smack and mac ii) Almost good which means part of second string contained in first string. Eg: smack and smart . Both are 60% similar and should be classified as almost good. iii)Bad which means none of the elements in second string contained in first string. Eg:smack and van However, If I would like to perform the same task without importhing SequenceMatcher, how will I be able to perform it? I am stuck at writing an algorithm to slice the strings and compare it with another. Also, is there anyways to define the algorithm SequenceMatcher? Here's a link to my code Sa=input('enter something A: ') Sb=input('enter something B: ') Sc=Sa.lower() Sd=Sb.lower() from difflib import SequenceMatcher if Sd in Sc or SequenceMatcher(a=Sc,b=Sd).ratio() ==1: print('Good') if Sd not in Sc and 0&lt;SequenceMatcher(a=Sc,b=Sd).ratio() &lt;1: print('Almost Good') if SequenceMatcher(a=Sc,b=Sd).ratio() ==0: print('Bad') Much appreciated!
has comment: http://stackoverflow.com/comment/81926122
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/81878792
has text: check "isin" http://pandas-docs.github.io/pandas-docs-travis/generated/pandas.DataFrame.isin.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47461927
score: 0

http://stackoverflow.com/comment/81818107
has text: And pay attention to singular/plural...
comment on: http://stackoverflow.com/q/47431178
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81878235
comment on: http://stackoverflow.com/q/47461480
has text: Nevermind I realized how dumb this question is.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47480641
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81916773
type: Answer
has body: I got the same errors that you did. First, I had to move line 4 after "file" is defined, or, in this case, "f". Then, the second error was the syntax of the print command. If you place a comma before timestr, it should print fine. The third problem was that I was getting permission denied, apparently from trying to open a whole directory. I have rewritten some of your script to something that I think better suits your needs. import glob import time import os timestr = time.strftime("%Y%m%d_%H%M%S") files = glob.glob('*.*') for file in files: print('created: %s' % time.ctime(os.path.getctime(file)), timestr) print('last modified: %s' % time.ctime(os.path.getmtime(file)), timestr) However, seeing your first posted example, I thought I could modify this to match it. Here's what I came up with: import glob import time import os files = glob.glob('*.*') print(' created modified file_name') for file in files: print('%s' % time.strftime("%Y%m%d_%H%M%S", time.gmtime(os.path.getctime(file))), end=' ') print('%s' % time.strftime("%Y%m%d_%H%M%S", time.gmtime(os.path.getmtime(file))), end=' ') print(file) Running it gave me: created modified file_name 20170723_223307 20170723_223307 36e73b41-4366-4bf8-825f-9f16e41b1b41.tmp 20160928_232029 20171116_081039 desktop.ini 20171124_215147 20171124_215413 help.py 20171124_215637 20171124_221613 help2.py 20171124_214353 20171124_214353 test.txt Now, it's just a matter of you getting the parameters on the right places and configuring the print commands to suit your exact needs. Edit: With the request to extract EXIF data, the code looks like this. Forgive the blank except. import glob import time import os from PIL import Image files = glob.glob('*.*') print(' created modified EXIF file_name') for file in files: print('%s' % time.strftime("%Y:%m:%d %H:%M:%S", time.gmtime(os.path.getctime(file))), end=' ') print('%s' % time.strftime("%Y:%m:%d %H:%M:%S", time.gmtime(os.path.getmtime(file))), end=' ') try: print('%s' % Image.open(file)._get…
accepted answer of: http://stackoverflow.com/q/47479661
has comment: http://stackoverflow.com/comment/81916339
answers question: http://stackoverflow.com/q/47479661
score: 1

http://stackoverflow.com/comment/82009907
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47495342
has text: Hello Kootstra! Using the .yaml format would solve the problem if all my variables were contained in a single .yaml file, so I accepted the answer. But still, the problem is like this: I have multiple files with the same variable names, and these variables names must be the same, only their values are different. For the sake of practicality I can't put all the data in a single .yaml file repeating all variables for each 'Set' (as in your example) and just changing its value, because this file would be HUGE in the future and difficult to maintain.

http://stackoverflow.com/q/47481929
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81919753
has comment: http://stackoverflow.com/comment/81919145
score: 0
answer count: 0
has body: Here's a question... how to update the statusbar (OSX) quickly for a few seconds of network access, using PyQt5. It's mainly for show, but you know how that goes. Here's the code in question: def process_item(rownumber): window.statusBar().showMessage("Server Activity...") QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) message = [] # item_name = Listing[rownumber] # setup message to message.append("rename") # TCP server message.append(item_name) # retval = joe_sender.sendmessage(message) # TCP send app_data = retval # TCP return QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor)) window.statusBar().showMessage("") There's a few seconds of "dead time" while the data goes back and forth to a simple TCP server on a remote machine. I wanted to get the status bar to say "Network access" or something similar during this time, but the change doesn't take effect until about 80% of the delay is done. Is there any way I can speed this up, making it take effect instantly? As it is now, it changes and changes back faster than you can see it. I've tried a call to window.update() but that had no effect. Any ideas?
tagged with: pyqt5
has title: Brief statusbar change during network access
tagged with: macos
type: Question

http://stackoverflow.com/a/47527669
has body: I think you have to find first positive value and use its position as rows EDIT: I changed name count to last to make it more readable # --- function --- def move(data): rows = len(data) # - find positive - for x in range(rows): if data[x][-1] &gt; 0: rows = x # use its position as `rows` break # don't seach other positiove values # - star moving - # set "last" checked row last = rows-1 # check "last" row if data[last][-1] == 0: # move previous values while last &gt; 0: data[last][-1] = data[last-1][-1] last -= 1 # put 0 in first place data[0][-1] = 0 # --- tests --- examples = [ { # Condition 1 - Works 'data': [[0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0], [0, 0, 0]], 'expected': [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0]], # My Results. }, { # Condition 2 - Works 'data': [[0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3], [0, 0, 0]], 'expected': [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]], # This is what I want to get. (But it doesn't work) } ] for example in examples: data = example['data'] expected = example['expected'] print(' before:', data) move(data) print(' after:', data) print('expected:', expected) print(' correct:', data == expected) print('---') Result: before: [[0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0], [0, 0, 0]] after: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0]] expected: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0]] correct: True --- before: [[0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3], [0, 0, 0]] after: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]] expected: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]] correct: True --- EDIT: BTW: instead of while you can use for with reversed range() if it makes it more readable def move(data): rows = len(data) # - find positive - for x in range(rows): if data[x][-1] &gt; 0: rows = x # use its position as `rows` break # don't seach other positiove values # - star moving - # set "last" checked row last = rows-1 # check "last" row if …
upvote count: 2
answers question: http://stackoverflow.com/q/47525815
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82013423
has comment: http://stackoverflow.com/comment/82022341
has comment: http://stackoverflow.com/comment/82012970
score: 2
has comment: http://stackoverflow.com/comment/82023619
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47525815

http://stackoverflow.com/a/47537882
has body: Well first of all you can immediately start to break your problem down into several smaller, more manageable chunks of work. You have a number of assumed operations in this. You will be searching, comparing, extracting and writing to disk. Unfortunately based on the information provided searching will be the most inefficient part of the solution. You will have to analyse two sets of data. You should start by writing functions to handle this rather than attack the problem head on. Divide and conquer! def scan_log_file(file, search_term): # Scan over the given input and determine if the search term is present .... # Your implementation here def extract_host(data): # Return your host address from the input data ... return address def extract_message_id(data): # given a line that may include the message id, search it ... return message_id def write_file_data(filename, data): # Here you append data to the file you want ... So getting to actually searching the file data. You could use regular expressions to achieve this nicely. If you are not familiar with them, now is a great time to get to know them. They are a super useful in your tool belt. For example you can look up your message ids using something like so: import re results = re.search('address (\d\.\d.\d.\d)') results.group(0) # get the first accepted group, i.e the host address You can iterate over your first data set, extract message ids, then perform a scan on your second set, extract the host address, write the comparison of the first set to the file finaloutput.txt, write the host address to file host_results.txt. That's a fairly naive implementation. It should however get you started. I am not sure how large your files may eventually become but I would also suggest looking into generators for reading the log files bit by bit in smaller streams rather than bulk loading huge data sets into memory But much like the existing comments. There could be optimizations made from assumptions about your data. Is it pred…
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82110946
answers question: http://stackoverflow.com/q/47537226
type: Answer
has comment: http://stackoverflow.com/comment/82111046
accepted answer of: http://stackoverflow.com/q/47537226

binary
tags question: http://stackoverflow.com/q/47426198
tags question: http://stackoverflow.com/q/47483687
tags question: http://stackoverflow.com/q/47508803
tag name: binary
tags question: http://stackoverflow.com/q/47536336
tags question: http://stackoverflow.com/q/47463826
tags question: http://stackoverflow.com/q/47516877
tags question: http://stackoverflow.com/q/47515103
tags question: http://stackoverflow.com/q/47413640
type: Tag
tags question: http://stackoverflow.com/q/47536131

http://stackoverflow.com/comment/81933483
type: Comment
type: QuestionComment
has text: @furas r_ingredients_wtht_tags is a list. So you are saying I generate another list of all the four items and write that as a row. Didn't cross my mind but let me try it. '\n' was an attempt to add a new line after each item in r_ingredients_wtht_tags. Should not even be there.
comment on: http://stackoverflow.com/q/47488938
score: 0

http://stackoverflow.com/q/47443685
has answer: http://stackoverflow.com/a/47443744
has answer: http://stackoverflow.com/a/47443753
has body: When defining a class in Python 2.7, you feed in variables to an init() function, then assign these to instance variables using e.g self.x class NewClass(object): def __init__(self, x, y): self.x = x self.y = y If using a large number of variables, is there a way to simplify this process i.e. not have to explicitly define each instance variable? Or is there a good reason why they are explicitly defined?
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: Is there a simple way of assigning instance variables in a Python class?
answer count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/47443744
downvote count: 1
has comment: http://stackoverflow.com/comment/81842606
has comment: http://stackoverflow.com/comment/81842724
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47443792
accepted answer: http://stackoverflow.com/a/47443792
has comment: http://stackoverflow.com/comment/81842471
has comment: http://stackoverflow.com/comment/81842502
tagged with: python

group-by
tags question: http://stackoverflow.com/q/47435537
tags question: http://stackoverflow.com/q/47383540
tags question: http://stackoverflow.com/q/47512234
tags question: http://stackoverflow.com/q/47494720
tag name: group-by
tags question: http://stackoverflow.com/q/47527957
type: Tag
tags question: http://stackoverflow.com/q/47434426

http://stackoverflow.com/a/47458153
accepted answer of: http://stackoverflow.com/q/47457279
type: Answer
answers question: http://stackoverflow.com/q/47457279
score: 2
has comment: http://stackoverflow.com/comment/81927775
upvote count: 2
has comment: http://stackoverflow.com/comment/81871363
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81871399
has body: Try to follow this steps: Let's say that this is your directory: project_folder ├── app_1 ├── app_2 ├── static │ ├── css │ │ ├── bootstrap.css │ ├── fonts │ └── js ├── templates In your settings.py file you have to specify the path to the folder with static files named static in my example: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] Than in any of your html file you can load boostrap.css file like that: {% load static %} &lt;!DOCTYPE html&gt; &lt;html lang="en" xmlns="http://www.w3.org/1999/html"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;&lt;/title&gt; &lt;link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt;
has comment: http://stackoverflow.com/comment/81875428
has comment: http://stackoverflow.com/comment/81901578
has comment: http://stackoverflow.com/comment/81877043

http://stackoverflow.com/q/47401709
score: 0
has title: Create a django model for a table imported externally
accepted answer: http://stackoverflow.com/a/47401792
answer count: 1
has answer: http://stackoverflow.com/a/47401792
has body: I am new to django, so please excuse if I am totally wrong. I have a django installation in which some tables are manually imported from outside source. There is one table with large number of fields. In my current django I need to interact with only few of its fields. Can I create a django model for that table with just the fields I need and will it work? Will it mess up migrations completely? How is such a situation usually handled in django?
type: Question
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/81950453
comment on: http://stackoverflow.com/q/47497309
has text: hopefully this helps: https://stackoverflow.com/questions/8971243/free-tool-for-watching-coordinates-in-pdf
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47493955
type: AnsweredQuestion
score: 0
has body: I'm having two problems with arguments in my program, the first problem is that I'm trying to print an error if no arguments are passed to the program and also I'm trying to instead having to use -n which stands for 'no argument' to actually not have to pass any argument to load the file into the program, I want it to just run like python3 program.py file file2 file3 instead of using python3 -n file file2 file3 etc.. I have commented out what I tried to check for the argument if the argument is just the program file [0] to exit def main(): script = sys.argv[0] action = sys.argv[1] noargfile = sys.argv[1:] filenames = sys.argv[2:] OutContent = filenames or noargfile #Load files with arguments -d &amp; --default print("Loading Files....", sys.argv[1:]) for arg in filenames: try: myfile = open(arg, "r") fileContent = myfile.readlines() myfile.close() OutContent = OutContent + fileContent #if len(sys.argv) == script: #print("No Argument") #sys.exit(0) if action == '--default': counter = 0 # set a counter to 0 for line in OutContent: #for each line in load if the " 200 " is found add 1 to the counter and repeat until done. if re.findall(r"\s\b200\b\s", line): counter += 1 print("\nTotal of (Status Code) 200 request:", counter) elif action == '-d': counter = 0 # set a counter to 0 for line in OutContent: #for each line in load if the " 200 " is found add 1 to the counter and repeat until done. if re.findall(r"\s\b200\b\s", line): counter += 1 print("\nTotal of (Status Code) 200 request:", counter) elif action == '-n': menu(arg, OutContent) except OSError: print("File could not be opened " + filenames) if __name__ == "__main__": main() I get an index out of range error, I don't understand why File "program.py", line 161, in main action = sys.argv[1] IndexError: list index out of range
accepted answer: http://stackoverflow.com/a/47494058
has comment: http://stackoverflow.com/comment/81942935
tagged with: python
has title: Check for empty argument Python
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47494080
answer count: 2
has answer: http://stackoverflow.com/a/47494080
tagged with: sys
has comment: http://stackoverflow.com/comment/81942957
has answer: http://stackoverflow.com/a/47494058
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/81997946
score: 0
has text: See my comment above; you can just tell max to use "key=len" and skip all that.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47520688

http://stackoverflow.com/comment/81773735
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47409569
has text: it work, but I dont get value. cause I use the radio button if I click I get the value, If I click the radiobutton will get the value in backend. any solution?
score: 0

http://stackoverflow.com/comment/81985091
has text: More than a non-clean solution this seems just brutal
comment on: http://stackoverflow.com/a/47514673
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82049277
has text: Yep but it's outside of the scope of this question and these comments now, as that is general python knowledge. I would recommend taking a python course.
type: AnswerComment
comment on: http://stackoverflow.com/a/47425473
type: Comment
score: 0

http://stackoverflow.com/comment/81754552
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ, so which column should I use here to train my model ? A little brief answer from your end would help me please
type: QuestionComment
comment on: http://stackoverflow.com/q/47400357
score: 0

relative-path
type: Tag
tags question: http://stackoverflow.com/q/47532500
tag name: relative-path

http://stackoverflow.com/q/47432432
answer count: 0
tagged with: amazon-s3
tagged with: amazon-ec2
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: Accessing the zip file in S3 from EC2 instance using boto3 package in Python
has body: Please find the code snippet I need to access a zip file in S3 and access the files in the zip file for further processing Code Snippet Option 1:Live connection and reading the file content Issue: Memory leak s3_resource = boto3.resource('s3', aws_access_key_id = 'XXXXXXX', aws_secret_access_key = 'XXXXX') file = s3_resource.Object('xxxxxx',filePath).get() with io.BytesIO(file['Body'].read()) as t: t.seek(0) with ZipFile(t, 'r') as myzip: Option 2:Download the file to a temp file Issue: The process cannot access the file because it is being used by another process:(at line file=s3.download_file('bucket','filename', f.name) f = tempfile.TemporaryFile(delete=False) print(f) s3 = boto3.client('s3', aws_access_key_id = 'xxxxx', aws_secret_access_key = 'jxxx') file=s3.download_file('bucket','filename', f.name) with ZipFile(f.name, 'r') as myzip: print('done') Please let me know the efficient way of handling this issue
type: UnansweredQuestion
tagged with: python

github
tags question: http://stackoverflow.com/q/47411740
tags question: http://stackoverflow.com/q/47392105
tag name: github
type: Tag
tags question: http://stackoverflow.com/q/47425528
tags question: http://stackoverflow.com/q/47521113
tags question: http://stackoverflow.com/q/47494410
tags question: http://stackoverflow.com/q/47510845

http://stackoverflow.com/comment/81999171
has text: hello. how do you create the m variable? can you add the full code and some data ? e.g. the specific frame that causes the error ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47521116
type: QuestionComment

http://stackoverflow.com/comment/81787539
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47403110
has text: Thanks so much for your help. But, What I meant is that for example in the picture that I just added in the edited version of my question, "I" is the prediction that goes to the next level. But while training shouldn't we feed the next time step with ground truth and not the prediction? I'm sorry my question was vague
type: AnswerComment

http://stackoverflow.com/q/47497316
tagged with: dictionary
has body: I have a dictionary, this is a example dict it can have any number of fields {'name': 'satendra', 'occupation': 'engineer', 'age': 27} How can i convert this to tuple so that it will result ordered list of tuple. # Expected output [('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)] UPDATE OrderedDict are useful when ordered list of tuple passed to it not for a JSON object, so i guess this is not a duplicate
has comment: http://stackoverflow.com/comment/81949916
has comment: http://stackoverflow.com/comment/81950006
duplicate of: http://stackoverflow.com/q/15711755
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47497473
accepted answer: http://stackoverflow.com/a/47497473
has comment: http://stackoverflow.com/comment/81950034
answer count: 3
possible better answer: http://stackoverflow.com/a/47497484
has comment: http://stackoverflow.com/comment/81950070
has answer: http://stackoverflow.com/a/47497484
linked to: http://stackoverflow.com/q/44640015
has comment: http://stackoverflow.com/comment/81949952
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81950090
linked to: http://stackoverflow.com/q/15711755
has answer: http://stackoverflow.com/a/47497348
has comment: http://stackoverflow.com/comment/81949881
downvote count: 3
has comment: http://stackoverflow.com/comment/81949919
has title: Convert a dict to tuple preserving order
has comment: http://stackoverflow.com/comment/81949971
tagged with: python
score: -1

http://stackoverflow.com/a/47508951
has comment: http://stackoverflow.com/comment/81974109
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81973949
has comment: http://stackoverflow.com/comment/81973727
has comment: http://stackoverflow.com/comment/81974244
has comment: http://stackoverflow.com/comment/81974492
score: 0
has comment: http://stackoverflow.com/comment/81974622
has body: You've been bitten by De Morgan's laws. You need to use OR there, not AND. Here's a short demo derived from your code. import numpy as np img = np.random.choice([0, 255], size=(3, 4, 3), replace=True) print(img, '\n') b1, g1, r1 = 0, 0, 255 b2, g2, r2 = 0, 0, 0 # Separate the channels from image b, g, r = img[:, :, 0], img[:, :, 1], img[:, :, 2] mask = (b != b1) &amp; (g != g1) &amp; (r != r1) im = img.copy() im[:, :, :3][mask] = [b2, g2, r2] print(im, '\n') mask = (b != b1) | (g != g1) | (r != r1) im = img.copy() im[:, :, :3][mask] = [b2, g2, r2] print(im, '\n') typical output [[[ 0 0 255] [ 0 255 0] [255 255 255] [255 255 0]] [[ 0 0 0] [255 255 255] [255 255 255] [ 0 0 255]] [[255 0 0] [255 255 255] [255 255 0] [ 0 0 0]]] [[[ 0 0 255] [ 0 255 0] [255 255 255] [ 0 0 0]] [[ 0 0 0] [255 255 255] [255 255 255] [ 0 0 255]] [[255 0 0] [255 255 255] [ 0 0 0] [ 0 0 0]]] [[[ 0 0 255] [ 0 0 0] [ 0 0 0] [ 0 0 0]] [[ 0 0 0] [ 0 0 0] [ 0 0 0] [ 0 0 255]] [[ 0 0 0] [ 0 0 0] [ 0 0 0] [ 0 0 0]]]
answers question: http://stackoverflow.com/q/47508556
has comment: http://stackoverflow.com/comment/81974013
has comment: http://stackoverflow.com/comment/81974664
accepted answer of: http://stackoverflow.com/q/47508556

http://stackoverflow.com/q/47492136
has comment: http://stackoverflow.com/comment/81944209
accepted answer: http://stackoverflow.com/a/47528895
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81939686
has answer: http://stackoverflow.com/a/47528895
answer count: 2
has title: Scraping heirarchical data with Scrapy
has comment: http://stackoverflow.com/comment/81939739
upvote count: 0
tagged with: scrapy
downvote count: 1
favorite count: 0
type: Question
has body: The website I am trying to scrape has the following pages: A list of all books An info page of the book with all its chapters When you click a chapter, the first page will be displayed, and a drop-down of all the pages for that chapter will be available So far so good. I am able to scrape all the data I need, but the only problem is to reference a page to its chapter, or a chapter to its book. I've read about passing the book info to the meta like this: scrapy.Request(url=url, callback=self.parse_chapter, meta={book: book}) But I can't figure out how to reference them in my item pipeline. Any help?
possible better answer: http://stackoverflow.com/a/47531804
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47531804
has comment: http://stackoverflow.com/comment/81960804

http://stackoverflow.com/a/67372126
upvote count: 2
answers question: http://stackoverflow.com/q/47404653
downvote count: 0
has body: It looks this issue has been fixed in the future version of matplotlib. Try to run "pip install --upgrade matplotlib". I met the same issue "AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'". It was fixed when upgrade the package matplotlib.
type: Answer
score: 2

http://stackoverflow.com/q/47500129
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47500263
has comment: http://stackoverflow.com/comment/81955791
possible better answer: http://stackoverflow.com/a/47500263
downvote count: 0
has comment: http://stackoverflow.com/comment/81955901
has comment: http://stackoverflow.com/comment/81955691
has body: I have xml string below and trying to print text between tags domain, receive_time , serial and seqno for each entry tag. xml=""" query job enqueued with jobid 19032 19032 19032 14:10:09 14:10:09 19:00:00 ACT 19032 64 1 <receive_time>2017/11/26 14:10:08</receive_time> 007901004140 10156449120 1 <receive_time>2017/11/26 14:10:08</receive_time> 007901004140 10156449120 """ using xml.etree.ElementTree. To get what's between domain tag I was trying node.attrib.get('domain') or node.get('domain')..please advise import xml.etree.ElementTree as ET tree = ET.fromstring(xml) for node in tree.iter('entry'): print node It can be other python library too, does not have to be xml.etree. I do not want to print text between tags blindly, I need to print tag name followed by text so i.e.: domain: 1 receive_time: 2017/11/26 14:10:08 serial: 007901004140 seqno: 10156449120 etc
linked to: http://stackoverflow.com/q/25218358
has answer: http://stackoverflow.com/a/47500262
tagged with: http://stackoverflow.com/tag/xml
type: Question
answer count: 2
has title: extract text between xml tags in python
score: 5
upvote count: 5
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47500262

http://stackoverflow.com/comment/81921100
type: QuestionComment
has text: Please explain your components in details.
type: Comment
comment on: http://stackoverflow.com/q/47483103
score: 0

http://stackoverflow.com/comment/81917080
has text: file_path=open('~/posNegLabel/20040921.csv', 'r')
comment on: http://stackoverflow.com/q/47479446
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47508990
has title: Can't find Python executable
downvote count: 0
has body: Error: Can't find Python executable "D:\Python", you can set the PYTHON env variable. at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:483:19) I do have python installed (2.7.14) in D:\Python, and I have setup the environment variables I also tried SET PYTHON=D:\Python. python command from command line works fine. python.exe is in D:\Python What am I doing wrong ?
answer count: 1
score: 6
favorite count: 0
type: Question
upvote count: 6
has answer: http://stackoverflow.com/a/47509836
accepted answer: http://stackoverflow.com/a/47509836
tagged with: python
tagged with: node.js
type: AnsweredQuestion

http://stackoverflow.com/comment/81744589
type: Comment
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/47395676
has text: Why not use `collections.Counter()`?

http://stackoverflow.com/q/47523179
has answer: http://stackoverflow.com/a/47523251
has comment: http://stackoverflow.com/comment/82002784
type: AnsweredQuestion
has body: So the assignment is to create a list of tuples that stores the date of the run, how long you ran, and how many miles you ran for that date. The program should continue to ask the user to input the information about running times until the user inputs "done". The output should be all of the tuples that were stored in the list called 'run_data'. Here is what I have: def data(date, time, distance): list1 = [(date, time, distance)] done = False while input == done: run_data = list1.append((date, time, distance)) def main(): d = input('input the date of your run in the form mmdd: ') t = input('input how long your run was in minutes: ') m = input('input the distance you ran in miles: ') running = data(d, t, m) print(running) main() I have no errors when it comes to inputting it, but after asking for the distance, it outputs none. I'm confused as to why it's outputting that and not sure where I went wrong. I would like to mention that I'm a beginner to using python so any help will be greatly appreciated. Thanks!
score: 0
tagged with: list
tagged with: while-loop
has comment: http://stackoverflow.com/comment/82002772
has title: How to store tuples and continue to ask the user to input more values until user inputs 'done'?
type: Question
tagged with: tuples
answer count: 2
possible better answer: http://stackoverflow.com/a/47523287
accepted answer: http://stackoverflow.com/a/47523251
tagged with: python
has answer: http://stackoverflow.com/a/47523287

http://stackoverflow.com/q/47536089
score: 0
tagged with: matplotlib
has body: I am attempting to develop a fairly general purpose graph using matplotlib but keep getting an error ValueError: left cannot be &gt;= right. My code is: def perf_plot(x, y, data, title = ''): import matplotlib.pyplot as plt import statsmodels.api as sm plt.style.use('ggplot') df = data if y == 'slope': z = 'bp01' else: z = 'slope' y = df[y].astype(float) x = df[x].astype(float) z = df[z].astype(float) blue = '#348EA9' orange = '#F48B37' green = '#52BA9B' red = '#EF4846' fig, ax1 = plt.subplots() fig.suptitle(title, fontsize=14, fontweight='bold') fig.subplots_adjust(top=0.85) ax1.scatter(x ,y, color = orange) lowess_y = sm.nonparametric.lowess(y, x ,frac=0.1) ax1.plot(lowess_y[:, 0], lowess_y[:, 1], color = blue) ax1.set_ylabel(y, color = blue) ax1.set_xlabel(x, color = 'b') ax2 = ax1.twinx() lowess_z = sm.nonparametric.lowess(z, x, frac=0.1) ax2.plot(lowess_z[:, 0], lowess_z[:, 1], color = green) ax2.set_ylabel(z, color = green) fig.tight_layout() plt.show() return After some googling, I found that this error is generally correlated with tight_layout() and the use of a title. Removing the title does not resolve the problem, but if I remove tight_layout the graph does print but both axis are placed on the left side of the graph. As the point is to do something like this, I am not really how to get the duel axis without tight_layout. Ideas? Error code: perf_plot(x_, y_, df1) Traceback (most recent call last): File "&lt;ipython-input-149-36ff57804093&gt;", line 1, in &lt;module&gt; perf_plot(x_, y_, df1) File "&lt;ipython-input-148-ef2f325b64f9&gt;", line 37, in perf_plot fig.tight_layout() File "C:\Users\user\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1755, in tight_layout self.subplots_adjust(**kwargs) File "C:\Users\user\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1620, in subplots_adjust self.subplotpars.update(*args, **kwargs) File "C:\Users\user\AppData\Local\Continuum\Anaconda2\lib\site-pa…
has comment: http://stackoverflow.com/comment/82030487
type: Question
has title: Python Matplotlib: General Purpose Graphing with Twinx()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82030714
answer count: 1
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47536832
has comment: http://stackoverflow.com/comment/82030375

one-to-many
tags question: http://stackoverflow.com/q/47536903
type: Tag
tag name: one-to-many

statistics
tags question: http://stackoverflow.com/q/47519029
tags question: http://stackoverflow.com/q/47496327
tags question: http://stackoverflow.com/q/47491303
tags question: http://stackoverflow.com/q/47534817
tags question: http://stackoverflow.com/q/47492722
tags question: http://stackoverflow.com/q/47446782
tag name: statistics
tags question: http://stackoverflow.com/q/47420403
tags question: http://stackoverflow.com/q/47449991
type: Tag

http://stackoverflow.com/q/47535669
has answer: http://stackoverflow.com/a/47538580
accepted answer: http://stackoverflow.com/a/47538580
score: 1
has comment: http://stackoverflow.com/comment/82028298
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82030276
tagged with: python
has title: Keras: void labeled pixels in image segmentation
favorite count: 0
type: Question
upvote count: 2
tagged with: image-segmentation
linked to: http://stackoverflow.com/q/46097968
tagged with: keras
type: AnsweredQuestion
has body: I currently have a keras-model that classifies each pixel as either belonging to object or background using a fully convolutional network. As I have only 2 classes (object or background) I am using a sigmoid activation in the output layer and binary_crossentropy loss. However, for several images I am unsure of what class some of the pixels belong to, therefore I would like to label these pixels as void such that the networks weights are not updated based on the prediction for these pixels. Is there a method for dealing with void labels in Keras? One way of doing this in general would be to specify loss weights for each pixel, and set the weight for void pixels to 0. (E.g. like this for tensorflow). I investigated using sample_weights in Keras, but I could not get that to work as it does not seem to be made for weighting pixels.

http://stackoverflow.com/comment/81803395
has text: I was concerned about static code analysis for python as python is `live` but vulture seems to be an interesting idea! But Apart from finding `unused` classes it would be interesting to see `least used` ones.
type: AnswerComment
comment on: http://stackoverflow.com/a/47424212
score: 0
type: Comment

http://stackoverflow.com/comment/81919143
comment on: http://stackoverflow.com/a/47482138
type: AnswerComment
score: 0
has text: yes, thank you @chepner
type: Comment

http://stackoverflow.com/q/47420141
has comment: http://stackoverflow.com/comment/81795029
favorite count: 0
has comment: http://stackoverflow.com/comment/81794474
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/81794609
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81794525
has comment: http://stackoverflow.com/comment/81794505
tagged with: python
tagged with: inheritance
has comment: http://stackoverflow.com/comment/81796584
has title: Why do we prefer to use self.method() instead of Class.method(self)
score: 2
has body: For example, for some class: class Class(object): def __init__(self): pass def something(self): # yes I know this could be static print("something") and instance instance = Class() the following are both technically valid: instance.something() # normal Class.something(instance) # but also technically valid Is there some explicit reasoning why the first use case is preferred? I can think of examples like iterating over instances and calling methods, but I can also think of some cases where it may be easier to interpret my code when explicit reference to the Class I am using is visible. Apologies if this has been answered before. I could not find it, which may be due to my difficulty in phrasing the question.
tagged with: oop
has comment: http://stackoverflow.com/comment/81796545
answer count: 1
has answer: http://stackoverflow.com/a/47420205

http://stackoverflow.com/comment/108559922
type: Comment
has text: I think I found my problem, when I do `print matplotlib.__version__` in my jupyter notebook I get the version `1.5.1`. So it means that my Jupyter notebook still sees an old version of the library
comment on: http://stackoverflow.com/a/47492708
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81827810
type: QuestionComment
comment on: http://stackoverflow.com/q/47436776
score: 2
has text: How do you run the code? Is this the **whole** code? Aren't you able to edit your question? @ElisByberi: you might have answered your own question.
type: Comment

http://stackoverflow.com/comment/81840444
comment on: http://stackoverflow.com/a/47442225
score: 0
type: AnswerComment
has text: @AhmetUluer. Can you please make sure you run the script in a console using `python script.py` (or if you're on windows, in a command window, using `python.exe script.py`). This should produce a traceback when the error happens.
type: Comment

http://stackoverflow.com/comment/81987136
score: 0
type: Comment
type: QuestionComment
has text: You're asking how to write to a file? Have you read any python tutorials? This is a pretty basic question with many, many examples on the internet.
comment on: http://stackoverflow.com/q/47512856

http://stackoverflow.com/q/47489836
type: Question
has answer: http://stackoverflow.com/a/71097690
upvote count: 8
has comment: http://stackoverflow.com/comment/81934833
has answer: http://stackoverflow.com/a/47489918
accepted answer: http://stackoverflow.com/a/47489918
tagged with: python
has title: convert emoji unicode to TEXT in python
type: AnsweredQuestion
has body: I have an application made in python (yowsup), I receive text and emoji in my bot... I manage to get the &#128512; to convert to "\U0001F600" code... now i need to convert u"\U0001F600" to :grinning: TEXT or GRINNING FACE got some source from this page.... http://www.fileformat.info/info/unicode/char/1F600/index.htm @signals.message_received.connect def handle(message): #message.log() to see message object properties #print(message.log()) params = {} params_upload = {} zapsend_host = config.config_variables['zapsend_host'] zapsend_port = config.config_variables['zapsend_port'] # CASE TEXT-MESSAGE AND NOT GROUP if helper.is_text_message(message.message_entity) and helper.isGroupJid(message.conversation) == False: #converted here.... params['msg'] = message.text.encode('unicode_escape') params['number'] = message.conversation params['whatsapp']= config.config_variables['user'] params['media'] = 'text' params['caption'] = '' params['name'] = message.who_name database_helper.sync_contacts(message.conversation, message.who_name) database_helper.save_message_receive(params, message) print("MSG FROM CLIENT: "+ message.conversation +" =&gt; " + params['msg']) requests_helper.request_get(zapsend_host, zapsend_port,'zapsend',params)
answer count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/81934936
score: 6
has answer: http://stackoverflow.com/a/51007945
has comment: http://stackoverflow.com/comment/81934853
tagged with: emoji
possible better answer: http://stackoverflow.com/a/51007945
favorite count: 0

http://stackoverflow.com/q/47494011
has title: Convert Python Script to Google Sheets Script
has comment: http://stackoverflow.com/comment/81943398
has comment: http://stackoverflow.com/comment/81943039
type: Question
tagged with: google-sheets-api
tagged with: python
has comment: http://stackoverflow.com/comment/81943074
has comment: http://stackoverflow.com/comment/81970632
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81943354
accepted answer: http://stackoverflow.com/a/47524181
has body: The following code block is a python script with added Google Sheets script method title and arguments. I would like to use this code in a Google Sheets custom script. function D20PROBS(INPUT1, INPUT2) { count=0 for i in range(1,21): for j in range(1,21): if i+INPUT1 &gt; j+INPUT2: count+=1 print(count) }
has answer: http://stackoverflow.com/a/47524181
score: 0
answer count: 1

http://stackoverflow.com/q/47476737
has comment: http://stackoverflow.com/comment/81908457
favorite count: 0
has body: I am making an id3 classifier using entropy for cost calculation, but when I am splitting categorical attributes I keep getting a TypeError: 'int' object is not subscriptable, when running the line: child = [x for x in records if x[attr_name] in a_i], in the method: split_categorical The dataset: sunny, 85, 85, false, No sunny, 80, 90, true, No overcast, 83, 78, false, Yes rain, 70, 96, false, Yes rain, 68, 80, false, Yes rain, 65, 70, true, No overcast, 64, 65, true, Yes sunny, 72, 95, false, No sunny, 69, 70, false, Yes rain, 75, 80, false, Yes sunny, 75, 70, true, Yes overcast, 72, 90, true, Yes overcast, 81, 75, false, Yes rain, 71, 80, true, No full code: import csv import math from statistics import median, mode from collections import Counter from enum import Enum class AttrType(Enum): cat = 0 # categorical (qualitative) attribute num = 1 # numerical (quantitative) attribute target = 2 # target label class NodeType(Enum): root = 0 internal = 1 leaf = 2 class SplitType(Enum): bin = 0 # binary split multi = 1 # multi-way split class Attribute(object): def __init__(self, label, type): assert type in AttrType self.label = label self.type = type self.stat = None # holds mean for numerical and mode for categorical attributes class Splitting(object): def __init__(self, attr, infogain, split_type, cond, splits): self.attr = attr # attribute ID (index in ATTR) self.infogain = infogain # information gain if splitting is done on this attribute self.split_type = split_type # one of SplitType self.cond = cond # splitting condition, i.e., values on outgoing edges self.splits = splits # list of training records (IDs) for each slitting condition class Node(object): def __init__(self, id, type, parent_id, children=None, edge_value=None, val=None, split_type=None, split_cond=None): self.id = id # ID (same as the index in DT.model list) self.type = type # one of NodeType self.parent_id = parent_id # ID of parent node (None if root) self.children = children # list of IDs of chil…
type: AnsweredQuestion
tagged with: python
score: -1
tagged with: list-comprehension
has title: Classification TypeError: 'int' object is not subscriptable
type: Question
upvote count: 0
tagged with: split
has answer: http://stackoverflow.com/a/47521236
accepted answer: http://stackoverflow.com/a/47521236
tagged with: classification
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81960689
has comment: http://stackoverflow.com/comment/81961537

http://stackoverflow.com/a/78878373
has body: I got solution on this. Object creation, add_axes and plot do in one cell you will get result.
score: 0
has comment: http://stackoverflow.com/comment/139123228
answers question: http://stackoverflow.com/q/47507830
type: Answer

http://stackoverflow.com/q/47510098
has body: I have been encountering a problem that I can't seem to solve I need to take a list of strings and calculate some values and then add the relevant string and the relevant integer to a numpy array. I've been told to create the numpy array of zeroes first as it will be of a known length so I can do that. My problem is how do I iteratively add each string to the first column (names) and each value (labels) to the second and then sort the full array alphabetically by the first column fileCount = sum([len(files) for r, d, files in os.walk(inputDirectory)]) labelArray = np.zeros(shape = (fileCount,2)) arrayInsertCounter = 0 for label, subDirectories in enumerate(inputDirectory): subDirPath = os.path.join(inputDirectory, subDirectories) for name in subDirPath: labelArray[arrayInsertCounter] = [name,label] arrayInsertCounter += 1
tagged with: python
has comment: http://stackoverflow.com/comment/81975970
has comment: http://stackoverflow.com/comment/81975877
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47510683
type: UnansweredQuestion
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/81975755
has title: Creating a numpy array and then sorting array
has comment: http://stackoverflow.com/comment/81975937
tagged with: sorting
score: 0
has comment: http://stackoverflow.com/comment/81975777

http://stackoverflow.com/a/47413664
has body: You can do this: In [5]: s = slice(2, None) In [6]: target[s] Out[6]: 'abc' In [7]: df.query('B == @target[@s]') Out[7]: A B 2 2 abc But really, why not just df_ss2 = df.query('B == "%s"' % target[2:]) (or variations using format specifiers or f-strings)? Pushing any calculation into the string to make it implicitly evaluated rather than explicitly evaluated will have a lot of downsides, but I can't see many upsides besides syntactic sugar.
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47413310
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81792979
type: Answer
has comment: http://stackoverflow.com/comment/81792914
answers question: http://stackoverflow.com/q/47413310

http://stackoverflow.com/q/47455323
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81864886
tagged with: python
accepted answer: http://stackoverflow.com/a/47455441
has body: I know this has been asked 1000 times before but what i am experiencing is really weird and I cant troubleshoot it. I have a date column structured like this: 24JUN2017:14:46:57 I use: pd.to_datetime('24JUN2017:14:46:57', format="%d%b%Y:%H:%M:%S") and it works fine. But when I try to input the whole column: pd.to_datetime(df['date_column'], format="%d%b%Y:%H:%M:%S") I get the error of the title. Anyone knows why I might be experiencing this? ps:I have checked for any empty spaces and there are none
has answer: http://stackoverflow.com/a/47455441
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81864885
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/81865081
tagged with: python-datetime
answer count: 1
has title: Weird behavior with datetime: error: time data '0' does not match format '%d%b%Y:%H:%M:%S'
downvote count: 1

http://stackoverflow.com/a/47430146
has body: name_id = {'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}], 'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]} name_id['project-1'][0]['name'] = 'john' name_id['project-1'][1]['name'] = 'steve' name_id['project-2'][0]['name'] = 'jack' name_id['project-2'][1]['name'] = 'anna' The ['project-1'] gets the value corresponding to the project-1 key in the dictionary name_id. [0] is the list index for the first element in the dictionary value. ['name'] is also a key, but of the dictionary in the first element of the list. It gives you the final value that you want.
answers question: http://stackoverflow.com/q/47429981
type: Answer
score: 0

http://stackoverflow.com/a/47471178
answers question: http://stackoverflow.com/q/47468656
score: -2
has comment: http://stackoverflow.com/comment/81903790
type: Answer
upvote count: 0
downvote count: 2
has body: You could also go like: Button(command=lambda : [some_function(), some_other_function(), some_another_function()]) be mindful that their order do matter. I'd also rather use a handle function like in Reblochon Masque's answer though.

http://stackoverflow.com/comment/81959514
has text: ah yes, just changed it, that is now what I tried last.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47498974

google-cloud-platform
tags question: http://stackoverflow.com/q/47507951
tags question: http://stackoverflow.com/q/47482321
tags question: http://stackoverflow.com/q/47393631
tags question: http://stackoverflow.com/q/47475255
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/47455680
tags question: http://stackoverflow.com/q/47527868
tags question: http://stackoverflow.com/q/47466195
tags question: http://stackoverflow.com/q/47390142
tags question: http://stackoverflow.com/q/47518731
tags question: http://stackoverflow.com/q/47406152
type: Tag

http://stackoverflow.com/a/75468526
score: 0
type: Answer
has body: try this please import pyodbc connection_string = "Driver=SQL Anywhere 17;Server=demo17;UID=dba;PWD=sql;DBN=demo" connection_object = pyodbc.connect(connection_string) cursor = connection_object.cursor() sql_string = "select 1" result = cursor.execute(sql_string) counter = result.fetchone()[0] print(counter) connection_object.close()
answers question: http://stackoverflow.com/q/47393518
has comment: http://stackoverflow.com/comment/133224082

http://stackoverflow.com/a/47536708
has body: You have a problem on this line in your import file: 5384 | Associate Editor IJSEM (2001) (Trichlorobacter thiogenes) | 0 | 0 | | Associate Editor, IJSEM \"Validation List no. 78 (footnote ||).\" Int. J. Syst. Evol. Micr obiol. (2001) 51:1-2. (Note: type strain information) | 115783 | it splits into 9 fields. Your format string for the insert query expects only 7. You need to add some validation in the file parsing to make sure the sub-lists that you push into the big import list (list variable in your code) always have exactly 7 elements, and deal with the exceptions accordingly - if the line has too few columns, either ignore it or populate with defaults, if it has too many, decide which ones are correct. I believe in this particular case the problem is caused by the incorrect assumption that the delimiter | can never appear in the string, as it does in footnote ||. You can solve it by adding some regex logic to filter out such abnormalities.
answers question: http://stackoverflow.com/q/47517050
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82146054
type: Answer
accepted answer of: http://stackoverflow.com/q/47517050

http://stackoverflow.com/a/47539680
answers question: http://stackoverflow.com/q/47539538
has comment: http://stackoverflow.com/comment/82036474
type: Answer
score: 0
type: AcceptedAnswer
has body: We have managed to integrate ninja into the our setup.py. https://github.com/onnx/onnx/commit/d1bfcebd9c21a836d88b63ea8715c7a5b137ef32 It creates ninja build files on the fly and invoke ninja at the link stage.
accepted answer of: http://stackoverflow.com/q/47539538

http://stackoverflow.com/q/47431197
favorite count: 0
type: Question
has body: I get a very unexpected result using skimage.measure LineModelND. It is not remotly close to a least square solution. Here a code example showing the problem: import skimage.measure import numpy as np import matplotlib.pyplot as plt #create some data x = np.arange(0,100,0.5) y = 5 * x + 20 yNoise = y + np.random.uniform(low=-30.0, high=30, size=y.shape) #Add some really bad data points numOfBadData = 50 badDataIdx = np.random.choice(np.arange(y.shape[0]), numOfBadData) yNoise[badDataIdx] = 0 data = np.vstack((x,yNoise)).T #least square p = np.polyfit(data[:,0], data[:,1], 1) #p = np.polyfit(x, yNoise, 1) lineX=[np.min(x), np.max(x)] yLeastSq = np.polyval(p, lineX) #fit using LineModelND model = skimage.measure.LineModelND() model.estimate(data) modelPredictY = model.predict_y(lineX) plt.figure('Data compare') plt.clf() plt.plot(x, yNoise, '.g', label='data points') plt.plot(lineX, yLeastSq, color='red', label='least square solution') plt.plot(lineX, modelPredictY, '-', color='blue', label='LineModelND') plt.legend() plt.show() Giving: OutputImage I understand that the polynomial fit is taking the distance parallel to the y-axis, which is not the same as using the perpendicular distance as in lineModelND. Never the less I expected something close in this example. Any idea why those two methods are giving very different results?
has title: Unexpected behaviour of skimage.measure.LineModelND
has comment: http://stackoverflow.com/comment/82072057
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81960130
has comment: http://stackoverflow.com/comment/81967168
tagged with: scikit-image
tagged with: python
has comment: http://stackoverflow.com/comment/82006802
tagged with: data-fitting
has comment: http://stackoverflow.com/comment/81988522
has comment: http://stackoverflow.com/comment/81843819
has comment: http://stackoverflow.com/comment/82076973
has comment: http://stackoverflow.com/comment/82036229
downvote count: 0
has comment: http://stackoverflow.com/comment/81854848
answer count: 0
has comment: http://stackoverflow.com/comment/81963465
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82091701

http://stackoverflow.com/comment/81815895
type: Comment
score: 0
type: AnswerComment
has text: @M.Jones , True, But if you cast to int, you have to insert numbers only. You got the literal error as you inserted as input something that is not a number.
comment on: http://stackoverflow.com/a/47430612

http://stackoverflow.com/a/47438590
has comment: http://stackoverflow.com/comment/81832496
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47437464
downvote count: 0
upvote count: 1
has body: Here's some code that "repairs" the string in the 2nd row by simply removing the brackets. It works in Python 2 and Python 3 with the given data, but it may fail on more complicated data. import json data = r''' {"ts":"2017-11-19T11:11:01.394","v":{"path":"D:\\Tableau Extract\\Logs\\log.txt"}} {"ts":"2017-11-19T11:11:01.394",["v":{"path":"D:\\Tableau Extract\\Logs\\log_bk.txt"]}} '''.splitlines() for row in data: if not row: continue row = row.replace('[', '').replace(']', '') d = json.loads(row) print(d) Python 2 output {u'ts': u'2017-11-19T11:11:01.394', u'v': {u'path': u'D:\\Tableau Extract\\Logs\\log.txt'}} {u'ts': u'2017-11-19T11:11:01.394', u'v': {u'path': u'D:\\Tableau Extract\\Logs\\log_bk.txt'}}
type: Answer
answers question: http://stackoverflow.com/q/47437464

http://stackoverflow.com/comment/81902477
type: Comment
has text: Let's hope the OP's data doesn't contain floats in scientific notation without a decimal point, eg '12E3'.
type: AnswerComment
comment on: http://stackoverflow.com/a/47473730
score: 0

http://stackoverflow.com/comment/81854648
has text: Also suggest you read the documentation on how to use Python virtual environments as not use the preferred configuration. http://modwsgi.readthedocs.io/en/develop/user-guides/configuration-guidelines.html
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47449502
type: Comment

http://stackoverflow.com/comment/81924398
score: 0
comment on: http://stackoverflow.com/q/47484753
type: Comment
type: QuestionComment
has text: How do you want the output to look like

http://stackoverflow.com/q/47490576
has answer: http://stackoverflow.com/a/47490636
tagged with: python
has title: How to do a rolling week-to-date sum in python's Pandas
type: AnsweredQuestion
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has body: Suppose I have the following code: import pandas as pd frame = pd.DataFrame( { "Date":["11/1/2017","11/2/2017","11/3/2017","11/4/2017", "11/5/2017","11/6/2017","11/7/2017","11/8/2017","11/9/2017","11/10/2017","11/11/2017", "11/12/2017"], "Day":["Wed","Thr","Fri","Sat", "Sun","Mon","Tue","Wed","Thr","Fri","Sat", "Sun"], "Sales":[5,5,10,5, 5,10,5,5,15,5,0, 5] }) frame.reset_index() print(frame) print() frame['RollingSum']=frame["Sales"].rolling(window=7, min_periods = 1, win_type='boxcar').sum() print(frame) Which prints the following output: Date Day Sales 0 11/1/2017 Wed 5 1 11/2/2017 Thr 5 2 11/3/2017 Fri 10 3 11/4/2017 Sat 5 4 11/5/2017 Sun 5 5 11/6/2017 Mon 10 6 11/7/2017 Tue 5 7 11/8/2017 Wed 5 8 11/9/2017 Thr 15 9 11/10/2017 Fri 5 10 11/11/2017 Sat 0 11 11/12/2017 Sun 5 Date Day Sales RollingSum 0 11/1/2017 Wed 5 5.0 1 11/2/2017 Thr 5 10.0 2 11/3/2017 Fri 10 20.0 3 11/4/2017 Sat 5 25.0 4 11/5/2017 Sun 5 30.0 5 11/6/2017 Mon 10 40.0 6 11/7/2017 Tue 5 45.0 7 11/8/2017 Wed 5 45.0 8 11/9/2017 Thr 15 55.0 9 11/10/2017 Fri 5 50.0 10 11/11/2017 Sat 0 45.0 11 11/12/2017 Sun 5 45.0 Now suppose that rather than a flat 7 day window, I want the left endpoint to be the most recent Sunday (or first day in the data set)... how could I achieve that? Desired output: Date Day Sales WTDSum 0 11/1/2017 Wed 5 5.0 1 11/2/2017 Thr 5 10.0 2 11/3/2017 Fri 10 20.0 3 11/4/2017 Sat 5 25.0 4 11/5/2017 Sun 5 5.0 5 11/6/2017 Mon 10 15.0 6 11/7/2017 Tue 5 20.0 7 11/8/2017 Wed 5 25.0 8 11/9/2017 Thr 15 40.0 9 11/10/2017 Fri 5 45.0 10 11/11/2017 Sat 0 45.0 11 11/12/2017 Sun 5 5.0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47490636

http://stackoverflow.com/q/47385933
has comment: http://stackoverflow.com/comment/81725285
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47386199
linked to: http://stackoverflow.com/q/17778372
tagged with: python
has comment: http://stackoverflow.com/comment/81724945
duplicate of: http://stackoverflow.com/q/17778372
tagged with: recursion
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/81724924
accepted answer: http://stackoverflow.com/a/47386199
has title: python recursive function returning none instead of string
has body: The below python function prints value using print function but is returning none if made to return string value. can anyone help me on how to return a string value from this below function. csv_full_list = ['mycsv_0', 'mycsv_1'] def create_csv_name(comm, index): global csv_full_list if comm + '_' + str(index) in csv_full_list: index += 1 # increment index by 1 create_csv_name(comm, index=index) else: print '%s_%i' % (comm, index) return '%s_%i' % (comm, index) print(create_csv_name('mycsv', 0)) out put expected : mycsv_2 but returns: None
linked to: http://stackoverflow.com/q/31739963
has answer: http://stackoverflow.com/a/47386276
possible better answer: http://stackoverflow.com/a/47386276
has comment: http://stackoverflow.com/comment/81724846

http://stackoverflow.com/a/47437408
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81830661
has comment: http://stackoverflow.com/comment/81829919
has body: df = pd.DataFrame({'code':['0012'],'name':['Jason'],'value':[100]},index=[0]) df.to_csv('test.csv') !type test.csv #I used type because I am on a windows box, you can use !cat if on linux box Output: ,code,name,value 0,0012,Jason,100 It does out put 0012, but if you open this in Excel, excel will want to convert 0012 into 12. You could use quoting to explicitly define as string. df.to_csv('test.csv',quoting=1) Output: "","code","name","value" "0","0012","Jason","100"
accepted answer of: http://stackoverflow.com/q/47437109
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47437109
has comment: http://stackoverflow.com/comment/81830168
has comment: http://stackoverflow.com/comment/81830329

http://stackoverflow.com/q/47416164
answer count: 1
has answer: http://stackoverflow.com/a/47416716
accepted answer: http://stackoverflow.com/a/47416716
type: Question
has title: Extract specific strings from the df
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: I would like to format the result of a data frame to look more readable. The df looks like this: lack_of_minutes['Period'] = pd.to_datetime(lack_of_minutes['time']) - lack_of_minutes['START_TIME'] The lack_of_minutes df is type timedelta64[ns]. To avoid the error TypeError: Timedelta('0 days 01:08:12') is not JSON serializable i returned the json like this: return json.dumps(data_load, indent=4, sort_keys=True, default=str) Basically it just converts everything it doesn't know to strings But the format that it's returning the time it's like this: 0 days 17:25:35 I would like to exclude the 0 days and return only the time. 17:25:35 to be more readable. My first idea was to slice the df but didn't work. What is the correct approach to do this. I am using python 2.x

http://stackoverflow.com/q/47428768
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/81815402
score: 3
has comment: http://stackoverflow.com/comment/81835260
has comment: http://stackoverflow.com/comment/81812101
linked to: http://stackoverflow.com/q/11055303
has comment: http://stackoverflow.com/comment/81812038
has body: I need to say that multiprocessing is something new to me. I read some about it but it makes me more confused. I want to understand it on a simple example. Let's assume that we have 2 functions in first one I just increment 'a' variable and then assign it to 'number' variable, in second I start first function and each every one second I want to print 'number' variable. It should looks like: global number def what_number(): a=1 while True: a+=1 number=a def read_number(): while True: --&gt; #here I need to start 'what_number' function &lt;-- time.sleep(1) print(number) if __name__ == "__main__": read_number() How can I do that? Is there an easy and proper way to do that ? UPDATE: I saw noxdafox answer I'm really thankfull but it isn't exactly what I want. First of all I don't want send value in first function ('main' in noxdafox code). Second I don't want to get all values so quene will won't work. I need to get after each second number of while loops. Code should be something like : import multiprocessing import time number = 0 def child_process(): global number while True: number += 1 print(number) def main(): process = multiprocessing.Process(target=child_process) process.start() while True: print("should get same number:",number) time.sleep(0.001) if __name__ == "__main__": main() If u run above code you get something like: but this blue selected values should be same ! and that's the main problem :) P.S sorry for chaos
favorite count: 0
tagged with: python-multiprocessing
tagged with: multiprocessing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81812050
has comment: http://stackoverflow.com/comment/81812042
possible better answer: http://stackoverflow.com/a/47429558
has comment: http://stackoverflow.com/comment/81811999
type: Question
has comment: http://stackoverflow.com/comment/81811850
has title: Parallel multiprocessing in python easy example
answer count: 2
has answer: http://stackoverflow.com/a/47429558
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/423379
accepted answer: http://stackoverflow.com/a/47430983
has answer: http://stackoverflow.com/a/47430983
tagged with: parallel-processing
linked to: http://stackoverflow.com/q/8533318

http://stackoverflow.com/a/47473484
type: Answer
accepted answer of: http://stackoverflow.com/q/47408474
score: 0
has body: I finally found a solution. After having set the icon, we just need to remove the border and to resize the icon. We can do so with: self.load_scale.setStyleSheet('QPushButton{border: 0px solid;}') self.load_scale.setIconSize(QSize(25, 25)) That gives me a better looking icons:
answers question: http://stackoverflow.com/q/47408474
type: AcceptedAnswer

http://stackoverflow.com/q/47529906
has title: Pandas "read_sql" UnicodeDecodeError
tagged with: database
has body: I use pandas to read from Vertica DataBase: pd.read_sql(query, self._conn) But it fails with UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 1: invalid continuation byte. Other queries don't fail, so the problem is in some specific column from this query. I need all data - what should i do? I can make changes in Vertica too, but i can't change the table values... P.S. This is how i create a connection for Vertica: conn_info = url2vertica(url) conn_info["read_timeout"] = 2400 conn_info["ssl"] = False vrt = vertica_python.connect(**conn_info)
tagged with: python
has comment: http://stackoverflow.com/comment/82017898
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47550735
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47550735
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82020557
score: 3
tagged with: vertica

http://stackoverflow.com/comment/81850966
type: Comment
has text: Thanks for the link to documentation. Also I think he can use any of the ensemble methods such as bagging/boosting which uses bootstrapping to get more accurate results with random sampling with replacement. It will provide voting for classification and averaging for regression.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47437478

http://stackoverflow.com/comment/81866086
comment on: http://stackoverflow.com/a/47452657
type: AnswerComment
has text: This should be the `Accepted Answer`. For `Element is not clickable at point (383, -5335)` see this [Element is not clickable at point (36, 72). Other element would receive the click:](https://stackoverflow.com/questions/44912203/selenium-web-driver-java-element-is-not-clickable-at-point-36-72-other-el/44916498#44916498)
type: Comment
score: 0

http://stackoverflow.com/a/47469223
upvote count: 2
has comment: http://stackoverflow.com/comment/83473612
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47468835
downvote count: 0
has body: The actual stripe module being imported is likely an older version. Can you check the value of stripe.VERSION? I'd recommend reinstalling the stripe module, e.g. via pip uninstall stripe then pip install --upgrade stripe. If you're using a virtual environment, make sure that you've activated it before running the pip commands.
accepted answer of: http://stackoverflow.com/q/47468835
type: Answer
has comment: http://stackoverflow.com/comment/117557941
score: 2
has comment: http://stackoverflow.com/comment/83473670

http://stackoverflow.com/a/47475335
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81907685
has comment: http://stackoverflow.com/comment/81907966
accepted answer of: http://stackoverflow.com/q/47474984
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81907614
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81917922
answers question: http://stackoverflow.com/q/47474984
has body: One problem with your code is that you do not always get 200 values around the maximum. Imagine your maximum in one row is the second value, then you will only get 102 values. So casting it back into a numpy array will anyways not work. My suggestion, create a new list and append each item to the list, that is, # Import import numpy as np # Random data N=np.random.random((30000,1000)) # List for new results Nnew=[] # Loop for item in N: item = item[max([0,item.argmax()-100]) : item.argmax()+100] Nnew.append(item)

http://stackoverflow.com/q/47426950
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/81809492
favorite count: 0
type: Question
has body: EDIT: This does not appear to touch jinja. I was wrong. Its pure django templates. FIXED: Embarrassing: Combination of old django-templated-email and workarounds for broken 1.9 template system. With new django (v1.11.x) and new lib (v2.2.0) it works fine again. This codebase started around 1.4. Not sure how this lib update was missed. I don't know if django fixed the template loader bug (it couldn't remember dirs to search on the second pass) or if the lib fixed it I am using Django for email templating. Our template uses {% extends %} to dynamically derive from a base template depending on the style of email chosen by the user. It appears that the {extends} is never re-evaluated. Whichever value was supplied for the base_template parameter is always re-used. It feels like the two where textually combined. Using django-templated-email package (which uses std templates) This uses the default DjangoTemplates engine I've logged all calls to cached.Loader and the base template is never re-requested {% include footer %} seem to be re-fetched from the loader every time Debug=True|False results in no change I clear the template cache before each call, to no effect Our email templates look like this: # email/object_created.email {% extends base_template %} {% block subject_line %}New Object Created{% endblock %} {% block html_content %} Hello {{ name }}, {% endlbock %} # base_template (email/base/*.email) are like this: ...static html code, different in each base/*.email file... {% include 'email/partials/contents-footer.html' %} Cache Clearing works like this: from django.template import engines for template in engines.all(): for loader in template.engine.template_loaders: loader.reset() for ln in loader.loaders: ln.reset() I'm not sure about how Jinja2 actually behaves with {extends} and didn't see anything in the documentation saying this will or will not happen. We call send_templated_email like this: send_templated_mail( template_name="object_created", template_prefix=…
has comment: http://stackoverflow.com/comment/81809245
has title: Using {%extends var_name%} not being re-evaluated in
tagged with: python
has comment: http://stackoverflow.com/comment/81809095
has comment: http://stackoverflow.com/comment/81809353
has comment: http://stackoverflow.com/comment/81809480
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47429955
upvote count: 2
has comment: http://stackoverflow.com/comment/81808938
has answer: http://stackoverflow.com/a/47429955
has comment: http://stackoverflow.com/comment/81809428
answer count: 1

http://stackoverflow.com/comment/81877043
type: Comment
comment on: http://stackoverflow.com/a/47458153
score: 0
type: AnswerComment
has text: actually, still not loaded....I have base, forum, index, user as sub-folder in static, and each sub-folder has its own css, img, js folder. Does it matter?

http://stackoverflow.com/comment/82005723
type: AnswerComment
comment on: http://stackoverflow.com/a/47510461
score: 0
has text: Exception Type: AssertionError Exception Value: 'FileUploaderViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method.
type: Comment

http://stackoverflow.com/q/47520929
favorite count: 0
type: Question
has title: What is the purpose of the sum(rlist) == len(list) in this code?
has body: The problem is Write a function matchAll(pattern, list), return True if the pattern matches all the strings in the list. The answer is: import re def matchAll(pattern,lst): outlist=[(re.search(pattern, i) != None) for i in lst] #out = True #for i in outlist: # out= i and out return sum(outlist)==len(outlist) I understand everything they did except for the last line. Why do you have to check if the sum of the list is equal to the length of the list? Thanks
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47520977
tagged with: python
tagged with: regex
answer count: 3
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/47520958
has answer: http://stackoverflow.com/a/47520994
has comment: http://stackoverflow.com/comment/81998424
downvote count: 1

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/47403435
type: Tag

http://stackoverflow.com/comment/82032292
score: 0
has text: Could be Python version, some library problem or something else. But what I can tell you is that when you use `manage.py runserver` you are not using Apache & WSGI at all - so one can work where the other doesn't.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47537675

http://stackoverflow.com/comment/81867122
score: 0
has text: Hi i know how to get the first elements . Im still more interested how to through the levels until item id without duplicates and in a loop.
comment on: http://stackoverflow.com/a/47455819
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47466144
has comment: http://stackoverflow.com/comment/81886821
has title: Preventing overflow in python
has comment: http://stackoverflow.com/comment/81886951
favorite count: 0
type: Question
has body: Python newbie here using Python 2.7 and working from a boilerplate. I came across this line in a boilerplate function which is causing problems for me: x[x &lt; -100] = -100 The comment says that this is supposed to prevent overflow, but I have no idea how. The x that I am passing in is a float. I tried searching the python documentation but maybe I was using the wrong keywords? Can anybody help me understand this? Thanks!
has answer: http://stackoverflow.com/a/47466438
accepted answer: http://stackoverflow.com/a/47466438
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/81886857
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/q/47538130
has answer: http://stackoverflow.com/a/47538302
type: Question
has body: i'm trying to user Date Picker Range from http://www.daterangepicker.com/ and i have this on my html: Rango: my urls.py: url(r'^subestados/$',se.tabla, name='subestados'), url(r'^subestados/(?P<yearb>[0-9]{4})/(?P<monthb>[0-9]{2})/(?P<dayb>[0-9]{2})/(?P<yearf>[0-9]{4})/(?P<monthf>[0-9]{2})/(?P<dayf>[0-9]{2})/$',se.tabla, name='subestados'), I've seen other post about this, but i can't find a solution that works for me, i understand there is a ajax method to make the post but i don't know how to implement it: $.ajax({ url:'/', type : "POST", data: {start : 'start', end : 'end'}, success: function(response){}, complete: function(){}, error: function(xhr, textStatus, thrownError){} }); The javascript works i can see the calendar and all the options but can't find the way to do what i want. Any clues about this ?
has title: Django date picker range Javascript post
type: UnansweredQuestion
tagged with: django
tagged with: javascript
tagged with: python
tagged with: jquery
tagged with: ajax
has comment: http://stackoverflow.com/comment/82033484
score: 0
answer count: 1

http://stackoverflow.com/comment/82034073
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47538247
type: Comment
has text: No, `df["A"]` is no different than if you had hard-coded `dfA`. It's just a variable holding a reference to a value.

http://stackoverflow.com/q/47507362
has body: class Solution(object): def moveZeroes(self, nums): nums.sort(key =lambda x : 1 if x == 0 else 0) return nums My function looks like above. I don't seem to understand how code key =lambda x : 1 if x == 0 else 0 works. I also tried to change the lambda function to: def getKey(item): if item == 0: return 1 else: return 0 But don't seem to understand how key=1 or 0, affects the result.
upvote count: 1
tagged with: lambda
has title: Working of python's sort key
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81970522
downvote count: 6
has answer: http://stackoverflow.com/a/47507696
has comment: http://stackoverflow.com/comment/81971068
score: -5
has comment: http://stackoverflow.com/comment/81970509
has comment: http://stackoverflow.com/comment/81970511
tagged with: python
linked to: http://stackoverflow.com/q/13669252
has answer: http://stackoverflow.com/a/47507837
has comment: http://stackoverflow.com/comment/81971062
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81971233

http://stackoverflow.com/a/47531215
answers question: http://stackoverflow.com/q/47529759
type: Answer
upvote count: 6
score: 6
has body: You do not only want to set the text which is shown but also change the text which is internally stored. To do this all at once use the TextBox's .set_val() method. import matplotlib.pyplot as plt import matplotlib.widgets temp_descr = 'wow' axLabel = plt.axes([0.7, 0.05, 0.21, 0.075]) textbox = matplotlib.widgets.TextBox(axLabel, 'Label: ', temp_descr) textbox.set_val("jojojo") plt.show()
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47529759
downvote count: 0

http://stackoverflow.com/a/47521236
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47476737
has body: Yeah you are right, records is a list of indexes to records, but I treated records as it was the value of the indexes. I made som changes to the function and it works now: def __entropy(self, records): n = Counter([self.data[x][4] for x in records]) return sum([(-freq / len(records)) * math.log(freq / len(records), 2) for freq in n.values()])#eksempel:
answers question: http://stackoverflow.com/q/47476737
type: Answer
score: 0

http://stackoverflow.com/a/47385715
upvote count: 4
has comment: http://stackoverflow.com/comment/81728379
has comment: http://stackoverflow.com/comment/81727035
answers question: http://stackoverflow.com/q/47385646
has body: los = ["abc are all letters, elephants", "bananas are yellow, apples are fruits"] sum((itm.count("are") for itm in los))
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/81734043
type: Answer

http://stackoverflow.com/a/47414946
score: 1
has body: you should try df_notnull = df.dropna(how='all') This will get you only non null rows. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81783564
answers question: http://stackoverflow.com/q/47414848
upvote count: 2

http://stackoverflow.com/q/47416861
answer count: 1
accepted answer: http://stackoverflow.com/a/47417083
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47417083
upvote count: 25
downvote count: 0
tagged with: python
tagged with: keras
has body: can anyone tell me how is backpropagation done in Keras? I read that it is really easy in Torch and complex in Caffe, but I can't find anything about doing it with Keras. I am implementing my own layers in Keras (A very beginner) and would like to know how to do the backward propagation. Thank you in advance
type: AnsweredQuestion
tagged with: keras-layer
has title: Backward propagation in Keras?
score: 25
tagged with: deep-learning

http://stackoverflow.com/q/47477945
has title: how to reshape an N length vector to a 3x(N/3) matrix in numpy using reshape
type: Question
upvote count: 2
tagged with: arrays
tagged with: python
accepted answer: http://stackoverflow.com/a/47477954
score: 2
tagged with: matrix
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47477954
downvote count: 0
answer count: 1
favorite count: 0
tagged with: numpy
has body: i have a numpy array of shape (12,). I want to reshape it so that [[1,2,3,4,5,6,7,8,9,10,11,12]] becomes [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] I have tried a.reshape(3,4) and a.reshape(-1,4) but nothing is producing what i want. is there a simple way of doing this or do i need to create a new array and set each value individually?

http://stackoverflow.com/comment/90965239
score: 0
has text: so s6ew-h6mp is not the endpoint? what's the difference of the two?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50728593

http://stackoverflow.com/comment/81815835
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47430275
has text: Właściwie to 'x' tutaj jest niepotrzebne, mój punkt widzenia. 'g' to `g = nx.Graph ()` z Networkx. 2 kod polega na porównaniu pierwszego i ostatniego węzła i przejścia przez "shortest_path", czy dany wybór jest jednoznaczny.

http://stackoverflow.com/comment/81956398
has text: see [server.py](https://github.com/furas/python-examples/blob/master/socket/basic/version-4/server.py) in folder `version-4` on [GitHub/furas/python-examples](https://github.com/furas/python-examples/tree/master/socket/basic)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47500435

http://stackoverflow.com/q/47540616
downvote count: 1
tagged with: sttwitterapi
favorite count: 0
possible better answer: http://stackoverflow.com/a/69000484
has answer: http://stackoverflow.com/a/47541651
tagged with: python
tagged with: twitter
accepted answer: http://stackoverflow.com/a/47541651
score: -1
has body: # Initiate the connection to Twitter twitter = Twitter(auth=oauth) # Search for latest tweets about "pakistan" results = twitter.search.tweets(q='pakistan',until=2008 - 08 - 19, ) print results I am trying to retrieve tweets that are earlier than this date by one week. It does not return anything. However, I have searched manually on twitter and found that tweets exist.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/69000484
upvote count: 0
type: AnsweredQuestion
tagged with: twitter-search
has title: Twitter API - Python , searching for tweet by date

http://stackoverflow.com/q/47397059
tagged with: session
tagged with: python
accepted answer: http://stackoverflow.com/a/47397153
tagged with: templates
type: Question
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/47397153
favorite count: 0
has body: I have an multidomain app in django. mx.myapp.com nz.myapp.com hn.myapp.com and it works well. The problem is when I login in mx.myapp.com and some link have to redirect to nz.myapp.com the session variables are not set. How do I keep logged whith my account throught the diferent domains? I think I have to transfer de session variables to another subdomain or something like that but I don't know how to do it. Please help.
type: AnsweredQuestion
tagged with: subdomain
has title: How to transfer session variables throught domain django?
score: 1

http://stackoverflow.com/a/47424593
score: 8
type: Answer
has comment: http://stackoverflow.com/comment/81804284
accepted answer of: http://stackoverflow.com/q/47424411
has comment: http://stackoverflow.com/comment/81804236
answers question: http://stackoverflow.com/q/47424411
downvote count: 0
type: AcceptedAnswer
has body: Many image functions expect batches containing multiple images. The first dimension identifies an image's index in the batch. If you only have one image to process, you can reshape it with the following code: resize_image = tf.reshape(image, [-1, 224, 224, 3])
upvote count: 8

http://stackoverflow.com/a/47438167
has comment: http://stackoverflow.com/comment/81852576
has comment: http://stackoverflow.com/comment/81877081
score: 1
type: Answer
has body: First filter all id which contains another values from list and then filter all id which not contains a values: L = [4,5,6] a = df.loc[~df['status'].isin(L), 'id'] df = df[~df['id'].isin(a)] print (df) id description status 15 2 world1 4 16 2 world2 4 17 2 world3 5 18 2 world15 6 19 2 world8 6 20 2 world4 5 21 2 world7 5 Detail: print (a) 0 1 2 1 6 1 14 1 Name: id, dtype: int64 Timings: np.random.seed(123) N = 100000 L = np.random.randint(1000,size=N) df = pd.DataFrame({'status': np.random.choice([4,5,6,7], p = (0.3,0.3,0.39,0.01), size=N), 'id':np.random.choice(L, N), 'description':np.random.choice(L, N)}) print (df) L = [4,5,6] In [461]: %%timeit ...: a = df.loc[~df['status'].isin(L), 'id'] ...: df[~df['id'].isin(a)] ...: ...: 100 loops, best of 3: 1.91 ms per loop #Wen's solution In [462]: %%timeit ...: df['status']=df['status'].mask(~df['status'].isin([4,5,6])) ...: df.groupby('id').filter(lambda x : ~x.status.isnull().any() ) ...: 10 loops, best of 3: 111 ms per loop
has comment: http://stackoverflow.com/comment/81912987
accepted answer of: http://stackoverflow.com/q/47438067
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47438067
downvote count: 0
has comment: http://stackoverflow.com/comment/81845615

http://stackoverflow.com/q/47538169
type: Question
has title: Concatenating a tuple of dicts
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47538196
tagged with: data-structures
tagged with: dictionary
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47538196
answer count: 3
has comment: http://stackoverflow.com/comment/82033257
has comment: http://stackoverflow.com/comment/82033471
accepted answer: http://stackoverflow.com/a/47539555
has body: I have a tupple which contains multiple dicts where each dict contains a list as such: ({'num' : [1, 2, 3], 'let': ['a', 'b', 'c']}, {'num' : [4, 5, 6], 'let': ['d', 'e', 'f']}, {'num' : [7, 8, 9], 'let': ['g', 'h', 'i']}) I want to concatenate all of the dicts together into a single dict with one long list of the values from the previous dicts as such: {'let': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 'num': [1, 2, 3, 4, 5, 6, 7, 8, 9]} So far everything I have tried has either given me an error or resulted in the output having a list of lists rather than a single list.
has answer: http://stackoverflow.com/a/47539555
downvote count: 1
has answer: http://stackoverflow.com/a/47538352
favorite count: 0

http://stackoverflow.com/a/47463310
has body: Yes, the nested loops &amp; the range(len(self.mazeboard)) are highly unpythonic here, most of all when you just want to extend a matrix like 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 to 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 you could work in-place, completing the existing rows with ones, and adding rows of ones until you reach the proper dimension Self-contained example: mazeboard = [[0]*5 for _ in range(5)] x1 = 7 x2 = 7 old_len = len(mazeboard[0]) # extend the existing rows for m in mazeboard: m += [1]*(x1+1-old_len) # add rows mazeboard += [[1]*(x1+1) for i in range(len(mazeboard),x2+1)] print(mazeboard) result: [[0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]] so no nested loop, no useless copy, using list multiplication to generate the proper lengths for the lists to add.
accepted answer of: http://stackoverflow.com/q/47463177
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/81881871
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47463177
upvote count: 1

http://stackoverflow.com/comment/82017155
has text: Can you post the full traceback?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47530346
score: 1

http://stackoverflow.com/a/47391824
type: Answer
answers question: http://stackoverflow.com/q/47390846
has comment: http://stackoverflow.com/comment/81736735
score: 0
type: AcceptedAnswer
has body: Thanks for the comments. I solved by doing this: def multiple_exceptions(flist): exceptions = [] for f in flist: try: f() except Exception as e: exceptions.append(e.message) continue return exceptions def main(): multiple_exceptions([foo, bar]) error_messages = main() # list of e.messages occurred (to be raised whenever I want) Then I can raise my exception like e.g. raise Exception(error_messages[0]) (I only care about the first in this case let's say).
accepted answer of: http://stackoverflow.com/q/47390846

http://stackoverflow.com/comment/82026790
has text: And print that quadratic equation has no solution (in real number space) it will do the trick ;)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47534949
score: 0

http://stackoverflow.com/a/47410809
upvote count: 2
has body: The easiest way, since you're comparing with matlab, would be for you to use numpy import numpy as np a = np.array([1,2,2,3,1,4,2]) a &gt;= 2 # Just to check what you get by doing this boolean operation values = a[a&gt;=2] # using the conditional to filter a numpy array indeces = np.argwhere(a&gt;=2).reshape(-1) # to get the indices
downvote count: 0
answers question: http://stackoverflow.com/q/47410425
type: Answer
score: 2

http://stackoverflow.com/a/47498006
accepted answer of: http://stackoverflow.com/q/47497846
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81951338
answers question: http://stackoverflow.com/q/47497846
has body: You can use np.arctan2: np.arctan2(*v) However, as the angle is from the y-axis: |-&gt; | \ #so this is the positive direction | ------- | | diagram probably won't help It's necessary to swap the arguments to make it calculate the angle from X: np.arctan2(v[1], v[0])
type: Answer
score: 3
upvote count: 3

join
type: Tag
tags question: http://stackoverflow.com/q/47404571
tags question: http://stackoverflow.com/q/47528555
tags question: http://stackoverflow.com/q/47490122
tags question: http://stackoverflow.com/q/47504975
tag name: join
tags question: http://stackoverflow.com/q/47506763
tags question: http://stackoverflow.com/q/47458136
tags question: http://stackoverflow.com/q/47413225
tags question: http://stackoverflow.com/q/47472207
tags question: http://stackoverflow.com/q/47383958
tags question: http://stackoverflow.com/q/47405659
tags question: http://stackoverflow.com/q/47463515

http://stackoverflow.com/comment/81793844
type: Comment
comment on: http://stackoverflow.com/q/47419820
has text: It's not very clear what you're asking. Are you trying to print the values of a list seperated by `+` plus signs?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81755062
score: 0
type: AnswerComment
has text: OKAY it all worked but when running the code I get "Error %s % e" so technically it is failing..
comment on: http://stackoverflow.com/a/47398995
type: Comment

http://stackoverflow.com/comment/82990951
type: AnswerComment
comment on: http://stackoverflow.com/a/47541021
has text: Little reminder: https://stackoverflow.com/help/someone-answers, if the answer is good for you :)
type: Comment
score: 0

http://stackoverflow.com/comment/81935912
has text: Do you have to handle multiple levels of indentation, or just one?
comment on: http://stackoverflow.com/q/47484639
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82020487
has text: My upvote was ignored (I am a rookie here ;-) ), looking for the "Accept" button now.
score: 0
comment on: http://stackoverflow.com/a/47529023
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81928663
type: Comment
type: QuestionComment
has text: For point 1, there is no built-in way of doing this with searborn, but you might be able to place the violins manually after each other. This will probably be more work than it is worth and the result might look cluttered. Are you envisioning this organization on the x-axis: Thu{M, F}, Fri{M, F}, etc ?
score: 0
comment on: http://stackoverflow.com/q/47409086

http://stackoverflow.com/comment/81970822
comment on: http://stackoverflow.com/q/47476179
score: 0
has text: Thank you for your answer. I already updated the question.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81735832
comment on: http://stackoverflow.com/q/47391242
has text: Is it working when you run it NOT as Windows Service ? Did you open port 5555 in your firewall ?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47422132
upvote count: 3
answers question: http://stackoverflow.com/q/47420957
downvote count: 1
type: Answer
has body: The wait.until(..) function from selenium expects a function that it can call. However, you are, effectively, giving it a boolean. element = wait.until(waittest(driver, '//div[@id="text"]', "myCSSClass", "false")) Can be rewritten as: value = waittest(driver, '//div[@id="text"]', "myCSSClass", "false") element = wait.until(value) Which makes this more clear - waittest returns a boolean, and wait.until(..) tries to call it as a function - hence 'bool' object is not callable. You need to have your custom condition return a function that selenium can call to check if it's true yet. You can do this by defining a function inside your function: def waittest(locator, attr, value): def check_condition(driver): element = driver.find_element_by_xpath(locator) if element.get_attribute(attr) == value: return element else: return False return check_condition
score: 2

http://stackoverflow.com/a/47523158
type: Answer
accepted answer of: http://stackoverflow.com/q/47523102
score: 2
answers question: http://stackoverflow.com/q/47523102
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: for i in countryList: i = countryCodes[i] should change to for index, val in enumerate(countryList): countryList[index] = countryCodes[val] Because when you iterate an list through for i in countryList, the i is another variable, when you assign i to new value, the content of contryList remains unchanged, you need to use contryList[index] = val to make list change

http://stackoverflow.com/comment/82030157
type: QuestionComment
has text: Thats exactly what I thought in the beginning. Can you post that as an answer so I can vote it up for anyone else in this convo
comment on: http://stackoverflow.com/q/47535356
type: Comment
score: 0

http://stackoverflow.com/q/47499876
possible better answer: http://stackoverflow.com/a/47499911
has answer: http://stackoverflow.com/a/47500021
has comment: http://stackoverflow.com/comment/81955196
has comment: http://stackoverflow.com/comment/81955242
has answer: http://stackoverflow.com/a/47500140
upvote count: 10
tagged with: loops
has title: How to loop through multiple lists sequentially with one loop?
score: 8
favorite count: 0
duplicate of: http://stackoverflow.com/q/35205162
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81955152
has body: In Python 3.6.3 Is there a way to loop though one list after another? For example: deck = [(value, suit) for value in range(2, 11) + ["J", "Q", "K", "A"] for suit in ["H", "C", "D", "S"]] (In this case, I want to loop through the face cards right after the non-face cards.) For clarification: The above line throws a: TypeError: unsupported operand type(s) for +: 'range' and 'list' This is my problem.
answer count: 5
linked to: http://stackoverflow.com/q/35205162
tagged with: python
has answer: http://stackoverflow.com/a/47499938
has answer: http://stackoverflow.com/a/47499993
accepted answer: http://stackoverflow.com/a/47499938
has comment: http://stackoverflow.com/comment/81955584
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47499911
downvote count: 2

http://stackoverflow.com/comment/81909509
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47477347
has text: Wow, you're right. So it's just a matter of `re.search` behaving poorly?
type: Comment

http://stackoverflow.com/comment/81854126
type: QuestionComment
has text: It says [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) that in javascript all operands of bitwise operators are converted to 32 bit signed integers. You can just observe the results of evaluating `2650800128 & 2650800129` on python and javascript.
comment on: http://stackoverflow.com/q/47449241
score: 0
type: Comment

http://stackoverflow.com/a/47430275
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47430030
has body: Code 1 Use a conditional list comprehension together with enumeration: e00 = [[c_val, d_val] for i, c_val in enumerate(c1) for d_val d1[i] if not d_val % 2] Code 2 Only slight modifications required. g = ... # Undefined in sample code. sciezki = [] for out2_val in out2: x1 = out2_val[-len(out2_val)] x2 = out2_val[-1] z1 = nx.shortest_path(g, x1, x2) if z1 == out2_val and len(z1) == 8: sciezki.append(z1) x = '\n'.join(map(str,sciezki)) # Remove if possible.
has comment: http://stackoverflow.com/comment/81815835
accepted answer of: http://stackoverflow.com/q/47430030

http://stackoverflow.com/comment/81976711
has text: @cᴏʟᴅsᴘᴇᴇᴅ - I add some another values, because OP guaraanteed at least 4 non nan values.
type: Comment
comment on: http://stackoverflow.com/a/47510242
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81992463
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47517998
type: Comment
has text: @AmitTripathi the one caveat being that perhaps you might want a function with no bound state, but you still want inheritance. Although, I've rarely found that to be necessary. Usually, I have a mix of class definitions and standalone functions in a module.

http://stackoverflow.com/a/47407428
has body: Use mix of Seaborn's lmplot and regplot: import seaborn as sns #Use lmplot to plot scatter points graph = sns.lmplot(x='x_value', y='y_value', hue='water_value', data=df, fit_reg=False) #Use regplot to plot the regression line for the whole points sns.regplot(x='x_value', y='y_value', data=df, scatter=False, ax=graph.axes[0, 0]))
score: 5
answers question: http://stackoverflow.com/q/47407173
upvote count: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81771651

http://stackoverflow.com/comment/81755083
type: AnswerComment
has text: @BradSolomon Nice solution :-)
type: Comment
comment on: http://stackoverflow.com/a/47400661
score: 0

http://stackoverflow.com/a/47403074
answers question: http://stackoverflow.com/q/47402999
has body: You can do this in a loop making use of python's [:#] slice notation: Let's say the user's input for slicing chunk sizes is stored in a list. They want chunks of 3, 2, 1 and 2, so the user input defining the chunks gets stored into a list that has has [3,2,1,2]. Then, loop through that list and use it to get your slices: input_list = [0,1,2,3,4,5,6,7] chunk_list = [3,2,1,2] output_list = [] for i in chunk_list: output_list.append(input_list[:i]) input_list = input_list[i:] print(output_list) Prints: [[0, 1, 2], [3, 4], [5], [6, 7]]
score: 1
has comment: http://stackoverflow.com/comment/81759916
has comment: http://stackoverflow.com/comment/81760758
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81760030

http://stackoverflow.com/q/47522991
has comment: http://stackoverflow.com/comment/82003045
has comment: http://stackoverflow.com/comment/82003361
has comment: http://stackoverflow.com/comment/82002857
has comment: http://stackoverflow.com/comment/82002738
tagged with: python
has comment: http://stackoverflow.com/comment/82002582
tagged with: primes
upvote count: 2
has answer: http://stackoverflow.com/a/47523079
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47523079
has comment: http://stackoverflow.com/comment/82002878
downvote count: 2
tagged with: primality-test
has body: So I'm trying to find the 10,001 prime number. Yes, its the euler #7 problem. The code i wrote appears to give me all the prime numbers from 3 to 10,001 but my answer is still incorrect. I know there are other questions about this that have been answered but stealing someone else code does not help me learn. So I'm looking for insight into where i went wrong with this. First I seperated out all the odd numbers and added them to a list. I noticed that there were squares of some of the prime numbers in the list so I check the list against the squares of every number from 2 to 10,0001. That should have left me with nothing but prime numbers but I am still getting the wrong answer. Any ideas would be great thank you prime = [i for i in range(2, 10002) if i % 2 != 0] for i in range(2, 10002): if i * i in prime: prime.remove(i * i) print(prime[-1])
answer count: 1
has comment: http://stackoverflow.com/comment/82002398
has title: what is the highest prime number between 1 and 10001
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82002960
tagged with: python-3.x

http://stackoverflow.com/comment/81951344
comment on: http://stackoverflow.com/q/47498038
has text: You don't run an app in VMware, you run an app in the OS running in the virtual machine running on VMware.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47405430
type: Answer
has comment: http://stackoverflow.com/comment/81764788
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81764739
answers question: http://stackoverflow.com/q/47405274
upvote count: 1
has body: This set of duplicates should essentially be the intersection of all rows which contain NaN values and rows which contain duplicate p1 elements, unioned with the those which are duplicates across both columns: dupe_1 = df['p1'].duplicated(keep=False) &amp; df['p2'].isnull() dupe_2 = df.duplicated(subset=['p1','p2']) total_dupes = dupe_1 | dupe_2 new_df = df[~total_dupes] Note that this will fail for a dataframe such as: p1 p2 0 a NaN 1 a NaN As both of those elements would be removed. Thus, we must first run df.drop_duplicates(subset=['p1','p2'], inplace=True, keep='last'), removing all but one of those rows, making the solution work fine once again.

http://stackoverflow.com/q/47438750
score: 0
has comment: http://stackoverflow.com/comment/81834999
tagged with: mnist
answer count: 1
tagged with: scikit-learn
type: Question
has answer: http://stackoverflow.com/a/47444315
tagged with: numpy
has comment: http://stackoverflow.com/comment/81833533
has comment: http://stackoverflow.com/comment/81834254
type: UnansweredQuestion
has title: NotImplementedError: invalid type in assignment
has comment: http://stackoverflow.com/comment/81834079
tagged with: python
has comment: http://stackoverflow.com/comment/81833573
has body: I have a csv data, the first column of the data is 'label' and columns after the first one to the end 784 column contains a representation of an image (28*28) format.I created a tuple of numpy array using load(filename) function. This function assigns a label to image. Now I want to use the data so generated in the function read(digits, path = ".") below. This format is used for Support Vector Machine Analysis of scikit library. In fact, I am trying to mimic (second example toward the bottom): http://cvxopt.org/applications/svm/index.html When I try to reformat the data, I receive an error copied below in the body. Is there a way, I can get it in the desired format? train_name=dir_path+'train8.csv' def load(filename): # read file into a list of rows with open(filename, 'rU') as csvfile: lines = csv.reader(csvfile, delimiter=',') rows = list(lines) # create empty numpy arrays of the required size data = np.empty((len(rows), len(rows[0])-1), dtype=np.float64) expected = np.empty((len(rows),), dtype=np.int64) # fill array with data from the csv-rows for i, row in enumerate(rows): data[i,:] = row[1:] expected[i] = row[0] result_data = data, expected return result_data &gt; Result: (array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]]), array([1, 1, 1, ..., 1, 1, 1])) def read(digits, path = "."): data= load(train_name) print "sizeImages = ",len(data[0]), "sizelabels = ", len(data[1]) lbl=data[1] size=len(data[1]) img=data[0] #print type(img) OUTPUT: &lt;type 'numpy.ndarray'&gt; img =[l[0] for l in img] # print type(img) OUTPUT: &lt;type 'list'&gt;, *This is used to unpack the numpy array from above.* ind = [ k for k in xrange(size) if lbl[k] in digits ] images = matrix(0, (len(ind), 28*28)) labels = matrix(0, (len(ind), 1)) #images = data[0] labels = img for i in xrange(len(ind)): images[i, :] = img[ ind[i]*28*28: (ind[i]…

http://stackoverflow.com/comment/81901748
type: Comment
has text: I agree why you said in efficient, didn't think of pd.Series
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47473595

http://stackoverflow.com/q/47390100
has comment: http://stackoverflow.com/comment/81733182
score: 0
has title: Scraping multiple pages property data with Python
tagged with: screen-scraping
answer count: 1
has answer: http://stackoverflow.com/a/47391133
has body: Need to scrap multiple pages data from the following website https://dubai.dubizzle.com/en/property-for-rent/commercial/office/?page=1 The fields to get are "Price, description, area and location" for multiple pages. I have written only the following code. In addition I don't know how to parse the phone number, because it only appears when you have opened the particular link from urllib.request import urlopen from bs4 import BeautifulSoup file = "Dubizzle.csv" f = open(file, "w") Headers = "Price,Area,Description,Location,Website\n" f.write(Headers) for page in range(1, 4): url = "https://dubai.dubizzle.com/en/property-for-rent/commercial/office/?page={}".format(page) html = urlopen(url) soup = BeautifulSoup(html, "html.parser")
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81733910

http://stackoverflow.com/a/68359044
has body: Although ctypes does not support this use case, it turns out the newer cffi library does: https://cffi.readthedocs.io/en/latest/using.html#extern-python-new-style-callbacks
accepted answer of: http://stackoverflow.com/q/47470452
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47470452

http://stackoverflow.com/a/47426501
answers question: http://stackoverflow.com/q/47425548
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: In pandas 0.21.0 you can use set_axis to rename columns as chained method. Here's a one line solution: df2[df2.a.isin(df1.a)]\ .squeeze()\ .value_counts()\ .reset_index()\ .set_axis(['No','Amount'], axis=1, inplace=False) Output: No Amount 0 1 3 1 2 2

http://stackoverflow.com/a/47525639
has comment: http://stackoverflow.com/comment/82017375
score: 0
has comment: http://stackoverflow.com/comment/82010660
has body: Set FEED_EXPORT_ENCODING='utf-8' i settings.py See docs here https://doc.scrapy.org/en/latest/topics/feed-exports.html#std:setting-FEED_EXPORT_ENCODING
answers question: http://stackoverflow.com/q/47524492
has comment: http://stackoverflow.com/comment/82008169
has comment: http://stackoverflow.com/comment/82013322
has comment: http://stackoverflow.com/comment/82007961
has comment: http://stackoverflow.com/comment/82016476
has comment: http://stackoverflow.com/comment/82013087
has comment: http://stackoverflow.com/comment/82020395
has comment: http://stackoverflow.com/comment/82020248
type: Answer
has comment: http://stackoverflow.com/comment/82015445
has comment: http://stackoverflow.com/comment/82012866

http://stackoverflow.com/comment/121455164
score: 0
comment on: http://stackoverflow.com/a/54173394
type: AnswerComment
type: Comment
has text: I'm thinking your best bet is to use something to record your screen. Loads of options for that. Then share a video of you operating the map.

tkinter
tags question: http://stackoverflow.com/q/47524358
tags question: http://stackoverflow.com/q/47502212
tags question: http://stackoverflow.com/q/47460324
tags question: http://stackoverflow.com/q/47520170
tags question: http://stackoverflow.com/q/47465611
tags question: http://stackoverflow.com/q/47454028
tags question: http://stackoverflow.com/q/47534721
tags question: http://stackoverflow.com/q/47471725
tags question: http://stackoverflow.com/q/47495285
tags question: http://stackoverflow.com/q/47421872
tags question: http://stackoverflow.com/q/47524967
tags question: http://stackoverflow.com/q/47462282
tags question: http://stackoverflow.com/q/47465171
tags question: http://stackoverflow.com/q/47455890
tags question: http://stackoverflow.com/q/47503706
tags question: http://stackoverflow.com/q/47416384
tags question: http://stackoverflow.com/q/47509499
tags question: http://stackoverflow.com/q/47537919
tags question: http://stackoverflow.com/q/47512856
tags question: http://stackoverflow.com/q/47447124
tags question: http://stackoverflow.com/q/47466995
tags question: http://stackoverflow.com/q/47422147
tags question: http://stackoverflow.com/q/47387713
tags question: http://stackoverflow.com/q/47457104
tags question: http://stackoverflow.com/q/47513681
tags question: http://stackoverflow.com/q/47533609
tags question: http://stackoverflow.com/q/47464001
tags question: http://stackoverflow.com/q/47429232
tags question: http://stackoverflow.com/q/47441547
tags question: http://stackoverflow.com/q/47514605
tags question: http://stackoverflow.com/q/47399690
tags question: http://stackoverflow.com/q/47401729
tags question: http://stackoverflow.com/q/47469911
tags question: http://stackoverflow.com/q/47441580
tags question: http://stackoverflow.com/q/47528539
tags question: http://stackoverflow.com/q/47483587
tags question: http://stackoverflow.com/q/47490055
tags question: http://stackoverflow.com/q/47515014
tag name: tkinter
tags question: http://stackoverflow.com/q/47443057
tags question: http://stackoverflow.com/q/47490851
tags question: http://stackoverflow.com/q/47395284
tags question: http://stackoverflow.com/q/47499069
tags question: http://stackoverflow.com/q/47392271
tags question: http://stackoverflow.com/q/47538986
tags question: http://stackoverflow.com/q/47457768
tags question: http://stackoverflow.com/q/47416044
tags question: http://stackoverflow.com/q/47468656
tags question: http://stackoverflow.com/q/47490816
tags question: http://stackoverflow.com/q/47460068
tags question: http://stackoverflow.com/q/47517718
tags question: http://stackoverflow.com/q/47424319
tags question: http://stackoverflow.com/q/47385250
tags question: http://stackoverflow.com/q/47494410
tags question: http://stackoverflow.com/q/47409437
tags question: http://stackoverflow.com/q/47460763
tags question: http://stackoverflow.com/q/47478047
tags question: http://stackoverflow.com/q/47456755
tags question: http://stackoverflow.com/q/47422037
tags question: http://stackoverflow.com/q/47424052
tags question: http://stackoverflow.com/q/47531729
tags question: http://stackoverflow.com/q/47475783
tags question: http://stackoverflow.com/q/47445582
tags question: http://stackoverflow.com/q/47534958
tags question: http://stackoverflow.com/q/47401017
tags question: http://stackoverflow.com/q/47483010
tags question: http://stackoverflow.com/q/47454039
tags question: http://stackoverflow.com/q/47446517
tags question: http://stackoverflow.com/q/47517091
tags question: http://stackoverflow.com/q/47492036
tags question: http://stackoverflow.com/q/47523824
tags question: http://stackoverflow.com/q/47513950
tags question: http://stackoverflow.com/q/47462903
tags question: http://stackoverflow.com/q/47433421
tags question: http://stackoverflow.com/q/47478332
tags question: http://stackoverflow.com/q/47402763
tags question: http://stackoverflow.com/q/47427719
tags question: http://stackoverflow.com/q/47538740
tags question: http://stackoverflow.com/q/47535299
tags question: http://stackoverflow.com/q/47522534

http://stackoverflow.com/q/47534530
tagged with: python
has body: https://www.youtube.com/watch?v=ZDa-Z5JzLYM&amp;list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc In this video series on OOP the Python-youtuber Corey Schafer uses instances of his Employee class to store data on employees like their salary and the coding language they know etc. I am rather new to 'higher level' programming and wanted to implement this in one of my projects where I also had to store and subsequently alter the attributes of many similar objects. Soon I realized, however, that it is rather cumbersome to handle the data after the instances have been constructed. For example, how can I iterate over all instances of a certain class or subclass or find instances that have a certain value for a specific attribute? Am I missing something big here or are there really no convenient ways to access the data this way? Finally I ended up using an extra dictionary that stored the instance names and an identifier number to somehow be able to read through the data but then I just could have used a dictionary in the first place. So, is the usage of class instances as data structure like it is displayed in this youtube series just a bad example on how to use classes/instances etc. or is there more to it than the videos show? I have read quite a bit about the topic but still can't figure out why you wouldn't use a dict in the first place or why fundamental built-in functions that would allow to e.g. easily fetch all instances of a subclass are lacking. Maybe someone can shed some light upon these issues and untangle my confusion. Thanks.
tagged with: data-structures
accepted answer: http://stackoverflow.com/a/47534881
has title: class instance as data structure in python
has answer: http://stackoverflow.com/a/47534881
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47581232
score: 0
answer count: 2
tagged with: instance
has comment: http://stackoverflow.com/comment/82026144
linked to: http://stackoverflow.com/q/12101958
tagged with: instance-variables
type: Question
has answer: http://stackoverflow.com/a/47581232

http://stackoverflow.com/q/47478365
type: UnansweredQuestion
has body: I am getting a complex json message through kafka. I need to extract the required fields from the json and store them in hive tables. I know I cannot use the spark driver sqlContext in the executors. I want to know how to use the sqlContext in the code run by the executors. Here is the code : kvs = KafkaUtils.createStream(ssc, zkQuorum, "spark-streaming", topic) msgs = kvs.map(lambda msg: msg[1]) msgs.foreachRDD(lambda rdd: rdd.foreach(lambda m : timeline_events(m))) def timeline_events(m): msg = json.loads(m) for msgJson in msg: event_id = msgJson['events'][0]['event_id'] event_type = msgJson['events'][0]['type'] incidence_source = msgJson['incident']['source'] csr_description = msgJson['incident']['data']['csr_description'] sc_display_priority = msgjson['incident']['data']['display_priority'] launch_tool_rec_label = msgJson['incident']['data']['LaunchTool'][0]['Label'] launch_tool_rec_uri = msgJson['incident']['data']['LaunchTool'][0]['URI'] launch_itg_rec_label = msgJson['incident']['data']['LaunchItg'][0]['Label'] launch_itg_rec_uri = msgJson['incident']['data']['LaunchItg'][0]['URI'] sqlContext.sql("Insert into nexus.timeline_events values({},{},{},{},{},{},{},{},{},{},{})".format(event_id, event_type, csr_description, incidence_source, sc_display_priority, launch_tool_rec_label,launch_tool_rec_uri, launch_tool_rec_id, launch_itg_rec_label, launch_itg_rec_uri, launch_itg_rec_id))
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: apache-kafka
tagged with: spark-streaming
has title: Using Hive SQLContext in spark executors
tagged with: python
answer count: 0

http://stackoverflow.com/comment/81835506
type: AnswerComment
has text: Becoming a nan there has nothing to do with a threshold.
comment on: http://stackoverflow.com/a/47439327
type: Comment
score: 0

http://stackoverflow.com/q/47523483
has comment: http://stackoverflow.com/comment/82003534
has comment: http://stackoverflow.com/comment/82003257
has body: For a DataFrame, let's call it weather1: Temp Month Apr 61 Jan 32 Jul 69 Oct 43 I would like to sort Month based on the actual calendar month order, and not alphabetically. I can do the following: ordered= ['Jan','Apr','Jul','Oct'] df.reindex(ordered) However I am looking for a more dynamic way to do this, perhaps using "date part" functions. Thank you in advance.
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47534635
answer count: 1
tagged with: python
favorite count: 0
score: 2
has title: Re-order DataFrame based on month (not alphabet)
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/29777828
accepted answer: http://stackoverflow.com/a/47534635

http://stackoverflow.com/q/47527272
accepted answer: http://stackoverflow.com/a/47527325
tagged with: python
has title: Getters and setters in Python
tagged with: properties
has body: I'm totally new to Python and I'm trying to write a class, which will store only two attributes, one of which is intended to be a number and another a datetime object. Though I'd also like, while storing date as a datetime, to initialize and output it using a string like "dd.mm.yyyy". So I go: class MyClass: number = None date = None def __init__(self, params): self.number = params["number"] self.date = params["date"] @property def date(self): return datetime.datetime.strftime(self.date, '%d.%m.%Y') @date.setter def date(self, value): self.date = datetime.datetime.strptime(value, '%d.%m.%Y') def get_vars(self): return vars(self) But at runtime @property points at self.date and says: Expected type 'datetime', got 'str' instead. How can it ever get a string, when it's meant to be converted to date while setting. Why is this happening? Confused. For example: &gt;&gt;&gt; MyClass({'number': 42, 'date': '28.12.2017'}) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;string&gt;", line 8, in __init__ File "&lt;string&gt;", line 16, in date File "&lt;string&gt;", line 16, in date TypeError: strptime() argument 1 must be str, not datetime.datetime
has answer: http://stackoverflow.com/a/47527325
score: 2
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/82010875
tagged with: datetime
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/q/47488454
score: 0
has title: Using two columns as key in spark python
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47489204
has body: I have 4 columns and many rows in my csv file. Date(MM/DD/YY) Arr_Dep Dom_Int Num_Fl 01/01/15 0:00 Arrival Domestic 357 03/01/15 0:00 Arrival International 269 06/01/15 0:00 Departure Domestic 82 08/01/15 0:00 Departure International 5 05/01/16 0:00 Arrival Domestic 44 06/01/16 0:00 Arrival Domestic 57 07/01/16 0:00 Departure International 51 08/01/16 0:00 Departure International 40 08/01/17 0:00 Arrival Domestic 1996 10/01/17 0:00 Departure International 21 I have to find the average number of flights per month in a particular year depending on whether the flight was arrival or departure. So output I'm expecting for the above input is: 2015, arrival, 313 2015, departure, 44 2016, arrival, 51 2016, departure, 46 2017, arrival, 1996 2017, departure, 21 I'm facing issue as to how should I include two columns in my key i.e. Arr_Dep and Date column in my map function to finally reduce it to get the average. I have written following script so far. Not sure how to proceed from pyspark import SparkContext from operator import add import sys sc = SparkContext(appName="example") input_file = sys.argv[1] lines = sc.textFile(input_file) first = lines.map(lambda x : ((x.split(",")[0].split(" ")[0][5:]).encode('ascii','ignore'), int(x.split(",")[-1]), x.split(",")[1])) second = first.filter(lambda x : "Arrival" in x[1] or "Departure" in x[1]) third = second.map(lambda x : (x[0],x[1])) result = third.reduceByKey("Not sure how to calculate average") output = result.collect() for v in sorted(output, key = lambda x:x[0]): print '%s, %s' % (v[0], v[1]) I'm not sure about the above script. I'm new to spark and python. Any ideas how to proceed?
type: Question
tagged with: apache-spark

http://stackoverflow.com/comment/81806251
has text: this answer might be similar and helpful [A python script that activates the virtualenv and then runs another python script?](https://stackoverflow.com/a/30927921/1248974)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47425520

http://stackoverflow.com/q/47441952
has comment: http://stackoverflow.com/comment/85132437
tagged with: filtering
tagged with: convolution
has answer: http://stackoverflow.com/a/48822437
upvote count: 3
score: 3
tagged with: image-processing
favorite count: 0
has title: 3D convolution in python
tagged with: numpy
has comment: http://stackoverflow.com/comment/81839243
type: Question
downvote count: 0
type: UnansweredQuestion
tagged with: python
has body: I need to wite a code to perform a 3D convolution in python using numpy, with 3x3 kernels. I've done it right for 2D arrays like B&amp;W images but when i try to extend it to 3D arrays like RGB is a mess. I need help to improve my method. Here is the 2D code: def convolucion_3x3(arreglo, kernel): (dim_x, dim_y) = arreglo.shape (ker_x, ker_y) = kernel.shape matriz_convolucionada = np.zeros((dim_x, dim_y)) for i in range(dim_x): for j in range(dim_y): resultado = 0 for x in range(-1, 2): try: if i + x not in range(dim_x): raise ValueError() for y in range(-1, 2): try: if j + y not in range(dim_y): raise ValueError() resultado += arreglo[i + x, j + y] * kernel[x + 1][y + 1] ''' Para el kernel sumo un 1 a cada índice para que lo corra desde 0 hasta 2 y no de -1 a 1 ''' except ValueError: pass except ValueError: pass matriz_convolucionada[i][j] = resultado return matriz_convolucionada The next one is my attempt to the RGB images: def convolucion(arreglo, kernel): (dim_x, dim_y, dim_z) = arreglo.shape (ker_x, ker_y) = kernel.shape matriz_convolucionada = np.zeros((dim_x, dim_y, dim_z)) for k in range(dim_z): for i in range(dim_x): for j in range(dim_y): resultado = 0 for x in range(-1, 2): try: if i + x not in range(dim_x): raise ValueError() for y in range(-1, 2): try: if j + y not in range(dim_y): raise ValueError() resultado += arreglo[i + x, j + y, k] * kernel[x + 1][y + 1] ''' Para el kernel sumo un 1 a cada índice para que lo corra desde 0 hasta 2 y no de -1 a 1 ''' except ValueError: pass except ValueError: pass matriz_convolucionada[i][j][k] = resultado return matriz_convolucionada
has comment: http://stackoverflow.com/comment/81839053
answer count: 1

http://stackoverflow.com/a/47470435
accepted answer of: http://stackoverflow.com/q/47469996
upvote count: 1
downvote count: 0
type: Answer
has body: I believe you need DataFrame.sort_index: import natsort as ns #add parameter values for remove MultiIndex in columns df = df.pivot_table(index='name', columns='Duration', values='sum', aggfunc='sum', fill_value=0) #https://stackoverflow.com/a/47240142/2901002 c = sorted(ns.natsorted(df.columns), key=lambda x: not x.isdigit()) df = df.reindex(c, axis=1) map_dict = { 'Invoice A': 'A1. Retail', 'Invoice B': 'A1. Retail', 'Invoice Z': 'A1. Retail', 'Invoice C': 'C1. Plastics', 'Invoice F': 'C1. Plastics', 'Invoice D': 'C2. Electronics', 'Invoice J': 'C2. Electronics' } #create new level of MultiIndex and assign back df.index = pd.MultiIndex.from_arrays([df.rename(map_dict).index, df.index], names=['name','one']) #sorting index df = df.sort_index() print (df) 2 3 2Y 3Y name one A1. Retail Invoice A 25.5 0.0 0.0 20.0 Invoice B 50.0 -10.5 25.0 0.0 C1. Plastics Invoice C 125.0 11.2 0.0 0.5 C2. Electronics Invoice D 0.0 0.0 15.0 80.1
answers question: http://stackoverflow.com/q/47469996
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47384535
has answer: http://stackoverflow.com/a/47384615
duplicate of: http://stackoverflow.com/q/44548721
favorite count: 0
type: AnsweredQuestion
has body: If I have the the following dataframe. If there is a null in either Participation, Homework, Test, Presentation (if there is a null is any of the four columns), then I want to remove that row. How do I achieve this in Pandas. Name Participation Homework Test Presentation Attendance Andrew 92 Null 85 95 88 John 95 88 98 Null 90 Carrie 82 99 96 89 92 Simone 100 91 88 99 90 Here, I would want to remove everyone except for Carrie and Simone from the dataframe. How do I achieve this in pandas? I found this on Stackoverflow, which I think may help df = df[pd.notnull(df['column_name'])], but is there anyway I can do this for all four columns (so a subset) instead of each column individually? Thanks!
accepted answer: http://stackoverflow.com/a/47384602
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47384568
possible better answer: http://stackoverflow.com/a/47384568
type: Question
has title: Removing rows with null values in any of a subset of columns (pandas)
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47384602
tagged with: null
upvote count: 1
linked to: http://stackoverflow.com/q/44548721

http://stackoverflow.com/a/47394343
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47392917
type: Answer
has comment: http://stackoverflow.com/comment/81772133
has body: Passing the logger as an argument looks fine to me. But if you have many calls to do_something then passing the same logger in each call is not only too verbose but prone to errors --you might pass the wrong logger by mistake. Also, while you do need to make do_something aware of the logger, doing it at the point where you are calling it probably does not make sense --you want to do something, not mess with loggers. OOP to the rescue: make do_something a method of a class and pass the logger when instantiating the class, then you do not need to pass it to the method. # utils.py class UsefulObject: def __init__(self, logger): self._logger = logger def do_something(self): print('hello') self._logger.debug('test') Now in the client module you create an instance of UsefulObject and you can call .do_something on it without passing the logger every time. # one.py from utils import UsefulObject logger = logging.getLogger(__name__) useful_object = UsefulObject(logger) # do this once # ... useful_object.do_something() # do this many times, do not pass the logger
downvote count: 0

http://stackoverflow.com/comment/81895716
type: Comment
score: 0
type: AnswerComment
has text: good point; I assumed that was the case. I added a note to mention this assumption, thanks for the assist @Piinthesky.
comment on: http://stackoverflow.com/a/47467372

http://stackoverflow.com/comment/81842680
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47443131
has text: Your private key file has a password/passcode. Assuming you know what it is, you should provide this password as a second argument to the `paramiko.RSAKey.from_private_key` function.

http://stackoverflow.com/comment/81799149
comment on: http://stackoverflow.com/q/47422326
score: 0
type: QuestionComment
has text: Yes you can. What's the problem?
type: Comment

http://stackoverflow.com/q/47437666
has comment: http://stackoverflow.com/comment/81830319
has answer: http://stackoverflow.com/a/47437740
has title: Enter and store a number starting with 0 (zero) in Python?
has comment: http://stackoverflow.com/comment/81829702
tagged with: zero
score: 2
upvote count: 2
downvote count: 0
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/81829812
tagged with: octal
answer count: 1
has comment: http://stackoverflow.com/comment/81831098
favorite count: 0
has body: I am working on a simple student attendance program in Python2. I am using an HID scanner that acts as a keyboard. The student IDs each have a barcode with their ID numbers on them. Unfortunately, the ID numbers start with zero, so that scanner produces the value with the zero. Once the scan occurs, it produces the invalid token error since Python thinks it is an octal number and some of the numbers in the sequence are 8 and 9. The simple code I am testing now is: def Main(): while(loop == True): scan = input('Please scan your ID: ') dateTime = time.strftime('%I:%M:%S %d/%m/%y') print(dateTime) print(scan) EDITED: The error is: ============== RESTART: /home/pi/Desktop/Barcode Entry Node2.py ============== Please scan your ID: 0971558 Traceback (most recent call last): File "/home/pi/Desktop/Barcode Entry Node2.py", line 18, in &lt;module&gt; Main() File "/home/pi/Desktop/Barcode Entry Node2.py", line 13, in Main scan = input('Please scan your ID: ') File "&lt;string&gt;", line 1 0971558 ^ SyntaxError: invalid token &gt;&gt;&gt; I have tried a bunch of different work arounds, but they all give me an error. I tried to convert it to a string in the declaration line but that did not seem to work the way I tried. Also, the scanner does not have the option to enclose the input in quotation marks. Anyone have the magic bullet I am missing? TIA EDIT: sorry - wrong cut and paste . . . DUH!
type: Question
has comment: http://stackoverflow.com/comment/81829900
has comment: http://stackoverflow.com/comment/81831768
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/81846919
type: AnswerComment
has text: I modified your solution `df.loc[df.last_valid_index()+1, ['a', 'b']] = ("string", datetime.today().strftime('%Y-%m-%d'))`, what do you think?
comment on: http://stackoverflow.com/a/47445660
type: Comment
score: 0

http://stackoverflow.com/comment/82181904
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47511303
has text: @sea that didn't work either.
score: 0

http://stackoverflow.com/q/47437633
has title: How to change dates in column?
has answer: http://stackoverflow.com/a/47437697
tagged with: pandas
score: 1
tagged with: datetime
possible better answer: http://stackoverflow.com/a/47437994
has answer: http://stackoverflow.com/a/47437994
favorite count: 0
type: Question
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
has body: I have a problem with Pandas, Python. I have several rows with different dates, where the dates are String "2016-02-28" ABC123 "2016-02-29" CDE345 "2016-03-30" FGH567 "2016-03-31" XYZ235 ... Here we see that feb has two different days, 28 and 29. I am only interested in the month. Thus, I want these rows to have the same day, like this: "2016-02-29" ABC123 "2016-02-29" CDE345 "2016-03-31" FGH567 "2016-03-31" XYZ235 ... It does not really matter which day they get, as long as it is the same day but preferable the last day. I cannot truncate and only keep "2016-02" because I later need the day. I can convert it timestamp if it becomes easier. df ["DATE"] = pandas.to_datetime (df ["DATE"]) (Another question, why does this line convert the DATE column to Timestamp instead of datetime?? It says to convert to datetime, but instead it becomes Timestamp?) I have tried to resample, but to no avail. I dont want to do this manually, by cutting and pasting Strings as I have done earlier. There should be a more elegant solution?
accepted answer: http://stackoverflow.com/a/47437697
tagged with: timestamp
type: AnsweredQuestion

http://stackoverflow.com/a/63565264
answers question: http://stackoverflow.com/q/47445582
has body: I think the problem lies with the command you set the button to execute. the below code for example tk.Button(..., command=submit()) In this code, the command submit() will be executed even before the mainloop runs, and at that instance of time, answer[7] is nowhere present. Just change the command styling to tk.Button(..., command=submit) and it should work. MOREOVER -- (Useful info) In case of functions which expect arguments to be supplied, the lambda keyword is used like below:: tk.Button(..., command=lambda x: submit(x))
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/81885962
type: Comment
has text: `curl` won't follow redirect by default. You should use `curl -L`
type: QuestionComment
score: 8
comment on: http://stackoverflow.com/q/47464961

http://stackoverflow.com/comment/81995611
type: QuestionComment
score: 0
has text: what's the content of `idk.py`? or is that the file you don't know how to write?
comment on: http://stackoverflow.com/q/47519632
type: Comment

http://stackoverflow.com/comment/81858322
comment on: http://stackoverflow.com/q/47450938
type: QuestionComment
score: 0
has text: indeed. You can do that for a whole `Series` with [`tz_convert`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.tz_convert.html#pandas.Series.dt.tz_convert) `pd.Series([pd.to_datetime(utc_str, utc=True)]).dt.tz_convert(pytz.timezone('Europe/Berlin'))`
type: Comment

http://stackoverflow.com/q/47465883
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81892464
answer count: 0
type: UnansweredQuestion
has title: Efficient way to load indexed text file into a numpy array?
upvote count: 1
tagged with: python
has body: I have a large text file which has the format: ID Data 1 4,5,6,7,2,3,4 3 1,2,3,6,2,1,3 2 1,5,4,2,3,2,8 What is an efficient way to load this into a 2d numpy array where ID is used as the row index and Data is split into integer values. I have looked at loadtxt and genfromtxt but cannot figure out how to efficiently handle the two level data format - tabs then commas. As asked for, my current solution is: import numpy as np import csv size = (3, 7) arr = np.zeros(size) with open(filename, 'r') as f: reader = csv.reader(f, delimiter='\t') next(reader) for id, data in reader: arr[int(id) - 1] = [int(x) for x in data.split(',')] print arr
has comment: http://stackoverflow.com/comment/81886403
score: 0
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47383112
has body: I am trying to do operations on a dataframe but I cannot seem to reformat it in the way that I want. I have: &gt;&gt;df = pd.DataFrame({ 'person':['Al','Al','Bob','Bob','Bob','Sue','Sue'], 'pet':['Cat','Dog','Fish','Fish','Zebra','Fish','Dog']}) &gt;&gt;df person pet 0 Al Cat 1 Al Dog 2 Bob Fish 3 Bob Fish 4 Bob Zebra 5 Sue Fish 6 Sue Dog I want to aggregate to the person level and have nested labels like so: person pet_info pet number 0 Al Cat 1 Dog 1 1 Bob Fish 2 Zebra 1 .... such that there are two labels/column names within the pet_info column so that: for row in df: print(row['person']) for stuff in row['pet_info']: print(stuff['pet']) will output: Al Cat Dog Bob Fish ... Any ideas on how to do this? I can't seem to implement this change in this way and I am reasonably familiar with pandas... Thanks!
answer count: 1
favorite count: 0
type: Question
tagged with: pandas
downvote count: 1
tagged with: dataframe
tagged with: python
score: -1
upvote count: 0
has answer: http://stackoverflow.com/a/47383124
has title: Embed 2D labelled array in Pandas
type: UnansweredQuestion

http://stackoverflow.com/comment/81792784
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47419178
has text: Possible duplicate of [Correct way to write line to file?](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file)
score: 0

http://stackoverflow.com/comment/81829953
type: Comment
type: QuestionComment
has text: @MooningRawr Yeah, my bad, sorry. Bad situations can always appear. But in this case, unlikely.
score: 0
comment on: http://stackoverflow.com/q/47437716

http://stackoverflow.com/a/47472272
has comment: http://stackoverflow.com/comment/81908096
has body: A Conv2D layer requires four dimensions, not three: (batch_size, height, width, channels). And the TimeDistributed will require an additional dimension: (batch_size, frames, height, width, channels) So, if you're really going to work with TimeDistributed+Conv2D, you need 5 dimensions. Your input_shape=(86,28,28,3), or your batch_input_shape=(batch_size,86,28,28,3), where I assumed you've got an RGB video (3 color channels). Usually, you just pass an input shape to the TimeDistributed. model.add(TimeDistributed(Dense(....), input_shape=(86,28,28,3)) You will need the batch_input_shape only in the case of using stateful=True LSTM's. Then you just replace the input_shape with the batch_input_shape. Notice that only the convolutional 2D layers will see images in terms of height and width. When you add the LSTM's, you will need to reshape the data to bring height, width and channels into a single dimension. For a shape (frames, h, w, ch): model.add(Reshape((frames,h*w*ch))) And you should not use TimeDistributed with these LSTMs, only with the convolutional layers. Your approach of using model.add(TimeDistributed(Flatten())) is ok instead of the reshape. Notice also that Keras has recently implemented a ConvLSTM2D layer, which might be useful in your case: https://keras.io/layers/recurrent/#convlstm2d
type: Answer
has comment: http://stackoverflow.com/comment/81903223
score: 11
has comment: http://stackoverflow.com/comment/81906562
upvote count: 11
has comment: http://stackoverflow.com/comment/81902930
has comment: http://stackoverflow.com/comment/101185881
has comment: http://stackoverflow.com/comment/81907128
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47470385
accepted answer of: http://stackoverflow.com/q/47470385
has comment: http://stackoverflow.com/comment/81908645

http://stackoverflow.com/comment/81916819
type: Comment
type: QuestionComment
has text: @cardamom Where does `json.dumps()` put quotes?
comment on: http://stackoverflow.com/q/47478475
score: 0

http://stackoverflow.com/a/47399989
has comment: http://stackoverflow.com/comment/81753452
downvote count: 0
has comment: http://stackoverflow.com/comment/81754250
has body: Make proper use of the function argument; names changed to clarify the nature of the variables. def read_config(filename='config.dat'): try: dest = '/home/admin/Documents/backup/' afile = open(filename) #Interate through list of files '\n' filelist = afile.read().split('\n') #Copy through interated list and strip white spaces and empty lines for file in filelist: if file: shutil.copy(file.strip(), dest) except FileNotFoundError: pass
answers question: http://stackoverflow.com/q/47399875
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/81828301
score: 0
comment on: http://stackoverflow.com/a/47436702
type: Comment
type: AnswerComment
has text: just calling stop() function in raised_button function simple charm have been struggling with , Thanks @furas

http://stackoverflow.com/comment/81850130
has text: Glad to hear it. Don't forget to upvote and accept this answer if that solves your problem :)
type: AnswerComment
comment on: http://stackoverflow.com/a/47447436
type: Comment
score: 0

http://stackoverflow.com/comment/81826241
comment on: http://stackoverflow.com/q/47435904
has text: That loop will tie up that entire process.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81901861
score: 0
has text: Yeah sorry, I read "java" instead of js. In JS did you try Number() or ParseInt() ?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47452872

windowserror
tags question: http://stackoverflow.com/q/47403805
tag name: windowserror
type: Tag

http://stackoverflow.com/a/47468977
accepted answer of: http://stackoverflow.com/q/47467077
has body: You could do something like this: import numpy as np import pandas as pd import matplotlib.pyplot as plt np.random.normal(0, 10) df = pd.DataFrame({ 'v1': np.random.normal(0, 3, 20), 'v2': np.random.normal(0, 3, 20), 'v3': np.random.normal(0, 3, 20), 'v4': np.random.normal(0, 3, 20), 'v5': np.random.normal(0, 3, 20), 'v6': np.random.normal(0, 3, 20), }) # Generically define how many plots along and across ncols = 3 nrows = int(np.ceil(len(df.columns) / (1.0*ncols))) fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(10, 10)) # Lazy counter so we can remove unwated axes counter = 0 for i in range(nrows): for j in range(ncols): ax = axes[i][j] # Plot when we have data if counter &lt; len(df.columns): ax.hist(df[df.columns[counter]], bins=10, color='blue', alpha=0.5, label='{}'.format(df.columns[counter])) ax.set_xlabel('x') ax.set_ylabel('PDF') ax.set_ylim([0, 5]) leg = ax.legend(loc='upper left') leg.draw_frame(False) # Remove axis when we no longer have data else: ax.set_axis_off() counter += 1 plt.show() Results in: Adapted from: How do I get multiple subplots in matplotlib?
answers question: http://stackoverflow.com/q/47467077
score: 6
type: Answer
upvote count: 6
type: AcceptedAnswer
downvote count: 0

ordereddictionary
tags question: http://stackoverflow.com/q/47454535
tags question: http://stackoverflow.com/q/47469433
tags question: http://stackoverflow.com/q/47436956
type: Tag
tag name: ordereddictionary

http://stackoverflow.com/a/47418496
has comment: http://stackoverflow.com/comment/81791070
downvote count: 0
has comment: http://stackoverflow.com/comment/81791319
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47418295
answers question: http://stackoverflow.com/q/47418295
score: 1
type: Answer
has body: Using pd.to_datetime %timeit df['time'].apply(lambda x: parser.parse(x)) 1 loop, best of 3: 812 ms per loop %timeit pd.to_datetime(df.time) 100 loops, best of 3: 4.25 ms per loop len(df) Out[290]: 20000

http://stackoverflow.com/q/47524113
downvote count: 0
upvote count: 1
has body: I'm using Odoo 10 calendar, and try to customize function delete recurrent event. I override the unlink function of calendar. Event, and I can delete the recurrent event now. But after deleting the virtual events still shown, and I don't know how to refresh the calendar view. I tried to return from unlink function, but nothing change: return { 'type': 'ir.actions.client', 'tag': 'reload' } Can anyone help?
has title: Odoo 10 refresh calendar after delete
tagged with: odoo-10
tagged with: odoo
score: 1
tagged with: python
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47536463
has answer: http://stackoverflow.com/a/47537100
type: AnsweredQuestion
score: 12
answer count: 2
has title: pip install keep asking user and password
downvote count: 0
has answer: http://stackoverflow.com/a/47918179
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82030264
has comment: http://stackoverflow.com/comment/82030616
upvote count: 12
has comment: http://stackoverflow.com/comment/82034564
tagged with: nexus
has body: I am new to PyPI hosting on private, so I hosted private PyPI repo on Nexus3 with python 2.7, I put the following in pip.conf: [global] extra-index-url = https://username:password@example.com/repository/package/simple However, it keeps pops up to ask the user and password. Since I pass the username and password already in URL, should it just pass without aksing? Anyone have the same case and how do you solve it?
tagged with: pip
has comment: http://stackoverflow.com/comment/82029868
tagged with: python
possible better answer: http://stackoverflow.com/a/47918179
has comment: http://stackoverflow.com/comment/82030736
accepted answer: http://stackoverflow.com/a/47537100
has comment: http://stackoverflow.com/comment/82030996

http://stackoverflow.com/q/47410554
has answer: http://stackoverflow.com/a/47415529
tagged with: python
has title: Python: How to keep region inside canny close edge's area
score: 2
has answer: http://stackoverflow.com/a/47458235
favorite count: 0
tagged with: edge-detection
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
type: UnansweredQuestion
has body: I'm using canny algorithm to find the edges. Next, I want to keep the region inside the closed curves. My code sample is: import cv2 import numpy as np from matplotlib import pyplot as plt import scipy.ndimage as nd from skimage.morphology import watershed from skimage.filters import sobel img1 = cv2.imread('coins.jpg') img = cv2.imread('coins.jpg',0) edges= cv2.Canny(img,120,200) markers = np.zeros_like(img) markers[edges&lt;50] = 0 markers[edges==255] = 1 img1[markers == 1] = [0,0,255] img1[markers == 0] = [255,255,255] cv2.imshow('Original', img) cv2.imshow('Canny', img1) #Wait for user to press a key cv2.waitKey(0) My output image is I want to show the original pixels values inside the coins. Is that possible?
downvote count: 0

http://stackoverflow.com/comment/81971844
comment on: http://stackoverflow.com/a/47450879
type: Comment
has text: Yes, sure, only change `list(zip([{'Unit': a}]*len(x),x))` to `list(zip([{'unit': a}]*len(x),x))` and `df[c2].applymap(lambda x: {'Value': x}).apply(f)` to `df[c2].applymap(lambda x: {'value': x}).apply(f)`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81933974
has text: @furas Thank you for the quick answer, I am new to this but if I understand what you are saying correctly can I just write `conn[x], addr = s.accept()` and then have all the users on a list?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47489369
type: QuestionComment

http://stackoverflow.com/a/47528504
downvote count: 0
has comment: http://stackoverflow.com/comment/82028776
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82013778
has comment: http://stackoverflow.com/comment/82013854
has comment: http://stackoverflow.com/comment/82019898
answers question: http://stackoverflow.com/q/47514886
type: Answer
has body: The problem with your code is that your success_url calls the HomeView and thus the get() method of HomeView is called. And in get() method you created again a new form object.You must initialise your form with the instance that you want to update: form = HomeForm(instance = your_serverlist_object) And as you have to call the same HomeView at the first time as well as after edit you can pass some query parameter to detect which kind of form object you need to send in context.Like: success_url="%s?edit=true" % reverse_lazy('serverlist') Now in HomeView overriding dispatch method. class HomeView(TemplateView): template_name = 'serverlist.html' def dispatch(self, request, *args, **kwargs) query = request.GET.get("q") if query: self.posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: self.posts = serverlist.objects.all() def get(self, request): if request.GET.get('edit', ''): form = HomeForm(instance = self.posts) else: form = HomeForm() args = {'form' : form, 'posts' : self.posts} return render(request, self.template_name, args)
has comment: http://stackoverflow.com/comment/82013484
has comment: http://stackoverflow.com/comment/82013645
has comment: http://stackoverflow.com/comment/82014700
has comment: http://stackoverflow.com/comment/82018475
has comment: http://stackoverflow.com/comment/82018451

http://stackoverflow.com/q/47435477
has body: I have a dataframe df_KO with the following columns: Date, Reg (Registration Number) and a measure of the quality of this particular component (Status). For a certain use, I want to replace the values of these measurements with either KO or OK depending on a certain threshold with the function: df_KO.Status = df_KO.apply(lambda row: replace_func(row["Status"]), axis=1) Where replace_func is: def replace_func(value): if value &lt; 0.25: return "OK" elif value &gt;= 0.25: return "KO" else: return np.nan However, I also want to keep the original measurement values, so I have made a copy of the DF. But to my surprise the following statement: df_KO_raw = df_KO df_KO_raw["Reg"] = "Dummy" print(df_KO_raw.head(5)) df_KO.Status = df_KO.apply(lambda row: replace_func(row["Status"]), axis=1) print(df_KO_raw.head(5)) Gives the following output: Date Reg Status 0 2017-02-02 11:52:37 Dummy 0 1 2017-02-04 03:02:57 Dummy 0 2 2017-01-27 12:50:53 Dummy 0.00406572 3 2017-01-29 10:58:50 Dummy 0.00754577 4 2017-01-31 22:43:44 Dummy 0.0037902 Date Reg Status 0 2017-02-02 11:52:37 Dummy OK 1 2017-02-04 03:02:57 Dummy OK 2 2017-01-27 12:50:53 Dummy OK 3 2017-01-29 10:58:50 Dummy OK 4 2017-01-31 22:43:44 Dummy OK Why is this happening? I'm clearly trying to perform an operation on only the df_KO DF, why does it change the values in df_KO_raw as well? Oh it has also changed the values of df_KO. I'm probably overlooking something obvious, but at this point I can't really see what. Thanks in advance. Regards
has comment: http://stackoverflow.com/comment/81825128
linked to: http://stackoverflow.com/q/13419822
upvote count: 2
answer count: 0
score: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81825534
type: Question
linked to: http://stackoverflow.com/q/4794244
tagged with: pandas
has comment: http://stackoverflow.com/comment/81826729
has comment: http://stackoverflow.com/comment/81825393
has title: Why does a function overwrite another dataframe pandas
tagged with: dataframe
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/47480955
downvote count: 2
has comment: http://stackoverflow.com/comment/81916866
upvote count: 1
has title: Dictionary value "not defined" Python
has answer: http://stackoverflow.com/a/47481341
has comment: http://stackoverflow.com/comment/81916807
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47481123
has comment: http://stackoverflow.com/comment/81917011
tagged with: key-value
type: UnansweredQuestion
has body: I'm working on a simple grocery list for class. In the first step we create an empty dictionary and list to be filled by input from a user. All grocery items go into a dictionary (grocery_item{}) and all of the dictionaries are to be added to the list (grocery_history). My script currently looks like this: grocery_item = {} grocery_history = [] stop = 'go' while stop == 'go' or stop == 'c': item_name = input("Item name: \n" ) quantitiy = int(input("Quantitiy purchased:\n" )) cost = float(input("Price per item:\n" )) grocery_item.update({'name' : item_name, 'number' : quantitiy, 'price' : cost}) grocery_history.append(grocery_item) stop = input("Would you like to enter another item?\n Type 'c' for continue or 'q' to quite:\n") If I print grocery_history at this point, it will print the list of dictionaries exactly as I intended. In the next step of the grocery list, we are trying to find the grand total of the items. However, whenever I try to find each items individual value, using for loops to get to each dictionary in the list, I receive an error claiming that keys are not defined, even though it just printed the dictionary entry for that grocery item, and all of the keys had values. My script for this section looks like this: grand_total = 0 for item in grocery_history: I = 0 for price in item: item_total = number * price grand_total += item_total print(number + name + '@' + '$' + price + 'ea' + '$' + round(item_total,2)) item_total = 0 I += 1 print('$' + round(grand_total,2)) The error is for the line in which I am trying to find the item_total, because it is the first line I try to use one of the keys. I have tried to rewrite the keys as grocery_item(numbers)/grocery_item(price), and receive the same error message. I appreciate any help, and thanks in advance!
tagged with: python
score: -1
tagged with: dictionary
answer count: 2

http://stackoverflow.com/comment/81858409
has text: Thank you yes, I've got that step. It's computing the dot product of the velocity vector and the offset vector between each particle and every other particle, resulting in a nxn array of angles between all particles and every other particle.
comment on: http://stackoverflow.com/q/47446909
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47408671
downvote count: 0
upvote count: 1
has body: If I understood right you want to access the labels based on the feature importance. If this is the case then you can do the following: #after fitting the model use this to get the feature importance feature_importance = clf.feature_importances_ # make importances relative to max importance feature_importance = 100.0 * (feature_importance / feature_importance.max()) # sort the importances and get the indices of the sorting sorted_idx = np.argsort(feature_importance) #match the indices with the labels of the x matrix #important: x must have columns names to do this x.columns[feature_names[sorted_idx]] This will give you the feature names in ascending order. This means that the first name is the feature the least important and the last name is the feature that is the most important of all.
answers question: http://stackoverflow.com/q/47397337
type: Answer
score: 1

http://stackoverflow.com/comment/82293165
type: QuestionComment
score: 0
has text: I know what's wrong ,since you said that heroku doesn't read my runtime.txt,and then I try to install python 3.6.3 in virtualenv,but failed,it turned out that my ubuntu system was broken,due to long time to find the cause,I reinstall the system,install 3.6.3,and no problems happened on the way on heroku.thank you so much..
comment on: http://stackoverflow.com/q/47524285
type: Comment

http://stackoverflow.com/q/47398338
type: Question
has title: How do I return a list of bytes in rust-cpython?
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: rust
score: 2
has comment: http://stackoverflow.com/comment/81795889
has comment: http://stackoverflow.com/comment/81795393
has body: I'm trying to return a list of bytes to be used in Python: fn example(_py: Python) -&gt; PyResult&lt;PyList&gt; { let result = some_function(); let elements_raw = vec![]; for entry in result { elements_raw.push(PyBytes::new(_py, &amp;entry.0)); } let x: &amp;[PyBytes] = &amp;elements_raw; let py_list = PyList::new(_py, x); Ok(py_list) } However, this line complains because PyList requires a PyObject: let py_list = PyList::new(_py, x); Is there any way to cast a PyBytes into a PyObject? Is there some better way to return a list of bytes?
has comment: http://stackoverflow.com/comment/81750737
favorite count: 0

http://stackoverflow.com/comment/81779588
comment on: http://stackoverflow.com/q/47413170
has text: What is your desired output?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47386149
has comment: http://stackoverflow.com/comment/81725636
has title: Union of two defaultdict in python
tagged with: unix
tagged with: c++
has comment: http://stackoverflow.com/comment/81725313
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/81725417
downvote count: 0
upvote count: 1
tagged with: collections
favorite count: 0
has body: I have two defaultdict, size of these defaultdict is too large. Sample of these two defaultdict are like: a = {'20170101':('a','b','c','d'),'20170102':('a','b','e','g'),'20170103':('w','q','c','d'),'20170104':('m','b','n','d'),'20170105':('a','d','f','h'),'20170106':('a','s','t','i')} b = {'20170101':('x','y','z','d'),'20170102':('w','b','e','h'),'20170103':('a','b','m','n'),'20170104':('g','a','n','u'),'20170105':('a','d','g','v'),'20170106':('u','v','t','s')} I want to get the count of common elements in respective dates, I tried the following code, and its working, but now I want to optimize it with space and time perspective. for key in a.viewkeys() &amp; b.viewkeys(): count = len(set(b[key]) &amp; set(a[key])) print key,"-",count data is quite high. dates may have 100 000 elements in it. I'm new in c++, so if anyone who could help in building cpp library and integrate it with python.
type: Question
tagged with: defaultdict
has comment: http://stackoverflow.com/comment/81726430
has comment: http://stackoverflow.com/comment/81725382
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81726491
tagged with: python

http://stackoverflow.com/q/47525063
tagged with: apache-spark
tagged with: encoding
linked to: http://stackoverflow.com/q/9942594
has body: I have a Spark Dataframe that must be saved in PostgreSQL. I think I have the appropriate Python sentence except for the encoding options, since I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 95: ordinal not in range(128) My current sentence is as: df.write.jdbc(url=jdbc_url, table='{}.{}'.format(schema_name, table_name), mode='overwrite', properties=properties) It seems by default Pyspark is trying to encode the dataframe as ASCII, thus I should specify the correct encoding (UTF-8). How to do that? I've tried with option("charset", "utf-8"), option("encoding", "utf-8") and many other combinations I've seen in the Internet. I've also tried to add "client_encoding":"utf8" in the properties passed to jdbc. But nothing seems to work. Any help would be really appreciated. Additional info: Python 2.7 Spark 1.6.2 EDIT 1 My database is UTF-8 encoded: $ sudo -u postgres psql db_test -c 'SHOW SERVER_ENCODING' server_encoding ----------------- UTF8 (1 row) EDIT 2 I noticed together with this error another one was hidden in the logs: the PostgreSQL driver was complaining about the table I wanted to create was already created! Thus, I removed it from PostgreSQL and everything went like a charm :) Unfortunately, I was not able to completely understand how one thing was related to the other... Maybe because the table that was already created used ASCII encoding and there was some kind of incompatibility among it and the data that was intended to be saved?
has comment: http://stackoverflow.com/comment/82095462
downvote count: 2
answer count: 1
has title: Write Spark Dataframe in PostgreSQL with UTF-8 encoding
linked to: http://stackoverflow.com/q/5090858
has comment: http://stackoverflow.com/comment/82007823
favorite count: 0
type: Question
tagged with: postgresql
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/47525902
upvote count: 2
score: 0

http://stackoverflow.com/q/47417003
has comment: http://stackoverflow.com/comment/81787889
downvote count: 0
upvote count: 1
tagged with: string
score: 1
has comment: http://stackoverflow.com/comment/81789205
has comment: http://stackoverflow.com/comment/81788250
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81787835
has body: I have a string like: &lt;number&gt;xx&lt;-&gt;a&lt;T&gt;b&lt;F&gt;c&lt;F&gt;d&lt;F&gt;e&lt;F&gt;f&lt;F&gt;g&lt;T&gt;h&lt;F&gt;i&lt;F&gt; How can I efficiently parse this string so that i.e. xx has a value of null a has a value of 1 b has a value of 0
linked to: http://stackoverflow.com/q/10281863
tagged with: python
accepted answer: http://stackoverflow.com/a/47417541
has comment: http://stackoverflow.com/comment/81788594
has comment: http://stackoverflow.com/comment/81788126
has answer: http://stackoverflow.com/a/47417541
has title: python string tokenization - custom lexer?
tagged with: tokenize
tagged with: lexer
type: AnsweredQuestion

http://stackoverflow.com/q/47429651
accepted answer: http://stackoverflow.com/a/47543629
tagged with: python
has answer: http://stackoverflow.com/a/47543629
has title: How i can insert data from dataframe(in python) to greenplum table?
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81831282
tagged with: greenplum
favorite count: 0
type: Question
has body: Problem Statement: I have multiple csv files. I am cleaning them using python and inserting them to SQL server using bcp. Now I want to insert that into Greenplum instead of SQL Server. Please suggest a way to bulk insert into greenplum table directly from python data-frame to GreenPlum table. Solution: (What i can think) Way i can think is CSV-> Dataframe -> Cleainig -> Dataframe -> CSV -> then Use Gpload for Bulk load. And integrate it in Shell script for automation. Do anyone has a good solution for it. Issue in loading data directly from dataframe to gp table: As gpload ask for the file path. Can i pass a varibale or dataframe to that? Is there any way to bulkload into greenplum ?I dont want to create a csv or txt file from dataframe and then load it to greenplum.

http://stackoverflow.com/q/47511255
answer count: 1
type: Question
has body: I have following bottle template code to show my table: %for row in rows: %for col in row: {{col}} %end %end I would like to check all my cells and change their look if they do not contain "Some string": if col == "Some string": {{col}} else: {{col}} Do I need to do comparisons in a template (frontend) or in my "engine" (backend)?
tagged with: python
tagged with: bottle
accepted answer: http://stackoverflow.com/a/47511425
has title: Embedded python code in Bottle template - simple comparison using "if" statement
has answer: http://stackoverflow.com/a/47511425
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47402435
tagged with: python
has comment: http://stackoverflow.com/comment/81779169
accepted answer: http://stackoverflow.com/a/55454635
has answer: http://stackoverflow.com/a/55454635
downvote count: 0
upvote count: 50
has title: pytest fixture of fixture, not found
answer count: 1
linked to: http://stackoverflow.com/q/35777854
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/135352703
has body: Based on this stackoverflow: pytest fixture of fixtures I have the following code in the same file: @pytest.fixture def form_data(): return { ... } @pytest.fixture def example_event(form_data): return {... 'data': form_data, ... } But when I run pytest, it complains that fixture 'form_data' not found I am new to pytest so I am not even sure if this is possible?
type: AnsweredQuestion
tagged with: pytest
score: 50

http://stackoverflow.com/comment/81913213
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47478810
score: 0
has text: Wait a second, is it not possible to have pyinstaller bundle my python script into an exe. That can both run on mac and windows? That's how I interpreted it: https://pyinstaller.readthedocs.io/en/stable/operating-mode.html#how-the-one-folder-program-works

http://stackoverflow.com/comment/81766195
type: QuestionComment
has text: please mention the line in which you are getting the error.
comment on: http://stackoverflow.com/q/47403634
score: 0
type: Comment

internationalization
tags question: http://stackoverflow.com/q/47392881
type: Tag
tag name: internationalization

http://stackoverflow.com/comment/81804658
has text: Do tweets with two keywords count twice in the table?
score: 0
comment on: http://stackoverflow.com/q/47419735
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81824992
type: AnswerComment
has text: Can you share the entire error. Also any chance you have a file named simplejson.py anywhere in the directory where your code is stored?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47434434

http://stackoverflow.com/comment/81948152
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47496445
type: Comment
has text: @omri_saadon well, are you sure?

http://stackoverflow.com/q/47497226
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83471060
has body: I am writing a simple producer/consumer app to call multiple URL's asynchronously. In the following code if I set the conn_count=1, and add 2 items to the Queue it works fine as only one consumer is created. But if I make conn_count=2 and add 4 items to the Queue only 3 request are being made. The other request fails with ClientConnectorError. Can you please help be debug the reason for failure with multiple consumers? Thank You. I am using a echo server I created. Server: import os import logging.config import yaml from aiohttp import web import json def start(): setup_logging() app = web.Application() app.router.add_get('/', do_get) app.router.add_post('/', do_post) web.run_app(app) async def do_get(request): return web.Response(text='hello') async def do_post(request): data = await request.json() return web.Response(text=json.dumps(data)) def setup_logging( default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG' ): path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: config = yaml.safe_load(f.read()) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level) if __name__ == '__main__': start() Client: import asyncio import collections import json import sys import async_timeout from aiohttp import ClientSession, TCPConnector MAX_CONNECTIONS = 100 URL = 'http://localhost:8080' InventoryAccount = collections.namedtuple("InventoryAccount", "op_co customer_id") async def produce(queue, num_consumers): for i in range(num_consumers * 2): await queue.put(InventoryAccount(op_co=i, customer_id=i * 100)) for j in range(num_consumers): await queue.put(None) async def consumer(n, queue, session, responses): print('consumer {}: starting'.format(n)) while True: try: account = await queue.get() if account is None: queue.task_done() break else: print(f"Consumer {n}, Updating cloud prices for account: opCo = {account.op_co!s}, customerId = {account.customer_id!s}") …
tagged with: python-asyncio
tagged with: python
has title: Python asyncio / aiohttp error
type: Question
has comment: http://stackoverflow.com/comment/81956438
tagged with: aiohttp
answer count: 0
has comment: http://stackoverflow.com/comment/81964136

http://stackoverflow.com/comment/81829760
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47437616
score: 0
has text: Thanks a lot. I understand now.

http://stackoverflow.com/a/47387639
has comment: http://stackoverflow.com/comment/81768859
score: 1
has body: In your view.py file the render has no clue where to get the name variable from. Here is one way to fix it: You can pass the name parameter from ser.html to the backend as GET param: &lt;div&gt; &lt;a v-bind:href="'searchnew/?name='+post.name"&gt; {{post.name}}&lt;/a&gt; &lt;/div&gt; Then in your view.py file, get the name variable: def det(request): name = request.GET.get('name') return render(request,"det.html",{'name' :name}) In det.html it will be available. If you'd like to do it with POST request, change the ser.html to run a VueJS function, something like this: &lt;div&gt; &lt;a v-on:click="funcToPost"&gt;{{post.name}}&lt;/a&gt; &lt;/div&gt; In the VueJS object implement the method funcToPost to do the POST call, something like this: var app = new Vue({ // ... some code here methods: { funcToPost: function() { // ... some code here $.ajax({ // ... some code here data: { name: {{name}} } }) } } }) In view.py change request.GET.get('name') to request.POST.get('name'). Hope this solves your problem. Good luck.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81769222
has comment: http://stackoverflow.com/comment/81768910
has comment: http://stackoverflow.com/comment/81768090
has comment: http://stackoverflow.com/comment/81768480
has comment: http://stackoverflow.com/comment/81768984
has comment: http://stackoverflow.com/comment/81769194
type: Answer
accepted answer of: http://stackoverflow.com/q/47386118
has comment: http://stackoverflow.com/comment/81768997
answers question: http://stackoverflow.com/q/47386118

http://stackoverflow.com/q/47536176
type: Question
has title: UpdateView gives blank/empty forms instead of previous data I edit
has body: I'm using UpdateView to edit data using forms. But, when I click edit button the forms are blank/empty without the previous data. I even added {% with server.id as server_id %} {% with forms.id as edit_form %} in my index.html.. Does anoyone have anyclue what I am missing? view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) #if not form.cleaned_data['ServerName']: #post.servername = " " post.save() #text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text' : text} return render(request, self.template_name,args) class PostDelete(DeleteView): model = serverlist success_url = reverse_lazy('serverlist') class PostEdit(UpdateView): model = serverlist #post = serverlist.objetcs.get(server_id=server_id) fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status'] success_u…
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: mysql
tagged with: web
accepted answer: http://stackoverflow.com/a/47537339
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47537339
score: 0
tagged with: django
answer count: 1

http://stackoverflow.com/a/47473007
type: Answer
accepted answer of: http://stackoverflow.com/q/47472864
score: 0
answers question: http://stackoverflow.com/q/47472864
type: AcceptedAnswer
has body: rows = ( [u'ABC'], [u'DEF'], [u'GHI']) print rows for i in rows: print i if i == [u"DEF"]: print("Hello") if i[0] == u"DEF": print "world" I do not know, what exactly is your problem. The string is inside a list. Either you compare the complete list with a list of this string or the first element of the list with the string itself.

http://stackoverflow.com/q/47392881
has answer: http://stackoverflow.com/a/47393259
tagged with: python
has title: PyQt5 - Translated texts do not appear in the GUI
tagged with: internationalization
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: pyqt5
has body: Despite existing, translated texts do not appear in my GUI. Here is the main.py from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow import sys, os from view.MainWindow import MainWindow if __name__=='__main__': app = QApplication(sys.argv) mainWindow = MainWindow() MainWindow.show(mainWindow) translator = QtCore.QTranslator() (filepath,filename)=os.path.split(__file__) trad_path=os.path.join(filepath,'translate','fr_FR.qm') print (trad_path) translator.load(trad_path) app.installTranslator(translator) sys.exit(app.exec_()) The main.py file is under a src folder alongside a translate folder containing the fr_FR.qm file. The print (trad_path) shows that the path to the file is correct Inside , the MainWindow.py file I have a showEvent() function that calls the set_translatable_textes() function def showEvent(self,ev): print('in show event') self.set_translatable_textes() def set_translatable_textes(self): self.choose_session_label.setText( QCoreApplication.translate( 'Main Window','A text that has translation')) #self.choose_session_label.setText('Untranslated text') self.edit_button.setText(self.tr('Edit')) #self.edit_button.setText('Untranslated text') I try two kinds of translation : With QCoreApplication.translate() With tr() None of them is working. To be sure I call the function, I replace each statements with the commented statement under. They both work. I am probably doing something wrong but what?
type: Question

http://stackoverflow.com/q/47395284
has answer: http://stackoverflow.com/a/63898877
tagged with: tkinter
linked to: http://stackoverflow.com/q/50367837
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81761203
has comment: http://stackoverflow.com/comment/81744441
downvote count: 1
favorite count: 0
has title: Tkinter GUI does not run properly when auto boot
has body: this is my first time using Raspberry Pi 3 with Python Tkinter to make a GUI. I have written my script using Python. My code uses Raspberry Pi 3 GPIO 8 and GPIO 11 as inputs. I have 2 relay connected to the 2 inputs terminal. The relay will act as a switch. My code will count how many times the relay have switched on and display in the GUI. I have tested it using Raspberry Pi 3 LxTerminal with sudo python /home/pi/Desktop/test.py The GUI opens and it works perfectly. Every time the relay switches, the count +1. Then I decided to make it auto boot every time I reboot my Pi. I uses the following technique. sudo nano /etc/profile Then add the following code to the final line and save it. sudo python /home/pi/Desktop/test.py I reboot my Raspberry Pi and the GUI boot automatically. But the GUI does not response to the relay switching. I tried rebooting a few times and it worked after a few reboot. Then I tried to reboot again and the next time it does not work again. This steps keep repeating over and over again. Some times the GUI work, some times it doesn't. Anyone have come across this sorts of problem? What should I do to make the GUI auto boot to works 100%? NOTE: Having 5V 1A phone charger to supply power to Pi. (Tried using 5V 2.1A as well) Connected a HDMI to VGA converter to connect to a monitor Does not have keyboard and mouse when the GUI is set to auto boot
tagged with: raspberry-pi
type: Question
answer count: 2
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47398214

http://stackoverflow.com/comment/81760425
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47403134
has text: Which parameters are you filling in with keywords? Show the api and usage that is failing.

http://stackoverflow.com/comment/81772043
has text: apologies, just re-ran. It is a Keyerror on the field I tried to groupby. `\groupby.py", line 2842, in _get_group raise KeyError(gpr) KeyError: 'MyField'`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47397692

http://stackoverflow.com/q/47423673
has title: Remove empty key,pairs from JSON using python
has comment: http://stackoverflow.com/comment/81802257
score: -4
accepted answer: http://stackoverflow.com/a/47423751
answer count: 1
favorite count: 0
has body: i have json data data = [ {"A": "1", "C": "", "B": "2", "E": "4", "D": "3"}, {"A": "", "C": "6", "B": "5", "E": "7", "D": ""}, {"A": "", "C": "", "B": "", "E": "8", "D": ""}, {"A": "", "C": "", "B": "9", "E": "", "D": "10"} ] I want to remove empty key/value using python so that it looks like this data = [ {"A": "1", "B": "2", "E": "4", "D": "3"}, {"C": "6", "B": "5", "E": "7"}, {"E": "8"}, {"B": "9", "D": "10"} ]
type: Question
has comment: http://stackoverflow.com/comment/81802740
has comment: http://stackoverflow.com/comment/81803392
tagged with: python
has comment: http://stackoverflow.com/comment/81802113
has answer: http://stackoverflow.com/a/47423751
downvote count: 4
type: AnsweredQuestion
upvote count: 0
tagged with: http://stackoverflow.com/tag/json

ssl
tags question: http://stackoverflow.com/q/47475154
tags question: http://stackoverflow.com/q/47492461
tags question: http://stackoverflow.com/q/47516722
type: Tag
tags question: http://stackoverflow.com/q/47478994
tags question: http://stackoverflow.com/q/47524816
tags question: http://stackoverflow.com/q/47387266
tag name: ssl

http://stackoverflow.com/comment/81866422
has text: Thanks your solution worked and thanks for the link :)
type: Comment
comment on: http://stackoverflow.com/a/47449275
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81779644
score: 0
has text: Your welcome, I would very much appreciate if you could select this answer as helpful. Have a good day.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47401432

http://stackoverflow.com/comment/81995482
comment on: http://stackoverflow.com/a/47519541
score: 0
type: Comment
type: AnswerComment
has text: I like this formatting. Is there any way to add a "total" subcase to both, ``A`` and ``B``?

http://stackoverflow.com/comment/81874679
type: QuestionComment
has text: The directory structure is BottleTempl --> templates.py, parse.py BottleTempl --> views --> index.tpl
comment on: http://stackoverflow.com/q/47459950
score: 0
type: Comment

http://stackoverflow.com/a/47404475
score: 1
upvote count: 1
type: Answer
has body: you are incorrectly importing the file, change: from uploadfileapp.Best_model_forecast_v11 import * to; from uploadfileapp.models.Best_model_forecast_v11 import *
has comment: http://stackoverflow.com/comment/81772275
answers question: http://stackoverflow.com/q/47403771
downvote count: 0

http://stackoverflow.com/q/47397768
tagged with: nlp
has comment: http://stackoverflow.com/comment/81840883
has comment: http://stackoverflow.com/comment/81749134
score: 0
answer count: 0
has title: is there any text preprocessing which can detect san andreas as a single word Api for python
has comment: http://stackoverflow.com/comment/81780074
type: Question
has body: I am working twitter data for analysis but before analysis, i want to preprocess data. i tried nltk.word_tokenize(), but they don't remove punctuation and they don't understand san andreas and a single word but in tweets, there are many words like this. here is code def inital(): return 0 def get_vocab(lst): vocab_count=defaultdict(inital) i=0 for txt in lst: if type(txt)!=float: txt=txt.decode("utf8") for words in nltk.word_tokenize(txt): vocab_count[words]+=1 return vocab_count
tagged with: nltk
has comment: http://stackoverflow.com/comment/81749637
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/81810584
comment on: http://stackoverflow.com/q/47426938
type: QuestionComment
type: Comment
score: 0
has text: you write python code like javascript

http://stackoverflow.com/comment/81860219
has text: its mean when i run ng build then files are created in django static folder instead of dist
comment on: http://stackoverflow.com/a/47451372
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/53607065
type: Answer
has comment: http://stackoverflow.com/comment/139190665
upvote count: 27
has body: On Windows, you can install with pip: pip install opencv-python
has comment: http://stackoverflow.com/comment/129801870
answers question: http://stackoverflow.com/q/47450179
downvote count: 0
score: 27

http://stackoverflow.com/comment/81939067
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47481069
type: Comment
has text: Okay, I now understand why this is happening. But what would be the best way to prevent, so that it behaves as expected? Would I have to resort to calling Parallelogram.__init__() explicitly, or is there a way I can still get super() to work?

http://stackoverflow.com/a/47515574
downvote count: 0
type: Answer
upvote count: 1
has body: You may want to consider a sort of memoization to shorten the computation. Here we record the initial number and break if the number's value is below that number, since we have already seen those results. Then when the numbers are printed, it will return a reference to a previously printed series. To get it to print to infinity, see @Bill-the-Lizard's answer. def collataz(number): print(number, end=': ') initial_number = number while True: if number == 1 : print("DONE!") break if number % 2 == 0 : number = number //2 if number &lt; initial_number: print('[{}]'.format(number)) break print(number, end=' ') elif number % 2 ==1 : number = 3 * number + 1 print(number, end=' ') # form Bill the Lizard: n = 1 while True: collatz(n) n += 1 Here is the first 20 lines of this. 1: DONE! 2: [1] 3: 10 5 16 8 4 [2] 4: [2] 5: 16 8 [4] 6: [3] 7: 22 11 34 17 52 26 13 40 20 10 [5] 8: [4] 9: 28 14 [7] 10: [5] 11: 34 17 52 26 13 40 20 [10] 12: [6] 13: 40 20 [10] 14: [7] 15: 46 23 70 35 106 53 160 80 40 20 [10] 16: [8] 17: 52 26 [13] 18: [9] 19: 58 29 88 44 22 [11] 20: [10]
answers question: http://stackoverflow.com/q/47515111
has comment: http://stackoverflow.com/comment/81987788
score: 1

http://stackoverflow.com/comment/81793800
has text: Are you super sure the file exists? Try df = pd.read_csv(r'purchases.csv') if you are.
score: 1
comment on: http://stackoverflow.com/q/47419823
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81905589
has text: For me, that raises an value error: ValueError: No objects to concatenate. Any idea why this could be?
type: AnswerComment
comment on: http://stackoverflow.com/a/47475406
score: 0
type: Comment

http://stackoverflow.com/q/47407741
answer count: 3
tagged with: mocking
has answer: http://stackoverflow.com/a/64794304
has answer: http://stackoverflow.com/a/47407845
type: UnansweredQuestion
tagged with: methods
downvote count: 1
favorite count: 0
tagged with: unit-testing
type: Question
tagged with: python-mock
upvote count: 18
tagged with: python
score: 17
has answer: http://stackoverflow.com/a/75861838
has body: Trying to write a testcase for my class based function. This is skeleton of my class class Library(object): def get_file(self): pass def query_fun(self): pass def get_response(self): self.get_file() response = self.query_fun() # some business logic here return response I need to create a testcase that can mock just the query_fun and do the rest. tried below but seems is not the right direction: from unittest import mock, TestCase from library.library import Library class TestLibrary(TestCase): def setUp(self): self.library = Library() @mock.patch('library.library.Library') def test_get_response(self, MockLibrary): mock_response = { 'text': 'Hi', 'entities': 'value', } MockLibrary.query_fun.return_value = mock_response response = MockLibrary.get_response() self.assertEqual(response, mock_response) What I'm expecting is to setup mock and calling get_response will not actually call the original query_fun method, but instead call the mock query_fun.
has title: How to mock just the method inside the class

http://stackoverflow.com/comment/81949917
comment on: http://stackoverflow.com/a/47496643
type: Comment
type: AnswerComment
score: 0
has text: And I don't have a pygimp.interp file in my GIMP installation

http://stackoverflow.com/q/47474254
has answer: http://stackoverflow.com/a/47474618
answer count: 1
has body: I get the following error when I run my code and I don't know why: Traceback (most recent call last): File "python", line 27, in &lt;module&gt; File "python", line 25, in members_of_circles sqlite3.OperationalError: no such column: circleCat.name the code : import sqlite3 con = sqlite3.connect(":memrory:") cur = con.cursor() def creat_tables () : cur.execute("CREATE table circleCat (id INTEGER PRIMARY KEY, name TEXT, description TEXT)") cur.execute("CREATE table members( id INTEGER PRIMARY KEY, name TEXT, level TEXT, crcl TEXT)") def add_a_member(name, level, crcl): cur.execute("INSERT INTO members (name, level, crcl) VALUES (?, ?, ?)" , (name, level, crcl)); def add_a_circle(name, description): cur.execute("INSERT INTO circleCat (name, description) VALUES (?, ?)" , (name, description)); creat_tables () add_a_circle("Gaming", "for Gaming") add_a_member("hossam", "beginner", "Gaming") def members_of_circles(): cur.execute("SELECT name FROM members WHERE members.crcl = circleCat.name") members_of_circles()
score: 0
has comment: http://stackoverflow.com/comment/81903768
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/81903654
has title: sqlite3.OperationalError: no such column: circleCat.name
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/47480030
type: AcceptedAnswer
downvote count: 0
score: 4
has body: When you import spam as sp, you make sure that there are no conflicts with other import commands: import spam as sp import myfunctions as my sp.foo() my.foo() This is working as expected, but this isn't: from spam import * from myfunctions import * foo() foo() #Which foo() is meant? UNCLEAR!!! When you avoid this problem by using import spam as sp, why would you want to use from spam import * anyways? I don't think there is any point in this.
answers question: http://stackoverflow.com/q/47479965
type: Answer
accepted answer of: http://stackoverflow.com/q/47479965
upvote count: 4

http://stackoverflow.com/comment/82006553
has text: There is problem in `6.` row all data are in first cell.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47525204

http://stackoverflow.com/comment/81760830
type: QuestionComment
has text: @Chase, "like bash"? Bash doesn't have any control over how programs it invokes behave, and inasmuch as GNU tools let you put options after positional arguments, doing so is an [active violation of POSIX utility syntax guidelines](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02) -- see #9 in particular.
comment on: http://stackoverflow.com/q/47403438
type: Comment
score: 2

http://stackoverflow.com/q/47471725
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
upvote count: 0
downvote count: 2
answer count: 1
tagged with: button
has title: Arguments in button command to change global variable value python tkinter
has body: I'm trying to get a set of buttons that will change the value of my global variable "y". I'm pretty new to python, and am very new to tkinter. I have tried using lambda and solutions in similar questions haven't seemed to fix the issue. Here is my code: import tkinter as tk from tkinter import * master=Tk() def assignint(value): global y y = value y= StringVar() frame = Frame(master) frame.grid(row=0, columnspan=4) for i in range(2): Grid.rowconfigure(master,i,weight=1) for i in range(4): Grid.columnconfigure(master,i,weight=1) Button1 = Button(master,text='Fault1',command= lambda: assignint(0)) Button1.grid(row=1, column=0,sticky=N+S+E+W) Button2 = Button(master,text='Fault2',command= lambda: assignint(1)) Button2.grid(row=1, column=1,sticky=N+S+E+W) Button3 = Button(master,text='Fault3',command= lambda: assignint(2)) Button3.grid(row=1, column=2,sticky=N+S+E+W) Button4= Button(master,text='Fault4',command= lambda: assignint(3)) Button4.grid(row=1, column=3,sticky=N+S+E+W) if y.get()!='': print('The value of y is:', y.get()) mainloop()
has answer: http://stackoverflow.com/a/47471794
has comment: http://stackoverflow.com/comment/81898240
tagged with: global-variables
favorite count: 0
type: Question
score: -2
accepted answer: http://stackoverflow.com/a/47471794
has comment: http://stackoverflow.com/comment/81898277
has comment: http://stackoverflow.com/comment/81898326

http://stackoverflow.com/comment/81882218
comment on: http://stackoverflow.com/q/47463612
type: QuestionComment
has text: Python comes with an interactive interpreter. You can type those commands into the interpreter and see what they do. Then you can experiment with them to learn more. Apart from the Python documentation there is also builitin help: try typing `help(input)` for example.
score: 0
type: Comment

http://stackoverflow.com/q/47520486
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81997904
has comment: http://stackoverflow.com/comment/81998005
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82001686
tagged with: dicom
has answer: http://stackoverflow.com/a/47520529
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81997853
has body: I'm trying to learn how to use pydicom for reading and processing dicom images. I'm using Python 3. import dicom import numpy ds = pydicom.read_file(lstFilesDCM[0]) print(ds.pixel_array)` I get an error NameError: name 'pydicom' is not defined. If I change ds = pydicom.read_file(lstFilesDCM[0]) to ds = dicom.read_file(lstFilesDCM[0]) (using dicom.read_file instead), I get the following error: NotImplementedError: Pixel Data is compressed in a format pydicom does not yet handle. Cannot return array I also verified that pydicom is properly installed and updated. How do i fix this?
has answer: http://stackoverflow.com/a/47520815
tagged with: python
tagged with: pydicom
has title: pydicom is not defined
type: Question
has comment: http://stackoverflow.com/comment/81997493

http://stackoverflow.com/q/47422758
accepted answer: http://stackoverflow.com/a/47423029
tagged with: django
tagged with: python
has title: How to count the number of resuts of an if on Django built in templates
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47423029
answer count: 2
downvote count: 0
tagged with: django-template-filters
has body: I have the following situation: {% for subject in subjects %} {% if subject.media &lt; 60 %} {% endif %} {% endfor %} The result of that is "161616", because I have 16 subjects on my database, but I want to show the number of subjects that are below the media, like "3".
possible better answer: http://stackoverflow.com/a/47422814
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47422814

http://stackoverflow.com/comment/81930489
type: Comment
type: QuestionComment
has text: @Dan-Dev yes, take a look: https://pastebin.com/t6pajB9g When I run this script, the cheapest result is 1182EUR. When I search exactly the same route manually, it is 579EUR. It's because of the airline of third flight.
score: 0
comment on: http://stackoverflow.com/q/47487029

http://stackoverflow.com/a/67062828
has comment: http://stackoverflow.com/comment/118582966
has comment: http://stackoverflow.com/comment/118602228
answers question: http://stackoverflow.com/q/47526775
type: Answer
score: 4
upvote count: 4
has body: try this pdf.multi_cell(0, 5, 'text' + '\n' +'test asdfaf')
downvote count: 0

http://stackoverflow.com/q/47540445
has body: I can't find it anywhere and pip install is not working for me on Windows bash. I am using a virtualenv in Windows bash. When I run a python file that has a flask cache import, I get the following error: Traceback (most recent call last): File "run.py", line 3, in &lt;module&gt; from app import app File "/mnt/c/Users/.../app/__init__.py", line 1, in &lt;module&gt; from main import * File "/mnt/c/Users/.../app/main.py", line 2, in &lt;module&gt; from flask_cache import Cache ImportError: No module named flask_cache
has answer: http://stackoverflow.com/a/47661307
favorite count: 0
has comment: http://stackoverflow.com/comment/82363273
has comment: http://stackoverflow.com/comment/82283300
type: Question
has answer: http://stackoverflow.com/a/47540464
has comment: http://stackoverflow.com/comment/82038479
possible better answer: http://stackoverflow.com/a/47540464
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/82038569
score: -4
has comment: http://stackoverflow.com/comment/82280963
has comment: http://stackoverflow.com/comment/82039717
tagged with: pip
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/82280343
has comment: http://stackoverflow.com/comment/82283560
accepted answer: http://stackoverflow.com/a/47661307
has title: What's the sudo apt-get install command for installing flask-cache?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82283573
downvote count: 4
tagged with: bash
has comment: http://stackoverflow.com/comment/82283160
has comment: http://stackoverflow.com/comment/82281134

http://stackoverflow.com/a/47422054
type: Answer
score: 0
has body: Just tried the same thing here, and both work: import configparser config = configparser.ConfigParser() #this works print(config.read('config.ini')) #this works too print(config.read('./../config.ini'))
answers question: http://stackoverflow.com/q/47420889

http://stackoverflow.com/a/47385052
accepted answer of: http://stackoverflow.com/q/47384763
type: Answer
answers question: http://stackoverflow.com/q/47384763
has body: Different methods can be used for removing leading and trailing spaces, for converting multiple spaces to one and to remove spaces before exclamation mark, comma etc: mystr = " Hello . To , the world ! " print(mystr) mystr = mystr.strip() # remove leading and trailing spaces import re # regex module mystr = re.sub(r'\s+'," ", mystr) # convert multiple spaces to one space. mystr = re.sub(r'\s*([,.!])',"\\1", mystr) # remove spaces before comma, period and exclamation etc. print(mystr) Output: Hello . To , the world ! Hello. To, the world!
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47425022
score: 1
accepted answer of: http://stackoverflow.com/q/47419735
has body: Since each tweet can have multiple keywords, I don't think there is a clean way to do it. My solution would be to create a pd.Series out of the keywords, and use apply to loop through the keywords. Assume that the list you provided above is in the variable keywords, and DataFrame of tweets is in df. I'm also assuming that Overall Sentiment Score is the most common sentiment, and the Overall Subjectivity is the mean. def summarize(data): """ Extract the statistics for a given sub-dataframe """ return pd.Series({ "total_tweets" : len(data) "total_retweets" : data.retweet_count.sum() "total_favorites" : data.favorite_count.sum() "total_comments" : data.reply_count.sum() "overall_sentiment_score" : data.sentiment.mode().loc[0] "overall_subjectivity" : data.subjectivity.mean() }) s = pd.Series(keywords) res = s.apply(lambda word: summarize(df[df.text.str.contains(word)]))
type: Answer
answers question: http://stackoverflow.com/q/47419735
has comment: http://stackoverflow.com/comment/81813156
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81812969
has comment: http://stackoverflow.com/comment/81813196
has comment: http://stackoverflow.com/comment/81816220

http://stackoverflow.com/comment/81831579
comment on: http://stackoverflow.com/q/47427645
type: Comment
type: QuestionComment
has text: Blurp, You are right! the file was empty and I fix that. However, The output file looks away different than text file. Here is a sample:
score: 0

http://stackoverflow.com/comment/82011611
type: AnswerComment
comment on: http://stackoverflow.com/a/47516814
type: Comment
has text: Wow! great, thank you. One last question and I'll be all good. Is there a way to filter for a specific port? I'm running it right now and see a lot of UDP with various port that are unreachable. I want to listen on port 80. Thanks :)
score: 0

http://stackoverflow.com/q/47517351
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/81998479
type: UnansweredQuestion
has body: I first installed opencv and opencv-contrib from below link https://github.com/opencv Then I tried cmake with visual c++ but it failed because it cannot find the file "MSBuild.exe" even though I have Visual C++2017 installed in my PC.Then I tried it with mingw makefile and it generated files sucessfully.But to my suprise there is no .pyd or any python linked file. I am now clueless how to go further linking it with python3. :(
has comment: http://stackoverflow.com/comment/81992399
tagged with: python
has comment: http://stackoverflow.com/comment/81991377
has comment: http://stackoverflow.com/comment/81995213
tagged with: c++
score: 0
answer count: 0
has title: How to link Open CV builded with mingw with Python3
tagged with: msbuild
has comment: http://stackoverflow.com/comment/81991353
has comment: http://stackoverflow.com/comment/81992306

http://stackoverflow.com/a/68597319
downvote count: 0
answers question: http://stackoverflow.com/q/47533772
type: Answer
upvote count: 1
has body: Gensim v4.x.x simplified a lot of what @gojomo described above, as he also explained in his other answer here. Based on those answers, here's an example of how you can multiprocess most_similar in a memory-efficient way, including logging of progress with tqdm. Swap in your own model/dataset to see how this works at scale. import multiprocessing from functools import partial from typing import Dict, List, Tuple import tqdm from gensim.models.word2vec import Word2Vec from gensim.models.keyedvectors import KeyedVectors from gensim.test.utils import common_texts def get_most_similar( word: str, keyed_vectors: KeyedVectors, topn: int ) -> List[Tuple[str, float]]: try: return keyed_vectors.most_similar(word, topn=topn) except KeyError: return [] def get_most_similar_batch( word_batch: List[str], word_vectors_path: str, topn: int ) -> Dict[str, List[Tuple[str, float]]]: # Load the keyedvectors with mmap, so memory isn't duplicated keyed_vectors = KeyedVectors.load(word_vectors_path, mmap="r") return {word: get_most_similar(word, keyed_vectors, topn) for word in word_batch} def create_batches_from_iterable(iterable, batch_size=1000): return [iterable[i : i + batch_size] for i in range(0, len(iterable), batch_size)] if __name__ == "__main__": model = Word2Vec( sentences=common_texts, vector_size=100, window=5, min_count=1, workers=4 ) # Save wv, so it can be reloaded with mmap later word_vectors_path = "word2vec.wordvectors" model.wv.save(word_vectors_path) # Dummy set of words to find most similar words for words_to_match = list(model.wv.key_to_index.keys()) # Multiprocess batches = create_batches_from_iterable(words_to_match, batch_size=2) partial_func = partial( get_most_similar_batch, word_vectors_path=word_vectors_path, topn=5, ) words_most_similar = dict() num_workers = multiprocessing.cpu_count() with multiprocessing.Pool(num_workers) as pool: max_ = len(batches) with tqdm.tqdm(total=max_) as pbar: # imap required for tqdm to function properly for result in pool.imap…
score: 1

http://stackoverflow.com/q/47435804
upvote count: 1
favorite count: 0
type: Question
tagged with: timestamp
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47435863
tagged with: python
has body: In python im trying to generate a timestamp based on a string input: The data 19/21/2016 12:29:07 First I tried: import time import datetime s = "19/04/2016" seconds = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()) print seconds Which worked, than I tried (with same imports): s = "19/04/2016 12:29:07" seconds = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y %H:M:S").timetuple()) print seconds But I get the following error: ValueError: time data '19/04/2016 12:29:07' does not match format '%d/%m/%Y %H:M:S' %H Hour (24-hour clock) as a zero-padded decimal number. %M Minute as a zero-padded decimal number. %S Second as a zero-padded decimal number. Why is the input not valid when adding the %H:%M:%S ?
has title: Python convert string to timestamp
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47435863
downvote count: 0

file-transfer
tags question: http://stackoverflow.com/q/47436349
tags question: http://stackoverflow.com/q/47539028
type: Tag
tag name: file-transfer

http://stackoverflow.com/q/47520966
score: 2
has body: I'm creating a custom ui in Maya 2017 which uses PyQt5 (well... technically PySide2, but it's essentially the same). I've got a few CustomContextMenu popup menus that I've created in my ui and I've used popup.setTearOffEnabled(True) to be able to tear them off into a separate window (popup, being the QMenu item). I cannot seem to figure out how to set the title for the resulting torn off window. Currently, each torn off window is titled "Maya-2017", but I'd like to give it a unique name for clarity. I've noticed that Maya's menu items with tear off functionality name the resulting window with the menu's name, so it would seem this is doable. Am I just missing something obvious? I have tried using popup.setTitle('test name') on the QMenu thinking it would then name the tear off window this title, but it doesn't seem to do anything. Other than that, I'm at a loss.
has answer: http://stackoverflow.com/a/47522267
type: AnsweredQuestion
upvote count: 2
tagged with: pyside2
answer count: 1
downvote count: 0
tagged with: pyqt5
favorite count: 0
type: Question
tagged with: titlebar
has title: How to set QMenu tear-off window title?
tagged with: python
accepted answer: http://stackoverflow.com/a/47522267
tagged with: qmenu

http://stackoverflow.com/comment/81807625
has text: do you get error message ? Always add full error message (Traceback) in question.
type: Comment
comment on: http://stackoverflow.com/q/47424073
score: 0
type: QuestionComment

http://stackoverflow.com/a/47435208
answers question: http://stackoverflow.com/q/47434234
score: 0
has body: You have made an oversight course_id = fav_course.fav_id course = Course.objects.filter(id=course_id) course_list.append(course) By following you have appended whole course Queryset (even if it holds 1 element it is still not that element as you use only filter) as first element of an array, which makes course.id non existent or null in template world You should have get instead course_id = fav_course.fav_id # Get single course instead of filtering selection out course = Course.objects.get(id=course_id) course_list.append(course)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47434234
type: Answer

http://stackoverflow.com/comment/81817932
has text: Indeed, I retracted the flag
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47431752
score: 0

http://stackoverflow.com/comment/81789809
type: Comment
comment on: http://stackoverflow.com/q/47417852
type: QuestionComment
has text: Hint: `dnf list installed | grep python3-devel`
score: 0

http://stackoverflow.com/comment/81865063
type: QuestionComment
score: 1
has text: Is that rounding error?
comment on: http://stackoverflow.com/q/47455156
type: Comment

http://stackoverflow.com/comment/81848505
comment on: http://stackoverflow.com/q/47444521
score: 0
has text: I renamed assistant_library_with_local_commands_demo.py to test2.py.... Sorry.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47451428
has body: A dictionary is the way to do things. In [332]: airports = [['BCN','Barcenlona'],['DUB','Dublin']] In [333]: dict(airports) Out[333]: {'BCN': 'Barcenlona', 'DUB': 'Dublin'} In [334]: mapping = dict(airports) In [335]: mapping.get('DUB') Out[335]: 'Dublin' Convert the array to a dictionary, and use either dict indexing with [], or dict.get (does not throw KeyErrors). The advantage of a dictionary is that it is idiomatically more suited to your data, and facilitates constant, O(1) time lookup for values, which is ideal if repeated searches is a use case with your data. If you must use a 2D array, you can try and make this as efficient as possible using next: next((y for x, y in airports if x == code), 'Not Found') next can accept two arguments - a generator comprehension (any iterator) a default argument that is returned if the iterator does not return anything Here's a quick sample: In [336]: next((y for x, y in airports if x == 'DUB'), 'Not Found') Out[336]: 'Dublin' In [337]: next((y for x, y in airports if x == 'XXX'), 'Not Found') Out[337]: 'Not Found' Without the default argument, next would throw a StopIteration with an invalid key: In [338]: next(y for x, y in airports if x == 'XXX') --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) Keep in mind that you cannot escape the O(N) complexity pitfall without a dictionary.
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47451284
downvote count: 0
answers question: http://stackoverflow.com/q/47451284
score: 3
type: Answer

http://stackoverflow.com/q/47526059
possible better answer: http://stackoverflow.com/a/47526928
answer count: 2
has comment: http://stackoverflow.com/comment/82007996
tagged with: dataframe
tagged with: python
has body: When I update the dataframe, I should check if the value exists in the dataframe index, but I want to know which way is faster, thanks! 1. if value in set(dataframe.index) 2. if value in dataframe.index
has title: How to quickly check if a value exists in pandas DataFrame index?
has comment: http://stackoverflow.com/comment/82008523
tagged with: pandas
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82008133
accepted answer: http://stackoverflow.com/a/47526105
downvote count: 0
has answer: http://stackoverflow.com/a/47526928
has answer: http://stackoverflow.com/a/47526105
has comment: http://stackoverflow.com/comment/82008733
has comment: http://stackoverflow.com/comment/82008290
favorite count: 0
has comment: http://stackoverflow.com/comment/82008156
type: Question

http://stackoverflow.com/q/47415134
has body: New to networkx library, I would like to know if there is a way to obtain a multi-graph from a unidrected graph generated using the barabasi_albert_graph. Any suggestions ?
tagged with: python
tagged with: networkx
score: 0
answer count: 0
has title: How to convert a undirected graph to multigraph using networkx
has comment: http://stackoverflow.com/comment/81884236
has comment: http://stackoverflow.com/comment/81910349
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/81927687
comment on: http://stackoverflow.com/q/47485606
score: 0
has text: @hpaulj thank you your comment was helpful with mentioning that lack of coma makes the indexing on 1d
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47534484
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47533991
type: Answer
answers question: http://stackoverflow.com/q/47533991
has body: How about doing a depth-first search to find all connected components? def dfs(board, start): visited, stack = set(), [start] while stack: vertex = stack.pop() cur_i, cur_j = vertex[0], vertex[1] if vertex not in visited: visited.add(vertex) for i,j in [(-1,0),(1,0),(0,-1),(0,1)]: if (cur_i+i, cur_j+j) not in visited and 0 &lt;= cur_i+i &lt; len(board) and 0 &lt;= cur_j+j &lt; len(board[0]) and board[cur_i+i][cur_j+j] == "O": stack.append((cur_i+i, cur_j+j)) return list(visited) board = [["X", "X", "X", "X"], ["X", "O", "O", "X"], ["X", "X", "O", "X"], ["X", "O", "X", "X"]] all_o = [(x, y) for x, row in enumerate(board) for y, col in enumerate(row) if col == 'O'] res = [] done = set() for cur in all_o: if cur not in done: comps = dfs(board, cur) done |= set(comps) res.append(comps) print(res) Output: [[(1, 2), (1, 1), (2, 2)], [(3, 1)]] Reference: I modified the DFS code from this blog post.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82055457
type: QuestionComment
comment on: http://stackoverflow.com/q/47535866
has text: Sure that solution relies on changing the seaborn source code. If you want to do that you can of course specifically ask about any problems you encounter on the way.
score: 0
type: Comment

http://stackoverflow.com/q/47385721
type: Question
accepted answer: http://stackoverflow.com/a/47385762
has answer: http://stackoverflow.com/a/47386088
has comment: http://stackoverflow.com/comment/81724417
tagged with: python
tagged with: dictionary
has title: List of Potentials from Dictionary
has comment: http://stackoverflow.com/comment/81724482
possible better answer: http://stackoverflow.com/a/47386013
has answer: http://stackoverflow.com/a/47386013
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 3
has body: I have the following list, and I am trying to create a list of potential friends which basically means everyone who is not currently friends with the person in question. The keys of the dictionary are the persons, and the list of values are their friends. person_to_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D- Cat'], 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'], 'Dylan D- Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'], 'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']} Here is the code I have so far, I am not sure as to how I should update my list of potential friend. def friends_score(person, person_to_friends): score = 0 potential_friends = [] for item in person_to_friends: if item == person: potential_friends = #this is where I am unsure as to how to proceed FYI, the definition of a potential friend is anyone that the person is not currently friends with. For example, if Jay Pritchett was the person, the potential friends would be everyone EXCEPT for the people in the list of values: ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'] EXPECTED OUTCOME &gt;&gt;&gt; friends_score('Jay Pritchett') ['Mitchell Pritchett', 'Phil Dunphy', 'Luke Dunphy', 'Cameron Tucker', 'Alex Dunphy','Haley Gwendolyn Dunphy','Dylan D-Money', 'Gilbert D-Cat','Chairman D-Cat']
has answer: http://stackoverflow.com/a/47385762
has comment: http://stackoverflow.com/comment/81725231

http://stackoverflow.com/q/47474246
has title: Hive trying to read current working directory when called in Python script
answer count: 1
has comment: http://stackoverflow.com/comment/81936653
has body: I am attempting to execute a Hive script from a Python wrapper. Part of code looks like print(HiveArgs) Hive = subprocess.Popen(HiveArgs, stderr=subprocess.PIPE, stdout=subprocess.PIPE) HiveOutput = Hive.communicate() print("Out:" + HiveOutput[0]) print("=================================") print("Err:" + HiveOutput[1]) The output of this is: ['hive', '-i ', '/edw/edwdev/tmp/spark.txn.init.tmp', '-f ', '/edw/edwdev/tmp/test.hql.tmp'] Out: ================================= Err: Logging initialized using configuration in file:/etc/hive/2.5.0.2-3/0/hive-log4j.properties Exception in thread "main" java.io.FileNotFoundException: File file:/data/edw/edwdev/ does not exist at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:624) at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:850) at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:614) at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:422) at org.apache.hadoop.fs.ChecksumFileSystem$ChecksumFSInputChecker.&lt;init&gt;(ChecksumFileSystem.java:146) at org.apache.hadoop.fs.ChecksumFileSystem.open(ChecksumFileSystem.java:348) at org.apache.hadoop.fs.FileSystem.open(FileSystem.java:782) at org.apache.hadoop.hive.cli.CliDriver.processFile(CliDriver.java:427) at org.apache.hadoop.hive.cli.CliDriver.processInitFiles(CliDriver.java:439) at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:708) at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:684) at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:624) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.hadoop.util.RunJar.run(RunJar.java:233) at org.apache.hadoop.util.R…
has comment: http://stackoverflow.com/comment/81904154
has comment: http://stackoverflow.com/comment/81903918
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47526194
tagged with: python
tagged with: hive
has comment: http://stackoverflow.com/comment/81930487
score: 0
tagged with: subprocess

http://stackoverflow.com/q/47502317
has comment: http://stackoverflow.com/comment/81960403
tagged with: deep-copy
tagged with: python
has title: In-place operations and user defined functions
type: Question
has body: What is the conventional wisdom around using in-place operations within user defined functions? Using in-place operations in side of user defined functions will violate the "no-side-effect" maxim which user defined functions usually abide. This is very dangerous! For example: import numpy as np np.random.seed(123) X = np.random.rand(4,2) def my_shuffle(Y): np.random.shuffle(Y) return(Y) print(X) print(my_shuffle(X)) print(X) #Oops My solution: import numpy as np np.random.seed(123) X = np.random.rand(4,2) def my_shuffle_fix(Y): import copy Y_copy = copy.deepcopy(Y) np.random.shuffle(Y_copy) return(Y_copy) print(X) print(my_shuffle_fix(X)) print(X) #Better Is this a good work around?
answer count: 0
has comment: http://stackoverflow.com/comment/81960579
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81960589
has comment: http://stackoverflow.com/comment/81961045
has comment: http://stackoverflow.com/comment/81960477
tagged with: copy
score: 0

http://stackoverflow.com/q/47413104
has comment: http://stackoverflow.com/comment/81817633
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81780954
answer count: 1
tagged with: django-forms
has body: Hi I'd like to know how can i add a glyphicon to the left of "input" in my code because I'm using django and I have to use forms.py you know. My HTML code : {% csrf_token %} {{ form.as_p }} Connexion forms.py : class ConnexionForm(forms.Form): user = forms.CharField(label='', max_length=30, widget=forms.TextInput(attrs={'placeholder': "Nom d'utilisateur"})) password = forms.CharField(label='', widget=forms.PasswordInput)
tagged with: glyphicons
type: Question
has title: Add a glyphicon even if i use Django
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/81779562
tagged with: django
has answer: http://stackoverflow.com/a/47415733
tagged with: python
accepted answer: http://stackoverflow.com/a/47415733
has comment: http://stackoverflow.com/comment/81784060
has comment: http://stackoverflow.com/comment/81781385

http://stackoverflow.com/a/47456323
has body: So this solution is not a full solution to your exact problem, but I think it might be a good approach that can get you at least part of the way there. The issues I have in general with line detection approaches is that they usually heavily rely on multiple hyperparameters. More annoyingly, they are slow since they are searching a wide array of angles; your lines are strictly either horizontal or vertical. As such, I'd recommend using morphology. You can find a general overview of morphology on the OpenCV site and you can see it applied to remove the music bars in a score on this tutorial on the OpenCV site. The basic idea I thought was: Detect horizontal and vertical lines Run connectedComponents() on the detected lines to identify each line separately Get user mouse position and define a window around it If a label from the connected components is in that window, then grab that component Draw that component on the image Now, this is a very basic idea and ignores some of the challenges involved. However, what this will do for sure is, if you click anywhere and there is a line in your image within the window of that click, you will get it. There are no missed lines here. Additional good news is it doesn't ignore the thicker borders and such in the image where you would naturally want this to stop (note this problem exists for line detection schemes). This will only detect lines that have a defined width and if the line gets thicker (turns into an arrow or hits a line going a different direction) it cuts it off. The bad news is that this uses pre-defined width for your lines. You can somewhat skirt around this by using a hit-or-miss transform, but note that the implementation is currently broken for versions of OpenCV older than 3.3-rc; see here for more (you can get around the broken implementation easily). Anyways, a hit-or-miss transform here allows you to say "I want a horizontal line but it can be a few pixels wide or just one pixel wide". Of course the wider yo…
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47420130

http://stackoverflow.com/q/47470664
has comment: http://stackoverflow.com/comment/81895877
has title: Pythonic way to encapsulate method arguments of a class
has comment: http://stackoverflow.com/comment/81896046
type: Question
tagged with: oop
has answer: http://stackoverflow.com/a/47470805
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47470795
has comment: http://stackoverflow.com/comment/81895827
tagged with: encapsulation
tagged with: python
tagged with: inheritance
has body: Objects of my class A are similar to network connections, i.e. characterized by a handle per connection opened. That is, one calls different methods with a handle (a particular connection) as argument. My class A (python 2.7) looks like: class A(object): def __init__(self, *args): ... some init def my_open(self, *args) handle = ... some open return handle def do_this(self, handle, *args): foo_this(handle, args) def do_that(self, handle, *args): foo_that(handle, args) A typical usage is a = A(args) handle = a.my_open(args2) a.do_this(handle, args3) Now, in a particular situation, there is only one connection to take care of, i.e. one handle in play. So, it is reasonable to hide this handle but keep class A for the more general situation. Thus, my first thoughts on a class B which "is a" kind of class A (usage stays the same but hides handle) are: class B(A): def __init__(self, *args): super(A, self).__init__(args) self.handle = None def my_open(self, *args): self.handle = super(A, self).__init__(args) def do_this(self, *args): super(A, self).do_this(self.handle, args) def do_that(self, *args): super(A, self).do_that(self.handle, args) Unfortunately, in my opinion, it seems very convoluted. Any better ideas?
score: 0
answer count: 2

http://stackoverflow.com/a/56332537
type: Answer
has body: The problem is in : app.config['MYSQL_CURSORCLASS'] = 'DictCursor' Looking at flaskext.mysql source , that feature is not yet implemented . And since flaskext.mysql is using pymysql , you can use DictCursor from pymysql.cursors Example : from flaskext.mysql import MySQL from flask import Flask from pymysql import cursors app=Flask(__name__) mysql = MySQL(cursorclass=cursors.DictCursor) mysql.init_app(app) cursor = mysql.connect().cursor()
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/138886451
has comment: http://stackoverflow.com/comment/138884626
has comment: http://stackoverflow.com/comment/138885384
answers question: http://stackoverflow.com/q/47478913

http://stackoverflow.com/q/47477728
accepted answer: http://stackoverflow.com/a/47480809
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/81916438
has answer: http://stackoverflow.com/a/47480809
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81911132
answer count: 2
downvote count: 0
has body: I am making a project for a class, and i am trying to predict nfl socre games using linear regression and predict functions from sklearn, my problem comes when i want to fit the training data into de fit function, here is my code: onehotdata_x1 = pd.get_dummies(goal_model_data,columns=['team','opponent']) # Crea el object de regression linear regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(onehotdata_x1'home','team','opponent', onehotdata_x1['goals']) This is the structure of dataframe(goal_model_data): team opponent goals home NE KC 27 1 BUF NYJ 21 1 CHI ATL 17 1 CIN BAL 0 1 CLE PIT 18 1 DET ARI 35 1 HOU JAX 7 1 TEN OAK 16 1 and this is the error that i get when i run the program: Traceback (most recent call last): File "predictnflgames.py", line 76, in &lt;module&gt; regr.fit(onehotdata_x1'home','team','opponent', onehotdata_x1['goals']) File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2133, in __getitem__ return self._getitem_array(key) File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2177, in _getitem_array indexer = self.loc._convert_to_indexer(key, axis=1) File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 1269, in _convert_to_indexer .format(mask=objarr[mask])) KeyError: "['team' 'opponent'] not in index"
has answer: http://stackoverflow.com/a/47480780
possible better answer: http://stackoverflow.com/a/47480780
tagged with: scikit-learn
has title: Fit dataframe into linear regression sklearn

http://stackoverflow.com/comment/81995598
has text: See also: [mcve]
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47518631

http://stackoverflow.com/q/47459303
has comment: http://stackoverflow.com/comment/81873314
possible better answer: http://stackoverflow.com/a/47459394
type: Question
has answer: http://stackoverflow.com/a/47459440
has comment: http://stackoverflow.com/comment/81873810
has answer: http://stackoverflow.com/a/47459394
tagged with: python
has comment: http://stackoverflow.com/comment/81876862
score: -1
has title: Get list number for a given element in list of lists
has comment: http://stackoverflow.com/comment/81876995
has comment: http://stackoverflow.com/comment/81873282
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81873198
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81873144
has body: Let's say we have N elements from 0 to N - 1 (N is known) scattered into k lists as follows: X = [[0, 1, 6], [2, 4], [3, 5]] for N = 7, k = 3 Given the number how can I determine the number of the group it is in? For example 1 is in first group and 5 is int the third group. I can nest loops and check it manually (for each given number check each group where it can be) but how do I do this with more clean and functional-like style in Python? It'd more useful especially when I have list of numbers [1, 3, 5] and want to transform it into list of groups of each of elements ie. [1, 3, 3] EDIT: I was asked to present the way I am doing it now so here it comes: results = [] numbers = [1, 3, 5] for number in numbers: for i in range(len(X)): if number in X[i]: results.append(i)
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47459440

http://stackoverflow.com/comment/81925968
has text: Just an advice. Do not try to build a full program until you are able to to simple things. So 1/ define what data should lie in your file and what format you want to use (assuming text here since your current code write text data) 2/ Write code that writes the data in the file 3/ Write code that reads data from the file. When those 3 points are ok, put everything together and ask a more precise question if you are stuck somewhere.
comment on: http://stackoverflow.com/q/47485278
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47716087
answers question: http://stackoverflow.com/q/47540607
score: -2
upvote count: 1
has body: The answer was simple, i was working from my Google Drive directory on my personal computer, i was offline at the time of the error and the Backup and Sync program was not running therefore it took me a while to realize that i still don't have full permissions over the folder. Moving my script and necessary files to a folder in my Documents fixed the error. Thanks for the help Marco and Josh!
downvote count: 3
type: Answer

http://stackoverflow.com/comment/81988523
score: 1
comment on: http://stackoverflow.com/q/47489392
type: QuestionComment
type: Comment
has text: As a general remark, the sequences are too short and too few for proper training. 3 sequences of length 3 for 3 states. HMM is a statistical model providing a statistical representation, therefore you need enough samples for all the computed probabilities to be statistically significant.

http://stackoverflow.com/a/47415801
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47409112
accepted answer of: http://stackoverflow.com/q/47409112
type: Answer
has body: You cannot do that with gridlayout alone. You could make a gridlayout with two columns, and put horizontal boxlayouts in the grid you need to split. Or you could use stacklayout. stacklayout I would just use two gridlayouts inside a vertical boxlayout. You simply put both gridlayouts in a boxlayout. So the Popup will contain the boxlayout, and won't complain about multiple widgets. MyBoxLayout: orientation: "vertical" GridLayout1: cols: 2 GridLayout2: cols: 4
downvote count: 0
score: 1
upvote count: 1

sqlalchemy
tags question: http://stackoverflow.com/q/47518264
tags question: http://stackoverflow.com/q/47491593
tags question: http://stackoverflow.com/q/47428746
tags question: http://stackoverflow.com/q/47524720
tags question: http://stackoverflow.com/q/47447356
tags question: http://stackoverflow.com/q/47450319
tags question: http://stackoverflow.com/q/47537331
tags question: http://stackoverflow.com/q/47418868
tags question: http://stackoverflow.com/q/47478837
tags question: http://stackoverflow.com/q/47513622
tags question: http://stackoverflow.com/q/47498415
tags question: http://stackoverflow.com/q/47429929
tags question: http://stackoverflow.com/q/47416699
tags question: http://stackoverflow.com/q/47494094
tags question: http://stackoverflow.com/q/47487497
tags question: http://stackoverflow.com/q/47481853
tags question: http://stackoverflow.com/q/47402225
tags question: http://stackoverflow.com/q/47458722
tags question: http://stackoverflow.com/q/47536589
tags question: http://stackoverflow.com/q/47511126
tags question: http://stackoverflow.com/q/47505706
tags question: http://stackoverflow.com/q/47480297
tags question: http://stackoverflow.com/q/47391715
tags question: http://stackoverflow.com/q/47404633
tags question: http://stackoverflow.com/q/47509920
tags question: http://stackoverflow.com/q/47425787
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/47425197
tags question: http://stackoverflow.com/q/47521700
type: Tag

http://stackoverflow.com/comment/81987788
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47515574
has text: this is neat - saves a lot of time as well. Needs lots of memory though if you want to keep them all in memory for "whos the longest" checking. But I guess you could only store the length information with the startnumber as key for that ... +1
type: Comment

http://stackoverflow.com/a/49388032
has body: The python library automatically syncs so the sync method response rarely contains anything useful BUT that information is contained in the api class which has an overridden _find_object method. Therefore you can use the same notation as a dict to find elements - i.e. api['projects']. I know this is an old question but I'd been having this problem and was struggling to find an answer so hopefully this will be useful to someone at some point!
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47521676

http://stackoverflow.com/q/47390083
favorite count: 0
type: Question
answer count: 2
has title: Bloomberg Intraday Historical Speed Up
downvote count: 0
accepted answer: http://stackoverflow.com/a/47404086
upvote count: 1
tagged with: python
has body: I am using the python API to download intraday data (5min bars) for a number of securities. But that process is painfully slow, and I imagine I am not making the best effort in terms of concurrent requests. Unfortunately, I find the API to be quite unfriendly (I use mostly the blpapi wrapper to get around the messaging, though I'm keen to play with the bloomberg api directly if need be). I'd be glad if anyone would have an example as for how to tweak my requests to make it less time consuming
possible better answer: http://stackoverflow.com/a/53505389
tagged with: bloomberg
has answer: http://stackoverflow.com/a/53505389
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81733171
has answer: http://stackoverflow.com/a/47404086

http://stackoverflow.com/comment/81738969
has text: Your first number can't be represented as a double precision float, so it is not what you expect. There are tons of questions about this if you care to search
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47393018

http://stackoverflow.com/comment/81804842
has text: I am sure it can be done in a single script or command I believe.
type: Comment
comment on: http://stackoverflow.com/a/47424982
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81786294
score: 0
type: Comment
type: QuestionComment
has text: My current solution is: `row = {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', row)}`
comment on: http://stackoverflow.com/q/47414502

http://stackoverflow.com/q/47534958
has comment: http://stackoverflow.com/comment/82027778
type: Question
has body: This is mainProgram(): def mainProgram(): typedCountry = e.get() Country = typedCountry.lower() print 'Your country is: ' + typedCountry + '\n' if Country in bannedCountries: banned(typedCountry) if Country in cpBannedCountries: cpBanned(typedCountry) if Country in skrillBannedCountries: skrillBanned(typedCountry) if Country in bacsCountries: Bacs(typedCountry) if Country in sepaCountries: sepa(typedCountry) if Country in eftCountries: eft(typedCountry) if Country in ltdCountries: ltd(typedCountry) if Country in marketsCountries: markets(typedCountry) I ask the user to enter a country in a box, I have several lists of different countries, and I check if the user input matches any of the countries in every list. If it does I run a separate function that prints a line. This is the main tkinter code master = Tk() e = Entry(master) e.pack() e.focus_set() def clear_text(): #WHAT TO ENTER HERE??? b = Button(master, text = "Search", bg="lightyellow", command = mainProgram) b.pack() c = Button(master, text="Quit", bg="orange", command=master.quit) c.pack() d = Button(master, text="Clear", bg="orange", command=clear_text) d.pack() mainloop() Before this I have several lists of different countries, and a dozen or so functions that just print stuff for the user, it is not relevant here. I use tkinter to create an input box where a user can type a country (input gets assigned to typedCountry) and three buttons: Search, Clear and Quit. Search runs the mainProgram() function and the returned function gets printed to the tkinter box. However since I do not know exactly where it's being printed, I don't know how to tell the Clear button to delete the contents of the text box without destroying it completely. This is how it looks like when I search for say United States: https://i.sstatic.net/mPCBm.jpg Then I search for Austria: https://i.sstatic.net/omJPV.jpg As you can see, one is printed below the other one, but I need to clear them out of the box. Since I don't know where tkinte…
tagged with: tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/82027078
accepted answer: http://stackoverflow.com/a/47535485
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47535485
has title: Deleting the text from within a tkinter window?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82027639

http://stackoverflow.com/q/47390243
type: Question
tagged with: numpy
has body: I have following numpy matrix(value_matrix). [[0.3,0.5,1,0.2,0.9,0.5,0.6,0.3,0.7,0.8] [0.9,0.6,0.1,0.4,0.2,0.7,0.6,0.9,0.5,0.4]] I need to get elements from each row (inside a loop) where the column number(index) is inside another numpy array. ex: key_array -&gt; [2,0,1,3] ex: value_matrix.item(0,key_array) kind of retrieval method. How can I do this with numpy?
has comment: http://stackoverflow.com/comment/81733417
tagged with: python
score: -1
has title: Numpy matrix get set of elements keys in another array
has answer: http://stackoverflow.com/a/47390349
accepted answer: http://stackoverflow.com/a/47390349
type: AnsweredQuestion
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/47406290
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81766290
answers question: http://stackoverflow.com/q/47406231
has body: In pandas for replace values in index or columns is used function rename: df = df.rename(d) print (df) Country South Korea 12 United States 13 United Kingdom 14 Hong Kong 15 For me timings are practically same: df = pd.concat([df] * 100000) In [11]: %timeit df.rename(d) 10 loops, best of 3: 75.7 ms per loop In [12]: %timeit pd.Series(df.index).replace(d) 10 loops, best of 3: 71.8 ms per loop In [13]: %timeit pd.Series(df.index.values).replace(d) 10 loops, best of 3: 75.3 ms per loop
has comment: http://stackoverflow.com/comment/81766266
type: Answer
accepted answer of: http://stackoverflow.com/q/47406231
score: 2
upvote count: 2

http://stackoverflow.com/q/47459747
has comment: http://stackoverflow.com/comment/81875239
has answer: http://stackoverflow.com/a/54913694
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81875791
has comment: http://stackoverflow.com/comment/88803084
linked to: http://stackoverflow.com/q/30992717
has comment: http://stackoverflow.com/comment/81875206
has comment: http://stackoverflow.com/comment/82010747
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81874979
tagged with: python
tagged with: pygame
has title: pip install is not working
has answer: http://stackoverflow.com/a/47460018
answer count: 4
has answer: http://stackoverflow.com/a/50942227
has comment: http://stackoverflow.com/comment/81874846
score: 2
has comment: http://stackoverflow.com/comment/81874158
upvote count: 2
has comment: http://stackoverflow.com/comment/81874957
has comment: http://stackoverflow.com/comment/81875225
downvote count: 0
has answer: http://stackoverflow.com/a/47460697
has body: I am trying to install pygame with pip install . but every time i tried i faced to this error. Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Operation cancelled by user* I have done it with other libraries but I faced the same problem
has comment: http://stackoverflow.com/comment/81874436

http://stackoverflow.com/q/47460399
has title: Encrypting and Decrypting Files in Python
answer count: 1
has comment: http://stackoverflow.com/comment/81875390
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47460799
has body: I want to encrypt and decrypt the file in Python. The file will be very small, maybe 1 KB. After investigation I have found some package for it: https://pypi.python.org/pypi/simple-crypt https://pypi.python.org/pypi/cryptoshop/2.0.1 https://pypi.python.org/pypi/pyAesCrypt https://github.com/surajsinghbisht054/py-filecipher But now I am perplex what to use. What is current (2017) standard?
has answer: http://stackoverflow.com/a/47460799
tagged with: encryption
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81990500
type: Comment
comment on: http://stackoverflow.com/q/47517110
score: 1
type: QuestionComment
has text: use button `{}` to correctly format code in question

http://stackoverflow.com/comment/82015882
type: AnswerComment
has text: Ok thanks ! The second solution should be more efficient
score: 0
comment on: http://stackoverflow.com/a/47527374
type: Comment

http://stackoverflow.com/comment/82008549
score: 0
has text: I don't get it. The information of url you provided only contains the comment of the first page. I still can't parser all of the comments.
type: Comment
comment on: http://stackoverflow.com/a/47526231
type: AnswerComment

http://stackoverflow.com/comment/81834802
score: 1
has text: Even df.apply(lambda x: list(set(x)), axis = 1) would work
comment on: http://stackoverflow.com/a/47439956
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81990804
comment on: http://stackoverflow.com/q/47516963
score: 0
type: Comment
has text: If by "earliest ancestor" you mean the first to occur in your list, then `max` should take the first occuring one anyway. Am I missing something?
type: QuestionComment

http://stackoverflow.com/a/47405090
upvote count: 1
has comment: http://stackoverflow.com/comment/82842050
type: Answer
has comment: http://stackoverflow.com/comment/81763777
answers question: http://stackoverflow.com/q/47405067
has body: By adding an else to your code: punctuation = "!\"#$%&amp;()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~" def remove_punct(theStr): theStr_sans_punct = "" for letter in theStr: if letter not in punctuation: theStr_sans_punct = theStr_sans_punct + letter else: theStr_sans_punct = theStr_sans_punct + " " return theStr_sans_punct
score: 1
downvote count: 0

http://stackoverflow.com/q/47499675
downvote count: 0
has title: find named entities from tokenized sentences in SPACY v2.0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/71090674
has answer: http://stackoverflow.com/a/71090674
tagged with: python
tagged with: nlp
accepted answer: http://stackoverflow.com/a/47502965
type: AnsweredQuestion
has body: I am trying to do: Tokenize sentences from text Compute Named Entities for each word present in sentence This is what I have done so far: nlp = spacy.load('en') sentence = "Germany and U.S.A are popular countries. I am going to gym tonight" sentence = nlp(sentence) tokenized_sentences = [] for sent in sentence.sents: tokenized_sentences.append(sent) for s in tokenized_sentences: labels = [ent.label_ for ent in s.ents] entities = [ent.text for ent in s.ents] Error: labels = [ent.label_ for ent in s.ents] AttributeError: 'spacy.tokens.span.Span' object has no attribute 'ents' Is there any alternative way to find named entities of tokenized sentence? Thanks in advance
answer count: 2
tagged with: spacy
has answer: http://stackoverflow.com/a/47502965
score: 2
upvote count: 2

python-curses
tag name: python-curses
type: Tag
tags question: http://stackoverflow.com/q/47481955

http://stackoverflow.com/comment/81782385
comment on: http://stackoverflow.com/a/47411798
score: 0
type: Comment
has text: No you can't. But I can still get what I want i.e. the mean latitude and longitude of a set of [lat, lon] coordinates. See the second answer down, here: https://stackoverflow.com/questions/1185408/converting-from-longitude-latitude-to-cartesian-coordinates
type: AnswerComment

http://stackoverflow.com/comment/81823112
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47434428
score: 0
has text: Well, you can simply post requests with data from file `xmldata` without reading it. See [this](http://docs.python-requests.org/en/master/user/advanced/#streaming-uploads) part of documentation. Just use `request = session.post(starturl, auth=(username,password), data=xmldata, headers=post_headers)` where `xmldata` is opened file. However I am not sure if this will solve your problem.

http://stackoverflow.com/comment/82004336
type: Comment
has text: can you please let me know, how to call main. For example, I tried `client_simulator.main()` but its giving me same error
type: QuestionComment
comment on: http://stackoverflow.com/q/47524054
score: 1

eval
tag name: eval
tags question: http://stackoverflow.com/q/47443806
tags question: http://stackoverflow.com/q/47486151
type: Tag

parsing
tags question: http://stackoverflow.com/q/47452222
tags question: http://stackoverflow.com/q/47441408
tags question: http://stackoverflow.com/q/47457069
tags question: http://stackoverflow.com/q/47395334
tags question: http://stackoverflow.com/q/47502382
tags question: http://stackoverflow.com/q/47508048
tags question: http://stackoverflow.com/q/47490341
tags question: http://stackoverflow.com/q/47491111
tags question: http://stackoverflow.com/q/47525920
tag name: parsing
tags question: http://stackoverflow.com/q/47497851
tags question: http://stackoverflow.com/q/47531812
tags question: http://stackoverflow.com/q/47433632
tags question: http://stackoverflow.com/q/47444501
tags question: http://stackoverflow.com/q/47497031
tags question: http://stackoverflow.com/q/47498553
type: Tag

http://stackoverflow.com/comment/82010247
type: AnswerComment
comment on: http://stackoverflow.com/a/47517003
score: 0
type: Comment
has text: @guy you are right, it wasn't main problem in question so I didn't see it.

http://stackoverflow.com/a/47402609
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81760279
accepted answer of: http://stackoverflow.com/q/47399143
has comment: http://stackoverflow.com/comment/81847359
type: Answer
has comment: http://stackoverflow.com/comment/81917437
answers question: http://stackoverflow.com/q/47399143
score: 0
has body: Divining from your code I am assuming that f has 4 dimensions: tt, zz, i, j grid has 3 dimensions: zz, i, j Vf has 3 dimensions: tt, i, j Fake data: TT = 5 ZZ = 3 I = 5 J = 4 grid = np.random.randint(0, 255, (ZZ, I, J)) f = np.random.rand(TT,ZZ,I,J) The nested for loops can be vectorized: abs(grid[zz,i,j]-grid[zz+1,i,j]) is essentially numpy.diff() on the first axis which can be performed on the complete array without a loop. term1 = np.absolute(np.diff(grid, axis = 0)) term1's shape is (ZZ-1, I, J). In order to multiply it by f, the zz dimension needs to be the same so that the multiplication will broadcast across f's tt dimension/axis. From the innermost loop statement we see that the last element of zz isn't used - for zz in range(sal.shape[1]-1):. w = term1 * f[:,:-1,...] From Vf[tt,i,j] += we see that the zz axis has disappeared so it is summing accros the zz axis. vf = w.sum(axis = 1) ... term1 = np.absolute(np.diff(grid, axis = 0)) w = term1*f[:,:-1,...] vf = w.sum(axis = 1) Running my fake data through your nested for loops: Vf = np.zeros((TT,I,J)) for tt in range(TT): ## print('time',str(tt)) for j in range(J): ## print('j',str(j)) for i in range(I): ## print('i',str(i)) for zz in range(ZZ-1): Vf[tt,i,j] += abs(grid[zz,i,j]-grid[zz+1,i,j])*f[tt,zz,i,j] And comparing v to Vf indicates that the result is the same: &gt;&gt;&gt; np.all(Vf == vf) True &gt;&gt;&gt; There are some einsum equivalents which can sometimes be faster. w = term1*f[:,:-1,...] can be replaced with w = np.einsum('ijkl, ijkl-&gt;ijkl',f[:,:-1,...], term1[None,...]) and vf = w.sum(axis = 1) can be replaced with vf = np.einsum('wxyz-&gt;wyz', w) Combining the operation to a single einsum produces noticeable speedup vf = np.einsum('ijkl, ijkl-&gt;ikl',f[:,:-1,...], term1[None,...])

http://stackoverflow.com/q/47500476
tagged with: python
tagged with: dictionary
has body: For some reason, I cannot perfectly emulate a dictionary behaviour for my type. class IValType: def __init__(self, v): self.v = v def __repr__(self): return self.v.__repr__() def __str__(self): return self.v.__str__() def __eq__(self, other): return self.v.__eq__(other) class Map(IValType, dict): def __init__(self, v: dict): super(Map, self).__init__(v) print("debug") def __contains__(self, item): return self.v.__contains__(item) def __getitem__(self, item): return self.v[item] def __setitem__(self, key, value): self.v[key] = value def __delitem__(self, key): self.v.__delitem__(key) def __missing__(self, key): return self.v.__missing__(key) def __get__(self, instance, owner): return self.__get__(instance, owner) def __iter__(self): return self.v.__iter__() def __len__(self): return len(self.v) @staticmethod def fromkeys(seq): return dict.fromkeys(seq) def values(self): return self.v.values() def keys(self): return self.v.keys() def items(self): return self.v.items() def pop(self, k): return self.v.pop(k) def popitem(self): return self.v.popitem() def setdefault(self, k, default=None): return self.v.setdefault(k, default) def get(self, k): return self.v.get(k) def update(self, __m, **kwargs): self.v.update(__m, **kwargs) The test for equality fails. class MainTest(unittest.TestCase): def test_4(self): # make a full test for dicts d = {"k": 1,"p":2} dm = Map(d) self.assertIn("k", dm) self.assertEqual(dm["k"], d["k"]) self.assertDictEqual(dm,d) AssertionError: {'p': 2, 'k': 1} != {'p': 2, 'k': 1} - {'p': 2, 'k': 1} + {'k': 1, 'p': 2} I have implemented almost every magical method, what I am missing? I don't have these troubles with reimplementing Lists in the same way, and they are tested (successfully) for equality too. This is py 3.5 Any help please?
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/81956458
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81956550
has comment: http://stackoverflow.com/comment/81956611
has comment: http://stackoverflow.com/comment/81956519
has comment: http://stackoverflow.com/comment/81956489
answer count: 1
has comment: http://stackoverflow.com/comment/81956480
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81956467
has answer: http://stackoverflow.com/a/47500580
accepted answer: http://stackoverflow.com/a/47500580
linked to: http://stackoverflow.com/q/4352244
has title: emulating dict interface python
has comment: http://stackoverflow.com/comment/81956462

http://stackoverflow.com/comment/81824930
type: QuestionComment
has text: What have you tried so far? Please post your code.
score: 4
comment on: http://stackoverflow.com/q/47435216
type: Comment

http://stackoverflow.com/comment/81838138
type: QuestionComment
has text: @volcano Just because you can not think of wider use-cases it does not mean they don't exist. You could implement, for example, an `@skip` decorator which replaces a function object with `None` it the module namespace in order to exclude it from a test runner's collection phase (*note*: this is not how unittest's `skip` and `skipIf` decorators are implemented). Imagining there is some "contract" that a function decorator should always return a function, when there is no such restriction in the language, is not useful to anybody.
type: Comment
comment on: http://stackoverflow.com/q/47439924
score: 0

http://stackoverflow.com/comment/81850609
has text: Hey, the output is an empty file in this case :( set([])
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47446822
type: AnswerComment

http://stackoverflow.com/comment/81839314
type: Comment
type: QuestionComment
has text: I don't keep the connection indefinitely, streaming objects continuously. I send one response but not until the object is there to be sent. Thus, long polling.
score: 0
comment on: http://stackoverflow.com/q/47441899

http://stackoverflow.com/q/47406475
answer count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47442444
has answer: http://stackoverflow.com/a/47443510
has title: When to use multiple event loops?
score: 19
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-asyncio
tagged with: event-loop
tagged with: async-await
tagged with: python
upvote count: 19
has body: I have a web app built on a Python 3.5+ async framework (apistar, sanic, etc). The app makes various IO calls - to a database, Redis, etc - which are also async. Some docs recommend using an additional event loop: import asyncio import peewee from peewee_async import Manager, PostgresqlDatabase loop = asyncio.new_event_loop() # Note: custom loop! database = PostgresqlDatabase('test') objects = Manager(database, loop=loop) It's my understanding that await statements allow the event loop to context switch whenever it hits IO, so additional event loops seem completely unnecessary. What is the benefit of using an additional event loop, and when should additional loops be used?

http://stackoverflow.com/a/47461346
score: 0
accepted answer of: http://stackoverflow.com/q/47459346
has body: you can try this solution if you want by regex: Live Demo of regex import re import collections pattern='((?&lt;=time:.).*?(?=;))|((?&lt;=A:.).*?(?=;))|((?&lt;=B:.\().*?(?=\)))|((?&lt;=C:.\().*?(?=\)))|((?&lt;=D\().*?(?=\)))|((?&lt;=E:.\().*?(?=\)))' string_1="""time: 2017-12-24 13:13:34 +0000; A: 61792; B: ( 60328, 60344, 60344, 60344 ); C: ( "-3672", "-3656", 1547, 1578 ); D( 1500, 1484, 1500, ); E: ( 313, 328 ) time: 2017-12-25 13:13:35 +0000; A: 6134; B: ( 628, 60374, 6044 ); C: ( "-72", "6", 157, 157 ); D( 1700, 1654, 1580, ); E: ( 3103, 3208 )""" match=re.finditer(pattern,string_1,flags=re.MULTILINE|re.DOTALL) print('A B C D E Time') print('----------------') dict_1={} for i in match: if i.group(1): if 'time' not in dict_1: dict_1['time']=[i.group(1)] else: dict_1['time'].append(i.group(1)) if i.group(2): if 'A' not in dict_1: dict_1['A']=[i.group(2)] else: dict_1['A'].append(i.group(2)) if i.group(3): if 'B' not in dict_1: dict_1['B']=[i.group(3).split()] else: dict_1['B'].append(i.group(3).split()) if i.group(4): if 'C' not in dict_1: dict_1['C']=[i.group(4).split()] else: dict_1['C'].append(i.group(4).split()) if i.group(5): if 'D' not in dict_1: dict_1['D']=[i.group(5).split()] else: dict_1['D'].append(i.group(5).split()) if i.group(6): if 'E' not in dict_1: dict_1['E']=[i.group(6).split()] else: dict_1['E'].append(i.group(6).split()) sorted = collections.OrderedDict(sorted(dict_1.items())) for i in zip(*sorted.values()): print(i) output: A B C D E Time ---------------- ('61792', ['60328,', '60344,', '60344,', '60344'], ['"-3672",', '"-3656",', '1547,', '1578'], ['1500,', '1484,', '1500,'], ['313,', '328'], '2017-12-24 13:13:34 +0000') ('6134', ['628,', '60374,', '6044'], ['"-72",', '"6",', '157,', '157'], ['1700,', '1654,', '1580,'], ['3103,', '3208'], '2017-12-25 13:13:35 +0000')
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47459346
has comment: http://stackoverflow.com/comment/81905544
has comment: http://stackoverflow.com/comment/81906565

http://stackoverflow.com/comment/81802884
type: Comment
type: QuestionComment
has text: Do you already have the equation describing the trend line or do you want to compute it from the data points? Besides that, ``pyplot.plot(x,y,'-')`` generates you a linear plot and ``pyplot.plot(x,y,'o')`` will generate the markers for the data.
score: 0
comment on: http://stackoverflow.com/q/47423889

http://stackoverflow.com/comment/81743610
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47394765
has text: Regex way of doing ? Nice one

http://stackoverflow.com/comment/81854645
has text: http://www.geeksforgeeks.org/merge-k-sorted-arrays/ `O(kn*logk)` using MinHeap.
type: QuestionComment
comment on: http://stackoverflow.com/q/47449818
score: 0
type: Comment

http://stackoverflow.com/a/47499151
has comment: http://stackoverflow.com/comment/81962360
upvote count: 1
has comment: http://stackoverflow.com/comment/99028288
accepted answer of: http://stackoverflow.com/q/47498307
has comment: http://stackoverflow.com/comment/88084092
answers question: http://stackoverflow.com/q/47498307
type: Answer
has body: Is the function EMD.getEMD actually doing the computation? It appears to be the case, and if my assumption is correct you're misunderstanding tensorflow. Tensorflow development progresses in two stages, first you build a graph of your operations, we usually separate all of this code into a build_graph() function. At this point no data is passed in, we are only defining the operations that we'll do. Second, you create a session, pass in the variable, and ask tensorflow to compute certain values, such as the loss. You'll actually do computations in tensorflow using a call to sess.run([ops_to_compute], feed_dict={placeholder_1:input_1, placeholder_2:input_2, ...}) In order to use a custom loss function, you'll need to define the loss function in tensorflow. If you ever use a numpy function in the definition of the loss function you know you've done it wrong. You have to define the loss function using tensorflow operations. It's usually quite trivial to do so. You'll generally just look at the numpy operations that you have in your current code and re-create the same tensorflow operation.
has comment: http://stackoverflow.com/comment/96358556
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47420592
has comment: http://stackoverflow.com/comment/81795661
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81795827
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47420544
answers question: http://stackoverflow.com/q/47420544
has comment: http://stackoverflow.com/comment/81795692
type: Answer
has comment: http://stackoverflow.com/comment/81795797
has body: You should never modify the list you are iterating through! You could solve it by creating a second list: temp_inventory = list(player.inventory) for item in player.inventory: if item.name == "dead goblin": goblins_taken += 1 temp_inventory.remove(item) player.inventory = temp_inventory This I have tried and works: a = [1,2,3,2,1] b = list(a) elems_removed = 0 for elem in a: if elem == 2: elems_removed += 1 b.remove(elem) print(a) print(b) a=b print(a) print(elems_removed)
has comment: http://stackoverflow.com/comment/81795548
has comment: http://stackoverflow.com/comment/81795684

http://stackoverflow.com/q/47493409
tagged with: arrays
downvote count: 0
has body: This differs from Write multiple numpy arrays to file in that I need to be able to stream content, rather than writing it all at once. I need to write multiple compressed numpy arrays in binary to a file. I can not store all the arrays in memory before writing so it is more like streaming numpy arrays to a file. This currently works fine as text file = open("some file") while doing stuff: file.writelines(somearray + "\n") where some array is a new instance every loop however this does not work if i try and write the arrays as binary. arrays are created at 30hz and grow too big to keep in memory. They also can not each be stored into a bunch of single array files because that would just be wasteful and cause a huge mess. So i would like only one file per a session instead of 10k files per a session.
linked to: http://stackoverflow.com/q/3419082
upvote count: 7
has comment: http://stackoverflow.com/comment/81942399
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: file-io
tagged with: binaryfiles
accepted answer: http://stackoverflow.com/a/47493582
has comment: http://stackoverflow.com/comment/81942716
tagged with: python
has answer: http://stackoverflow.com/a/47493582
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47493641
answer count: 2
has answer: http://stackoverflow.com/a/47493641
has title: Streaming multiple numpy arrays to a file
score: 7

http://stackoverflow.com/comment/81814453
type: AnswerComment
comment on: http://stackoverflow.com/a/47421736
score: 0
has text: Doesn't seem to work for some reason... seems to be a problem with the rv.append
type: Comment

http://stackoverflow.com/q/47502398
score: 13
has title: Python Statsmodels Mixedlm (Mixed Linear Model) random effects
tagged with: python
tagged with: mixed-models
upvote count: 13
tagged with: statsmodels
tagged with: random-effects
answer count: 2
has answer: http://stackoverflow.com/a/62773179
has answer: http://stackoverflow.com/a/47594609
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I am a bit confused about the output of Statsmodels Mixedlm and am hoping someone could explain. I have a large dataset of single family homes, including the previous two sale prices/sale dates for each property. I have geocoded this entire dataset and fetched the elevation for each property. I am trying to understand the way in which the relationship between elevation and property price appreciation varies between different cities. I have used statsmodels mixed linear model to regress price appreciation on elevation, holding a number of other factors constant, with cities as my groups category. md = smf.mixedlm('price_relative_ind~Elevation+YearBuilt+Sale_Amount_1+LivingSqFt',data=Miami_SF,groups=Miami_SF['City']) mdf = md.fit() mdf.random_effects Entering mdf.random_effects returns a list of coefficients. Can I interpret this list as, essentially, the slope for each individual city (i.e., the individual regression coefficient relating Elevation to sale price appreciation)? Or are these results the intercepts for each City?

http://stackoverflow.com/q/47533991
possible better answer: http://stackoverflow.com/a/47534516
type: AnsweredQuestion
has body: I have a list like this: board = [["X", "X", "X", "X"], ["X", "O", "O", "X"], ["X", "X", "O", "X"], ["X", "O", "X", "X"]] How can I group all connecting neighbours? I can find all individual "O"'s like this for instance, all_o = [ (x, y) for x, row in enumerate(board) for y, col in enumerate(row) if col == 'O' ] Yielding me this: [(1, 1), (1, 2), (2, 2), (3, 1)] Now I want to group by the connected items: Where my expected output would be this: [[(1, 1), (1, 2), (2, 2)], [(3, 1)]] I don't quite know ho to approach this, been looking at itertools.groupby, is that something I could use here?
score: 0
tagged with: grouping
tagged with: python
accepted answer: http://stackoverflow.com/a/47534484
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47534484
answer count: 2
has title: Python group connecting values
has answer: http://stackoverflow.com/a/47534516
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82024572

http://stackoverflow.com/comment/81832416
has text: but it still throws errors. Traceback (most recent call last): File "rawkiller.py", line 163, in <module> main() File "rawkiller.py", line 48, in main initial_executing(value_map) File "rawkiller.py", line 62, in initial_executing compress(value_map) File "rawkiller.py", line 107, in compress print ("[*] " + len(value_map[7]) + " have been moved to:") TypeError: cannot concatenate 'str' and 'int' objects
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47438424
type: Comment

http://stackoverflow.com/q/47523741
has body: I have list A, which contains values separated by "|" and looks like this df1['original']= ['aaa|bbb|ccc','aaa|ccc','aaa|ccc|ddd'] output: aaa|bbb|ccc aaa|ccc aaa|ccc|ddd In another df, I have another two columns. First one looks like this: df1['title']=['aaa','bbb','ccc','ddd']. And correspondingly, I have another column next to df1['title']. df1['new_value']=['x','y','z','w']. output: title new_value aaa x bbb y ccc z ddd w I want to search every value in df1['original'] and replace by the searching results based on df1['title'] and df1['new_value']. I want to keep the| in the original column. And the final output should look like this: df1['New']=['x|y|z','x|z','x|z|w'] output: New x|y|z x|z x|z|w This is more like a conditional lookup in excel and any ideas how to achieve this in python? Thanks for your time! The link below can only match the ones that contain one value. Look up and replace values in a list (pandas)
tagged with: lookup
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47523933
possible better answer: http://stackoverflow.com/a/47523933
score: 0
tagged with: conditional-statements
has title: Look up and replace partial values in a list
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47524153
has answer: http://stackoverflow.com/a/47524135
tagged with: replace
type: Question
accepted answer: http://stackoverflow.com/a/47524153
tagged with: python

http://stackoverflow.com/comment/81965227
type: AnswerComment
has text: This seems to be working, although because of a different problem, the showing of the variable won't update, so I'll need to solve that before I can answer that definitely :)
comment on: http://stackoverflow.com/a/47504374
type: Comment
score: 0

http://stackoverflow.com/comment/82099749
has text: All right ! I'll try with this. Thank you for your help :)
comment on: http://stackoverflow.com/a/47482958
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81729218
comment on: http://stackoverflow.com/a/47388058
type: AnswerComment
has text: However it is important to note that both `''` and `None` evaluate to `False` in an `if` condition (ie when passed to `bool`) https://stackoverflow.com/a/39984051/1453822
score: 1
type: Comment

http://stackoverflow.com/q/47402267
has title: What is the correct way to convert bytes to a hex string in Python 3?
has body: I'm working on the CryptoPals challenges and I'm stuck on Challenge 2 Set 1. I'm familiar with bitwise xor-ing, but I can't get the desired result in a hex string. This is my function right now: def strxor(s1, s2): bytes1 = unhexlify(s1) bytes2 = unhexlify(s2) b = b"" for c1, c2 in zip(bytes1, bytes2): b += bytes([c1^c2]) return hexlify(b) It currently returns the desired hex string, but as a bytes object instead of a string. How do I convert these? Or is there a better way to handle this?
tagged with: python
tagged with: cryptography
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47402339
answer count: 1
tagged with: xor
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47402339

http://stackoverflow.com/comment/81998054
type: QuestionComment
score: 0
has text: There is a discrepancy between the error you have posted and what I obtain by running the posted grammar : `$ grun N start -tokens -diagnostics input.txt` (which contains `a(1)`) gives `[@0,0:0='a',<CONSTANTLIST>,1:0] ... line 1:0 mismatched input 'a' expecting DATALOGPROGRAM`. How did you run it ?
comment on: http://stackoverflow.com/q/47498553
type: Comment

user-interface
tags question: http://stackoverflow.com/q/47517328
tags question: http://stackoverflow.com/q/47502212
tags question: http://stackoverflow.com/q/47481919
tags question: http://stackoverflow.com/q/47454028
tags question: http://stackoverflow.com/q/47423659
tags question: http://stackoverflow.com/q/47422147
tags question: http://stackoverflow.com/q/47494941
tags question: http://stackoverflow.com/q/47493365
tags question: http://stackoverflow.com/q/47483587
tags question: http://stackoverflow.com/q/47524060
type: Tag
tags question: http://stackoverflow.com/q/47489567
tags question: http://stackoverflow.com/q/47459072
tags question: http://stackoverflow.com/q/47401017
tags question: http://stackoverflow.com/q/47532153
tags question: http://stackoverflow.com/q/47520983
tag name: user-interface
tags question: http://stackoverflow.com/q/47427719
tags question: http://stackoverflow.com/q/47410970
tags question: http://stackoverflow.com/q/47503739
tags question: http://stackoverflow.com/q/47529864

http://stackoverflow.com/comment/81799862
type: AnswerComment
comment on: http://stackoverflow.com/a/47421653
has text: Mind posting the relevant source code of that portion of the page? Maybe everything contained within the tag? You can do right click > inspect element > edit as HTML > copy text
type: Comment
score: 0

http://stackoverflow.com/comment/81942514
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47493641
has text: Ah, I see. My answer assumes that you will create the file, and then repeatedly add arrays to it. Yes, you would need to use `mode='a'` for the zipfile if you want to add to an existing file. You would also need to ensure that the name used for each array does not already exist in the NPZ file.
type: AnswerComment

http://stackoverflow.com/comment/82063876
has text: Similar question has already been answered , with method to pass password programtically https://stackoverflow.com/questions/47380378/run-process-as-admin-with-subprocess-run-in-python/47385474#47385474
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47526332

http://stackoverflow.com/comment/81744600
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47392668
type: Comment
has text: I marked it as a good answer, because it shows that I am on the wrong track. This is valuable information to me (and maybe others as well).

http://stackoverflow.com/a/47400771
has body: You could assign values to df.values, this should be really fast. v = df.values v[v.argmin(0), np.arange(len(v))] = newvalues df[:] = v df 0 1 2 3 0 2.776975 1.433614 3.000000 4.000000 1 1.328099 2.000000 0.255676 0.360205 2 1.000000 0.547384 0.791848 0.340333 3 1.475486 0.114053 0.904416 0.060585
type: Answer
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47400561

http://stackoverflow.com/comment/112783666
type: Comment
comment on: http://stackoverflow.com/a/47391255
type: AnswerComment
has text: @MadhurYadav Just do `p.legend()` within the for loop.
score: 1

http://stackoverflow.com/a/47651964
answers question: http://stackoverflow.com/q/47491586
type: Answer
has comment: http://stackoverflow.com/comment/82262107
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47491586
has body: Your code is running fine. You can try debugging it with pdb. You may be printing the method type at the time of loading the page, instead of uploading the .csv file.

http://stackoverflow.com/q/47496850
tagged with: syntax-error
answer count: 2
has comment: http://stackoverflow.com/comment/81948932
type: UnansweredQuestion
downvote count: 1
has title: How to fix "SyntaxError: invalid syntax" in discord bot
has answer: http://stackoverflow.com/a/51877842
favorite count: 0
score: 3
tagged with: bots
has comment: http://stackoverflow.com/comment/82041950
has comment: http://stackoverflow.com/comment/81948955
tagged with: python
upvote count: 4
tagged with: discord
has body: I am new at programming. I have been trying to make a discord bot, but every time I try to launch it it fails with SyntaxError: invalid syntax. Code: import discord.py from discord.ext.commands import Bot from discord.ext import commands import asyncio Client = discord.Client() bot_prefix= "^" client = commands.Bot(command_prefix=bot_prefix) @client.event async def on_ready(): print("Bot Online!") print("Name: {}".format(client.user.name)) print("ID: {}".format(client.user.id)) @client.command(pass_context=True) async def ping(ctx): await client.say("Pong!") client.run("ID") Error: C:\Users\Vanias&gt;"C:\Users\Vanias\Desktop\MemerBoy\Test 3 bot 3.py" Traceback (most recent call last): File "C:\Users\Vanias\Desktop\MemerBoy\Test 3 bot 3.py", line 1, in &lt;module&gt; import discord.py File "C:\Users\Vanias\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\__init__.py", line 20, in &lt;module&gt; from .client import Client, AppInfo, ChannelPermissions File "C:\Users\Vanias\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\client.py", line 38, in &lt;module&gt; from .state import ConnectionState File "C:\Users\Vanias\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\state.py", line 36, in &lt;module&gt; from . import utils, compat File "C:\Users\Vanias\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\compat.py", line 32 create_task = asyncio.async ^ SyntaxError: invalid syntax
has answer: http://stackoverflow.com/a/71706006
type: Question

http://stackoverflow.com/q/47533818
has body: I have a list lets say: DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z'] Now the other parameter of mine is like arguement, I write in udl and it returns ['udl'] so lets say another list arg_list = ['udl'] I want to check if u and d and l is in this list or i want to check if none of the letters in my direction letters list in the arg list to make it print error msg I have tried this: for letter in DIRECTION_LETTERS: for char in arg_list[4]: if letter in arg_list[4][0]: continue else: print (ERROR_MESSAGE_DIRECTIONS) return False return True
tagged with: python
has comment: http://stackoverflow.com/comment/82024269
accepted answer: http://stackoverflow.com/a/47533969
type: AnsweredQuestion
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/47533969
has title: Comparing letters in list with string in a list python
type: Question
possible better answer: http://stackoverflow.com/a/47533961
answer count: 2
has answer: http://stackoverflow.com/a/47533961

http://stackoverflow.com/a/47479485
has comment: http://stackoverflow.com/comment/81921231
type: Answer
has comment: http://stackoverflow.com/comment/81920112
score: 4
has body: The problem with this site is not the certificate validation since you have successfully switched it off. The problem instead is that the site only supports ciphers which are no longer considered secure, i.e. 3DES and RC4 based ciphers. The default ciphers in the ssl library don't include these ciphers for security reasons. To add support for these ciphers you can manually set the default cipher set. The following line sets DES-CBC3-SHA as the offered cipher. This way you can access the broken site: ssl._DEFAULT_CIPHERS = ('DES-CBC3-SHA') myBrowser = mechanize.Browser() ... Note that you should use this setting only for the specific site. While it might in theory be also possible to just set a larger cipher set for _DEFAULT_CIPHERS to handle all sites, this specific site suffers from additional problems: it looks like it will fail with the TLS handshake even if DES-CBC3-SHA is included in the offered cipher set but if newer ciphers (like GCM) are offered before DES-CBC3-SHA.
upvote count: 4
has comment: http://stackoverflow.com/comment/81916146
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47478994
has comment: http://stackoverflow.com/comment/81920511
downvote count: 0
has comment: http://stackoverflow.com/comment/81914626
accepted answer of: http://stackoverflow.com/q/47478994
has comment: http://stackoverflow.com/comment/81915854

http://stackoverflow.com/q/47433632
has body: I am try to re-learn python so my skills are lacking. I am currently playing with the Pubmed APIs. I am trying to parse the XML file that is given here, and then run a loop to go through each child ('/pubmedarticle') and grab a few things, for now just the article title, and enter them into a dictionary under the key of the pubmedid (pmid). i.e. the output should look like: {'29150897': {'title': 'Determining best outcomes from community-acquired pneumonia and how to achieve them.'} '29149862': {'title': 'Telemedicine as an effective intervention to improve antibiotic appropriateness prescription and to reduce costs in pediatrics.'}} Later I will add in more factors like author and journal etc, for now I just want to figure out how to use lxml package to get the data I want into a dictionary. I know there are plenty of packages that can do this for me, but that defeats the purpose of learning. I've tried a bunch of different things and this is what I'm currently trying to do: from lxml import etree article_url = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&amp;retmode=xml&amp;tool=PMA&amp;id=29150897,29149862" page = requests.get(article_url) tree = etree.fromstring(page.content) dict_out = {} for x in tree.xpath('//PubmedArticle'): pmid = ''.join([x.text for x in x.xpath('//MedlineCitation/PMID[@Version="1"]')]) title = ''.join([x.text for x in x.xpath('//ArticleTitle')]) dict_out[pmid] = {'title': title} print(dict_out) I probably have a misunderstanding about how to go about this process, but if anyone can offer insight or lead me in the right direction for resources, that would be greatly appreciated. Edit: My apologies. I wrote this far quicker than I should have. I have fixed up all the cases. Also, the result it throws seems to combine the PMIDs while just giving the first title: {'2725403628806902': {'title': 'Handshake Stewardship: A Highly Effective Rounding-based Antimicrobial Optimization Service.Monitoring, documenting and reporti…
type: AnsweredQuestion
score: 0
tagged with: lxml
has comment: http://stackoverflow.com/comment/81821851
linked to: http://stackoverflow.com/q/7414747
accepted answer: http://stackoverflow.com/a/47436395
has comment: http://stackoverflow.com/comment/81821583
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
type: Question
has answer: http://stackoverflow.com/a/47436395
has answer: http://stackoverflow.com/a/47433905
answer count: 2
has title: Parsing Pubmed API xml with lxml then grabbing children into dictionary
has comment: http://stackoverflow.com/comment/81822721
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/47433905

http://stackoverflow.com/comment/81756818
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47401563
score: 1
has text: change `occCode` to `x` which is the parameter the function is provided with.

http://stackoverflow.com/a/51702032
has body: This piece of code might help you. It is based on Keras implementation of Adam optimizer (beta values are Keras defaults) from keras import Callback from keras import backend as K class AdamLearningRateTracker(Callback): def on_epoch_end(self, logs={}): beta_1=0.9, beta_2=0.999 optimizer = self.model.optimizer if optimizer.decay&gt;0: lr = K.eval(optimizer.lr * (1. / (1. + optimizer.decay * optimizer.iterations))) t = K.cast(optimizer.iterations, K.floatx()) + 1 lr_t = lr * (K.sqrt(1. - K.pow(beta_2, t)) /(1. - K.pow(beta_1, t))) print('\nLR: {:.6f}\n'.format(lr_t))
downvote count: 1
has comment: http://stackoverflow.com/comment/99292403
type: Answer
upvote count: 2
score: 1
answers question: http://stackoverflow.com/q/47490834

http://stackoverflow.com/comment/81888460
comment on: http://stackoverflow.com/q/47448731
has text: @AntonyHatchkins did you try this (copyPaste) using google api explorer? Is this working fine there?
type: Comment
score: 0
type: QuestionComment

heroku
tags question: http://stackoverflow.com/q/47401071
tags question: http://stackoverflow.com/q/47384364
type: Tag
tags question: http://stackoverflow.com/q/47446480
tags question: http://stackoverflow.com/q/47423762
tags question: http://stackoverflow.com/q/47477771
tags question: http://stackoverflow.com/q/47452107
tags question: http://stackoverflow.com/q/47524285
tags question: http://stackoverflow.com/q/47406557
tag name: heroku

http://stackoverflow.com/comment/139708656
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47426089
has text: Beside the point, but `del` is a statement, not a function.
type: Comment

http://stackoverflow.com/comment/81908235
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47475130
has text: Solved: Included opencv_ffmpeg320_64.dll next to my executable.
type: Comment

http://stackoverflow.com/a/47417042
has comment: http://stackoverflow.com/comment/81789608
downvote count: 1
has body: Dict of sets of indices Here's a mix of Horia's proposal and my original one. You can define a dict with cities as key and sets of indices as values: list1 = ['London', 'Manchester', 'Liverpool', 'Edimburgh'] list2 = ['Dublin', 'Cork', 'Galway', 'Paris', 'Rome'] list3 = ['Berlin', 'Munich', 'Frankfurt', 'Paris', 'Milan', 'Rome', 'Madrid', 'Barcelona', 'Lisbon'] list4 = ['Washington', 'New York', 'San Francisco', 'LA', 'Boston'] # Note that 'Paris' and 'Rome' are both in list2 and list3 groups = [list1, list2, list3, list4] indices = {} for i, group in enumerate(groups): for city in group: indices.setdefault(city, set()).add(i) The structure is compact and looks like this: print(indices) #{'London': {0}, 'Manchester': {0}, 'Liverpool': {0}, 'Edimburgh': {0}, 'Dublin': {1}, 'Cork': {1}, 'Galway': {1}, 'Paris': {1, 2}, 'Rome': {1, 2}, 'Berlin': {2}, 'Munich': {2}, 'Frankfurt': {2}, 'Milan': {2}, 'Madrid': {2}, 'Barcelona': {2}, 'Lisbon': {2}, 'Washington': {3}, 'New York': {3}, 'San Francisco': {3}, 'LA': {3}, 'Boston': {3}} For any city pair, you can get a set of common indices thanks to set intersection: def common_groups(city1, city2): return indices.get(city1, set()) &amp; indices.get(city2, set()) print(common_groups('London', 'Liverpool')) # {0} print(common_groups('London', 'Paris')) # set() print(common_groups('Cork', 'Paris')) # {1} print(common_groups('Rome', 'Paris')) # {1, 2} print(common_groups('Rome', 'Nowhere')) # set() An empty set is falsey in Python. With n cities, creating the dict will be O(n), space requirement should be O(n) and lookup performance will be O(1). As a bonus, the query doesn't just return a boolean but a set of indices. Finally, thanks to set intersections, this method would also work if you want to check that three or more cities are in the same group.
score: 21
type: Answer
accepted answer of: http://stackoverflow.com/q/47416917
has comment: http://stackoverflow.com/comment/81789722
upvote count: 22
answers question: http://stackoverflow.com/q/47416917
type: AcceptedAnswer

http://stackoverflow.com/a/47440279
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47440096
answers question: http://stackoverflow.com/q/47440096
has body: The value for page_nr is extracted from the URL, and is therefore a string. If you need it to be an int, it's simple to convert it - you could do this in the view, for example: return render(request, 'post/posts.html', { 'post': post, 'form': form, 'comments': comments, 'my_page_nr': int(page_nr), })
has comment: http://stackoverflow.com/comment/81841377

http://stackoverflow.com/a/47490636
score: 4
has body: We using cumsum twice in group and group calculation df['WTDSum']=df.groupby(df.Day.eq('Sun').cumsum()).Sales.cumsum() df Out[520]: Date Day Sales WTDSum 0 11/1/2017 Wed 5 5 1 11/2/2017 Thr 5 10 2 11/3/2017 Fri 10 20 3 11/4/2017 Sat 5 25 4 11/5/2017 Sun 5 5 5 11/6/2017 Mon 10 15 6 11/7/2017 Tue 5 20 7 11/8/2017 Wed 5 25 8 11/9/2017 Thr 15 40 9 11/10/2017 Fri 5 45 10 11/11/2017 Sat 0 45 11 11/12/2017 Sun 5 5
upvote count: 4
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47490576
answers question: http://stackoverflow.com/q/47490576
type: Answer

http://stackoverflow.com/q/47496477
type: Question
has answer: http://stackoverflow.com/a/47496627
tagged with: python
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: maya
has answer: http://stackoverflow.com/a/47514877
has body: How can I change IK Handle's radius in Autodesk Maya? Click to see what Radius I mean.
tagged with: skinning
has title: IK Handle radius in Maya
favorite count: 0

http://stackoverflow.com/comment/81975336
has text: @MHarisKhan ok - I updated my post. Try `textFile` instead with a comma-separated list of files - or use the wildchar `*` if you want to select a directory.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47491758

http://stackoverflow.com/q/47478913
type: Question
score: 5
type: UnansweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/51353363
tagged with: python
answer count: 6
tagged with: flask
has answer: http://stackoverflow.com/a/47478962
has answer: http://stackoverflow.com/a/78773352
has answer: http://stackoverflow.com/a/61126926
downvote count: 0
has title: Python/Flask mysql cursor: Why it doesn't work?
tagged with: mysql
has answer: http://stackoverflow.com/a/65317207
has body: from flask import Flask from flask_mysqldb import MySQL app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = 'password' app.config['MYSQL_DB'] = 'todoapp' app.config['MYSQL_CURSORCLASS'] = 'DictCursor' mysql = MySQL(app) cur = mysql.connection.cursor() if __name__ == '__main__': app.run() There is error which is displayed after executing program: cur = mysql.connection.cursor() AttributeError: 'NoneType' object has no attribute 'cursor'. According to documentaction it should work. I use Ubuntu 16.04, I have installed MySQL and it works properly. Could anyone explain why it doesn't work?
has answer: http://stackoverflow.com/a/56332537
favorite count: 0

http://stackoverflow.com/comment/81797367
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47421497
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
type: Comment

http://stackoverflow.com/q/47444578
tagged with: pandas
has comment: http://stackoverflow.com/comment/81844658
linked to: http://stackoverflow.com/q/22536179
upvote count: 1
has comment: http://stackoverflow.com/comment/81845578
answer count: 1
linked to: http://stackoverflow.com/q/47454335
duplicate of: http://stackoverflow.com/q/22536179
has answer: http://stackoverflow.com/a/47444959
has comment: http://stackoverflow.com/comment/81844492
favorite count: 0
type: Question
has title: How to add days of the week x axis labels
downvote count: 3
score: -2
tagged with: matplotlib
tagged with: python
has body: I have a dataframe in which each row relates to a day of the week, starting on Sunday. there are 39 rows in total. I would like to plot the numerical values from the column Physical one week at a time with the days of the week labelled on the x-axis. I have this so far: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("health.csv", header = None, names = ['Physical', 'Emotional']) ax = df['Physical'].plot() plt.show() This gives: How can I label the x-axis by the days of the week, starting on Sunday and split the weeks so that they are separated vertically. The full data is: 5,5 6,7 6,9 6,7 5,6 7,9 5,9 6,7 7,6 7,4 7,5 6,7 7,9 7,9 5,6 8,7 9,9 7,7 7,6 7,8 7,9 7,9 7,6 7,8 6,6 6,6 6,7 6,6 6,5 6,6 7,5 7,5 7,5 7,6 7,5 8,6 7,6 7,7 6,6
has comment: http://stackoverflow.com/comment/81845265
accepted answer: http://stackoverflow.com/a/47444959
has comment: http://stackoverflow.com/comment/81845231
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81844879

http://stackoverflow.com/a/65705939
answers question: http://stackoverflow.com/q/47437396
type: Answer
score: 0
has body: Try adding the following code at the start of your script import os os.environ['KMP_DUPLICATE_LIB_OK']='True' It might have something to do with the kernel trying to import a module multiple times that it just crashes.

http://stackoverflow.com/comment/81971921
type: QuestionComment
type: Comment
has text: You can just use a `dictionary` and have it's keys like `anger` and then just append to the key's value a list with the values.
score: 0
comment on: http://stackoverflow.com/q/47508048

http://stackoverflow.com/q/47437357
tagged with: pandas
duplicate of: http://stackoverflow.com/q/20250771
tagged with: python
has comment: http://stackoverflow.com/comment/81829941
score: 0
linked to: http://stackoverflow.com/q/20250771
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81829497
has title: How to change contents of dataframe using dictionaries?
type: Question
has body: Is there a python pandas method to rename contents of a DataFrame using dictionaries or otherwise? I normally use rename method on index labels and column titles. But when dataframe entries are to be replaced using dictionaries I use set_index to make them index, then use rename method on index and later reset_index. I understand this is round-about. Is there any other way this can be done using fewer lines of code? example: Suppose below is my dataframe &amp; I want to change acronyms under column title State with State Names i.w. CA - California, IL - Illinois etc Rank State Metro CountyName 1 NY New York Queens 2 CA Los Angeles-Long Beach-Anaheim Los Angeles 3 IL Chicago Cook 4 PA Philadelphia Philadelphia 5 AZ Phoenix Maricopa 6 NV Las Vegas Clark 7 CA San Diego San Diego 8 TX Dallas-Fort Worth Dallas 9 CA San Jose Santa Clara

http://stackoverflow.com/q/47387158
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47387237
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
has title: Python3 Remove \n from list
favorite count: 0
type: Question
has body: Helle @all! I trying to remove \n characters from a list it looks like this: tryed a for loop: for hotel in hotel_url_list: hotel.replace('\n', '') it doesn't work! phyton3 prints: ['\n/hotel/at/alpen-adria-stadthotel.de.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaA6IAQGYAQfCAQp3aW5kb3dzIDEwyAEM2AEB6AEB-AELkgIBeagCAw;\n/sid=e812ccd62b87bc158a2175bdc410f874;ucfs=1;] Thanks for your help!
tagged with: list
tagged with: python
tagged with: replace

http://stackoverflow.com/comment/81749673
comment on: http://stackoverflow.com/q/47398321
score: 0
type: Comment
type: QuestionComment
has text: I assume the "Robot Framework" is the issue here? Because I have no issue with selenium in 3+

http://stackoverflow.com/q/47500417
has answer: http://stackoverflow.com/a/47502073
has title: Django celery tasks number limit issue
has body: I have problem run celery workers to execute same task multiple times in parallel. I ran 3 workers and set --concurrency to 2 for all workers. But it only executes 3 tasks over all 3 workers. I hope to run about 10 workers. celery -A my_app worker -l info -c 2 -n worker1 celery -A my_app worker -l info -c 2 -n worker2 celery -A my_app worker -l info -c 2 -n worker3 Please help me whether I can run more than 3 tasks at a time.
tagged with: multithreading
tagged with: django
has comment: http://stackoverflow.com/comment/81964143
tagged with: celery
type: AnsweredQuestion
tagged with: worker
score: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47502073
type: Question

http://stackoverflow.com/q/47524492
accepted answer: http://stackoverflow.com/a/47532103
has answer: http://stackoverflow.com/a/47532103
has comment: http://stackoverflow.com/comment/82016096
has comment: http://stackoverflow.com/comment/82005197
has body: I have created a crawlspider with Scrapy. I need to get a specific part of the page with a Xpath : item = ExplorerItem() item['article'] = response.xpath("//div[@class='post-content']").extract() Then I am using this item in pipelines.py. But item['article'] gives me a result in unicode: `u' \n\t\t\t\t\t D\xe9signation \n ` I need to convert it in UTF-8.
has comment: http://stackoverflow.com/comment/82005424
score: -1
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/82020458
has comment: http://stackoverflow.com/comment/82016648
has answer: http://stackoverflow.com/a/47525639
answer count: 2
has comment: http://stackoverflow.com/comment/82005247
has comment: http://stackoverflow.com/comment/82020904
downvote count: 2
has title: Encoding issue with Scrapy (Python)
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47525639
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/47494385
favorite count: 0
score: 9
type: Question
has comment: http://stackoverflow.com/comment/81943830
has comment: http://stackoverflow.com/comment/81944068
tagged with: python-3.x
upvote count: 9
has comment: http://stackoverflow.com/comment/81943895
has answer: http://stackoverflow.com/a/47731229
downvote count: 0
has comment: http://stackoverflow.com/comment/81943962
has body: I have a list of numbers: a = [3, 6, 20, 24, 36, 92, 130] And a list of conditions: b = ["2", "5", "20", "range(50,100)", "&gt;120"] I want to check if a number in 'a' meets one of the conditions in 'b' and if yes, put these numbers in list 'c' In above case: c = [20, 92, 130] I created this code what seems to do what I want: c = [] for x in a: for y in b: if "range" in y: rangelist = list(eval(y)) if x in rangelist: c.append(x) elif "&gt;" in y or "&lt;" in y: if eval(str(x) + y): c.append(x) else: if x == eval(y): c.append(x) However my list 'a' can be very big. Is there not an easier and faster way to obtain what I want?
tagged with: python
tagged with: list-comprehension
answer count: 4
has comment: http://stackoverflow.com/comment/81943870
type: AnsweredQuestion
tagged with: list
has title: How to check if elements in list 'a' meet conditions in list 'b'?
has comment: http://stackoverflow.com/comment/81943799
has comment: http://stackoverflow.com/comment/81944622
has comment: http://stackoverflow.com/comment/81943974
has comment: http://stackoverflow.com/comment/81944002
has answer: http://stackoverflow.com/a/47498334
has answer: http://stackoverflow.com/a/47494514
has answer: http://stackoverflow.com/a/47494511
possible better answer: http://stackoverflow.com/a/47494511
accepted answer: http://stackoverflow.com/a/47494514

http://stackoverflow.com/q/47392290
tagged with: dask
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has title: Creating a dataframe column in python, based on the conditions on other columns
has answer: http://stackoverflow.com/a/47394087
score: 2
upvote count: 3
tagged with: pandas
has body: I have the following DataFrame (in reality I'm working with around 20 million rows): shop month day sale 1 7 1 10 1 6 1 8 1 5 1 9 2 7 1 10 2 6 1 8 2 5 1 9 I want another column: "Prev month sales", where sales are equal to the "Sales of previous month with same day, e.g. shop month day sale prev month sale 1 7 1 10 8 1 6 1 8 9 1 5 1 9 9 2 7 1 10 8 2 6 1 8 9 2 5 1 9 9
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81737840
type: Question
has comment: http://stackoverflow.com/comment/81737638

http://stackoverflow.com/a/47555252
has comment: http://stackoverflow.com/comment/82184191
has comment: http://stackoverflow.com/comment/82171743
answers question: http://stackoverflow.com/q/47510614
has body: I have to make some assumptions here because you didn't post the stack trace, and you didn't post a sample data file. But the only place you could have that error is line 9, and the only reason you would get that is because you are expecting the csv file to have 4 columns, and one line of the file (at a guess, the last one) does not. I suspect you have a trailing blank line at the end of your input file, but it might be duff data in the middle. A print statement (as timgeb suggests) would be good, but you could also put a permanent validation trap in your code, for example, for line in csv_reader: try: print(line[3]) except Exception as details: print('Invalid data:',line,'rejected due to',details)
has comment: http://stackoverflow.com/comment/82130703
has comment: http://stackoverflow.com/comment/82174616
type: Answer
has comment: http://stackoverflow.com/comment/82174386
has comment: http://stackoverflow.com/comment/82135585
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47510614

http://stackoverflow.com/a/53297903
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47514444
type: Answer
answers question: http://stackoverflow.com/q/47514444
has body: If you are using a somewhat recent version of Python 3, you can now also do pip install PySide2
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/81921211
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47483237
type: Comment
has text: Its shameful it took as long as it did to debug this. Any debugging tips are appreciated.

http://stackoverflow.com/a/47432758
has comment: http://stackoverflow.com/comment/81820515
score: 3
has comment: http://stackoverflow.com/comment/81827297
has comment: http://stackoverflow.com/comment/81821897
type: Answer
has comment: http://stackoverflow.com/comment/81822255
has body: From keras backend functions, you have the function greater that you can use: import keras.backend as K def customLossFunction(yTrue,yPred) greater = K.greater(yPred,0.5) greater = K.cast(greater,K.floatx()) #has zeros and ones multiply = (2*greater) - 1 #has -1 and 1 modifiedTrue = multiply * yTrue #here, it's important to know which dimension you want to sum return K.sum(modifiedTrue, axis=?) The axis parameter should be used according to what you want to sum. axis=0 -> batch or sample dimension (number of sequences) axis=1 -> time steps dimension (if you're using return_sequences = True until the end) axis=2 -> predictions for each step Now, if you have only a 2D target: axis=0 -> batch or sample dimension (number of sequences) axis=1 -> predictions for each sequence If you simply want to sum everything for every sequence, then just don't put the axis parameter. Important note about this function: Since it contains only values from yTrue, it cannot backpropagate to change the weights. This will lead to a "none values not supported" error or something very similar. Although yPred (the one that is connected to the model's weights) is used in the function, it's used only for getting a true x false condition, which is not differentiable.
accepted answer of: http://stackoverflow.com/q/47430437
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47430437
has comment: http://stackoverflow.com/comment/81828394

http://stackoverflow.com/q/47425595
has comment: http://stackoverflow.com/comment/81848130
has title: Flask Mail sending plain text only
type: Question
has comment: http://stackoverflow.com/comment/81851074
has comment: http://stackoverflow.com/comment/81848633
has comment: http://stackoverflow.com/comment/81848020
accepted answer: http://stackoverflow.com/a/47447988
has comment: http://stackoverflow.com/comment/81848037
has comment: http://stackoverflow.com/comment/81849284
tagged with: python
tagged with: flask
tagged with: flask-mail
has comment: http://stackoverflow.com/comment/81847959
type: AnsweredQuestion
score: 0
has body: I am sending emails with flask-mail but the email is received like a plain text, excluding the html formats and images. I can't figure out what's wrong with the code. Here is the send mail method: def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): app = current_app._get_current_object() msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject, sender=app.config['MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr This is the view function that sends the email: @main.route('/confirm', methods=['GET', 'POST']) def confirm(): send_email(current_user.email, 'Confirm Your Account', 'auth/email/confirm', user=current_user) And here is the HTML: Confirm Your Account Dear {{ user.first_name }} Thanks for signing up. Everything seems to work fine, no problem with sending the emails, the only issues that the email is received as a plain text excluding the images. Also something to note is that the {{ user.first_name }} is rendered correctly for the current user's first name. UPDATE: I am running the app on my localhost server on my computer. **ANOTHER UPDATE** Here is the new email payload, in my email reader. Received: from VE1EUR02HT153.eop-EUR02.prod.protection.outlook.com (2603:10a6:200:42::34) by AM3PR04MB0631.eurprd04.prod.outlook.com with HTTPS via AM4PR0701CA0024.EURPRD07.PROD.OUTLOOK.COM; Wed, 22 Nov 2017 08:21:43 +0000 Received: from VE1EUR02FT048.eop-EUR02.prod.protection.outlook.com (10.152.12.59) by VE1EUR02HT153.eop-EUR02.prod.protection.outlook.com (10.152.13.169) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P384) id 15.20.218.12; Wed, 22 Nov 2017 08:21:42 +0000 Authentication-Results: spf=pass (sender IP is 104.47.40.68) smtp.mailfrom=culturevulturez.net; live.com; dkim=pass…
has comment: http://stackoverflow.com/comment/81848220
has comment: http://stackoverflow.com/comment/81849367
has answer: http://stackoverflow.com/a/47447988
answer count: 1

http://stackoverflow.com/comment/81969065
has text: what dbapi are you using
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47506667
type: Comment

http://stackoverflow.com/q/47384581
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81722330
linked to: http://stackoverflow.com/q/3973685
has answer: http://stackoverflow.com/a/47384608
has title: Exponential powers with range
type: Question
tagged with: exponent
duplicate of: http://stackoverflow.com/q/3973685
has comment: http://stackoverflow.com/comment/81722401
answer count: 2
score: 5
upvote count: 5
possible better answer: http://stackoverflow.com/a/47384614
has body: I'm having a problem with my code def bconver(n,b): for i in range(n): x = b ** i I am trying to have b to the power of all the i values from the range of n. I need to be able to take those values and divide them by n allowing me to change it to any base. I have tried this code but it doesn't work since I can't divide those values after. Also, I need the answers not in a list x = [b ** i for i in range(n)]
has answer: http://stackoverflow.com/a/47384614
tagged with: range
tagged with: python
accepted answer: http://stackoverflow.com/a/47384608
favorite count: 0

http://stackoverflow.com/comment/81817671
has text: write your own function to split data first
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47431539
type: Comment

http://stackoverflow.com/a/47448211
has body: There are multiple locator you can use any of these as per your html u can use Using xpath //span[@class="a-size-small-a-color-secondary"] or //span[contains(text(),"Fantasy Flight Games")] For getting text you can use .text method use like this Fantas_text=driver.find_element_by_xpath("//span[@class="a-size-small-a-color-secondary"]").text print(Fantas_text)
accepted answer of: http://stackoverflow.com/q/47447178
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47447178

http://stackoverflow.com/comment/81760275
comment on: http://stackoverflow.com/q/47403273
score: 0
has text: You’ll probably eventually want to do this with [`zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest)
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47483437
upvote count: 3
answer count: 1
tagged with: tensorflow-serving
tagged with: tensorflow
favorite count: 0
type: Question
has title: Can I build a TensorFlow servable in Python
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/47691328
has body: I'm new to Google TensorFlow Serving. I'm trying to see if I have a model which is written in Python. Can I make it a "servable" for TensorFlow Serving to run? I searched on Internet but I only could find instructions about the TensorFlow Serving client. Any hint? Thanks!

http://stackoverflow.com/a/47531946
has body: The file containing the pickled data must be written and read as a binary file. See the documentation for examples. Your extraction function should look like: def extract_skills(path): with open(path, 'rb') as inputFile: skills = pickle.load(inputFile) Of course, you will need to dump your data into a file open as binary as well: def save_skills(path, skills): with open(path, 'wb') as outputFile: pickle.dump(outputFile, skills) Additionally, the logic of your main seems a bit flawed. While the code that follows if __name__ == '__main__' is only executed when the script is run as main module, the code that is not in the main should only be static, ie definitions. Basically, your script should not do anything, unless run as main. Here is a cleaner version. import pickle def extract_skills(path): ... def save_skills(path, skills): ... if __name__ == '__main__': inputPath = "skills_input.pickle" outputPath = "skills_output.pickle" skills = extract_skills(inputPath) # Modify skills save_skills(outputPath, skills)
has comment: http://stackoverflow.com/comment/82022307
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/47531812
has comment: http://stackoverflow.com/comment/82021764
has comment: http://stackoverflow.com/comment/82021039
type: Answer
has comment: http://stackoverflow.com/comment/82035256
upvote count: 3

http://stackoverflow.com/q/47443293
linked to: http://stackoverflow.com/q/16856788
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: reshape
tagged with: python
score: 4
upvote count: 4
tagged with: numpy
has title: Numpy : reshape 2D array in array of matrix blocks
answer count: 0
duplicate of: http://stackoverflow.com/q/16856788
tagged with: arrays
downvote count: 0
favorite count: 0
has body: I would like to reshape an 2D numpy array in a 3D array consisting of 2x2 (or in general PxP) blocks, respecting the spatial positions. x = np.arange(100).reshape(10,10) x array([[ 0, 1, 2, ..., 7, 8, 9], [10, 11, 12, ..., 17, 18, 19], [20, 21, 22, ..., 27, 28, 29], ..., [70, 71, 72, ..., 77, 78, 79], [80, 81, 82, ..., 87, 88, 89], [90, 91, 92, ..., 97, 98, 99]]) y = some_reshape_and_transpose(x) y[0] array([[ 0, 1], [10, 11]]) y[1] array([[ 2, 3], [12, 13]]) y.shape (25, 2, 2) The precise order of the blocks along the first dimension of the 3D tensor is not important. The reverse command would be appreciated as well !
type: Question

http://stackoverflow.com/a/47460302
accepted answer of: http://stackoverflow.com/q/47460214
has body: The problem seems to be that you prefix an absolute path with copy{c}. Use a suffix instead: os.rename(fullfilename, f'{fullfilename}-copy{c}') Also, you need to rename the existing file before downloading. After downloading is too late, the original file is already gone. So move the if statement before the download step. Finally, a drawback of using a simple suffix is that it goes after the filename extension .bmp. A simple remedy could be to use f'{fullfilename}-copy{c}.bmp' as the new name, with the drawback that there will be .bmp` twice. If that's an issue for you, then you can do better with a bit more work, splitting the base name and the extension, and using the base name to format the new name in the desired format.
score: 2
has comment: http://stackoverflow.com/comment/81875247
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47460214
type: Answer

http://stackoverflow.com/a/47495579
answers question: http://stackoverflow.com/q/47495510
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47495510
score: 3
has body: Here's one approach leveraging the sorted nature of input data, making use of the very efficient NumPy array-slicing and other NumPy functions - def start_stop_arr(initial_list): a = np.asarray(initial_list) mask = np.concatenate(([True], a[1:] != a[:-1], [True])) idx = np.flatnonzero(mask) l = np.diff(idx) start = np.repeat(idx[:-1], l) stop = np.repeat(idx[1:]-1, l) return start, stop Further performance boost is possible with concatenated repetitions - def start_stop_arr_concat_repeat(initial_list): a = np.asarray(initial_list) mask = np.concatenate(([True], a[1:] != a[:-1], [True])) idx = np.flatnonzero(mask) l = np.diff(idx) idx2 = np.concatenate((idx[:-1,None], (idx[1:,None]-1)),axis=1) ss = np.repeat(idx2, l, axis=0) return ss[:,0], ss[:,1] Sample run - In [38]: initial_list Out[38]: array([0, 0, 0, 1, 1, 2, 3, 3, 3]) In [39]: start_stop_arr(initial_list) Out[39]: (array([0, 0, 0, 3, 3, 5, 6, 6, 6]), array([2, 2, 2, 4, 4, 5, 8, 8, 8])) Runtime test - Other approach(es) - # @Mohammed Elmahgiubi's soln def reversed_app(initial_list): # input expected is a list reversed_initial_list = list(reversed(initial_list)) first = [initial_list.index(i) for i in initial_list] last = list(reversed([(len(initial_list) - (reversed_initial_list.index(i) + 1)) for i in reversed_initial_list])) return first, last def unique_app(a): # @B. M.'s soln _,ind1,inv1,cou1 = np.unique(a, return_index=True, return_inverse=True, return_counts=True) return ind1[inv1],(ind1+cou1-1)[inv1] Timings - Case #1 : Smaller dataset In [295]: initial_list = np.random.randint(0,1000,(10000)) ...: initial_list.sort() In [296]: input_list = initial_list.tolist() In [297]: %timeit reversed_app(input_list) 1 loop, best of 3: 789 ms per loop In [298]: %timeit unique_app(initial_list) 1000 loops, best of 3: 353 µs per loop In [299]: %timeit start_stop_arr(initial_list) 10000 loops, best of 3: 96.3 µs per loop Case #2 : Bigger dataset In [438]: initial_list = np.random.randint(0,100000,(1000000)) ...: initia…
type: Answer
upvote count: 3

http://stackoverflow.com/q/47526056
has title: Fast way to fill matrix from np.array of row index, column index, and max(values)
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47526176
linked to: http://stackoverflow.com/q/47525773
favorite count: 0
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82010109
has body: I have quite large arrays to fill matrix (about 5e6 elements). I know the fast way to fill is something like (simplified example) bbb = (np.array([1,2,3,4,1])) # row ccc = (np.array([0,1,2,1,0])) # column ddd = (np.array([55.5,22.2,33.3,44.4,11.1])) # values experiment = np.zeros(shape=(5,3)) experiment[bbb, ccc] = [ddd] # filling &gt;[[ 0. 0. 0. ] [ 11.1 0. 0. ] [ 0. 22.2 0. ] [ 0. 0. 33.3] [ 0. 44.4 0. ]] but if I want the max ddd instead. Something like at # filling #pseudocode experiment[bbb, ccc] = [ddd if ddd &gt; experiment[bbb, ccc]] The matrix should return &gt;[[ 0. 0. 0. ] [ 55.5 0. 0. ] [ 0. 22.2 0. ] [ 0. 0. 33.3] [ 0. 44.4 0. ]] What is a good fast way to get max to fill the matrix from np.array here?
type: AnsweredQuestion
tagged with: python-2.7
tagged with: matrix
score: 1
accepted answer: http://stackoverflow.com/a/47526176

http://stackoverflow.com/a/47540675
score: 20
answers question: http://stackoverflow.com/q/47540412
upvote count: 21
has comment: http://stackoverflow.com/comment/119686245
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/82060331
has comment: http://stackoverflow.com/comment/96056342
has comment: http://stackoverflow.com/comment/82066506
has body: rowcount refers to the number of rows affected by the last operation. So, if you do an insert and insert only one row, then it will return 1. If you update 200 rows, then it will return 200. On the other hand, if you SELECT, the last operation doesn't really affect rows, it is a result set. In that case, 0 would be syntactically incorrect, so the interface returns -1 instead. It will also return -1 for operations where you do things like set variables or use create/alter commands.
type: Answer
has comment: http://stackoverflow.com/comment/132966932
has comment: http://stackoverflow.com/comment/96056296
accepted answer of: http://stackoverflow.com/q/47540412

http://stackoverflow.com/comment/81843663
comment on: http://stackoverflow.com/q/47444179
score: 0
has text: What is the error are you're getting?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/67051608
type: Answer
answers question: http://stackoverflow.com/q/47533787
has comment: http://stackoverflow.com/comment/136769734
has body: Starting with PEP 585 it is possible to use builtin typings without importing the typing module, so starting with Python 3.9, Tuple[...] has been deprecated in favor of tuple[...]. e.g. def func(var: tuple[int, ...]): pass
score: 70
upvote count: 70
downvote count: 0
has comment: http://stackoverflow.com/comment/136796939

http://stackoverflow.com/comment/81810574
type: Comment
type: QuestionComment
score: 0
has text: @Shadow edited the code
comment on: http://stackoverflow.com/q/47426938

http://stackoverflow.com/q/47446703
score: 0
has comment: http://stackoverflow.com/comment/81848762
answer count: 1
has body: I've just started using Python to scrape the data. But my code as below freezes during work and I guess that's because some url did not response anything; I guess it would work if I just try that url again. My question here is, if I just revise the code like, reshomee = requests.get(homeUrl, headers=headerss, timeout=10) then does this code try that url again after 10 seconds with no response? I am just worried if it would be just over without trying again...? I couldn't help asking this because I have no idea how to try this code since url freezes very rare and randomly. Thank you! def reshome(tries=0): try: reshomee = requests.get(homeUrl, headers=headerss) return reshomee except Exception as e: print(e) if tries &lt; 10: print('try:' + str(tries)) sleep(tries*30+100) return reshome(tries+1) else: print('cannot make it')
has comment: http://stackoverflow.com/comment/81849013
type: Question
accepted answer: http://stackoverflow.com/a/47447585
has title: After timeout keep trying request
has answer: http://stackoverflow.com/a/47447585
has comment: http://stackoverflow.com/comment/81849087
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83494854
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47475083
has text: Good to know how to do it, would be even better with a link to a jupyter notebook where it's already done.

http://stackoverflow.com/q/47412815
has title: python neo4j not getting other relationships
tagged with: neo4j
has body: I am using neo4j library in python and writing cypher queries there itself. Here is a piece of my code : from neo4j.v1 import GraphDatabase, basic_auth from config import bolt_url,auth_id,auth_pass driver = GraphDatabase.driver(bolt_url, auth=basic_auth(auth_id, auth_pass)) session = driver.session() def get_some_data(limit=25) : query = 'MATCH (n)-[r]-(m) \ RETURN n,r,m LIMIT ' + str(limit) return session.run(query) result_some_data = get_some_data(limit=4) gen = result_some_data.records() for record in gen : n = record['n'] m = record['m'] r = record['r'] print() print(n) print(m) print(r) And this is what I get : &lt;Node id=68757 labels={'ContentItem'} properties={'id': '1'}&gt; &lt;Node id=72389 labels={'Person'} properties={'name': 'Tony'}&gt; &lt;Relationship id=288942 start=72389 end=68757 type='Inside' properties={}&gt; &lt;Node id=68757 labels={'ContentItem'} properties={'id': '1'}&gt; &lt;Node id=72390 labels={'Person'} properties={'name': 'Bruce'}&gt; &lt;Relationship id=288943 start=72390 end=68757 type='Inside' properties={}&gt; &lt;Node id=68757 labels={'ContentItem'} properties={'id': '1'}&gt; &lt;Node id=79758 labels={'Organization'}l properties={'name':'Oscorp'}&gt; &lt;Relationship id=278985 start=79758 end=68757 type='Inside' properties={}&gt; &lt;Node id=68758 labels={'ContentItem'} properties={'id': '2'}&gt; &lt;Node id=79759 labels={'Organization'} properties={'name': 'STAR Labs'}&gt; &lt;Relationship id=278986 start=79759 end=68758 type='Inside' properties={}&gt; PS : ignore the name properties, I have changed them. When I run the same cypher query on neo4j browser, I get this graph: In the image, you can see that there are 4 other relationships that are we don't get in python, namely the 2 linkedWith and the 2 RelatedTo relationships are missing. Now, I know that the neo4j is matching the requested relations and return them only, but coming to my question (Finally!), is there a way to get these 'other' 4 relationships as well?
has comment: http://stackoverflow.com/comment/81779856
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47413636
has comment: http://stackoverflow.com/comment/81780216
tagged with: cypher
tagged with: python
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81780013
has answer: http://stackoverflow.com/a/47413636
answer count: 1

http://stackoverflow.com/comment/81917131
has text: @sascha great...it works, thank you!
score: 0
comment on: http://stackoverflow.com/q/47480836
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47458470
answer count: 0
linked to: http://stackoverflow.com/q/4930524
type: UnansweredQuestion
type: Question
has title: Python freezes when trying to plot radar graph
has comment: http://stackoverflow.com/comment/81922397
has comment: http://stackoverflow.com/comment/82303248
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/82303663
has comment: http://stackoverflow.com/comment/81876083
has comment: http://stackoverflow.com/comment/81921362
score: 0
has body: I am using the code suggested by mrbump to create a radar graph (https://datascience.stackexchange.com/a/16420). The code is as follows: import numpy as np import matplotlib.pyplot as plt import seaborn as sns # improves plot aesthetics def _invert(x, limits): """inverts a value x on a scale from limits[0] to limits[1]""" return limits[1] - (x - limits[0]) def _scale_data(data, ranges): """scales data[1:] to ranges[0], inverts if the scale is reversed""" # for d, (y1, y2) in zip(data[1:], ranges[1:]): for d, (y1, y2) in zip(data, ranges): assert (y1 &lt;= d &lt;= y2) or (y2 &lt;= d &lt;= y1) x1, x2 = ranges[0] d = data[0] if x1 &gt; x2: d = _invert(d, (x1, x2)) x1, x2 = x2, x1 sdata = [d] for d, (y1, y2) in zip(data[1:], ranges[1:]): if y1 &gt; y2: d = _invert(d, (y1, y2)) y1, y2 = y2, y1 sdata.append((d-y1) / (y2-y1) * (x2 - x1) + x1) return sdata def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs): """ Set the radial locations and labels of the *r* grids. The labels will appear at radial distances *radii* at the given *angle* in degrees. *labels*, if not None, is a ``len(radii)`` list of strings of the labels to use at each radius. If *labels* is None, the built-in formatter will be used. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data radii = self.convert_xunits(radii) radii = np.asarray(radii) rmin = radii.min() # if rmin &lt;= 0: # raise ValueError('radial grids must be strictly positive') self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) elif fmt is not None: self.yaxis.set_major_formatter(FormatStrFormatter(fmt)) if angle is None: angle = self.get_rlabel_position() self.set_rlabel_position(angle) for t in self.yaxis.get_ticklabels(): t.update(kwargs) ret…

http://stackoverflow.com/comment/82004608
score: 1
type: Comment
has text: You could use `df.apply` instead.
type: AnswerComment
comment on: http://stackoverflow.com/a/47524190

http://stackoverflow.com/comment/81761447
type: QuestionComment
comment on: http://stackoverflow.com/q/47403782
score: 1
has text: As a first step to solve the problem, you might check out python's built-in [json](http://docs.python.org/2/library/json.html) module for reading the data, and [csv](http://docs.python.org/2/library/csv.html) module for writing the result to a `csv` file.
type: Comment

http://stackoverflow.com/comment/82037494
comment on: http://stackoverflow.com/a/47540197
type: AnswerComment
score: 0
has text: Haha, this is totally it. When I worked on this example I made that fix with out thinking about it. Only now, after reading your solution do I remember doing that lol!! ITS USUALLY the simple things.
type: Comment

http://stackoverflow.com/q/47429267
favorite count: 0
tagged with: numpy
type: Question
downvote count: 0
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/81815109
has body: I'm trying to train a basic feedforward neural network on a dataset of about 80 entries (mostly as a proof of concept, I'm aware my dataset is way too small). I based my code off of the MNIST dataset example. I've selected a batch size of 10 and am running it with 8 steps: learning_rate = 0.01 num_steps = 8 batch_size = 10 display_step = 1 num_input = 16 n_hidden_1 = 8 n_hidden_2 = 8 num_classes = 1 X = tf.placeholder("float", [None, num_input]) Y = tf.placeholder("float", [None, num_classes]) weights = { 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([num_classes])) } layer_1 = tf.add(tf.matmul(X, weights['h1']), biases['b1']) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) logits = tf.matmul(layer_2, weights['out']) + biases['out'] prediction = tf.nn.softmax(logits) loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op) correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for step in range(0, num_steps): batch_x, batch_y = manager.import_data() batch_x = batch_x[step * batch_size:(step + 1) * batch_size] batch_y = batch_y[step * batch_size:(step + 1) * batch_size] batch_x = np.reshape(batch_x, (batch_size, num_input)) batch_y = np.reshape(batch_y, (batch_size, num_classes)) sess.run(train_op, feed_dict={X: batch_x, Y: batch_y}) if step % display_step == 0 or step == 1: loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y}) print("Step " + str(st…
accepted answer: http://stackoverflow.com/a/47429940
has title: Why is this neural network's loss always 0.0 and accuracy always 1.0?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47429940
score: 1
tagged with: tensorflow

http://stackoverflow.com/q/47501275
accepted answer: http://stackoverflow.com/a/55925583
has body: My main function loads a largish dataframe from a csv supplied by the user (along with several other data objects), and then instantiates an object that forms a bunch of equations as part of a mathematical programming problem. Many of the equations' components are returned by calls to about 5 helper functions that I define in a utils file (most importantly, outside of the class that stores the optimization problem). These helper functions make reference to the data loaded in main, but I want their calls to show up in the equations as parameterized only by a time index t (not by the dataframe), for readability. Is the best way to accomplish this to define those functions in utils.py with the data as explicit parameters, and then use functools.partial before generating the equations to make them implicit? This seems like a verbose approach to me, but the other options seem worse: to define the helper functions inside of main, or to give up on the idea of a main function loading the data, which basically means giving up on having a main function. And possibly having confusing circular imports.
has answer: http://stackoverflow.com/a/55925583
has comment: http://stackoverflow.com/comment/81958329
has comment: http://stackoverflow.com/comment/81958304
type: Question
has title: Best way to make data loaded in main() an implicit argument of a function in Python
tagged with: functools
score: 0
tagged with: program-entry-point
answer count: 1
tagged with: python
type: AnsweredQuestion

libtorrent
tags question: http://stackoverflow.com/q/47428752
tags question: http://stackoverflow.com/q/47506800
type: Tag
tag name: libtorrent

http://stackoverflow.com/comment/81746205
type: QuestionComment
has text: you can use `pack_forget()` to remove element and `pack()` to add new one. You could use `Frame` to group widgets (Buttons) and then you can replace one frame with another.
type: Comment
comment on: http://stackoverflow.com/q/47394455
score: 0

http://stackoverflow.com/comment/81917189
comment on: http://stackoverflow.com/q/47481142
has text: Well whether the reason is "good" or not is a matter of opinion, but one might say the reason is "pragmatic" because dictionaries are more commonly used than sets. :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47462613
type: Answer
has body: Display['text'] = Display['text'] + ToDoAdd or: Display.config(text=Display.cget('text') + ToDoAdd)
score: 1
answers question: http://stackoverflow.com/q/47462282
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47462282

http://stackoverflow.com/comment/81960305
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47493345
has text: @Mohnish that is repeat the number by group length . When you print out grouped you will see that is list of list then we repeat the range value by the length of sub list will give back your group number

syntax
tags question: http://stackoverflow.com/q/47523823
type: Tag
tags question: http://stackoverflow.com/q/47393026
tag name: syntax

http://stackoverflow.com/a/47475641
type: Answer
answers question: http://stackoverflow.com/q/47475585
score: 0
accepted answer of: http://stackoverflow.com/q/47475585
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81917464
has body: You could do something like this: sum = 0 for count in range(1, 10): try: sum += int(input("Write an integer: ")) except ValueError: print("Your entry is not an integer.") print("The summation has ended.") break print("The sum of your numbers is: " + str(sum))

http://stackoverflow.com/comment/81968878
score: 2
comment on: http://stackoverflow.com/q/47496415
type: Comment
type: QuestionComment
has text: @timgeb: that duplicate was correct, I've re-closed it. I've added another post in the mix however. No, in this case `globals()` would not be helpful, but the advice to build a dictionary to hold a namespace *is*.

http://stackoverflow.com/q/47471177
score: 1
tagged with: calibration
has body: I am reading calibration methods for two days but did not actually make it that how it works. Two types of calibration are there; Platt scaling - prediction space parted into bins &amp; for each bin mean predicted value is plotted against true fraction of positive cases Isotonic regression - Mathematically it tries to fit a weighted least-squares via Quadratic Programming, subject to next observation is always non-decreasing with respect to previous observation. I have written a python module on calibration based on logistic regression (though I know LogisticRegression returns well calibrated predictions by default as it directly optimizes log-loss, I built it to check my understanding) import numpy as np import pandas as pd from sklearn import linear_model from sklearn.calibration import CalibratedClassifierCV from sklearn.model_selection import train_test_split from sklearn.metrics import log_loss from pandas import DataFrame class logistic_Calibration: def __init__(self, data, response): self.data = data self.response = response def Calibration(self): Xtrain, Xtest, ytrain, ytest = train_test_split(self.data, self.response, test_size=0.20, random_state=36) logreg = linear_model.LogisticRegression() logreg.fit(Xtrain, np.array(ytrain).flatten()) PredWO_calibration = logreg.predict_proba(Xtest) lossWO_calibration = log_loss(ytest, PredWO_calibration) clf_sigmoid = CalibratedClassifierCV(logreg, cv=5, method='sigmoid') clf_sigmoid.fit(Xtrain, np.array(ytrain).flatten()) PredWITH_calibration = clf_sigmoid.predict_proba(Xtest) lossWITH_calibration = log_loss(ytest, PredWITH_calibration) Loss_difference_WO_minus_W = lossWO_calibration - lossWITH_calibration return [lossWO_calibration, lossWITH_calibration, Loss_difference_WO_minus_W] But still I am unclear on the following parts, How isotonic regression maps the scores to probabilities? Platt scaling does not work for real time data as for that we do not have any class assigned, that means Brier score can not be calcul…
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: Probability calibration with predicted probability & actual outcome in python

http://stackoverflow.com/comment/82241065
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47398609
has text: @vasia I'm ready to do this project, I want to know how. Where should I start? I want to do exactly what I said earlier. I'm making my own graphics library to do things at the lowest level. I've improved my python and realized that python is a terrible language for this, but I'm willing to put up with the difficulty and try.

http://stackoverflow.com/comment/81809659
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47427603
score: 1
has text: The behavior you're relying on was never actually defined, and [they changed it in NumPy 1.13](https://docs.scipy.org/doc/numpy-1.13.0/release.html#ufunc-behavior-for-overlapping-inputs). Neither of your snippets will work in 1.13.

http://stackoverflow.com/a/47426825
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Here is code that does each of the data conversions you are looking for. These steps can all be combined, but are separated here so you can see each value. import hashlib import binascii binstr = '0110100001100101011011000110110001101111' hexstr = "{0:0&gt;4X}".format(int(binstr,2)) # '68656C6C6F' data = binascii.a2b_hex(hexstr) # 'hello' output = hashlib.sha256(data).hexdigest() print output OUTPUT: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
answers question: http://stackoverflow.com/q/47426198

http://stackoverflow.com/q/47448510
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/56654583
has answer: http://stackoverflow.com/a/47448729
tagged with: django
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47448729
has comment: http://stackoverflow.com/comment/81852258
has comment: http://stackoverflow.com/comment/81852215
has answer: http://stackoverflow.com/a/77382994
score: 10
has title: Change "Quit the server with CTRL-BREAK."
tagged with: python
has answer: http://stackoverflow.com/a/78560923
answer count: 4
has body: Is there a way in one of the Django scripts to change the CTRL+BREAK exit command to something else when using python manage.py runserver ?
accepted answer: http://stackoverflow.com/a/56654583
upvote count: 11

http://stackoverflow.com/comment/81875637
score: 1
has text: What about `range(min(x0,x1),max(x0,x1)+1)`? As far as I can see, the order does not matter.
type: Comment
comment on: http://stackoverflow.com/q/47459097
type: QuestionComment

http://stackoverflow.com/q/47470441
linked to: http://stackoverflow.com/q/49247477
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82701586
score: 0
linked to: http://stackoverflow.com/q/29109324
tagged with: pandas
has title: Cannot build Pandas from setup.py in Wine environment
answer count: 1
tagged with: wine
type: Question
tagged with: python-3.x
has body: I am attempting to cross-compile a Python script from my Linux platform to a Windows executable using Wine. I have successfully installed Python 3.6.0 for Windows 64 bit and pyinstaller, in addition to all of the Python dependencies for my program, inside of my Wine environment. Running wine py my_file.py runs my program correctly without raising any errors. However, when attempting to run the cross-compiled .exe built with pyinstaller the following error is raise: File "site-packages\pandas\__init__.py", line 35, in &lt;module&gt; ImportError: C extension: No module named 'pandas._libs.tslibs.timedeltas' not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first. [275] Failed to execute script parser I used git clone https://github.com/pandas-dev/pandas.git to download the Pandas source code into my Wine drive_c folder, then ran wine py setup.py build_ext --inplace --force and received the following error: fixme:ntdll:NtQueryInformationJobObject stub: 0x54 9 0x33eff0 112 0x33efec install requires: 'python-dateutil &lt; 2','numpy'. use pip or easy_install. $ pip install 'python-dateutil &lt; 2' 'numpy' fixme:msvcrt:__clean_type_info_names_internal (0x1e1f9bc8) stub fixme:ver:GetCurrentPackageId (0x33ef18 (nil)): stub However, running wine py -m pip freeze shows that I have the correct versions of these modules installed already: altgraph==0.14 beautifulsoup4==4.6.0 bs4==0.0.1 future==0.16.0 html5lib==0.999999999 lxml==4.1.1 macholib==1.8 numpy==1.13.3 pandas==0.21.0 pefile==2017.11.5 PyInstaller==3.3 pypiwin32==220 python-dateutil==1.5 pytz==2017.3 six==1.11.0 webencodings==0.5.1 I can also successfully import these modules from my Python interpreter: Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import dateutil &gt;&gt;&gt; print(…
has answer: http://stackoverflow.com/a/49332968
has comment: http://stackoverflow.com/comment/82803921

http://stackoverflow.com/q/47537055
possible better answer: http://stackoverflow.com/a/47537273
tagged with: python
has answer: http://stackoverflow.com/a/47537139
favorite count: 0
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/47537085
has answer: http://stackoverflow.com/a/47537085
upvote count: 2
downvote count: 0
has body: I have the following pandas dataframe: import pandas as pd df = pd.DataFrame({"pos": [1, 2, 3], "chain": ["A", "B", "C"]}) Giving: chain pos 0 A 1 1 B 2 2 C 3 and df.types: chain object pos int64 dtype: object I'm looking for a way to merge Series df["chain"] and df["pos"] to have the following: chain+pos 0 A1 1 B2 2 C3 and df.dtypes: chain+pos object dtype: object Is there an easy way to do it?
has answer: http://stackoverflow.com/a/47537273
type: AnsweredQuestion
has title: Merging values of two columns of dataframe with different dtypes
answer count: 3
tagged with: pandas

http://stackoverflow.com/q/47413535
has comment: http://stackoverflow.com/comment/81781016
type: Question
has body: df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) dfs = [] for index in range(len(df)): subtracted = df - df.loc[index] dfs.append(subtracted) Is there a way to do this with apply perhaps? Doing it like above gets pretty slow for large dataframes...
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47413938
type: AnsweredQuestion
tagged with: pandas
has title: How to efficiently subtract each row from pandas dataframe?
score: 1
answer count: 1
tagged with: dataframe
favorite count: 0
accepted answer: http://stackoverflow.com/a/47413938

http://stackoverflow.com/a/47430103
score: 0
answers question: http://stackoverflow.com/q/47428864
type: Answer
has body: In python, you need to use simpleHTTP. You can connect to that python based webserver and run your command.

http://stackoverflow.com/a/47563345
has body: This is the method I just found out, I cycle through the entire product catalog (I think it could work with other resources too), then through each metafield until I find the metafield I want. Then I call metafield.destroy(). Like this: for product in products: for metafield in product.metafields(): if metafield.namespace == "global": metafield.destroy() Originally I was working to do product.delete(metafield) but I kept getting a 406 error that I'm not sure how to resolve yet. Note that I am fine destroying my metafields this way because each metafield I use (to this point) is a unique product identifier, and not shared by any other resource and so destroying the entire metafield would have no negative consequences. I am not aware if this method destroys the metafield entirely, but would test the following case before using on shared metafields: Assume product A has metafield X Assume product B has metafield X destroy metafield X from product A does product B still have metafield X? Perhaps you can adapt this solution to something that works for your needs. EDIT: Shopify's python online documentation is horrid. I used dir() and help() to find all of this.
has comment: http://stackoverflow.com/comment/82085846
type: Answer
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47521580
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47521580

http://stackoverflow.com/a/47461979
has body: A quick demonstration of how could you go about it. You make an index keeping track how many did you already processed: years= [2004, 2005, 2006, 2007, 2008, 2009, 2010] data= [1,2,3,4,5,6,7] fifths=0 for i in range(len(years)//5+1): print(years[fifths], sum(data[fifths:fifths+5])) fifths+=5 You will get as output: 2004 15 2009 13
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47461781
downvote count: 0
type: Answer

http://stackoverflow.com/q/47530959
favorite count: 0
type: Question
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/47531366
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has body: I am trying to convert an byte array to PNG image and save it to a specific folder. The byte array comes from a C# server, python client will receive it and save as PNG image. I tried the following way: reply = s.recv(4096) image = Image.open(io.BytesIO(reply)) image.save("img1.png","PNG") It gives following error: Traceback (most recent call last): File "C:\Users\imran.s\Desktop\UnityClient.py", line 46, in &lt;module&gt; image.save("img1.png","PNG") File "C:\python64\lib\site-packages\PIL\Image.py", line 1895, in save self.load() File "C:\python64\lib\site-packages\PIL\ImageFile.py", line 233, in load "(%d bytes not processed)" % len(b)) OSError: image file is truncated (3 bytes not processed)
upvote count: 2
score: 1
tagged with: python-sockets
answer count: 1
has title: How can I convert an byte array to PNG image and save it to a specific folder?
downvote count: 1

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/47400003

http://stackoverflow.com/q/47395573
answer count: 1
has title: Iterate over bytes with findall
has answer: http://stackoverflow.com/a/47395825
accepted answer: http://stackoverflow.com/a/47395825
type: Question
tagged with: python-3.x
tagged with: python
has body: I'm trying to work with a settings file that is a binary file to find out how it's stuctured so that I might get some information about file location etc. from it. As far as I can tell, the interesting data is either exactly after or near escape chars b'\x03\SETTING' - here's an example with a setting I'm interested in 'LQ'.. \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 \x03HTAPp\x00\x00\x00\x02\x02\x00\x00\x01\x02L\x02\x00\x00\x00\x01 \x03LQ\x00\x00\x00\\\\Media\\Render_Drive\\mediafiles\\mxf\\k70255.2\\a08.56d829a7_56d82956d829a0.mxf \x03HTAPp\\x00\x00\x00\x02\x02\x00\x00\x01\x02L\x02\x00\x00\x00\x01 \x03LQ\x00\x00\x00\\\\Media\\Render_Drive\\mediafiles\\mxf\\k70255.2\\a07.56d829a6_56d82956d829a0.mxf so it looks like each 'sentence' starts with \x03 - &amp; the path I'm looking for here is on the 8th byte after the LQ setting '\x03LQ' The file also has other settings that I want to capture - and each time it looks like the setting is directly after an escape char and padded by a short desciption of the setting and a number of bytes. ATM I am reading the binary and can find a specific path (only, if I know how long it is right now) with open(file, "rb") as abin: abin.seek(0) data = abin.read() foo = re.search(b'\x03LQ', data) abin.seek(foo.start() + 8) # cursor lands on 8th byte eg = abin.read(32) # so I get the path of some length as eg..... This is not what I want, as I want to read the entire bytestring until the next escape char, and then find the next setting that occurs and read the path. I'm experimenting with findall(), but it just returns a list of bytes objects that are the same (it seems), and I don't understand how to search for each unique path &amp; the instance of each byte string and read from some cursor position in the data. Eg. bar = re.findall(b'\x03LQ', data) for bs in bar: foo = re.search(bs, data) abin.seek(foo.start() + 8) eg = abin.read(64) print('This is just the same path each time', eg) Pointers anyone?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47441022
tagged with: python
has body: I'm working with the Mnist data set, in order to learn about Machine learning, and as for now I'm trying to display the first digit in the Mnist data set as an image, and I have encountered a problem. I have a matrix with the dimensions 784x10000, where each column is a digit in the data set. I have created the matrix myself, because the Mnist data set came in the form of a text file, which in itself caused me quite a lot of problems, but that's a question for itself. The MN_train matrix below, is my large 784x10000 matrix. So what I'm trying to do below, is to fill up a 28x28 matrix, in order to display my image. import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg grey = np.zeros(shape=(28,28)) k = 0 for l in range(28): for p in range(28): grey[p,l]=MN_train[k,0] k = k + 1 print grey plt.show(grey) But when I try to display the image, I get the following error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Followed by a image plot that does not look like the number five, as I would expect. Is there something I have overlooked, or does this tell me that my manipulation of the text file, in order to construct the MN_train matrix, has resulted in an error?
score: 0
tagged with: mnist
tagged with: matplotlib
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47441158
type: UnansweredQuestion
has title: Image of Mnist data Python - Error when displaying the image

http://stackoverflow.com/comment/81887919
score: 0
type: Comment
type: QuestionComment
has text: Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve).
comment on: http://stackoverflow.com/q/47466671

http://stackoverflow.com/comment/81795943
score: 0
comment on: http://stackoverflow.com/q/47419174
type: Comment
type: QuestionComment
has text: As a general rule you can't do this with structured arrays. The elements of the array are defined by the compound dtype. If `minus` isn't defined for that compound dtype you can't subtract one such array from the other.

http://stackoverflow.com/q/47508048
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81972479
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I am trying to save a json response from web to csv file, the problem is that there are deeper levels and the key value pairs are to be separated and just the values need to be stored. code: import csv import json infile=open('oobar.json', "rb") json_s=infile.read() outfile=open("watsf.csv","wb") writer=csv.writer(outfile) count = 0 for data in(json.loads(json_s)): categories = data['document_tone'] for category in categories['tone_categories']: for tone in category['tones']: if count != 5: header = ([tone.values()[0]]) writer.writerow(header) count += 1 writer.writerow([tone.values()[1]]) infile.close() outfile.close() Expected Output Actual output: Json response to parse and extract the above values { "document_tone": { "tone_categories": [ { "category_id": "emotion_tone", "tones": [ { "tone_name": "Anger", "score": 0.077068, "tone_id": "anger" }, { "tone_name": "Disgust", "score": 0.01956, "tone_id": "disgust" }, { "tone_name": "Fear", "score": 0.043762, "tone_id": "fear" }, { "tone_name": "Joy", "score": 0.764404, "tone_id": "joy" }, { "tone_name": "Sadness", "score": 0.084368, "tone_id": "sadness" } ], "category_name": "Emotion Tone" } ] } I am trying to save a json response from web to csv file, the problem is that there are deeper levels and the key value pairs are to be separated and just the values need to be stored.
has answer: http://stackoverflow.com/a/47512845
tagged with: parsing
has comment: http://stackoverflow.com/comment/81972072
type: Question
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/81971921
accepted answer: http://stackoverflow.com/a/47512845
favorite count: 0
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81971843
has title: writing values as headers
downvote count: 0

http://stackoverflow.com/comment/81766675
score: 0
type: Comment
type: QuestionComment
has text: Your code has a serious bug. You define `c=m-1`, which prevents your code from finding the inverse of *m - 1* (mod *m*). Instead of throwing an error (like with `assert inverse > 0`), it will just use `inverse = 0` while attempting to decrypt each character.
comment on: http://stackoverflow.com/q/47406065

http://stackoverflow.com/comment/81848661
has text: If you initialize the variables inside a function, they won't be accessible outside of the function. Try initializing the ones you use elsewhere outside and before the definition of `importAccessDB`. Edit: just saw you tried putting them outside already.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47446530

http://stackoverflow.com/comment/82262107
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47651964
has text: ok, you are right, I was checking the method at the of loading the page and that's why it was giving me "GET". thanks @prakash09

http://stackoverflow.com/comment/128695512
comment on: http://stackoverflow.com/q/47496415
has text: Note for future closers: https://stackoverflow.com/questions/1373164/ is still the appropriate target in cases where OP *has already*, e.g., created multiple related variable names algorithmically rather than using a list and then wants to access them. However, sometimes the generation is done by e.g. a GUI form designer and is out of OP's control. In these cases, try to find something more specific.
type: Comment
type: QuestionComment
score: 0

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/47411492
tags question: http://stackoverflow.com/q/47393060
tags question: http://stackoverflow.com/q/47428508
tags question: http://stackoverflow.com/q/47448327
tags question: http://stackoverflow.com/q/47508874
tags question: http://stackoverflow.com/q/47464939
tags question: http://stackoverflow.com/q/47517230
tags question: http://stackoverflow.com/q/47431117
tags question: http://stackoverflow.com/q/47400357
tags question: http://stackoverflow.com/q/47425872
tags question: http://stackoverflow.com/q/47385781
tags question: http://stackoverflow.com/q/47502648
tags question: http://stackoverflow.com/q/47420403
tags question: http://stackoverflow.com/q/47465111
tags question: http://stackoverflow.com/q/47464067
tags question: http://stackoverflow.com/q/47490834
tags question: http://stackoverflow.com/q/47500817
tags question: http://stackoverflow.com/q/47464272
tags question: http://stackoverflow.com/q/47485216
tags question: http://stackoverflow.com/q/47527330
tags question: http://stackoverflow.com/q/47488774
tags question: http://stackoverflow.com/q/47472833
tags question: http://stackoverflow.com/q/47414819
tags question: http://stackoverflow.com/q/47498332
tags question: http://stackoverflow.com/q/47477043
tags question: http://stackoverflow.com/q/47460201
tags question: http://stackoverflow.com/q/47432870
tags question: http://stackoverflow.com/q/47404605
tags question: http://stackoverflow.com/q/47397872
tags question: http://stackoverflow.com/q/47432168
tags question: http://stackoverflow.com/q/47468627
tags question: http://stackoverflow.com/q/47413540
tags question: http://stackoverflow.com/q/47421731
tags question: http://stackoverflow.com/q/47417897
tags question: http://stackoverflow.com/q/47389516
tags question: http://stackoverflow.com/q/47436949
tags question: http://stackoverflow.com/q/47431661
tags question: http://stackoverflow.com/q/47433920
tags question: http://stackoverflow.com/q/47464999
tags question: http://stackoverflow.com/q/47486451
tags question: http://stackoverflow.com/q/47418871
tags question: http://stackoverflow.com/q/47410239
tags question: http://stackoverflow.com/q/47442102
tags question: http://stackoverflow.com/q/47538391
tags question: http://stackoverflow.com/q/47437398
tags question: http://stackoverflow.com/q/47470304
tag name: machine-learning
tags question: http://stackoverflow.com/q/47494698
tags question: http://stackoverflow.com/q/47494896
tags question: http://stackoverflow.com/q/47403336
tags question: http://stackoverflow.com/q/47458521
tags question: http://stackoverflow.com/q/47462962
tags question: http://stackoverflow.com/q/47423828
tags question: http://stackoverflow.com/q/47416982
tags question: http://stackoverflow.com/q/47530052
tags question: http://stackoverflow.com/q/47463987
tags question: http://stackoverflow.com/q/47399350
tags question: http://stackoverflow.com/q/47446407
tags question: http://stackoverflow.com/q/47520820
tags question: http://stackoverflow.com/q/47521872
tags question: http://stackoverflow.com/q/47480836
tags question: http://stackoverflow.com/q/47519104
tags question: http://stackoverflow.com/q/47490381
tags question: http://stackoverflow.com/q/47498748
tags question: http://stackoverflow.com/q/47387727
tags question: http://stackoverflow.com/q/47484481
tags question: http://stackoverflow.com/q/47462522
tags question: http://stackoverflow.com/q/47529887
tags question: http://stackoverflow.com/q/47511376
tags question: http://stackoverflow.com/q/47437582
tags question: http://stackoverflow.com/q/47475749
tags question: http://stackoverflow.com/q/47394462
tags question: http://stackoverflow.com/q/47463262
tags question: http://stackoverflow.com/q/47437893

http://stackoverflow.com/q/47534573
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: string
score: 0
tagged with: list
tagged with: twitter
tagged with: utf-8
has comment: http://stackoverflow.com/comment/82026244
has body: Im using the tweepy library to get a list of tweet texts, and I need to compare the words in 200 tweets with a list of stop words and remove the stop words in the tweet text list so I can say what are the words that appear most in the tweets searched. The thing is when I retrieve the tweet.texts I must encode it in order to get it so I get a list of b'word', which cannot be compared with my list of stop words that are regular strings. def get_tweetwords(): print("Ingrese el hashtag a buscar, no olvide escribir el numeral (#)(Ctrl+3)") hashtag=str(input()) while (hashtag[0])!="#": print("No olvide escribir el numeral. Vuelva a escribir el hashtag:") hashtag=str(input()) busqueda=tweepy.Cursor(api.search,q=hashtag).items(10) twlist=[] listadepalabras=[] for tweets in busqueda: twlist.append(tweets.text.encode('utf-8')) for i in twlist: x=i.split() for j in x: listadepalabras.append(j) return(listadepalabras) I need to decode the listadepalabras list into a string list in order to compare it with the stopwords list and remove its stopwords. def get_stopwords(): listastopwords=[item for item in open("stopwords.txt").readlines()] for item in listastopwords: if "\n" in listastopwords: listastopwords[listastopwords.index(item)]=item.replace("\n","") return(listastopwords) def sacar_stopwords(): listadepalabras=get_tweetwords() listastopwords=get_stopwords() for i in listadepalabras: for j in listastopwords: if i==j: listadepalabras.remove(j) return(listadepalabras) This is not working since my text list contains words with a b'word' format and my stopwords list is just 'word' def repeticiones_palabra(): listadepalabras=sacar_stopwords() diccionario=collections.Counter(listadepalabras) diccionario=dict(diccionario.most_common(10)) print ("-LAS 10 PALABRAS MAS UTILIZADAS SON-") print(diccionario) This should get me the 10 most used words in my list and it's working fine but I'm getting mostly stopwords and the hashtag I looked for so I can tell my stopwords are not getting r…
has title: Convert a list of 'utf-8' encoded strings into regular strings
has answer: http://stackoverflow.com/a/47534873

http://stackoverflow.com/comment/81984527
has text: Providing a full solution without any word of explanation isn't going to help the OP.
type: AnswerComment
comment on: http://stackoverflow.com/a/47514400
score: 0
type: Comment

http://stackoverflow.com/a/47439230
type: Answer
answers question: http://stackoverflow.com/q/47438949
score: 9
downvote count: 0
has body: Use rank with method='first' df.rank(1, ascending=False, method='first') 316 320 359 370 910 316 1.0 2.0 3.0 4.0 NaN 320 2.0 1.0 3.0 5.0 4.0 359 2.0 4.0 1.0 3.0 5.0 370 2.0 5.0 3.0 1.0 4.0 910 NaN 4.0 3.0 2.0 1.0
type: AcceptedAnswer
upvote count: 9
has comment: http://stackoverflow.com/comment/82021483
accepted answer of: http://stackoverflow.com/q/47438949

http://stackoverflow.com/q/47462735
tagged with: printing
answer count: 3
tagged with: while-loop
tagged with: validation
accepted answer: http://stackoverflow.com/a/47462914
has comment: http://stackoverflow.com/comment/81881433
has answer: http://stackoverflow.com/a/47462914
has body: I am having an issue with Python validation. I was wondering if there was a simple way to put validation on two input numbers to check a few things: If the inputs are ints if neither of the inputs equals a certain number, they are not valid. (For example, this would mean one of them would have to be 5. So a = 1 b = 4, a = 3 b = 2, a = 1 b = 1 wouldn't work) If the two numbers are the same number that is required it will not work (E.G. if a = 5 b = 5 will not work as 5 is the required number, however a = 1 b = 5 would work as 5 is only being inputted once). while True: a = input("Enter first input: ") b = input("Enter second input: ") try: val = int(a) val1 = int(a) if val1 != 5 or val != 5: print("I'm sorry but it must be a pos int and equal 5") continue break except ValueError: print("That's not an int") This is what I was trying to do, but I think I may be dreadfully wrong? Any help appreciated! Thanks.
favorite count: 0
has answer: http://stackoverflow.com/a/47463270
has comment: http://stackoverflow.com/comment/81880433
type: Question
possible better answer: http://stackoverflow.com/a/47462939
upvote count: 2
has comment: http://stackoverflow.com/comment/81880306
downvote count: 2
has answer: http://stackoverflow.com/a/47462939
has title: Python validation from if neither inputs equal a number
tagged with: python
linked to: http://stackoverflow.com/q/432842
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47492974
tagged with: numpy
has title: ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (1,)
has comment: http://stackoverflow.com/comment/81941197
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81941237
tagged with: python
score: 0
has body: I wrote a simple code to form taylor digram using skillmetrics package. I used python version Python 2.7.12.The code is as follows:- import matplotlib.pyplot as plt import pandas as pd import numpy as np import skill_metrics as sm fire=pd.read_csv('fire.csv') PMfire = zip(fire['Date'],fire['PM_fire'],fire['Embassy_PM']) #taylor_stats1 = sm.taylor_statistics('PM_fire','Embassy_PM','Date') o= {"Data":fire['Embassy_PM'],'Date':fire['Date']}# form date and and embassy datas p= {"Data":fire['PM_fire'],'Date':fire['Date']}# form dictionary containg pm_fire and date # Calculate statistics for Taylor diagram # The first array element corresponds to the reference series # for the while the second is that for the predicted series. taylor_stats1 = sm.taylor_statistics(p,o,'Data') sdev = np.array([taylor_stats1['sdev'][0]])# Calculate standard deviation crmsd = np.array([taylor_stats1['crmsd'][0]])#Calculate root mean square difference ccoef = np.array([taylor_stats1['ccoef'][0]])# Calculate correlation coefficient sm.taylor_diagram(sdev,crmsd,ccoef)#form taylor digram plt.savefig('taylor.png') plt.show() At first I was getting error as in the link AttributeError: 'module' object has no attribute 'to_rgb'. But, now I am getting following error: Traceback (most recent call last): File "<ipython-input-9-edf3b67792d8>", line 1, in <module> runfile('/home/mala/Downloads/F/taylor_plot.py', wdir='/home/mala/Downloads/F') File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile builtins.execfile(filename, *where) File "/home/mala/Downloads/F/taylor_plot.py", line 24, in <module> sm.taylor_diagram(sdev,crmsd,ccoef)#form taylor digram File "/usr/local/lib/python2.7/dist-packages/skill_metrics/taylor_diagram.py", line 91, in taylor_diagram overlay_taylor_diagram_circles(axes,cax,option) File "/us…
answer count: 0
tagged with: matplotlib
linked to: http://stackoverflow.com/q/47492556
has comment: http://stackoverflow.com/comment/81941556
linked to: http://stackoverflow.com/q/46890371
has comment: http://stackoverflow.com/comment/81941257
type: Question

http://stackoverflow.com/q/47446285
type: UnansweredQuestion
tagged with: python
has title: (Monkey) patch for micro python unit test
tagged with: monkeypatching
score: 2
upvote count: 2
tagged with: micropython
has comment: http://stackoverflow.com/comment/81848897
downvote count: 0
has body: I can’t find any examples, I will try to make the question specific: Given that micropython has some form of unit test library, how can I do monkey patch or similar to replace system objects output or input within test cases. The desire is to write test cases that cannot be mocked without altering the actual implementation code just for test, I.e network or file system objects replaced with mocks using patch - or a similar manual way of overriding the system objects for test purposes.
answer count: 1
favorite count: 0
tagged with: unit-testing
has answer: http://stackoverflow.com/a/61138276
type: Question
has comment: http://stackoverflow.com/comment/81960006
has comment: http://stackoverflow.com/comment/81924686

http://stackoverflow.com/comment/81830363
score: 0
has text: What do the delta updates look like? Are they what you would expect?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47437582

http://stackoverflow.com/q/47532143
tagged with: text-analysis
tagged with: information-extraction
type: UnansweredQuestion
tagged with: decoding
tagged with: python
has answer: http://stackoverflow.com/a/47537003
has title: Decode "x9f\x00ä\x00?\x00_\x00ë\" etc. string in Python 3
score: 0
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
has body: I would like to extract some general properties of pdf files. So far this has worked very well, except I've encountered a weird new error today while trying out a new input file. For the parsing, I'm using pdfminer.six. This is what the code to extract title, author, subject, etc. looks like: pdf_data = { 'Number of words': len(words), 'Number of paragraphs': len(paragraphs), 'Number of pages': len(pages) } if len(doc.info) &gt; 0: pdf_data_keys = ["latin", "windows-1252"] for key in pdf_data_keys: properValue = "" value = doc.info[0].get(key) if value is not None: for enc in encodings: try: properValue = value.decode(encoding=enc) break except Exception as ex: continue if properValue != "": pdf_data[key] = properValue Now, after running the code, I don't get any errors, but this shows up for title in the new file: 'Title': 'Ú\x9f\x00ä\x00?\x00_\x00ë\x00È\x00/\x00Å\x00Á\x00\x80\x00(\x00ë\x00ä\x00ñ\x00\x80\x00ï\x00?\x00Ê\x00%\x00À\x00\x80\x00è\x00ê\x00+\x00\x80\x00í\x00ä\x00ñ\x00è\x00ë\x00\x80\x00á\x00è\x00ã\x00\x80\x00@\x00\x80\x00á\x00è\x00ã\x00\x91\x00\x91\x00\x90\x00\x80\x00@\x00\x80\x00&lt;\x00í\x00\x90\x00\x93\x00\x99\x00\x16\x00\x94\x00\x99\x00\x94\x00\x95\x00\x96\x00\x16\x00\x80\x00@\x00\x80\x00ü\x00Â\x00Á\x00Ê\x00Ë\x00Ñ\x00Ä\x00Ç\x00È\x00\x80\x00@\x00\x80\x00Â\x00?\x00Á\x00Ê\x00Ë\x00Á\x00\x05\x00Ë\x00È\x00Í\x00È\x00È\x00Å\x00/\x00Ê\x00È\x00\x06\x00À\x00Á'} I've tried putting in every other type of encoding in existence, transforming the short list up there into this: encodings = ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp273', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1125', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp65001', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb1…
type: Question

http://stackoverflow.com/comment/81725774
comment on: http://stackoverflow.com/q/47386216
has text: This will be an ordinary set index and mapping. There are many answers for this question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47490964
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47491253
has comment: http://stackoverflow.com/comment/81937635
answer count: 1
has title: Scrapy following link not getting data
tagged with: web-scraping
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/81937660
accepted answer: http://stackoverflow.com/a/47491253
tagged with: python
has body: I am trying to follow a list of links and scrap data from each link with a simple scrapy spider but I am having trouble. In the scrapy shell when I recreate the script it sends the get request of the new url but when I run the crawl I do not get any data back from the link. The only data I get back is from the starting url that was scraped before going to the link. How do I scrape data from the link? import scrapy class QuotesSpider(scrapy.Spider): name = "players" start_urls = ['http://wiki.teamliquid.net/counterstrike/Portal:Teams'] def parse(self, response): teams = response.xpath('//*[@id="mw-content-text"]/table[1]') for team in teams.css('span.team-template-text'): yield{ 'teamName': team.css('a::text').extract_first() } urls = teams.css('span.team-template-text a::attr(href)') for url in urls: url = response.urljoin(url) yield scrapy.Request(url, callback=self.parse_team_info) def parse_team_info(self, response): yield{ 'Test': response.css('span::text').extract_first() }

http://stackoverflow.com/q/47389516
has body: I am developing a chat bot in Python. I have a data set for 4 intents. I have managed to build a classifier using tfidf and sklearn library to classify the input text in one of 4 trained intents. But, I want to add another intent i.e if user asks anything out of those 4 intents it should return fallback intent like it does in api.ai Now when I predict the intent of any rubbish text it always returns "intent no.2".
has title: how to add fallback intent in chatbot just like api.ai
upvote count: 0
answer count: 1
tagged with: machine-learning
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47417714
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: nlp
tagged with: chatbot

http://stackoverflow.com/q/47477709
tagged with: python-2.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81910690
downvote count: 0
score: 1
upvote count: 1
tagged with: macos
answer count: 1
favorite count: 0
has title: Terminate Python in Terminal (control-C just printing ^C) macOS 10.12
has body: So I've been using control-z to stop my python scripts, but I recently noticed they were still active in the activity monitor and can only terminate them there. Control-C doesn't work and only prints out ^C. Perhaps the combo got remapped? Any suggestions on how I can figure this out.
tagged with: terminal
type: Question
accepted answer: http://stackoverflow.com/a/47478014
has comment: http://stackoverflow.com/comment/81910636
has answer: http://stackoverflow.com/a/47478014
tagged with: python
has comment: http://stackoverflow.com/comment/81910762
tagged with: macos-sierra

http://stackoverflow.com/a/63981123
answers question: http://stackoverflow.com/q/47445099
score: 0
has body: instead of editing the config_init.py mentioned https://stackoverflow.com/a/47543691/5485370 It is easier to assign the temp db and path using the ibis.options: ibis.options.impala.temp_db = 'your_temp_db' ibis.options.impala.temp_hdfs_path = 'your_temp_hdfs_path'
type: Answer

twitter-rest-api
tags question: http://stackoverflow.com/q/47437488
tag name: twitter-rest-api
type: Tag

http://stackoverflow.com/comment/81803254
type: Comment
comment on: http://stackoverflow.com/a/47424173
type: AnswerComment
has text: What IIUC? in your answer text
score: 0

http://stackoverflow.com/q/47498553
tagged with: python
has comment: http://stackoverflow.com/comment/81954379
has comment: http://stackoverflow.com/comment/82003711
tagged with: antlr
has comment: http://stackoverflow.com/comment/82001075
has comment: http://stackoverflow.com/comment/82003434
has title: Antlr Python Error
has comment: http://stackoverflow.com/comment/81998054
score: 0
answer count: 0
tagged with: grammar
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81954520
has comment: http://stackoverflow.com/comment/81955905
tagged with: parsing
type: Question
has comment: http://stackoverflow.com/comment/81983426
has comment: http://stackoverflow.com/comment/81956379
has body: I am trying to generate the parse tree for the Antlr grammar in Python. My code: char_stream = InputStream('a(1)') lexer = MLexer(char_stream ) stream = CommonTokenStream(lexer) parser = MParser(stream) tree = parser.start() Error: line 1:0 mismatched input 'a' expecting &lt;INVALID&gt; When I checked the generated parser file by Antlr: literalNames = [ "&lt;INVALID&gt;", "' '", "'\t'", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "':-'", "','", "'('", "')'", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "'.'" ] symbolicNames = [ "&lt;INVALID&gt;", "&lt;INVALID&gt;", "&lt;INVALID&gt;", "DATALOGPROGRAM", "SCHEMALIST", "SCHEMA", "CLAUSELIST", "RULELIST", "FACTLIST", "GOALLIST", "FACT", "E_RULE", "GOAL", "BODY", "LITERALLIST", "LITERAL", "PREDICATE", "GOALSIGN", "COMMA", "LEFTBRAK", "RIGHTBRAK", "OPERATOR", "VARIABLELIST", "VARIABLE", "CONSTANTLIST", "CONSTANT", "Numbers", "Lrr", "Urr", "PERIOD" ] There are so many Invalids in the antlr generated parser file. How do I fix this? Please find the following grammar in Antlr: There are lot of "Invalid" in Symbolic Names and Literal Names grammar N; start : DATALOGPROGRAM; LITERAL : LEFTBRAK (VARIABLELIST) RIGHTBRAK; PREDICATE :Lrr (Lrr|Urr)+; GOALSIGN : ':-'; COMMA : ','; LEFTBRAK : '('; RIGHTBRAK : ')'; OPERATOR : '&gt;' | '&lt;' | '=' | '!=' | '&gt;=' | '&lt;=' ; VARIABLELIST : VARIABLE | VARIABLE (COMMA VARIABLE)*; VARIABLE : Urr | Urr (Lrr|Urr)+; / CONSTANTLIST : CONSTANT | CONSTANT (COMMA CONSTANT)*; CONSTANT : Lrr | Lrr (Lrr|Urr)+| Numbers ; //Constant must start with Lowercase letter Numbers : DIGIT; Lrr : LOWERCASE; Urr: UPPERCASE; PERIOD : '.'; fragment LOWERCASE : [a-z] ; fragment UPPERCASE : …
has comment: http://stackoverflow.com/comment/82007562

http://stackoverflow.com/a/64938691
has comment: http://stackoverflow.com/comment/134355441
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47446480
downvote count: 0
has body: As state above, the official Heroku documentation works (https://elements.heroku.com/buildpacks/buyersight/heroku-google-application-credentials-buildpack). For PHP Laravel users though, the config variable GOOGLE_APPLICATION_CREDENTIALS should be set to ../google-credentials.json. Otherwise, PHP will not find the file. Screenshot from Heroku

http://stackoverflow.com/comment/81916150
comment on: http://stackoverflow.com/q/47477897
has text: Please don't ask the same question within hours in several threads. https://stackoverflow.com/questions/47476434/how-to-show-data-per-row-instead-of-string
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81963586
type: QuestionComment
comment on: http://stackoverflow.com/q/47503631
has text: @sharatpc Yeah now I am trying on it! It's a lot more convenient to use pd.DataFrame.
score: 0
type: Comment

http://stackoverflow.com/comment/81775525
type: QuestionComment
has text: maybe this can help you to go around your problem: https://gist.github.com/anandsunderraman/e351485319a8a0e7df7e
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47391823

http://stackoverflow.com/comment/81973949
score: 0
comment on: http://stackoverflow.com/a/47508951
type: AnswerComment
has text: But thanks anyway, I'll have to find another way to isolate my red shape contour
type: Comment

http://stackoverflow.com/q/47411383
has body: I'm changing my TensorFlow code from the old queue interface to the new Dataset API. With the old interface I could specify the num_threads argument to the tf.train.shuffle_batch queue. However, the only way to control the amount of threads in the Dataset API seems to be in the map function using the num_parallel_calls argument. However, I'm using the flat_map function instead, which doesn't have such an argument. Question: Is there a way to control the number of threads/processes for the flat_map function? Or is there are way to use map in combination with flat_map and still specify the number of parallel calls? Note that it is of crucial importance to run multiple threads in parallel, as I intend to run heavy pre-processing on the CPU before data enters the queue. There are two (here and here) related posts on GitHub, but I don't think they answer this question. Here is a minimal code example of my use-case for illustration: with tf.Graph().as_default(): data = tf.ones(shape=(10, 512), dtype=tf.float32, name="data") input_tensors = (data,) def pre_processing_func(data_): # normally I would do data-augmentation here results = (tf.expand_dims(data_, axis=0),) return tf.data.Dataset.from_tensor_slices(results) dataset_source = tf.data.Dataset.from_tensor_slices(input_tensors) dataset = dataset_source.flat_map(pre_processing_func) # do something with 'dataset'
downvote count: 0
score: 21
upvote count: 21
tagged with: python
has comment: http://stackoverflow.com/comment/81781116
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/52179857
has comment: http://stackoverflow.com/comment/81780431
has comment: http://stackoverflow.com/comment/81780501
answer count: 1
has answer: http://stackoverflow.com/a/47414078
has comment: http://stackoverflow.com/comment/81776267
accepted answer: http://stackoverflow.com/a/47414078
favorite count: 0
has title: Parallel threads with TensorFlow Dataset API and flat_map
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81781167
has comment: http://stackoverflow.com/comment/81780898

http://stackoverflow.com/comment/81719466
type: QuestionComment
comment on: http://stackoverflow.com/q/47383380
score: 0
has text: Is this homework?
type: Comment

http://stackoverflow.com/q/47392996
tagged with: for-loop
has comment: http://stackoverflow.com/comment/81739158
has comment: http://stackoverflow.com/comment/81739042
has answer: http://stackoverflow.com/a/47393190
tagged with: python
tagged with: variables
has title: How to iterate through a list using a stepper variable in Python?
possible better answer: http://stackoverflow.com/a/47393190
type: AnsweredQuestion
score: 0
answer count: 2
has body: I am trying to write a function that returns a hangman style output given an input of guessed characters and a secret to be guessed. I start by making a new list aset to - as many times as the length of the secret. I then iterate through this variable and test if a[stepper] == letter where letter is the walker as we loop through. Currently to keep track of this stepper I am using this code a = ["-"] * len(secret) for curr in guessed: letter_count = 0 # Stepper for letter in secret: if curr == letter: a[letter_count] = curr letter_count += 1 Is there a built in functionality for letter_count as I am using here?
has comment: http://stackoverflow.com/comment/81739087
upvote count: 1
has comment: http://stackoverflow.com/comment/81738927
accepted answer: http://stackoverflow.com/a/47393054
downvote count: 1
favorite count: 0
tagged with: iteration
type: Question
has comment: http://stackoverflow.com/comment/81738975
has answer: http://stackoverflow.com/a/47393054

http://stackoverflow.com/a/47426347
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47426329
upvote count: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81807538
has body: You need to call the method by way of a instance of the class, also, arg3 in bah is undefined: Class foo: def bar(self, arg1, arg2): return arg1 + arg2 def bah(self, arg) arg3 = "SOMEVALL" aString = self.bar("s1", "s2") return aString + arg3 Then, in the shell: from FILENAME import foo print(foo().bah("SOMETHING"))
answers question: http://stackoverflow.com/q/47426329

http://stackoverflow.com/comment/118806692
has text: Just a silly question @Dimitris. How should I use your function? If I write something like this: `g = g.remove_attribute(tnode='926', attr='bipartite')` it appear this: AttributeError: 'Graph' object has no attribute 'remove_attribute'
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47477092

http://stackoverflow.com/a/47502036
upvote count: 1
has comment: http://stackoverflow.com/comment/81959923
has body: I believe you simply want to join all of the elements in the tuple: outfile.write(''.join(str(item) for item in ISBN13))
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47501999
answers question: http://stackoverflow.com/q/47501999
has comment: http://stackoverflow.com/comment/81960030
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81959855

http://stackoverflow.com/comment/82015650
type: Comment
score: 1
type: QuestionComment
has text: Your examples look like valid file names to me.
comment on: http://stackoverflow.com/q/47529120

http://stackoverflow.com/a/47473543
score: 2
answers question: http://stackoverflow.com/q/47471945
has body: Firstly you need to load your data into a numpy array (sorry i didn't quite follow your approach): def load_data(): csvlist = [] times = [] with open('freq.csv') as f: csvfile = csv.reader(f, delimiter=',') for i, row in enumerate(csvfile): timestamp = datetime.datetime.strptime(row[0],"%Y-%m-%d %H:%M:%S.%f") times.append(timestamp) csvlist.append(row[1:]) timestep = times[1]-times[0] csvarr = numpy.array(csvlist, dtype=numpy.float32) return timestep, csvarr The may well be a better way to do this? Then you need to calculate the magnitudes: rms = numpy.sqrt(numpy.sum(data**2, axis=1)) And then the fourier analysis: def fourier(timestep, data): N = len(data)//2 freq = fftpack.fftfreq(len(data), d=timestep)[:N] fft = fftpack.fft(data)[:N] amp = numpy.abs(fft)/N order = numpy.argsort(amp)[::-1] return freq[order] the return from this is a list of frequencies in decreasing order of importance.
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81770637
has text: It might be gold standard, but all of the real-world applications I've worked with were and are written and maintained in Python 2, which is unlikely to change for a while.
comment on: http://stackoverflow.com/a/47408599
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47529867
accepted answer of: http://stackoverflow.com/q/47529266
has body: You can use default argument to pass the function but that function not taking any arugment does upload_to. models.py def generate_random(): return random_number class WorkOrderUploadFile(models.Model): wo_num = models.CharField(max_length="16", default=generate_random)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47529266
type: AcceptedAnswer

http://stackoverflow.com/comment/81804046
type: Comment
has text: I am about ...post the option 2 :-) haha
type: AnswerComment
comment on: http://stackoverflow.com/a/47424535
score: 0

http://stackoverflow.com/comment/81900651
comment on: http://stackoverflow.com/q/47473107
has text: This is impossible to understand without an example input file. We have no idea what `conditions` looks like and the various `val` and `flags` things aren't defined, either. Please try to reduce this into a [mcve]
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/q/47475354
has title: Python pandas dataframe reshape long to wide, multiple columns and constant values
favorite count: 0
type: Question
tagged with: reshape
has body: I need to reshape a DataFrame from long to wide format. Example of what the data looks like: import pandas as pd df = pd.DataFrame({'id':[1,1,1,2,2,2,3,3], 'id_age': 30,30,30,23,23,23,29,29], 'product':['A','B','C','A','B','C','A','B'], 'rank':[1,2,3,3,1,2,2,1], 'result':['x','y','z','p','q','r','s','t']}) print(df) id id_age product rank result 0 1 30 A 1 x 1 1 30 B 2 y 2 1 30 C 3 z 3 2 23 A 3 p 4 2 23 B 1 q 5 2 23 C 2 r 6 3 29 A 2 s 7 3 29 B 1 t The desired output is id id_age product rank result 0 1 30 [A, B, C] [1, 2, 3] [x, y, z] 1 2 23 [A, B, C] [3, 1, 2] [p, q, r] 2 3 29 [A, B] [2, 1] [s, t] i.e. one row per id. I have tried to solve the problem by creating a pivot table, but I cannot figure out how to: reshape it for more than one column (product, rank, result) handle the values that are constant within individuals (id_age) get the columns in the final data frame to be in list format (and the order is important, the first value of the list in rank corresponds to the first value of the list in result for a given individual). Any recommendations on how to move forward on this issue is appreciated!
tagged with: python
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47475968
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/81906527
accepted answer: http://stackoverflow.com/a/47475406
score: 2
tagged with: pivot
has answer: http://stackoverflow.com/a/47475968
has answer: http://stackoverflow.com/a/47475406
downvote count: 0

http://stackoverflow.com/comment/81908643
type: Comment
type: QuestionComment
has text: Why do you think you need to use dict comprehension if you don't use this dict? You can just write max(x**2 for x in range(1, 20))
comment on: http://stackoverflow.com/q/47476928
score: 3

http://stackoverflow.com/a/47405577
type: Answer
score: 0
has body: You could try a list comprehension. lst = [u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest'] print([e for e in lst if ''.join(e.split('.')).isdigit()]) Prints: ['3.1.1', '3.2', '3.1.2', '3', '3.3.0', '3.2.2']
answers question: http://stackoverflow.com/q/47405420

http://stackoverflow.com/a/47507314
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/108628139
has body: Option 1 You could concatenate the two dataframes and group by columns. pd.concat([df1, df2], 1).dropna().mean(axis=1, level=0) A B apple 0.0 7.5 banana 2.5 7.5 If it's just A you want, then this should suffice - pd.concat([df1, df2], 1).dropna()['A'].mean(axis=1, level=0) A apple 0.0 banana 2.5 Option 2 An alternative would be to find the intersecting indices with index.intersection and index with loc - i = df1.index.intersection(df2.index) df1.loc[i, ['A']].add(df2.loc[i, ['A']]).div(2) A Name apple 0.0 banana 2.5
type: Answer
answers question: http://stackoverflow.com/q/47507274
score: 3
accepted answer of: http://stackoverflow.com/q/47507274

http://stackoverflow.com/comment/81782848
comment on: http://stackoverflow.com/q/47413958
score: 1
type: Comment
has text: `eval` and `exec` should generally be avoided because they can be a security risk. For details, please see [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by SO veteran Ned Batchelder. But of course you're free to use them if you know what you're doing. And sometimes you have no alternative. Also be aware that they aren't very fast. BTW, there's a lot of great info about exec, eval, and compile [here](https://stackoverflow.com/a/29456463/4014959).
type: QuestionComment

http://stackoverflow.com/comment/81781756
score: 0
comment on: http://stackoverflow.com/q/47413719
type: Comment
has text: My English is poor, so I can't get what's your purpose... Do you want to get the "whole" disk, or what?
type: QuestionComment

http://stackoverflow.com/comment/82014038
type: Comment
has text: Based on @chrisb's answer in the question @Vivek Harkrishnan mentioned, you could do `groupby` on `block` then choose `min('time')` as `start` and `max('time')` as `end`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47527776

http://stackoverflow.com/comment/81831822
has text: What is `all` in `answer.all()`? Why not simply `if prediction == answer` **inside** the `for` loop??
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47437893
type: Comment

http://stackoverflow.com/comment/82009398
score: 0
comment on: http://stackoverflow.com/q/47519491
type: Comment
type: QuestionComment
has text: This might not be the best idea, but `flask.g` could help here. http://flask.pocoo.org/docs/0.12/api/#flask.g

http://stackoverflow.com/comment/81976528
type: Comment
score: 0
type: AnswerComment
has text: sorted is so old now :)
comment on: http://stackoverflow.com/a/47510324

http://stackoverflow.com/comment/82420376
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47415923
has text: De nada, happy to help!
type: AnswerComment

http://stackoverflow.com/q/47512442
answer count: 2
has comment: http://stackoverflow.com/comment/81980763
upvote count: 0
type: UnansweredQuestion
downvote count: 3
has title: How do i place a double dash between values in an output (I'm using Python)?
favorite count: 0
tagged with: fibonacci
has comment: http://stackoverflow.com/comment/81980880
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/81980690
has comment: http://stackoverflow.com/comment/81981148
has answer: http://stackoverflow.com/a/47512733
has answer: http://stackoverflow.com/a/47512877
type: Question
has body: So I'm making a program that prints every value from 1 to a given input in the Fibonacci sequence and its for a class I'm in. He wants us to make it so that when the outputs are printed, they are all separated by double dashes. For example: 1 -- 1 -- 2 -- 3 -- 5 and so on. My question is how do I make it do this instead of commas between output values? Please don't say anything about how long my code is , but here's what I have so far: t = False def comma(num): if type(num) == int: return '{:,}'.format(num) elif type(num) == float: return '{:,.2f}'.format(num) else: print("Need a number to function comma") def fib(limit): numbers = ["0","1"] x3 = 1 x2 = 1 x1 = 1 while x3 &lt;= int(limit): if x3 &gt;=999: n = [(comma(x3))] numbers = numbers + n x1 = x2 x2 = x3 x3 = x2 + x1 return(numbers) def isint(value): try: int(value) return True except ValueError: return False def printFib(): b = False while b == False: limit = input("What is the limit value?") if isint(limit): 2 + 2 if int(limit) &gt;= 1 and int(limit) != 1 and int(limit) &lt;= 8944394323791464: b = True else: if int(limit) == 0 or int(limit) == 1: print("really it can't start.") elif int(limit) &gt;= 8944394323791464: print("Too big, just too big.") else: print("Use positive numbers above one, or I will tell Antonio Montoya that you killed his father and he will find you.") else: print("Use whole numbers.") print(str(fib(limit))) if input("Try again y/n?") == "y": printFib() printFib()

http://stackoverflow.com/comment/81850659
type: QuestionComment
type: Comment
score: 0
has text: I was confused because argparse _does_ work on Python 3: https://docs.python.org/3/library/argparse.html
comment on: http://stackoverflow.com/q/47447686

http://stackoverflow.com/q/47531563
linked to: http://stackoverflow.com/q/36250353
tagged with: python
has answer: http://stackoverflow.com/a/47531592
has answer: http://stackoverflow.com/a/47531737
has answer: http://stackoverflow.com/a/47531594
score: 8
type: Question
linked to: http://stackoverflow.com/q/30434492
duplicate of: http://stackoverflow.com/q/30434492
downvote count: 0
has title: Why is this python code running twice
has answer: http://stackoverflow.com/a/47531598
has answer: http://stackoverflow.com/a/47531608
favorite count: 0
accepted answer: http://stackoverflow.com/a/47531592
possible better answer: http://stackoverflow.com/a/47531737
tagged with: python-3.x
type: AnsweredQuestion
upvote count: 8
answer count: 5
has body: Here is the code import random print("Hello", end="") print("twice") and a screenshot of the code When I execute this code it for some reason is running twice. The problem seems to be from the import random statement, because if I either remove that statement or import some other module it works fine. What could be the reason for this, should I reinstall Python on my system.

http://stackoverflow.com/comment/81782885
comment on: http://stackoverflow.com/q/47399807
type: Comment
type: QuestionComment
has text: @mzjn Don't be sorry, I'm still learning about best practices on SO and I can't expect help without giving a little information.
score: 0

http://stackoverflow.com/a/47404103
score: 0
answers question: http://stackoverflow.com/q/47400345
type: Answer
has comment: http://stackoverflow.com/comment/81793675
has body: Your code repo is configured to use the console backend for emails, but your backtrace is showing the smtp backend is being used. I assume you've changed the backend and that's what's causing the error. By default, the smtp backend looks for an smtp server on localhost. I'm guessing you don't have one running there. If you want to send via gmail's smtp servers you can do so, you just need to configure the approriate settings in your settings.py file. See the django docs for what needs to be configured. Read the gmail docs for the exact smtp host address to use.
has comment: http://stackoverflow.com/comment/81795931
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47400345

http://stackoverflow.com/comment/81880241
has text: What type of variable are the values? Are they years, integers etc....?
type: QuestionComment
comment on: http://stackoverflow.com/q/47462690
score: 0
type: Comment

http://stackoverflow.com/q/47481433
tagged with: python
has comment: http://stackoverflow.com/comment/81917744
tagged with: image
has title: Can't paste an image onto another image with PIL properly
has comment: http://stackoverflow.com/comment/81917816
answer count: 0
score: 1
downvote count: 0
tagged with: image-processing
upvote count: 1
has comment: http://stackoverflow.com/comment/81919624
favorite count: 0
has body: I have this image: that I'm trying to paste on to this one: I want to get rid of the black background (so I'm assuming "make it transparent"?). I tried applying a black mask, but the result is this: I'm not quite understanding how to use a mask properly. I thought creating a black mask would get rid of the black portions. from PIL import Image image = Image.open(r'..jpg') image_2 = Image.open(r'...jpg') image_copy = image.resize((300,300)).copy() #fish image mask=Image.new('L', (300,300), color=0) position = ((200,100)) image_2.paste(image_copy, position, mask = mask) image_2.save('testing_1.png') EDIT: Playing around with the code a bit more I'm able to overlay the image onto the background, but it still has the black background surrounding it. I would like to get RID of the black background.
type: Question
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/81917764
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81919580
has comment: http://stackoverflow.com/comment/81917997

http://stackoverflow.com/a/47476905
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47476674
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81910573
score: 1
has body: What the sentence you're referring to is saying is that you should have this line in your script file: if __name__ == '__main__': And that any code that runs the script should appear in that block. By doing so, you ensure that the code won't automatically run when you import it from another file, since importing ignores the if statement mentioned above. For processing arguments (which should exist in the if block mentioned above, since you wouldn't want to do that when importing), you should use argparse for everything after Python 2.7. Here's a link to the documentation: Python argparse library You shouldn't have to override __getattr__
type: Answer
answers question: http://stackoverflow.com/q/47476674
downvote count: 0

http://stackoverflow.com/comment/81997014
comment on: http://stackoverflow.com/a/47520177
score: 0
type: Comment
has text: Edited to include a Python 3 version
type: AnswerComment

http://stackoverflow.com/a/47451232
has body: In start function, add self.crawler(). Then that function will initiate after calling driver variable. Then the browser will go to the url
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47451131

http://stackoverflow.com/a/47462105
answers question: http://stackoverflow.com/q/47461653
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47461653
has body: If I understood you correctly, when user inputs no both times, the loop will start over again: while(1): temp_input = input('Is it 6 am?') if(temp_input == 'yes'): #note that Yes, or YES, or yEs won't work in this case print('Checking temperature == 22 degrees') break temp_input = input('Is it 9 am?') if(temp_input == 'yes'): print('Checking temperature == 19 degrees') break This is a very simple solution, you can work on it and improve it
type: Answer

http://stackoverflow.com/comment/82015219
type: Comment
score: 0
has text: Let me give it a try
type: AnswerComment
comment on: http://stackoverflow.com/a/47527569

shell
tags question: http://stackoverflow.com/q/47474946
tags question: http://stackoverflow.com/q/47538080
tags question: http://stackoverflow.com/q/47398554
tags question: http://stackoverflow.com/q/47483530
type: Tag
tags question: http://stackoverflow.com/q/47418800
tag name: shell
tags question: http://stackoverflow.com/q/47526685
tags question: http://stackoverflow.com/q/47481902
tags question: http://stackoverflow.com/q/47426699
tags question: http://stackoverflow.com/q/47460273
tags question: http://stackoverflow.com/q/47388921
tags question: http://stackoverflow.com/q/47527621
tags question: http://stackoverflow.com/q/47389066
tags question: http://stackoverflow.com/q/47413270
tags question: http://stackoverflow.com/q/47413175
tags question: http://stackoverflow.com/q/47417279
tags question: http://stackoverflow.com/q/47407680
tags question: http://stackoverflow.com/q/47429532
tags question: http://stackoverflow.com/q/47408993

http://stackoverflow.com/comment/82034826
score: 0
has text: What should the program do with a test case like `a, b = ['R', 'R', 'Y', 'B'], ['G', 'R', 'P', 'R']
type: QuestionComment
comment on: http://stackoverflow.com/q/47538610
type: Comment

http://stackoverflow.com/comment/83657814
comment on: http://stackoverflow.com/a/47452562
type: Comment
type: AnswerComment
has text: @KenHilton `@staticmethod` does the same as ignoring the passing `self` argument (Python will still pass `self` to the function; it’s just that the decorator will skip it for you). There is no real benefit here in wrapping the function *again*. There are already enough levels of wrapping involved here. Also, `__call__` is still an instance method, so even though I don’t need `self` here, making it a static method would feel wrong. – As for `wraps`, I am using that.
score: 0

http://stackoverflow.com/a/47394364
has comment: http://stackoverflow.com/comment/81743546
type: AcceptedAnswer
has body: If you look at the &lt;input id="report_Entity_ClientState" ... &gt; node the type is hidden. So we have to unhide the WebElement first and send the chars as follows: entityElem = browser.find_element_by_xpath("//input[@id='report_Entity_ClientState']") browser.execute_script("arguments[0].removeAttribute('type')", entityElem); entityElem.send_keys('Entity1')
has comment: http://stackoverflow.com/comment/81751718
has comment: http://stackoverflow.com/comment/81744930
accepted answer of: http://stackoverflow.com/q/47390161
type: Answer
has comment: http://stackoverflow.com/comment/81771859
answers question: http://stackoverflow.com/q/47390161
has comment: http://stackoverflow.com/comment/81744797
score: 0
has comment: http://stackoverflow.com/comment/81810327
has comment: http://stackoverflow.com/comment/81810012
has comment: http://stackoverflow.com/comment/81746782

http://stackoverflow.com/q/47428990
type: Question
has title: get groups id more than one and get nothing results
tagged with: python
has answer: http://stackoverflow.com/a/47429343
accepted answer: http://stackoverflow.com/a/47429343
type: AnsweredQuestion
downvote count: 0
upvote count: 1
tagged with: odoo
score: 1
answer count: 1
has body: I was trying to give a condition for a group and directly for 2 group and of course I got two group ids. After getting the group ids I would like to execute the following code, but the result is blank. Here goes the code: new_data = [] check_groups = self.env['res.groups'].search([('name', 'in', ['groups_A', 'groups_B')]) for news in check_groups: new_data.append(news.id) self.groups_id= ([4, new_data]) I got two group ids and I did not get an error, just didn't get the result. But, if I use just one groups like : check_groups = self.env['res.groups'].search([('name', '=', 'groups_A')]) It works
favorite count: 0

http://stackoverflow.com/comment/89393433
type: AnswerComment
has text: Hi David, great answer- I a trying to reproduce your results with Sklearn.LogisticRegression but the results from predict_proba are different - why is this so you think ?
comment on: http://stackoverflow.com/a/47419474
type: Comment
score: 0

http://stackoverflow.com/q/47433755
answer count: 2
tagged with: file
has body: Here are the contents of res.txt one two three four Here is my code: inputlist = open ('res.txt' , 'r') a = inputlist.readline(3) b = inputlist.readlines() print a, b here is the result: one ['\n', 'two\n', 'three\n', 'four'] Are these two methods not designed for python 2.7? The .txt is saved on Lubuntu with Leafpad. What's happening? PS: I know that the second is a list, but it seems that the first method has grabbed out of it the first line, while it was supposed to just read the third line...
has title: Incomprehensible results with python readline(s)
tagged with: external
type: Question
has answer: http://stackoverflow.com/a/47433870
has answer: http://stackoverflow.com/a/47433864
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/comment/81873489
has text: how to extract feature from this sample dataset which is in hindi by using "Local context and collocation context"...Here ambiguous word is हार (necklace)..How to get two words from left and two words from right of the ambiguous....and how to use these features as a input in the "Naive Bayes" algorithm ??
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47387082

http://stackoverflow.com/a/47396828
has body: It is hard to understand why you need this ... from itertools import chain df.groupby(['name1','name2']).mounth.\ apply(lambda x :x.groupby(x.diff().ne(1).cumsum()).\ apply(lambda y: list(chain.from_iterable([y])) if len(y)&gt;1 else list(chain.from_iterable([y,y])))).\ groupby(level=['name1','name2']).apply(list) Out[1305]: name1 name2 A B [[1, 2], [4, 4]] B C [[2, 3]] Name: mounth, dtype: object
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/81747049
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47396442
score: 4
answers question: http://stackoverflow.com/q/47396442
has comment: http://stackoverflow.com/comment/81747005
downvote count: 0

http://stackoverflow.com/a/47426525
has comment: http://stackoverflow.com/comment/81809559
has comment: http://stackoverflow.com/comment/81823117
accepted answer of: http://stackoverflow.com/q/47426044
type: Answer
has comment: http://stackoverflow.com/comment/82048785
has comment: http://stackoverflow.com/comment/81808402
answers question: http://stackoverflow.com/q/47426044
has comment: http://stackoverflow.com/comment/82041725
has comment: http://stackoverflow.com/comment/81809488
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81808271
has comment: http://stackoverflow.com/comment/81867132
has comment: http://stackoverflow.com/comment/82045233
has body: I have updated your code below with the comments where necessary. array = tf.Variable(tf.zeros((b,n,m))) ones = tf.Variable(tf.ones((m))) labels = tf.Variable(tf.ones((b), dtype=tf.int32)) #labels = np.ones(b,dtype=np.int8) if you want a array with tf.control_dependencies([array[i,labels[i],:].assign(tf.ones(m)) for i in range(b)]): # should give the list of slice assignment here array = tf.identity(array) #conver to a tensor sess = tf.Session() with sess.as_default(): sess.run(tf.global_variables_initializer()) print(array.eval()) #print the new array (optional, only to see the values) Things you should note, [array[i][labels[i]] ---&gt; [array[i,labels[i],:]] Seems like a syntax error for me. tf.identity(array) returns a tensor as the shape of array. When you assign that to the array again, then the array becomes a tensor and not a variable anymore. You cannot do the slice assignment for a tensor. You need to provide a list of slice assignments as an argument to tf.control_dependencies Hope this helps.
has comment: http://stackoverflow.com/comment/81808349

http://stackoverflow.com/a/47502703
accepted answer of: http://stackoverflow.com/q/47502652
has body: Its likely that package_ids is a generator, and the conversion to a list to find out the number of items has exhausted it, or perhaps its simply an iterable that does not expose []. In any case, your code would be better expressed as: for q, x in enumerate(package_ids): if q == 0: query = 'Zero' + x else: query = 'More' + x This will handle any type of iterable including a generator. Or even more concise: for q, x in enumerate(package_ids): query = ('More' if not q else 'Zero') + x
type: Answer
has comment: http://stackoverflow.com/comment/81961346
answers question: http://stackoverflow.com/q/47502652
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81968608

http://stackoverflow.com/a/47442113
downvote count: 0
type: Answer
has body: Let's use this: np.random.seed(123) list_items = ['apple', 'grapple', 'tackle', 'satchel', 'snapple'] df = pd.DataFrame({'id':range(3), 'L':[np.random.choice(list_items, 3).tolist() for _ in range(3)]}) df L id 0 [tackle, snapple, tackle] 0 1 [grapple, satchel, tackle] 1 2 [satchel, grapple, grapple] 2 Use any and apply: df[df.L.apply(lambda x: any('grap' in s for s in x))] Output: L id 1 [grapple, satchel, tackle] 1 2 [satchel, grapple, grapple] 2 Timings: %timeit df.L.apply(lambda x: any('grap' in s for s in x)) 10000 loops, best of 3: 194 µs per loop %timeit df.L.apply(lambda i: ','.join(i)).str.contains('grap') 1000 loops, best of 3: 481 µs per loop %timeit df.L.str.join(', ').str.contains('grap') 1000 loops, best of 3: 529 µs per loop
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47441980
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47441980

http://stackoverflow.com/comment/81753601
type: Comment
comment on: http://stackoverflow.com/a/47400034
type: AnswerComment
has text: Thank you so much, I am wondering if `np.array_split` can also be applied to split `d` into 2/3 length and 1/3 length?
score: 0

http://stackoverflow.com/a/47472449
answers question: http://stackoverflow.com/q/47455454
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: After series of debug, I finally found a solution by converting the labels into arrays from array package:img=array("B", data). Before that I flatten the numpy.ndarray into list by data = ([int(i) for i in (dataset[:, 1:].flatten())]): Four hours of debug helped me. May be not very efficient but works for now. Posting solution here for somebody trying to do solve classification problems in scikit libraries. def read(digits, target_index): rows=18 cols=15 #lbl = array("b", reformatData['target']) if target_index == -1: data = dataset[:, :-1] target = dataset[:, -1] elif target_index == 0: data = dataset[:, 1:] #print (data[0].flatten(), type(data[0].flatten()),data[0].flatten().size) #data=(list(data[0].flatten())) data = ([int(i) for i in (dataset[:, 1:].flatten())]) #print ("data size: ", data.size,"length", type(data)) #target = dataset[:, 0] #print ("data size: ", target.size,"length", type(target) ) lbl=([int(i) for i in (dataset[:, 0].flatten())]) #print lbl #lbl =np.asarray(target[:].flatten()) lbl=array("b", lbl) #print(type(lbl)), len(lbl) #print ("length labell", lbl.size, "length", type(lbl) ) img=array("B", data) #print(type(img)), len(img) #print ("length of image: ",img.size, "length", type(img) ) ind = [ k for k in range(len(lbl)) if lbl[k] in digits] print ("index length ", len(ind), "length", type(ind) ) images = matrix(0, (len(ind), rows*cols)) print ("images length ", images.size, "images type", type(images)) labels = matrix(0, (len(ind), 1)) print ("lables length ", labels.size, "labels type", type(labels)) for i in xrange(len(ind)): images[i,:] = img[ind[i]*rows*cols:(ind[i]+1)*rows*cols] labels[i]= lbl[ind[i]] return images, labels print read(digits=[3], target_index=0)

http://stackoverflow.com/comment/81741845
comment on: http://stackoverflow.com/a/47394144
type: Comment
has text: different lines ? your code doesn't tell that !! Its checking for both conditions in the same line, each time. Can you recheck.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47468148
tagged with: amazon-web-services
upvote count: 67
has body: I want to copy a file from one s3 bucket to another. I get the following error: s3.meta.client.copy(source,dest) TypeError: copy() takes at least 4 arguments (3 given) I'am unable to find a solution by reading the docs. Here is my code: #!/usr/bin/env python import boto3 s3 = boto3.resource('s3') source= { 'Bucket' : 'bucketname1','Key':'objectname'} dest ={ 'Bucket' : 'Bucketname2','Key':'backupfile'} s3.meta.client.copy(source,dest)
has answer: http://stackoverflow.com/a/47468276
possible better answer: http://stackoverflow.com/a/47468284
type: AnsweredQuestion
answer count: 3
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/47468284
accepted answer: http://stackoverflow.com/a/47468350
has title: how to copy s3 object from one bucket to another using python boto3
score: 66
has answer: http://stackoverflow.com/a/47468350
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/121677192
linked to: http://stackoverflow.com/q/30161700
tagged with: python
tagged with: boto3

http://stackoverflow.com/comment/82037299
type: Comment
comment on: http://stackoverflow.com/q/47520049
type: QuestionComment
score: 0
has text: @Jean-FrançoisFabre Doi! That showed I was not in the right place. Thank you.

http://stackoverflow.com/comment/81991033
has text: I thought he wanted to access to a dictionary in a class of another file... so I imported the file and printed the dictionary... wasn't that the goal of the questions?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47505425
score: 0

http://stackoverflow.com/a/47385762
has comment: http://stackoverflow.com/comment/81724721
answers question: http://stackoverflow.com/q/47385721
has comment: http://stackoverflow.com/comment/81724640
score: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47385721
has comment: http://stackoverflow.com/comment/81724643
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81724566
type: Answer
upvote count: 1
has body: You could use the following comprehension: def friends_score(person, person_to_friends): # ... potential_friends = [ p for p in person_to_friends if p != person and p not in person_to_friends.get(person, []) ] # ... That collects all the keys of the dict that are not in the friends list of the specified person and are not the person themselves. That is roughly equivalent to the following: def friends_score(person, person_to_friends): # ... friends = person_to_friends.get(person, []) # for larger data sets, you might want to convert the friends to a set # friends = set(friends) potential_friends = [] for p in person_to_friends: if p != person and p not in friends: potential_friends.append(p) # ...

http://stackoverflow.com/comment/81901578
has text: sorry, my bad, placed static folder in a wrong place. Your suggestion works good！
type: Comment
comment on: http://stackoverflow.com/a/47458153
score: 0
type: AnswerComment

http://stackoverflow.com/q/47481462
possible better answer: http://stackoverflow.com/a/47481591
answer count: 2
has answer: http://stackoverflow.com/a/47481591
linked to: http://stackoverflow.com/q/29287695
linked to: http://stackoverflow.com/q/12190326
has comment: http://stackoverflow.com/comment/81917987
accepted answer: http://stackoverflow.com/a/47481662
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/9384320
has answer: http://stackoverflow.com/a/47481662
has title: count all occurences of each word from a list that appear in several thousand records in python
has body: I have a list of reviews and a list of words that I am trying to count how many times each word shows in each review. The list of keywords is roughly around 30 and could grow/change. The current population of reviews is roughly 5000 with the review word count ranging from 3 to several hundred words. The number of reviews will definitely grow. Right now the keyword list is static and the number of reviews will not be growing to much so any solution to get the counts of keywords in each review will work, but ideally it will be one where there isn't a major performance issue if the number reviews drastically increase or the keywords change and all the reviews have to be reanalyzed. I have been reading through different methods on stackoverflow and haven't been able to get any to work. I know you can use skikit learn to get the count of each word, but haven't figured out if there is a way to count a phrase. I have also tried various regex expressions. If the keyword list was all single words, I know I could very easily use skikit learn, a loop or regex, but I am having issues when the keyword has multiple words. Two links I have tried Python - Check If Word Is In A String Phrase matching using regex and Python the solution here is close, but it doesn't count all occurrences of the same word How to return the count of words from a list of words that appear in a list of lists? both the list of keywords and reviews are being pulled from a MySQL DB. All keywords are in lowercase. All text has been made lowercase and all non-alphanumeric except spaces have been stripped from the reviews. My original though was to use skikit learn countvectorizer to count the words, but not knowing how to handle counting a phrase I switched. I am currently attempting with loops and regex, but I am open to any solution # Example of what I am currently attempting with regex keywords = ['test','blue sky','grass is green'] reviews = ['this is a test. test should come back twice and not 3 times fo…
linked to: http://stackoverflow.com/q/5319922
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81917867
type: Question

http://stackoverflow.com/q/47478046
type: Question
has comment: http://stackoverflow.com/comment/81911225
linked to: http://stackoverflow.com/q/3337301
has title: Numpy (1, N) dimension to (N,) dimension conversion
has body: Here I got the first row from a numpy matrix firstRow = (allEigenVectors.T)[0, :] where firstRow.shape is (1,784) how can I convert it into (784,) shape ?
score: 1
duplicate of: http://stackoverflow.com/q/3337301
tagged with: python
tagged with: numpy
answer count: 0
type: UnansweredQuestion
downvote count: 0
duplicate of: http://stackoverflow.com/q/14476415
upvote count: 1
has comment: http://stackoverflow.com/comment/81910786
has comment: http://stackoverflow.com/comment/81910800
favorite count: 0

http://stackoverflow.com/comment/81933310
score: 1
type: Comment
type: QuestionComment
has text: `mytriple.multiply(a, 2, 3)` would work just fine. Your method only is available on `Triple` instances, nowhere else.
comment on: http://stackoverflow.com/q/47489152

http://stackoverflow.com/comment/82036312
has text: Yes, well j = [list], make a list from j where the sum is less than 15.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47539457

http://stackoverflow.com/q/47417049
tagged with: image-processing
upvote count: 1
favorite count: 0
type: Question
has body: Im learning Docker. And I don't really get the hang of docker volumes. So I set a simple task for me to understand it: I create a Container with a python script that resizes a JPEG for example: from PIL import Image from resizeimage import resizeimage with open('test-image.jpeg', 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_cover(image, [200, 100]) cover.save('test-image-cover.jpeg', image.format) Where do I put the Input File ? Should I create a Volume or a Bind Mount and put the JPEG File there? Im running Docker on a Virtual Machine ( Standard Docker Toolbox Installation on Win 10) Where do I find the resized Files on the Volumes? Right now I don't really care if the File is overwritten, if the app is running on server and two users use the container at the same time. What is the simplest way to input /process / output a file with a python script running in a container?
has title: Simple Docker Project / Process and Save JPEG - Use Volume?
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47419887
tagged with: virtualbox
has answer: http://stackoverflow.com/a/47419887
tagged with: docker
type: AnsweredQuestion
tagged with: docker-volume
score: 1
answer count: 1

http://stackoverflow.com/q/47535547
score: 1
upvote count: 1
has body: I have a list of values and a dataframe. What I want to do is use a foreach loop going through the list and for each item in the list drop the corresponding row from the dataframe: irrelevantList=['Blackcurrants', 'Cherries', '', 'Damsons', 'Gooseberries', 'Pears', 'Plums and Gages',] fruitveg_df this one contains lots of colums and rows(there is a column with label '2004'). I tired this: for item in irrelevantList: fruitveg_df.drop(fruitveg_df['2004']==item, inplace=True) but it is not working. Can somebody help please?
possible better answer: http://stackoverflow.com/a/47535665
favorite count: 0
has title: droping rows based on the values in cells by iterating through a list of values in pandas
type: Question
answer count: 2
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47535677
has answer: http://stackoverflow.com/a/47535665
has answer: http://stackoverflow.com/a/47535677
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/q/47474704
upvote count: 3
has title: How can I create a chain pipeline?
downvote count: 0
answer count: 1
favorite count: 0
has body: I would like to create a simply chain pipeline, I found this simple example: """ From https://stackoverflow.com/questions/33658355/piping-output-from-one-function-to-another-using-python-infix-syntax """ import collections def pipe(original): """ """ class PipeInto(object): data = {'function': original} def __init__(self, *args, **kwargs): self.data['args'] = args self.data['kwargs'] = kwargs def __rrshift__(self, other): return self.data['function']( other, *self.data['args'], **self.data['kwargs'] ) def __call__(self): return self.data['function']( *self.data['args'], **self.data['kwargs'] ) return PipeInto @pipe def select(df, *args): cols = [x for x in args] return df[cols] While the df &gt;&gt; select('one') works fine, the pipe= select(df, 'one') returns an object which needs to be called. How can select(df, 'one') work as a simple function call which returns the filtered DataFrame?
type: Question
tagged with: python-3.x
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/47475048
accepted answer: http://stackoverflow.com/a/47475048
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81905069
linked to: http://stackoverflow.com/q/33658355

http://stackoverflow.com/comment/81813476
has text: instead of `while True` and `sleep()` and `tkw.update()` you should use `cvs.after(10, redraw)`. Currently you doesn't start `mainloop` which runs all in Tkinter (BTW: it has to be `mainloop()` with `()`)
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/47429232
type: Comment

http://stackoverflow.com/comment/81905189
type: Comment
type: AnswerComment
score: 1
has text: Doesn't that break when the list isn't a range of consecutive numbers starting with 0?
comment on: http://stackoverflow.com/a/47462753

http://stackoverflow.com/q/47435833
tagged with: django-rest-framework
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47436905
has answer: http://stackoverflow.com/a/47436905
has body: How about create multi model instance through serializer? I have a views.py: class CloudServerCreateAPIView(CreateAPIView): """ Create CloudServer """ serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() Its serializer is this: class CloudServerCreateSerializer(ModelSerializer): count = serializers.IntegerField() class Meta: model = CloudServer exclude = [ 'expiration_time', 'buytime', 'availablearea', 'profile', ] def create(self, validated_data): count = validated_data.pop("count") for _ in range(0, count): # create the CloudServer instance, then save to database. And other logic stuff # But there must return a CloudServer instance. You see, my serializer, I override the create method, and I use for-loop to save the CloudServer instances to database. But the create method must return a instance, what to do with that? Because I access the view one time, to create the count times CloudServer instances, in my create method I have saved to database, what should I do then(in this line # But there must return a CloudServer instance.)?
tagged with: python
has title: How about create multi model instance through serializer?
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1

http://stackoverflow.com/q/47502264
has comment: http://stackoverflow.com/comment/81960324
upvote count: 1
has comment: http://stackoverflow.com/comment/81960411
has body: The question is simple. im building a recipe website with multiple users to submit their recipes. i want to build one page listing all the users and arrange the user hierarchy based on their latest post. what is the best way to query the users in the views.py and pass to the context? the code snippet is something like this; models.py class UserRecipe(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) as you can see the UserRecipe model linked to user using ForeignKey. So im building a view in views.py to list users and rank them based on the date of their last UserRecipe created_date. so in order to query users and arrange them based on their UserRecipe created_date what is the best way to do it?
downvote count: 0
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/47502778
favorite count: 0
accepted answer: http://stackoverflow.com/a/47502778
has comment: http://stackoverflow.com/comment/81960914
has comment: http://stackoverflow.com/comment/81961298
type: AnsweredQuestion
has title: Django : How to query users based on latest post
score: 1
has comment: http://stackoverflow.com/comment/81960609
tagged with: orm
linked to: http://stackoverflow.com/q/13757195
tagged with: python
type: Question

http://stackoverflow.com/comment/81981910
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47512795
type: AnswerComment
has text: I agree with you gentlemen, although I doubt the OP wants a numpy solution at this stage.

http://stackoverflow.com/q/47403052
type: UnansweredQuestion
has title: python merge two dataframe with common columns
has comment: http://stackoverflow.com/comment/81759831
type: Question
score: 0
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I am trying to merge two dataframe, which has 3 column with same name. df1 = ['id','first','last','present'] df2 = ['id','first','last','age','date','location'] I want to join on these three common columns, I tried following cols = df2.columns.difference(df1.columns) result = pd.merge(df1, df2[cols_to_use], left_index=True, right_index=True, how='outer') to get ['id','first','last','present','age','date','location'] Is this can be done in step pd.merge ?
has comment: http://stackoverflow.com/comment/81759882
has comment: http://stackoverflow.com/comment/81761124
has comment: http://stackoverflow.com/comment/81760004
answer count: 0

http://stackoverflow.com/q/47528645
tagged with: python
has answer: http://stackoverflow.com/a/47530581
has body: I am try to use nginx proxy odoo server. i changed the /etc/nginx/sites-available/odoo configure file.like this upstream odoo { server 127.0.0.1:8069; } server { listen 443 default; server_name www.cheeseyun.com; access_log /var/log/nginx/oddo.access.log; error_log /var/log/nginx/oddo.error.log; ssl on; ssl_certificate /etc/nginx/ssl/server.crt; ssl_certificate_key /etc/nginx/ssl/server.key; keepalive_timeout 60; ssl_ciphers HIGH:!ADH:!MD5; ssl_protocols SSLv3 TLSv1; ssl_prefer_server_ciphers on; proxy_buffers 16 64k; proxy_buffer_size 128k; location / { proxy_pass http://127.0.0.1:8069; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; } location ~* /web/static/ { proxy_cache_valid 200 60m; proxy_buffering on; expires 864000; proxy_pass http://127.0.0.1:8069; } } server { listen 80; server_name www.cheeseyun.com; add_header Strict-Transport-Security max-age=2592000; rewrite ^/.*$ https://$host$request_uri? permanent; } and use command to test configuer, #service nginx configtest * Testing nginx configuration [ OK ] use another way to test $sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful but when i use command start nginx server , there is no relate process start.no error.log or access.log .so i can't find out what cause this problem.can anyone help to find out the error ?
tagged with: proxy
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47532381
score: 1
has answer: http://stackoverflow.com/a/47532381
downvote count: 0
upvote count: 1
has title: use nginx proxy odoo python server
favorite count: 0
type: Question
tagged with: nginx
tagged with: odoo
possible better answer: http://stackoverflow.com/a/47530581

http://stackoverflow.com/q/47466397
type: Question
linked to: http://stackoverflow.com/q/1534210
score: 5
has answer: http://stackoverflow.com/a/47466745
has comment: http://stackoverflow.com/comment/81888521
type: UnansweredQuestion
has body: I'm working in a shared machine with no root privileges, but Python 2.y installed, but I would like to have both flavors of Python, also I would like to call Python 2.y just typing python (as usual) and for calling Python 3.x, type python3. I understand that this is possible because in my main equipment (whit root access, and the magic of sudo) I can "select" which one to use.
has answer: http://stackoverflow.com/a/59739948
tagged with: python
has comment: http://stackoverflow.com/comment/81887718
has answer: http://stackoverflow.com/a/76119952
downvote count: 2
tagged with: root
answer count: 3
upvote count: 7
has title: How to install python 3.x alongside with 2.y without root privileges
favorite count: 0

http://stackoverflow.com/q/47433987
has answer: http://stackoverflow.com/a/47434191
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47434585
tagged with: python-2.7
answer count: 3
score: 1
has title: Error in converting an array to 2D matrix in Python
downvote count: 0
has body: I have the problem regarding the output of this algorithm. For example: for input chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) it should return [[ 1, 2, 3], [4, 5, 6], [7, 8, '']] but instead it returns [[7, 8, 6], [7, 8, 6], [7, 8, 6]]. However, when m_list is defined under the loop for r in range(rows):, it returns correct value. I can't figure out why it returns wrong value if m_list is defined outside the loop for r in range(rows):. What could be the reason ? # --- Directions # Given an array and chunk size, divide the array into many subarrays # where each subarray is of length size # --- Examples # chunk([1, 2, 3, 4], 2) --&gt; [[ 1, 2], [3, 4]] # chunk([1, 2, 3, 4, 5], 2) --&gt; [[ 1, 2], [3, 4], [5, '']] # chunk([1, 2, 3, 4, 5, 6, 7], 3) --&gt; [[ 1, 2, 3], [4, 5, 6], [7, '', '']] import math def chunk (array, size): rows = 0 l = len(array) if l % size == 0: rows = l/size else: rows = int(math.floor(l/size) + 1) m_list = ['' for e in range(size)] m_matrix = [['' for g in range(size)] for w in range(rows)] i = 0 for r in range(rows): for u in range(size): if i == l: break else: m_list[u] = array[i] i += 1 m_matrix[r] = m_list return m_matrix length = int(raw_input('how many elements you want in the array?: ')) m_inputArray = ['' for q in range(length)] print 'Debug0:--&gt; ' + str(m_inputArray) for z in range(length): p = int(raw_input('Enter the value at index %i: ' %(z))) m_inputArray[z] = p m_inputSize = int(raw_input('Enter the size: ')) result = chunk(m_inputArray, m_inputSize) print result
upvote count: 1
has answer: http://stackoverflow.com/a/47434321
favorite count: 0
type: Question
tagged with: arrays
tagged with: python
tagged with: data-structures
possible better answer: http://stackoverflow.com/a/47434191
accepted answer: http://stackoverflow.com/a/47434585

http://stackoverflow.com/q/47415746
has comment: http://stackoverflow.com/comment/81883659
tagged with: python
tagged with: rewriting
has comment: http://stackoverflow.com/comment/81861782
has answer: http://stackoverflow.com/a/47454169
has comment: http://stackoverflow.com/comment/81862563
accepted answer: http://stackoverflow.com/a/47454169
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81862037
has comment: http://stackoverflow.com/comment/81846356
score: 2
tagged with: list
downvote count: 0
has comment: http://stackoverflow.com/comment/81846048
answer count: 1
favorite count: 0
tagged with: rhino3d
tagged with: string
has body: I have the following working code for Python I produced. It´s a rewriting system based on Lindenmayer. The Output C is: +-LF+RFR+FL-F-+RF-LFL-FR+F+RF-LFL-FR+-F-LF+RFR+FL-+ which I can interpret to draw a space-filling curve. C is the starting letter and the process is performed n times. C = 'L' n = 2 Code = {ord('L'):'+RF-LFL-FR+', ord('R'):'-LF+RFR+FL-'} while n: C = C.translate(Code) n -=1 print C Now I want, that the code is written automatically from a list. For example I have the list R=[['L', '+RF-LFL-FR+'], ['R', '-LF+RFR+FL-']] which should be automatically inserted in the code, so I can use it furthermore. The first element of every sub-list should be inserted in the ord() method and the second after the colon. Any suggestions? I found a way via list comprehension. The List R is L=+RF-LFL-FR+, R=-LF+RFR+FL-. Now I ask if theres a more efficient way to get to the code? R = ['L=+RF-LFL-FR+','R=-LF+RFR+FL-'] A = 'L' for i in range(0,len(R)): R[i]=R[i].split('=') print R Start = [] Rule = [] for i in range(0,len(R)): Start.append(R[i][0]) Rule.append(R[i][1]) #mapping via list comprehension while n: A=''.join([Rule[Start.index(i)] if i in Start else i for i in A]) n -=1 print A
type: Question
has title: Rewriting System for Python L-System

http://stackoverflow.com/q/47405393
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81764514
answer count: 2
has title: Python: regex to match between matches
has body: Text file output has syntax in a form of word&gt; data &lt;word, where the need is to remove the brackets. The data part can be pretty much anything (and of variable length), including new line, spaces, dots, letters etc. Currently i am using... text = re.sub("(&gt;)(.{1,10})(&lt;)", r"\2", text) ...but it has obvious limitations, 1 being length. The reason for not using * is because there are some restrictions, namely: no other &gt; or &lt; can be present inside the match except for its boundaries only 1 number inside the match can form a pattern of single digits, that is dog&gt; 7 4^ 8 0 . 2 1 6? &lt;cat &amp; exam&gt; 1961 5 . 66 9 &lt;ple shall not match, while test&gt; 0? &lt;string or over&gt; 1980 31, 6 000 &lt;flow are fine and brackets shall be removed How can this be approached?
type: Question
possible better answer: http://stackoverflow.com/a/47405846
has comment: http://stackoverflow.com/comment/81764397
has comment: http://stackoverflow.com/comment/81764745
has answer: http://stackoverflow.com/a/47405846
accepted answer: http://stackoverflow.com/a/47465239
has comment: http://stackoverflow.com/comment/81764704
tagged with: python
has answer: http://stackoverflow.com/a/47465239
tagged with: regex
has comment: http://stackoverflow.com/comment/81764605

http://stackoverflow.com/comment/81759625
type: QuestionComment
has text: and where does the 'third' value come from?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47402934

http://stackoverflow.com/q/47410849
has answer: http://stackoverflow.com/a/47410957
favorite count: 0
type: Question
has title: A python class contains an instance of another class, which object will be called first
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: My sample code is below: class Foo: def __init__(self): self.age = 0 def __str__(self): return str(self.age) class Bar: obj_foo = Foo() print obj_foo def __init__(self, name): self.name = name def __str__(self): return str(self.name) obj_bar = Bar("Sam") print obj_bar I want to know the execution flow. Can anyone help me to understand?
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81774921
downvote count: 1

http://stackoverflow.com/q/47392758
score: 40
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47482207
has answer: http://stackoverflow.com/a/47482207
tagged with: python
type: AnsweredQuestion
has title: Improving the performance of pandas groupby
upvote count: 43
tagged with: pandas
answer count: 1
downvote count: 3
has body: I have a machine learning application written in Python which includes a data processing step. When I wrote it, I initially did the data processing on Pandas DataFrames, but when this lead to abysmal performance I eventually rewrote it using vanilla Python, with for loops instead of vectorized operations and lists and dicts instead of DataFrames and Series. To my surprise, the performance of the code written in vanilla Python ended up being far higher than that of the code written using Pandas. As my handcoded data processing code is substantially bigger and messier than the original Pandas code, I haven't quite given up on using Pandas, and I'm currently trying to optimize the Pandas code without much success. The core of the data processing step consists of the following: I first divide the rows into several groups, as the data consists of several thousand time series (one for each "individual"), and I then do the same data processing on each group: a lot of summarization, combining different columns into new ones, etc. I profiled my code using Jupyter Notebook's lprun, and the bulk of the time is spent on the following and other similar lines: grouped_data = data.groupby('pk') datav + 'Diff' for v in val_cols = grouped_data[val_cols].transform(lambda x: x - x.shift(1)).fillna(0) datav + 'Mean' for v in val_cols = grouped_data[val_cols].rolling(4).mean().shift(1).reset_index()[val_cols] (...) ...a mix of vectorized and non-vectorized processing. I understand that the non-vectorized operations won't be faster than my handwritten for loops, since that's basically what they are under the hood, but how can they be so much slower? We're talking about a performance degradation of 10-20x between my handwritten code and the Pandas code. Am I doing something very, very wrong?

scapy
tags question: http://stackoverflow.com/q/47453968
tags question: http://stackoverflow.com/q/47448566
type: Tag
tag name: scapy

http://stackoverflow.com/a/47457213
has body: Your document is parsed as HTML, and the area element is an empty HTML element (cannot have any children). To parse it as XML instead, use BeautifulSoup(xml, "xml") (docs): By default, Beautiful Soup parses documents as HTML. To parse a document as XML, pass in “xml” as the second argument to the BeautifulSoup constructor: soup = BeautifulSoup(markup, "xml") You’ll need to have lxml installed. The other problem is that you have too many quotes surrounding your xml string, so it actually starts with "" (try printing it). Exactly three quotes (""") should suffice.
answers question: http://stackoverflow.com/q/47457069
score: 2
accepted answer of: http://stackoverflow.com/q/47457069
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/47493787
answers question: http://stackoverflow.com/q/47492783
score: 1
type: Answer
has body: You can also say plt.xlim(vel[0], vel[-1]) to directly force your array first and last elements to be the start and end points of your plot.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82021244
comment on: http://stackoverflow.com/q/47530574
type: Comment
type: QuestionComment
score: 0
has text: Add full logging to your URL request inside your code.https://stackoverflow.com/questions/7697963/how-to-debug-urllib2-request-that-uses-a-basic-authentication-handler Paste the full response (strip all personal information from it before you paste).

http://stackoverflow.com/a/47446659
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81848635
has body: One option is to use the replace() function. I've modified your code to include this function. file2= input("Enter the team-names file: ") ## E.g. teamNames.txt bob =open(file2) teamname = [] for line1 in bob: ##loop statement until no more line in file teamname.append(line1.replace("\n","")) print(teamname) Would give you the output: ['Collingwood', 'Essendon', 'Hawthorn', 'Richmond'] You could then modify teamname to get your requested output: print(", ".join(teamname))
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47446626

http://stackoverflow.com/q/47466666
has body: I cant understand the __add__ / __sub__ methods , why they need them , how they work and the overloading concept, Thanks
downvote count: 4
upvote count: 0
tagged with: python
tagged with: magic-methods
type: UnansweredQuestion
score: -4
answer count: 1
favorite count: 0
tagged with: selenium-webdriver
type: Question
has answer: http://stackoverflow.com/a/47466787
has title: Can anyone explain me magic methods and operator overloading in simple words?

http://stackoverflow.com/q/47519729
tagged with: pandas
answer count: 1
type: Question
has title: Read list with titles to pandas dataframe?
accepted answer: http://stackoverflow.com/a/47519795
has answer: http://stackoverflow.com/a/47519795
tagged with: dataframe
tagged with: python
has body: Let's say I have the following list in a file, lets call it data_list.txt: title1 value1 value2 value3 title2 value4 value5 value6 ... The list is long, about 100 titles, each has 1-20 values. I have a list of all the titles, lets call it titles_list. I want to read this file into a 2 column dataframe that looks like this : title1 value1 title1 value2 title1 value3 title2 value4 title2 value5 title2 value6 I have ideas for very ugly solution Iterate the file line by line If current line is from the titles_list save in a variable called current_title the title If current line is not from the titles_list, add it to the dataframe with current_title It will probably work, but I have a feelomh that I'm missing something and pandas has a better solution (or more elegant) Any suggestions ?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82025936
type: Comment
comment on: http://stackoverflow.com/a/47532947
has text: Thats good, because you just send a request and you get a 200 "OK" response. Now you should parse a url. `from xml.etree import ElementTree` can help you
type: AnswerComment
score: 0

http://stackoverflow.com/comment/127940008
type: Comment
has text: Try SLICEmyPDF in 1 of the answers at https://stackoverflow.com/questions/56017702/how-to-extract-table-from-pdf-in-python/72414309#72414309
type: QuestionComment
comment on: http://stackoverflow.com/q/47533875
score: 0

http://stackoverflow.com/a/47398274
downvote count: 0
has body: It looks like you want to map the integer to the target name? # NumPy rather than pandas concatenation might be a bit quicker iris = np.concatenate((iris_raw.data, iris_raw.target[:, None]), axis=1) iris = pd.DataFrame(iris, columns=iris_raw.feature_names + ['tgt_num']) mapped = dict(zip([0, 1, 2], iris_raw.target_names)) iris.loc[:, 'species'] = iris.tgt_num.map(mapped) print(iris) # sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) \ # 0 5.1 3.5 1.4 0.2 # 1 4.9 3.0 1.4 0.2 # 2 4.7 3.2 1.3 0.2 # 3 4.6 3.1 1.5 0.2 # 4 5.0 3.6 1.4 0.2 # # tgt_num species # 0 0.0 setosa # 1 0.0 setosa # 2 0.0 setosa # 3 0.0 setosa # 4 0.0 setosa
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47398008
type: Answer
answers question: http://stackoverflow.com/q/47398008
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47486930
has answer: http://stackoverflow.com/a/47487238
upvote count: 0
accepted answer: http://stackoverflow.com/a/47487238
downvote count: 2
has comment: http://stackoverflow.com/comment/81928816
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: 2d
has comment: http://stackoverflow.com/comment/81928908
has body: The following script generates a 2d list in python: matrix = [[0 for row in range (5)] for col in range (5)] i = 2 matrix[i][i] = 1 matrix[i+1][i] = 1 matrix[i][i+1] = 1 matrix[i+1][i+1] = 1 for row in matrix: for item in row: print(item,end=" ") print() print() The generated 2d list looks like this: 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 0 0 How can I find if I have a square with the same number (number must be 1) like shown up? The square with the same number must be 2x2
has title: Python 2d list value check
score: -2
has answer: http://stackoverflow.com/a/47487281
tagged with: python
has answer: http://stackoverflow.com/a/47487075
possible better answer: http://stackoverflow.com/a/47487075
has comment: http://stackoverflow.com/comment/81928933
has comment: http://stackoverflow.com/comment/81928697
tagged with: list
answer count: 3

http://stackoverflow.com/comment/81986869
type: QuestionComment
has text: @VivekKumar Thank you very much. May I ask you if you also have an answer to the other questions?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47514568

http://stackoverflow.com/q/47410242
score: 1
has comment: http://stackoverflow.com/comment/82881321
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47410542
upvote count: 2
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has title: Forming pandas dataframe from txt
has body: Given a .txt file consisting of a long string of space-separated numbers 12 0 84 9 5 1 49 ...... I want to create a pandas dataframe such that the first 500 numbers form the first column, the next 500 numbers the 2nd column, etc. (in total 10000 columns). How can this be implemented in python?
tagged with: pandas

http://stackoverflow.com/q/47452993
type: AnsweredQuestion
tagged with: for-loop
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/81861348
has body: I need someones opinion on how to extract and save the array data in one output file from this script. Files3 contain set number dataset files in Latitude, Longitude and Rainfall. Each dataset is arranged just like this: Latitude Longitude Rainfall -5.000 95.000 0.000 -4.900 95.000 0.000 -4.800 95.000 0.000 -4.700 95.000 0.000 -4.600 95.000 0.000 Objective : How to save all the dataset especially the rainfall and saved in file into this array. The problem is the output only picked up only one dataset. Latitude Longitude Rainfall1 Rainfall2 Rainfall3 Rainfall4 . . -5.000 95.000 0.000 0.000 0.000 0.000 -4.900 95.000 5.7 0 0.000 0.000 23.9 -4.800 95.000 0.000 10.4 0.000 0.000 -4.700 95.000 0.000 0.000 0.000 0.000 -4.600 95.000 0.000 0.000 0.000 0.000 The halfway script that I am using is just as follows: import numpy as np import matplotlib.pyplot as plt files=np.loadtxt('files3',dtype=str) for x in files: data=np.loadtxt(x) lat=data[:,0] lon=data[:,1] rain=data[:,2] rain=[lat,lon,rain] data1=np.array(rain) data1=data1.T np.savetxt( 'build-mean1.dat2',data1,fmt='%9.3f')
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81860915
has comment: http://stackoverflow.com/comment/81863848
tagged with: python
has comment: http://stackoverflow.com/comment/81863500
has answer: http://stackoverflow.com/a/47474075
accepted answer: http://stackoverflow.com/a/47474075
has title: Save array data in one output file using for loop Python

http://stackoverflow.com/a/47521302
upvote count: 1
answers question: http://stackoverflow.com/q/47521206
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81999334
score: 1
has comment: http://stackoverflow.com/comment/81999286
has body: I think the error message is clear Message: Unable to locate element: #tab-item-1090 > md-icon:nth-child(1). So basically when the test is running the selector is not correct and it doesn't find the element in your web app. I would suggest adding a unique id for example click me on that element (button or tab) in your web app and replace the #tab-item-1090 > md-icon:nth-child(1) with that foo. Edit: For more help why #tab-item-1090 > md-icon:nth-child(1) is not working we need to see the DOM of the web app.

http://stackoverflow.com/comment/81743297
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47394322
type: AnswerComment
has text: @ArneRecknagel I mean that when you already apply transformations within the function that is supposed to yield the data, then it is not straightforward to just get the untransformed data (if you ever need it). It's better to have things separated: One function yields the data, others transform it. Like that you can choose which transformations you want to apply, and things are also separately maintainable. Plus it feels more natural i.m.o.

http://stackoverflow.com/comment/81949234
comment on: http://stackoverflow.com/q/47496949
score: 0
type: Comment
type: QuestionComment
has text: @SPSP I need to do it in another line of code. EG: daysOfWeek.append[ ]

http://stackoverflow.com/q/47523325
tagged with: scipy
favorite count: 0
type: Question
has body: I am trying to do a brute force optimization in SciPy. (imported scipy.optimize as spo) res_brute = spo.brute(self.minimize_this, rranges, full_output=True, finish=spo.fmin) My question is: How do I make sure spo.fmin stops after N iterations? I can't seem to pass it any arguments.
tagged with: python
has title: How to pass max iterations to fmin in scipy brute optimization
score: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47524053

http://stackoverflow.com/comment/82075069
type: QuestionComment
comment on: http://stackoverflow.com/q/47502650
type: Comment
has text: More feedback. Once you post a question and comments come it is OK to edit the question, to improve what people ask you about and what isn't clear. But as answers start coming in it is better to _not_ tweak the question any more since that way you will likely invalidate what people answered. (Very small tweaks can change the question in a way that's hard to tell.) In this case, your added code makes this question morph into something else. It makes it a moving target; you don't want that.
score: 1

http://stackoverflow.com/comment/82022864
type: QuestionComment
has text: Just to make sure: You installed `sudo pip3 install plotly` and not plotply as you wrote, right?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47533128

http://stackoverflow.com/comment/81901184
has text: thanks for the answer. This is what I was looking for. But, can you also edit to add a custom hour? thank you
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47472986

http://stackoverflow.com/comment/81899899
has text: why exactly do you need the `map` function? Wouldn't it also be possible with `str(x)`?
comment on: http://stackoverflow.com/a/47472666
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/81977532
comment on: http://stackoverflow.com/a/47510424
type: AnswerComment
score: 0
has text: @Divakar: thanks for your answer. I ended up using COLDSPEED's but all answers are super cool, it's really a subjective call.
type: Comment

http://stackoverflow.com/q/47455294
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/47492027
type: AnsweredQuestion
answer count: 1
downvote count: 0
has title: Asynchronous GPU memory transfer with cupy
has body: Is it possible to asynchronously transfer memory from/to GPU with cupy (or chainer)? I'm training a relatively small network with very large data that does not fit into the GPU memory. This data should be kept on CPU memory and provided to GPU for its minibatch calculation sequentially. The memory transfer time is the dominant bottleneck of this application. I think the asynchronous memory transfer solves this problem, i.e. during the calculation of one minibatch, another minibatch is transferred to GPU in the background. I'm wondering it would be possible with cupy.cuda.Stream class, but I have no idea yet. I would appreciate any comments/advice. EDIT: I thought the following codes makes asynchronous memory transfer, but not. import numpy as np import cupy as cp a_cpu = np.ones((10000, 10000), dtype=np.float32) b_cpu = np.ones((10000, 10000), dtype=np.float32) a_stream = cp.cuda.Stream(non_blocking=True) b_stream = cp.cuda.Stream(non_blocking=True) a_gpu = cp.empty_like(a_cpu) b_gpu = cp.empty_like(b_cpu) a_gpu.set(a_cpu, stream=a_stream) b_gpu.set(b_cpu, stream=b_stream) # This should start before b_gpu.set() is finished. a_gpu *= 2 The nvvp shows the memory transfer takes place sequentially.
favorite count: 0
upvote count: 11
type: Question
tagged with: chainer
accepted answer: http://stackoverflow.com/a/47492027
tagged with: cupy

http://stackoverflow.com/q/47399830
type: UnansweredQuestion
has title: Show plots in new window instead of inline (not answered by previous posts)
has answer: http://stackoverflow.com/a/49325603
downvote count: 0
has comment: http://stackoverflow.com/comment/81804668
tagged with: interactive
answer count: 1
tagged with: plot
favorite count: 0
has body: Several existing posts address this question, but none of the solutions worked for me. I am using Spyder 3.2.4 with Python 3.6. I'd like plots to show up in a new window instead of as tiny in-line figures in the IPython console. I tried Tools > Preferences > IPython console > Graphics > Graphics backend > Automatic. I also tried Qt5 and Qt4 here, and closed and reopened the file I was trying to run (see code below). I also tried matplotlib qt directly in the console, with no result. I checked whether the windows might be popping up in the background, but they are not. Any ideas? Code: import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = x**2 plt.ion() plt.plot(x,y) plt.show()
type: Question
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/81754062
tagged with: matplotlib
tagged with: spyder
tagged with: python

http://stackoverflow.com/comment/82022832
type: AnswerComment
comment on: http://stackoverflow.com/a/47531972
has text: If not convert to datetime/period there is some problem with plot?
score: 0
type: Comment

http://stackoverflow.com/comment/81905958
has text: @NicoSchertler: Hi Nico, you are right if directly setting `w=0, b=0`, job is done. I'm trying to simulate the gradient descent and observe that the cost is approaching to zero. Can you elaborate more on `sigmoid_prime` and the derivatives? Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47475240
score: 0

http://stackoverflow.com/a/47450128
has comment: http://stackoverflow.com/comment/81856410
type: Answer
has comment: http://stackoverflow.com/comment/81856540
score: 0
has body: Your css selector seems to be wrong. You're trying to select tr:nth-child(7), however, I believe that it should be tr:nth-child(3)
answers question: http://stackoverflow.com/q/47450075

http://stackoverflow.com/comment/82002027
comment on: http://stackoverflow.com/q/47520820
type: QuestionComment
has text: `TypeError: can't multiply sequence by non-int of type 'float'` does not happen when they are both numpy arrays. Something is a list or a tuple or some other sequence and *not* a numpy array. Print `type(variable)` for each variable being multiplied, and you'll see something isn't a numpy array. You didn't show your definitions of `momentum_mu` and `momentum_v`, perhaps they're the offenders? For e.g. see my answer from earlier today [here](https://stackoverflow.com/questions/47520890/error-cant-multiply-sequence-by-non-int-of-type-float/47521032#47521032) from the same error message.
score: 0
type: Comment

http://stackoverflow.com/q/47444272
has body: I need to perform brain extraction on .nii images. I am using Anaconda on Windows 10 and have an environment based on Python 3.5.4. On Nipype I found the BET from FSL and I followed the code: mybet = fsl.BET() mybet.inputs.in_file = 'example.nii' mybet.inputs.out_file = 'example_bet.nii' result = mybet.run() Please note that I expect the output file example_bet.nii to be created by fsl.BET, not to be an image to be overwritten. I can only find solutions based on Unix systems and it seems one needs to have FSL installed on a Unix-based OS, which is not possible without a Virtual Machine in Windows. Well, this is the output I get: 171122-12:02:48,988 interface WARNING: FSLOUTPUTTYPE environment variable is not set. Setting FSLOUTPUTTYPE=NIFTI --------------------------------------------------------------------------- OSError Traceback (most recent call last) &lt;ipython-input-12-5b900fbd5263&gt; in &lt;module&gt;() 2 mybet.inputs.in_file = 'prova.nii' 3 mybet.inputs.out_file = 'prova_bet.nii' ----&gt; 4 result = mybet.run() ~\Anaconda3\envs\tensorflow\lib\site-packages\nipype\interfaces\base.py in run(self, **inputs) 1079 version=self.version) 1080 try: -&gt; 1081 runtime = self._run_wrapper(runtime) 1082 outputs = self.aggregate_outputs(runtime) 1083 runtime.endTime = dt.isoformat(dt.utcnow()) ~\Anaconda3\envs\tensorflow\lib\site-packages\nipype\interfaces\base.py in _run_wrapper(self, runtime) 1722 1723 def _run_wrapper(self, runtime): -&gt; 1724 runtime = self._run_interface(runtime) 1725 return runtime 1726 ~\Anaconda3\envs\tensorflow\lib\site-packages\nipype\interfaces\fsl\preprocess.py in _run_interface(self, runtime) 142 # in stderr and if it's set, then update the returncode 143 # accordingly. --&gt; 144 runtime = super(BET, self)._run_interface(runtime) 145 if runtime.stderr: 146 self.raise_exception(runtime) ~\Anaconda3\envs\tensorflow\lib\site-packages\nipype\interfaces\base.py in _run_interface(self, runtime, correct_return_codes) 1748 if not exist_val: 17…
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47446288
tagged with: nipype
has title: "command 'bet' could not be found on host" error while using BET in FSL on Windows 10 via Python 3.5
has answer: http://stackoverflow.com/a/47446288
answer count: 1
tagged with: image-processing
type: Question
tagged with: bioinformatics
tagged with: windows
tagged with: python

http://stackoverflow.com/q/47458805
has answer: http://stackoverflow.com/a/47458806
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/52179739
tagged with: pyspark
has body: I was trying to write to MongoDB a Spark dataframe that contains the string representation of an ObjectId that is the _id of another collection. The point is that PySpark has no support for ObjectId (Scala and Java ObjectId support explained here: https://github.com/mongodb/mongo-spark/blob/master/doc/1-sparkSQL.md) so, how could I insert an ObjectId into MongoDB from PySpark using the Spark Connector?
tagged with: python
accepted answer: http://stackoverflow.com/a/47458806
answer count: 4
possible better answer: http://stackoverflow.com/a/52179739
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/76039731
has title: Write PySpark dataframe to MongoDB inserting field as ObjectId
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/74130352
favorite count: 0

http://stackoverflow.com/comment/81857522
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47451334
has text: Hint: Try out max(score)

http://stackoverflow.com/comment/81905488
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47475240
score: 0
has text: Your derivatives don't look correct (both the `sigmoid_prime` and the derivatives of your cost).

http://stackoverflow.com/comment/81939965
has text: @Danny_ds I decided to leave that line as it is in the OP's code because I wanted to focus on the regex stuff, since that's the main thing that can be improved. Yes, `"};" in nextLine` does do a linear scan of the line, but that scan runs at C speed, so it's faster than if you tried to search for it using a Python loop. Sure, I could just check the first 2 chars of the line (they aren't bytes in Python 3, since it uses Unicode for text), eg by using the `.startswith` method, but then I'd have to assume there are no leading spaces, or pass the line through `.strip` first to trim off whitespace.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47490988
type: AnswerComment

http://stackoverflow.com/comment/81757714
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47401829
has text: @juanpa.arrivillaga That is also an issue, but I believe a different one than the OP is facing. They want the output to be without the "www." part!
type: Comment

http://stackoverflow.com/comment/81965150
comment on: http://stackoverflow.com/a/47504352
type: Comment
type: AnswerComment
has text: @TysonDogerzonda your error appears to be non-trivial. Looking into it a bit via `pdb`, it appears that `self.ready = False` erroneously during the execution of `update_check` (and therefore `_update_check`) --- see line 240 [here](https://github.com/JMSwag/PyUpdater/blob/master/pyupdater/client/__init__.py) in the source of pyupdater. Calling `client.refresh()` beforehand points towards an issue in `_get_key_data` at line 433. Specifically, at line 441 an `IOError` is raised trying to unzip the gziped file. At this point, chasing the bug seems like too much work. Hopefully this helps
score: 0

http://stackoverflow.com/comment/81820197
type: Comment
comment on: http://stackoverflow.com/q/47425374
type: QuestionComment
has text: @user3525290 Not quite, you put the div tags around brackets to say you want to capture these matches so that you can use backreferences (`\1`, `\2`) to refer back to them again in the replacement string, you can read more about it [here](https://docs.python.org/3/howto/regex.html#search-and-replace) around 3 examples down. The other answers have suggested using [lookaround](https://www.regular-expressions.info/lookaround.html) assertions which are equally valid and could be cleaner solutions.
score: 0

http://stackoverflow.com/a/47515769
has comment: http://stackoverflow.com/comment/81988239
has body: you can do it without pycharm by open a terminal (linux , mac os) or cmd (windows) and running pip install pandas pip install numpy
has comment: http://stackoverflow.com/comment/81988674
answers question: http://stackoverflow.com/q/47515386
type: Answer
has comment: http://stackoverflow.com/comment/81989543
score: 0
has comment: http://stackoverflow.com/comment/81988115

http://stackoverflow.com/comment/82026968
has text: You don't need the `if __name__ == '__main__':` as an umbrella for a toplevel script. That is just a common pattern for a module defining several fucntins and classes that can have a stand alone use, or be imported as part of another program
type: QuestionComment
comment on: http://stackoverflow.com/q/47534996
score: 0
type: Comment

http://stackoverflow.com/q/47429525
tagged with: python-3.x
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
has title: Python: Requests to local server not working
has body: I am using the python library requests to attempt to send a post request to my local server. I have successfully installed and imported requests--I just can't seem to post or get data from my local server. Both the server and my python program are on the same machine, the server is currently Django's development server. What I am trying: domain = 'localhost:8000' user = 'username' password = 'password' data = 'some data to be sent' r = requests.post(domain, data auth=(user,password)) Exception raised: raise InvalidSchema("No connection adapters were found for '%s'" % url) requests.exceptions.InvalidSchema: No connection adapters were found for 'localhost:8000' I have done all the basic things like ensuring that the server was up and running. I have also tried to substitue localhost with 127.0.0.1:8000.
answer count: 1
downvote count: 0
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/47429544
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47429544

http://stackoverflow.com/q/47442632
downvote count: 2
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/47442740
tagged with: python
score: -1
tagged with: flask
has answer: http://stackoverflow.com/a/47442740
has comment: http://stackoverflow.com/comment/81840400
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47442724
answer count: 2
has comment: http://stackoverflow.com/comment/81841611
has answer: http://stackoverflow.com/a/47442724
has title: How to write a Python for loop in an HTML file?
upvote count: 1
favorite count: 0
type: Question
has body: Let's say you pass through a Python list to an HTML file using Flask. How do you loop through that list by writing Python code in the HTML file?

http://stackoverflow.com/a/47419770
has comment: http://stackoverflow.com/comment/81797219
answers question: http://stackoverflow.com/q/47418061
type: Answer
accepted answer of: http://stackoverflow.com/q/47418061
has comment: http://stackoverflow.com/comment/81798689
score: 2
has comment: http://stackoverflow.com/comment/81797165
has comment: http://stackoverflow.com/comment/81798854
upvote count: 2
type: AcceptedAnswer
has body: You should parallelize what you are doing. Since most of the time spent by your function is waiting, you can verify a lot of works at once (not limited to your number of processors). Example: import pythonwhois from joblib import Parallel, delayed, cpu_count n_jobs = 100 # works in parallel def f(domain): details = pythonwhois.get_whois(domain) if 'No match for' in str(details): # simple but it works! print(domain) return domain else: return None domains= ['aaa.com', 'bbb.com', 'ccc.com', 'bbbaohecraoea.com'] result = Parallel(n_jobs=n_jobs, verbose=10)(delayed(f)(domain) for domain in domains) # create a list with the available domains available_domains=[domains[idx] for idx,r in enumerate(result) if r!=None] print(available_domains) # Result # ['bbbaohecraoea.com']
downvote count: 0
has comment: http://stackoverflow.com/comment/81799074
has comment: http://stackoverflow.com/comment/81799502
has comment: http://stackoverflow.com/comment/81800036

http://stackoverflow.com/a/47479709
has body: From your comment it sounds like you've resolved the issue, but to be explicit about it: in python2 / performs integer division if applied to integers, which returns 0 in all your examples. Changing 255 to 255.0 makes sure python performs the float division you want.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47470040
score: 0
accepted answer of: http://stackoverflow.com/q/47470040
type: Answer

sorting
tags question: http://stackoverflow.com/q/47509504
tags question: http://stackoverflow.com/q/47423040
tags question: http://stackoverflow.com/q/47460112
tags question: http://stackoverflow.com/q/47401829
tags question: http://stackoverflow.com/q/47445539
tags question: http://stackoverflow.com/q/47509233
tags question: http://stackoverflow.com/q/47539919
tags question: http://stackoverflow.com/q/47523386
tags question: http://stackoverflow.com/q/47466040
tags question: http://stackoverflow.com/q/47431431
tags question: http://stackoverflow.com/q/47494929
tags question: http://stackoverflow.com/q/47415876
tags question: http://stackoverflow.com/q/47492395
tags question: http://stackoverflow.com/q/47396893
tags question: http://stackoverflow.com/q/47400311
tags question: http://stackoverflow.com/q/47396680
tags question: http://stackoverflow.com/q/47386541
tags question: http://stackoverflow.com/q/47454716
tags question: http://stackoverflow.com/q/47539815
tags question: http://stackoverflow.com/q/47539789
tags question: http://stackoverflow.com/q/47469996
tags question: http://stackoverflow.com/q/47385617
tags question: http://stackoverflow.com/q/47521264
tags question: http://stackoverflow.com/q/47520888
tag name: sorting
tags question: http://stackoverflow.com/q/47422762
tags question: http://stackoverflow.com/q/47522199
tags question: http://stackoverflow.com/q/47402954
tags question: http://stackoverflow.com/q/47396602
tags question: http://stackoverflow.com/q/47513274
tags question: http://stackoverflow.com/q/47434924
tags question: http://stackoverflow.com/q/47510098
tags question: http://stackoverflow.com/q/47421681
tags question: http://stackoverflow.com/q/47537322
tags question: http://stackoverflow.com/q/47486683
tags question: http://stackoverflow.com/q/47383380
tags question: http://stackoverflow.com/q/47435092
type: Tag
tags question: http://stackoverflow.com/q/47449818
tags question: http://stackoverflow.com/q/47472245

http://stackoverflow.com/q/47540629
has comment: http://stackoverflow.com/comment/82038921
tagged with: python
has title: How to get and set data attributes of a class?
has comment: http://stackoverflow.com/comment/82040073
has comment: http://stackoverflow.com/comment/82039097
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82041023
has comment: http://stackoverflow.com/comment/82039243
score: 0
type: UnansweredQuestion
answer count: 1
has body: I want to implement 3D vector in Python that stores its components in a numpy array (or another container). And I want to access the components as x, y and z in order to get and set them. What is the best way to do it? I implemented it like this: import numpy as np class Vector3d: components = ['x', 'y', 'z'] def __init__(self): self._data = np.array([0.0, 0.0, 0.0]) def __getattr__(self, key): if key in self.components: index = self.components.index(key) return self._data[index] else: return super().__getattr__(key) def __setattr__(self, key, value): if key in self.components: index = self.components.index(key) self._data[index] = value else: return super().__setattr__(key, value) def __repr__(self): return repr(self._data) def norm(self): return np.linalg.norm(self._data) a = Vector3d() a.x = 1.2 a.y = 2.3 a.z = 3.4 print(a.x, a.y, a.z) print(a) print(a.norm()) What I dislike in it. First, I duplicated the code if key in self.components: index = self.components.index(key). Second, searching for the index every time seems to be non-optimal towards the consuming time. I believe there's a better way to implement it. Please, suggest me your approaches. I'm searching for a solution for Python 3.
has comment: http://stackoverflow.com/comment/82046547
has answer: http://stackoverflow.com/a/47541758

http://stackoverflow.com/a/47430940
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47430891
has body: from pymc3.math import switch should work. from theano.tensor import switch should also work.
answers question: http://stackoverflow.com/q/47430891
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81869236
score: 0
has text: You do not need tf functions on non-tensors object
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47457344

http://stackoverflow.com/q/47482942
has comment: http://stackoverflow.com/comment/81920826
downvote count: 1
accepted answer: http://stackoverflow.com/a/47483531
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47483531
has answer: http://stackoverflow.com/a/47483151
has title: Python - RecursionError: maximum recursion depth exceeded in comparison error
duplicate of: http://stackoverflow.com/q/3323001
tagged with: python
linked to: http://stackoverflow.com/q/3323001
possible better answer: http://stackoverflow.com/a/47483151
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81920990
upvote count: 2
has body: I wrote a simple code for a simple task, but I keep getting error message RecursionError: maximum recursion depth exceeded in comparison I have already spent a lot of time looking into it, but can't seem to figure it out. def printMultiTable(high): i = 1 while i &lt;= high: printMultiTable(i) i +=1 printMultiTable(7) The result I am expecting.
score: 1
has comment: http://stackoverflow.com/comment/81920891

http://stackoverflow.com/comment/81960559
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47502408
has text: Actually, this is printing `5` for me, so I'm probably wrong.
score: 0

http://stackoverflow.com/a/47471905
answers question: http://stackoverflow.com/q/47471817
has body: Not sure can you take this as an example? import uuid ... uuid = models.UUIDField(unique=True, default=uuid.uuid1, null=True, blank=True) here the uuid.uuid1 is just a method, not called. def uuid1(node=None, clock_seq=None): """Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the hardware address. If 'clock_seq' is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.""" # When the system provides a version-1 UUID generator, use it (but don't # use UuidCreate here because its UUIDs don't conform to RFC 4122). if _uuid_generate_time and node is clock_seq is None: _buffer = ctypes.create_string_buffer(16) _uuid_generate_time(_buffer) return UUID(bytes=bytes_(_buffer.raw)) global _last_timestamp import time nanoseconds = int(time.time() * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = int(nanoseconds/100) + 0x01b21dd213814000 if _last_timestamp is not None and timestamp &lt;= _last_timestamp: timestamp = _last_timestamp + 1 _last_timestamp = timestamp if clock_seq is None: import random clock_seq = random.randrange(1&lt;&lt;14) # instead of stable storage time_low = timestamp &amp; 0xffffffff time_mid = (timestamp &gt;&gt; 32) &amp; 0xffff time_hi_version = (timestamp &gt;&gt; 48) &amp; 0x0fff clock_seq_low = clock_seq &amp; 0xff clock_seq_hi_variant = (clock_seq &gt;&gt; 8) &amp; 0x3f if node is None: node = getnode() return UUID(fields=(time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node), version=1)
score: 0
type: Answer

http://stackoverflow.com/q/47460332
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81875862
has comment: http://stackoverflow.com/comment/81875873
score: 0
has comment: http://stackoverflow.com/comment/81875758
tagged with: pandas
has body: In Python3 and pandas I have two dataframes, "doacoes_cnpjs" and "te" doacoes_cnpjs.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 22811 entries, 0 to 47353 Data columns (total 19 columns): UF 22811 non-null object Partido_x 22811 non-null object Cargo_x 22811 non-null object Nome_candidato_x 22811 non-null object CPF_candidato 22811 non-null int64 CPF_CNPJ_doador 22811 non-null float64 Nome_doador 22811 non-null object Nome_doador_Receita 22811 non-null object Valor 22811 non-null float64 CPF_CNPJ_doador_originario 22811 non-null object Nome_doador_originario 22811 non-null object Nome_doador_originario_Receita 22811 non-null object Estado 22811 non-null object Cargo_y 22811 non-null object Nome_candidato_y 22811 non-null object CPF 22811 non-null int64 Nome_urna 22811 non-null object Partido_y 22811 non-null object Situacao 22811 non-null object dtypes: float64(2), int64(2), object(15) memory usage: 3.5+ MB te.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 5541 entries, 0 to 5664 Data columns (total 13 columns): DATA_LS 4118 non-null object DATA_INCLUS 2957 non-null object Proprietario 5541 non-null object Nome_propriedade 5541 non-null object Municipio 5525 non-null object Estado 5533 non-null object CNPJ_CPF_CEI 5541 non-null object CNPJ_CPF_CEI_limpo 5541 non-null float64 Trab_Envolv 4529 non-null float64 Ramo_atividade 2840 non-null object Localizacao 2734 non-null object Cod_ativ 2975 non-null object Tipo_lista 5541 non-null object dtypes: float64(2), object(11) memory usage: 606.0+ KB Dataframes have two columns with the same type of code - "CPF_CNPJ_doador" and "CNPJ_CPF_CEI_limpo". They are codes with integers, with 13 or 14 digits Example: "6158959000136", "78141843000103", "46991295000106", "5351494000172" ... I want to create a new dataframe from a comparison of "doacoes_cnpjs" and "te", using the columns "CPF_CNPJ_doador" and "CNPJ_CPF_CEI_limpo". But it can not be a common merge I want to compare only the first eight nu…
tagged with: python
has comment: http://stackoverflow.com/comment/81876285
has comment: http://stackoverflow.com/comment/81875609
has comment: http://stackoverflow.com/comment/81879663
type: Question
has title: How to compare two columns in pandas, with only part of codes?
answer count: 0

http://stackoverflow.com/comment/124459345
score: 0
type: AnswerComment
has text: This. Needs more upvotes, though.
comment on: http://stackoverflow.com/a/47492875
type: Comment

http://stackoverflow.com/a/47470711
score: 2
has comment: http://stackoverflow.com/comment/81901100
has comment: http://stackoverflow.com/comment/81898825
type: Answer
has comment: http://stackoverflow.com/comment/81896811
has comment: http://stackoverflow.com/comment/81901129
accepted answer of: http://stackoverflow.com/q/47469947
has comment: http://stackoverflow.com/comment/81898933
has body: Here's one approach - def patchify(img, patch_shape, stepsize_x=1, stepsize_y=1): strided = np.lib.stride_tricks.as_strided x, y = patch_shape p,q = img.shape[-2:] sp,sq = img.strides[-2:] out_shp = img.shape[:-2] + (p-x+1,q-y+1,x,y) out_stride = img.strides[:-2] + (sp,sq,sp,sq) imgs = strided(img, shape=out_shp, strides=out_stride) return imgs[...,::stepsize_x,::stepsize_y,:,:] Sample runs - 1] Input : In [156]: np.random.seed(0) In [157]: img = np.random.randint(11,99,(2,4,4)) In [158]: img Out[158]: array([[[55, 58, 75, 78], [78, 20, 94, 32], [47, 98, 81, 23], [69, 76, 50, 98]], [[57, 92, 48, 36], [88, 83, 20, 31], [91, 80, 90, 58], [75, 93, 60, 40]]]) 2] Output - Case #1 : In [159]: patchify(img, (2,2), stepsize_x=1, stepsize_y=1)[0] Out[159]: array([[[[55, 58], [78, 20]], [[58, 75], [20, 94]], [[75, 78], [94, 32]]], [[[78, 20], [47, 98]], [[20, 94], [98, 81]], [[94, 32], [81, 23]]], [[[47, 98], [69, 76]], [[98, 81], [76, 50]], [[81, 23], [50, 98]]]]) 3] Output - Case #2 : In [160]: patchify(img, (2,2), stepsize_x=2, stepsize_y=1)[0] Out[160]: array([[[[55, 58], [78, 20]], [[58, 75], [20, 94]], [[75, 78], [94, 32]]], [[[47, 98], [69, 76]], [[98, 81], [76, 50]], [[81, 23], [50, 98]]]]) 4] Output - Case #3 : In [161]: patchify(img, (2,2), stepsize_x=2, stepsize_y=2)[0] Out[161]: array([[[[55, 58], [78, 20]], [[75, 78], [94, 32]]], [[[47, 98], [69, 76]], [[81, 23], [50, 98]]]])
has comment: http://stackoverflow.com/comment/81896830
upvote count: 2
answers question: http://stackoverflow.com/q/47469947
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81898721

http://stackoverflow.com/q/47505488
has answer: http://stackoverflow.com/a/47505569
has answer: http://stackoverflow.com/a/47584675
tagged with: amazon-lex
tagged with: aws-lambda
type: Question
has title: Check sentiment of user in AWS Lex
has answer: http://stackoverflow.com/a/47505584
tagged with: python
tagged with: amazon-web-services
has body: How do we check user sentiment in AWS Lex by checking what user has said? Is there any built-in functionality available in Lex or some other AWS service?
type: AnsweredQuestion
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/47505569
possible better answer: http://stackoverflow.com/a/47584675

http://stackoverflow.com/a/47509389
has comment: http://stackoverflow.com/comment/123042244
upvote count: 30
score: 30
has comment: http://stackoverflow.com/comment/125164489
type: Answer
has body: My guess is that the driver gets garbage collected, in C++ the objects inside a function (or class) get destroyed when out of context. Python doesn´t work quite the same way but its a garbage collected language. Objects will be collected once they are no longer referenced. To solve your problem you could pass the object reference as an argument, or return it. def launchBrowser(): chrome_options = Options() chrome_options.binary_location="../Google Chrome" chrome_options.add_argument("start-maximized"); driver = webdriver.Chrome(chrome_options=chrome_options) driver.get("http://www.google.com/") return driver driver = launchBrowser()
answers question: http://stackoverflow.com/q/47508518
downvote count: 0
has comment: http://stackoverflow.com/comment/126069387

http://stackoverflow.com/a/47531592
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47531563
type: Answer
score: 29
has comment: http://stackoverflow.com/comment/85102510
upvote count: 29
has body: There's nothing wrong with python. The reason is simple: Your module is importing itself (because it is also named random) - this has to do with the lookup mechanics of python. python will try to import from your root folder first, before modules from pythonpath are imported. From the docs: When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: The directory containing the input script (or the current directory when no file is specified). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). The installation-dependent default.
has comment: http://stackoverflow.com/comment/135392653
answers question: http://stackoverflow.com/q/47531563

http://stackoverflow.com/comment/81883560
comment on: http://stackoverflow.com/q/47464418
score: 1
type: QuestionComment
has text: `node.generatenodes()` must be returning a list which you append to `opentable`. When you `pop` it into `node` you then expect `node` to be a `Nodes` object with `depth`, but it's a `list` object, with no `depth`.
type: Comment

http://stackoverflow.com/comment/81913593
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47479275
has text: Possible duplicate of [How to count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-to-count-the-occurrences-of-a-list-item)
score: 3

http://stackoverflow.com/comment/81739706
comment on: http://stackoverflow.com/q/47393433
has text: Mysql in READ-COMMITTED
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47397292
score: 0
answers question: http://stackoverflow.com/q/47397191
type: Answer
has body: First, reg = re.findall( can return an empty list, so test if list contains something before doing if string in reg[0][0]: I'd suggest: if reg and reg[0] and string in reg[0][0]: Then, the memory error could happen if you're hitting a veeeery long line which exceeds python memory. Unlikely, but can be done if the file is corrupt / the generation process "forgets" to issue newlines for a while, in which case you have to get the input fixed, otherwise the code will be really more complex.

http://stackoverflow.com/q/47459727
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81875801
has comment: http://stackoverflow.com/comment/81874666
has comment: http://stackoverflow.com/comment/81874740
tagged with: python
has comment: http://stackoverflow.com/comment/81874924
has title: Python and Button presses
has body: I have a project going right now on a Raspberry Pi running the most current version of Jessie OS. On this project, I would like to incorporate some buttons that would run bash scripts. I've been over the code a hundred time and made like 100 different versions of it and I keep running into the same issue. I'm using subprocess.call to start the script but then the program won't accept any more button presses just stuck on that script. I press button on input 7 and first script runs then no other button presses are recognized. I am a Python noob but I like to tinker any help would be appreciated. #!/bin/bash import RPi.GPIO as GPIO import time import os import subprocess GPIO.setmode(GPIO.BCM) GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(8, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: input_state = GPIO.input(7) if input_state == 0: print "start show" subprocess.call('/home/pi/lightshowpi/bin/lights.sh') time.sleep(0.5) input_state1 = GPIO.input(8) if input_state1 == 0: print "cleanup" subprocess.call('/home/pi/lightshowpi/bin/cleanup.sh') time.sleep(0.2) subprocess.call('/home/pi/lightshowpi/bin/lightson.sh')
answer count: 0
has comment: http://stackoverflow.com/comment/81874601
type: UnansweredQuestion
score: 1
tagged with: gpio
downvote count: 0
tagged with: button
has comment: http://stackoverflow.com/comment/81875649
has comment: http://stackoverflow.com/comment/81874978
upvote count: 1
has comment: http://stackoverflow.com/comment/81875171

http://stackoverflow.com/q/47455969
has answer: http://stackoverflow.com/a/47459022
has title: Make a plot for specific x-axis values and mark with * (x,y) values in the plot
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
score: -1
tagged with: plot
has comment: http://stackoverflow.com/comment/81867148
upvote count: 0
has comment: http://stackoverflow.com/comment/81872466
has comment: http://stackoverflow.com/comment/81867870
has comment: http://stackoverflow.com/comment/81866887
has comment: http://stackoverflow.com/comment/81867650
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81868977
favorite count: 0
type: Question
has body: l would like to get my plot with x-axis values following only c values, such that c=[0.000001,0.00001,0.0001,0.001,0.01,1.0]. In other way. l would like to show the y value for each c . Then mark in the plot the (c,y) values with * or squares. Here is what l tried : from sklearn.svm import LinearSVC penalty_param=[] lin_svm=[] lin_svm_train=[] for c in (0.000001,0.00001,0.0001,0.001,0.01,1.0): penalty_param.append(c) clf = LinearSVC(C=c) clf.fit(X_train,y_train) lin_svm.append(clf.score(X_test,y_test)) lin_svm_train.append(clf.score(X_train,y_train)) fig2, ax2 = plt.subplots() ax2.set_xslim((0.000001,0.00001,0.0001,0.001,0.01,1.0)) ax2.plot(penalty_param,lin_svm,label='Test accuracy',marker='o') ax2.plot(penalty_param,lin_svm_train,label='Train accuracy ',marker='*') ax2.set_xlabel(" C : penalty parameter") ax2.set_ylabel("Accuracy") ax2.legend(loc='best') ax2.set_title(' Linear SVM classifier accuracy in terms of C parameter') fig2.show() l got the following : What is wrong with my code ? EDIT-1

http://stackoverflow.com/q/47438082
has comment: http://stackoverflow.com/comment/81839424
has comment: http://stackoverflow.com/comment/81837030
tagged with: python-sphinx
type: UnansweredQuestion
tagged with: python
tagged with: google-earth-engine
score: 0
answer count: 0
tagged with: read-the-docs
has title: Build Read The Docs documentation from docs folder created with sphinx
tagged with: authentication
type: Question
has body: I have made a python package (https://github.com/gee-community/gee_tools) that depends entirely on Google Earth Engine Python API. Although the earthengine-api package is locally installed, to get full and real access to objects you need to authenticate in a simple way: import ee ee.Initialize() but in order to make it work you have to authorize access to your Earth Engine account by running earthengine authenticate The package work fine for me and all users that can authenticate. So, I built the documentation using sphinx, which looks really nice (http://geetools.readthedocs.io). The problem is that in my environment builds perfect, but in read the docs doesn't because it cannot authenticate in their environment, so the documentation doesn't build correctly. This is read the doc's log: python /home/docs/checkouts/readthedocs.org/user_builds/geetools/envs/latest/bin/sphinx-build -T -E -b readthedocs -d _build/doctrees-readthedocs -D language=en . _build/html Running Sphinx v1.5.6 making output directory... loading translations [en]... done building [mo]: targets for 0 po files that are out of date building [readthedocs]: targets for 7 source files that are out of date updating environment: 7 added, 0 changed, 0 removed reading sources... [ 14%] Documentation reading sources... [ 28%] Introduction reading sources... [ 42%] cloud_mask try n° 0 ERROR: Please authorize access to your Earth Engine account by running earthengine authenticate in your command line, and then retry. I don't want to put my credentials inside code, so, my question: is there a way to just 'upload' the docs folder I built locally to read the docs? or I just have to use another hosting provider? I read http://dont-be-afraid-to-commit.readthedocs.io/en/latest/documentation.html and found that you don’t want to commit your rendered files, just the source files

http://stackoverflow.com/a/47529398
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47527621
answers question: http://stackoverflow.com/q/47527621
type: Answer
has body: This would not work: stdin, stdout, stderr = ssh_client.exec_command('sudo su - root') stdin, stdout, stderr = ssh_client.exec_command("whoami") which is basically the same as following comamnds: [local-host] # ssh user@host sudo su - root [local-host] # ssh user@host whoami Instead you should write like this: stdin, stdout, stderr = ssh_client.exec_command('sudo su - root') stdin.write('whoami\n') # Here stdout.readlines() would not work as it would keep reading # until EOF (which means the `sudo` comamnd has exited). print(stdout.channel.recv(1024) )

http://stackoverflow.com/a/57699961
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47433031
score: 2
has body: I had some code that called 'LDA' and 'QDA' and got those errors. I changed the import statements as shown from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA and the code now runs as originally intended. Original code location: SKLearn Classifier Comparison
type: Answer

http://stackoverflow.com/a/47520203
downvote count: 0
has body: You can use string formatting: file_list = ['car', 'bike', 'bus'] for i, a in enumerate(file_list, 1): print("{n}. taking a {vehicle} is better than other options because {vehicle}'s let you get around the city faster".format(n=i, vehicle=a)) Output: 1. taking a car is better than other options because car's let you get around the city faster 2. taking a bike is better than other options because bike's let you get around the city faster 3. taking a bus is better than other options because bus's let you get around the city faster
score: 2
answers question: http://stackoverflow.com/q/47520145
type: Answer
has comment: http://stackoverflow.com/comment/81997308
upvote count: 2

http://stackoverflow.com/q/47435973
tagged with: python
type: AnsweredQuestion
tagged with: shellexecute
tagged with: printing
has title: Print PDF file in duplex mode via Python
score: 1
accepted answer: http://stackoverflow.com/a/47601776
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47601776
upvote count: 1
favorite count: 0
type: Question
tagged with: pywin32
has body: I have an script in Python that prints PDF files. The script works using win32api.ShellExecute() and everything is fine, but now, I need to print PDF files that have double sided content, user manuals in concrete. I have tried setting the duplex mode in win32print, but nothing works, the printer still print 2 pages on 2 sheets for my PDF instead of two pages on a double sided sheet. The printer works with this mode in other applications, but with the python script doesn't work well. This is part of the code I used to print: name = win32print.GetDefaultPrinter() printdefaults = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS} handle = win32print.OpenPrinter(name, printdefaults) level = 2 attributes = win32print.GetPrinter(handle, level) attributes['pDevMode'].Duplex attributes['pDevMode'].Duplex = 1 win32print.SetPrinter(handle, level, attributes, 0) win32print.GetPrinter(handle, level)['pDevMode'].Duplex win32api.ShellExecute(0,'print','file.pdf','.','/route',0) Any idea why this doesn't works? Thanks.

http://stackoverflow.com/comment/81935907
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47490284
has text: You should edit your question instead of adding information in a comment
type: Comment

http://stackoverflow.com/q/47501453
has comment: http://stackoverflow.com/comment/81959087
answer count: 1
has body: I had a simple question: I have a python script that generates a list of strings and what I want it to be able to pipe this output so that it can be compared to an existing text file in this form: python myscript.py | diff test.txt - The test.txt file in this case is just a text file that contains the words that are on a new line each. How would I got about doing this.
tagged with: unix
type: Question
has title: Piping a Python script in order for it to be compared to another text file
has answer: http://stackoverflow.com/a/47501623
tagged with: python
tagged with: diff
tagged with: piping
has comment: http://stackoverflow.com/comment/81958626
accepted answer: http://stackoverflow.com/a/47501623
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82001897
comment on: http://stackoverflow.com/q/47522611
score: 1
type: Comment
type: QuestionComment
has text: I don't know `gunicorn` at all, but I'm pretty sure that WSGI is pretty flexible on whether or not servers keep the same interpreter running for many requests or if they shut down between them. Your code probably shouldn't be using any global state like that. (Note that your `global` statement is completely unnecessary, since you're not rebinding `q` in `add`, just mutating it in place.)

http://stackoverflow.com/a/47533637
has body: Using np.unique and the void view method from here def unique_pairs(a, b): c = np.sort(np.stack([a, b], axis = 1), axis = 1) c_view = np.ascontiguousarray(c).view(np.dtype((np.void, c.dtype.itemsize * c.shape[1]))) _, i = np.unique(c_view, return_index = True) return a[i], b[i]
answers question: http://stackoverflow.com/q/47531532
type: Answer
score: 0

addition
tags question: http://stackoverflow.com/q/47424635
tags question: http://stackoverflow.com/q/47496557
type: Tag
tag name: addition

http://stackoverflow.com/q/47455850
has comment: http://stackoverflow.com/comment/81866069
tagged with: python
has comment: http://stackoverflow.com/comment/81866189
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81866830
score: 0
has answer: http://stackoverflow.com/a/47456389
answer count: 2
possible better answer: http://stackoverflow.com/a/47456174
has answer: http://stackoverflow.com/a/47456174
has comment: http://stackoverflow.com/comment/81866411
has comment: http://stackoverflow.com/comment/81867044
has body: I am using BytIO to first convert the plot (matplotlib) to PNG format and then obtaining the array of the PNG image, here is the code: from matplotlib import pyplot as plt import numpy as np import io from PIL import Image fig, ax = plt.subplots() ax.text(0.0,0.0,"Test", fontsize=45) ax.axis('off') ax.imshow(np.random.random((3,3))) with io.BytesIO() as memf: fig.savefig(memf, format='PNG') memf.seek(0) img = Image.open(memf).convert('RGB') arr = np.asarray(img) img.show() plt.show() print(arr) The image looks fine, but the array is not, it shows all values to be 255 in all 3 dimensions (RGB). What am I doing wrong? This is the image (img):
linked to: http://stackoverflow.com/q/4325733
accepted answer: http://stackoverflow.com/a/47456389
type: Question
linked to: http://stackoverflow.com/q/8218887
has comment: http://stackoverflow.com/comment/81866132
has title: Why am I getting all values of 255?
tagged with: matplotlib

http://stackoverflow.com/comment/81721930
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47384454
has text: Also, we are talking about multi _processing_ right? You've tagged this as multithreading which is handled differently in Python.
score: 1

http://stackoverflow.com/q/47511704
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47512105
has body: I am trying to use slug url like /post/5post-title or /post/post-title. I am currently using plain URLs in the form of /post/123 , I tried a lot of methods, and all failed.. Now I am trying "Migrating from primary-key based lookups" from https://keyerror.com/blog/slug-fields-an-alternative-approach and I got a broswer error 'Too many redirections'... How to solve this problem？ Or do you have a better method to change the plain url to slug url? My models: class Post(models.Model): title,article and someFields....... def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail',kwargs={'pk':self.pk}) def slug(self): return slugify(self.title) and my urls: urlpatterns=[ url(r'^$',views.IndexView.as_view(),name='index'), url(r'^post/(?P&lt;pk&gt;[0-9]+)(?:/(?P&lt;slug&gt;[\w-]+))?$',views.detail,name='detail'),] my views: def detail(request,pk,slug=None): post=get_object_or_404(Post,pk=pk) if slug!=post.slug(): return redirect(post, permanent=True) return render(request,'blog/detail.html',context=context) use a SlugField models and remove pk: class Post(models.Model): title=models.CharField(max_length=70) body=models.TextField() created_time=models.DateTimeField() modified_time=models.DateTimeField() excerpt=models.CharField(max_length=200,blank=True) category=models.ForeignKey(Category) tags=models.ManyToManyField(Tag,blank=True) author=models.ForeignKey(User) views=models.PositiveIntegerField(default=0) excerpt=models.CharField(max_length=100,blank=True) sluglookup = models.SlugField( unique=True, default=Post.slug, max_length=15,) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail',kwargs={'pk':self.pk}) def increase_views(self): self.views+=1 self.save(update_fields=['views']) def save(self,*args,**kwargs): if not self.excerpt: md=markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) self.excerpt=strip_tags(md.convert(self.body))[:54] super(Post,self)…
has answer: http://stackoverflow.com/a/47512105
accepted answer: http://stackoverflow.com/a/47512377
type: Question
has answer: http://stackoverflow.com/a/47512377
tagged with: django
tagged with: python
has title: I can not add a slug url to my django app

http://stackoverflow.com/q/47526541
score: 3
has comment: http://stackoverflow.com/comment/82015460
answer count: 0
upvote count: 3
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82009647
downvote count: 0
linked to: http://stackoverflow.com/q/31607458
has title: how to copy matplotlib figures to clipboard
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10635537
type: UnansweredQuestion
has body: After plotting the figure, I want to copy it to the clipbaoard instead of saving to figures. I searched the internet and the code does not work, either the required modules only support python 2.x or the program stopped by not well-defined functions. I am using Python 3.6 in Windows 10. My matplotlib version is 2.0.2. I tried 'PyGTK: copy matplotlib figure to clipboard' and got the error: ImportError: Gtk* backend requires pygtk to be installed. I then visited www.pygtk.org/downloads.html to download pygtk/PyGObject (Windows) but it requires python 2.6 or file not found. Can anyone show how to achieve it? import matplotlib.pyplot as plt a = [2,3,6,7,1] plt.plot(a) plt.show()
tagged with: python
has comment: http://stackoverflow.com/comment/82010828

http://stackoverflow.com/comment/81851164
has text: That changes nothing.
type: Comment
comment on: http://stackoverflow.com/a/47448076
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81899046
type: QuestionComment
has text: @bouteillebleu I decided to add a method on a custom manager. Not sure if that's the best way though. Thanks.
comment on: http://stackoverflow.com/q/47471817
score: 0
type: Comment

http://stackoverflow.com/comment/81906414
type: QuestionComment
has text: You can try threading instead of multiple processes. I can see a nice speed-up.
score: 0
comment on: http://stackoverflow.com/q/47474946
type: Comment

http://stackoverflow.com/a/47455375
accepted answer of: http://stackoverflow.com/q/47455207
has body: In pandas is possible create this index, but it is not easy. For me working converting index to lists and then to array: mask = np.count_nonzero(np.array(rounded.index.values.tolist()), axis=1) == n Sample: df = pd.DataFrame({0:[0,1.0,0,1], 'a':[[0,0],[1,0],[1,1],[0,1]]}) rounded = df.set_index('a').rename_axis(None) print (rounded) 0 [0, 0] 0.0 [1, 0] 1.0 [1, 1] 0.0 [0, 1] 1.0 n = 1 mask = np.count_nonzero(np.array(rounded.index.values.tolist()), axis=1) == n print (mask) [False True False True] print (rounded[mask]) 0 [1, 0] 1.0 [0, 1] 1.0
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47455207
type: AcceptedAnswer

http://stackoverflow.com/comment/81748753
type: QuestionComment
score: 0
has text: What do you mean? Which url?
comment on: http://stackoverflow.com/q/47397800
type: Comment

http://stackoverflow.com/comment/81764691
score: 0
has text: Hi,@MadPhysicist It is the third dimension with the length of 100. '-1' only at the end of each line. Not in the middle or start. I searched some of the documents it shows how to use indexing. Like you can use array[3,1000,70:100]. But here each has different numbers of '-1'. I don't know where to start to select this subset.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47405541

http://stackoverflow.com/a/47514516
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47514330
answers question: http://stackoverflow.com/q/47514330
type: Answer
has body: Use contains with join to look to see if string contains a "sub" string, and join base with '|' to make a regex: mylist = ['tim tam','unsalted butter','fresh goat milk'] df[~(df.ingredients.str.contains('|'.join(mylist)) | df.recipe.str.contains('|'.join(mylist)))] Output: id ingredients recipe 2 code3 coffee, sugar add coffee and sugar and mix
upvote count: 2
score: 2

http://stackoverflow.com/comment/81941469
score: 1
has text: @Bharath Woah... yeah. That does seem overly complicated!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47492761

http://stackoverflow.com/comment/81724528
comment on: http://stackoverflow.com/q/47385727
type: QuestionComment
type: Comment
has text: You're passing _all_ the POST parameters to a `UserRoleForm`, but it only handles one field, `user_role`. It seems like it would be much easier to just add the `user_role` to `UserEditForm`.
score: 3

http://stackoverflow.com/comment/81801328
comment on: http://stackoverflow.com/q/47422969
has text: Have you thought about using `PRAW`? It's the Python Reddit API Wrapper, you can find the repo [here](https://github.com/praw-dev/praw).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47444679
answers question: http://stackoverflow.com/q/47443491
type: Answer
has body: you really should make a better try at coding, but I was bored this is a dynamic system simulation with linear 'heating/cooling' model and bang-bang controller r_t = 1 # thermal resistance t_cold = 0.8 # cooling temp t_hot = 2.2 # heating temp t_lo, t_hi = 1, 2 # controller thresholds c_t = 100 # heat capacity t_obj = [0] # really cold start temp h = [] for s in range(1000): if t_obj[-1] &lt; t_lo: # bang-bang logic heat = 1 elif t_obj[-1] &gt; t_hi: heat = 0 # equation integrating the the heat/cooling input to t_obj t_obj += [t_obj[-1] + ((heat * t_hot + (1 - heat) * t_cold) - t_obj[-1])/r_t/c_t] h.append(heat) plt.plot(h) # debug plot of `heat` state plt.plot(t_obj)
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/comment/83451532
type: Comment
score: 0
type: AnswerComment
has text: I tried this myself with numpy and your updated solution seems to produce a valid matrix. can you confirm?
comment on: http://stackoverflow.com/a/47521809

http://stackoverflow.com/q/47539846
tagged with: nginx
has comment: http://stackoverflow.com/comment/82037442
tagged with: python
has title: Python can't find module wit ai
has comment: http://stackoverflow.com/comment/82037310
type: Question
tagged with: wit.ai
has body: I just coded a Facebook Chatbot running on ngninx ubuntu with pyhthon which worked perfectly until I wanted to add wit.ai to it. The code should work but I think python cant find the module wit although I added it. Here is the console: File "/var/www/chatbot/wit.py", line 1, in &lt;module&gt; from wit import Wit ImportError: cannot import name 'Wit' Here is the code of the wit.py: from wit import Wit access_token = "*****" client = Wit(access_token = access_token) def wit_response(msg): resp = client.message(msg) entity = None value = None try: entity = list(resp['entities'])[0] value = resp['entities'][entity][0]['value'] except: pass return (entity, value)
answer count: 0
has comment: http://stackoverflow.com/comment/82037535
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82037486
tagged with: pip
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/82036770
has comment: http://stackoverflow.com/comment/82036839
score: 0
has comment: http://stackoverflow.com/comment/82037142

http://stackoverflow.com/comment/133077887
score: 1
type: AnswerComment
has text: @krisskad the issue is related to the "read / write" permissions of the file. You will need to manage this depending on your situation. Where is your sqlite db file and how is your code interacting with it? will need more information before I can help you.
comment on: http://stackoverflow.com/a/48479810
type: Comment

http://stackoverflow.com/q/47508906
tagged with: python
tagged with: dictionary
has title: Python dictionary manipulation into list of dictionary
has answer: http://stackoverflow.com/a/47509075
accepted answer: http://stackoverflow.com/a/47509075
has comment: http://stackoverflow.com/comment/81974589
tagged with: list
has answer: http://stackoverflow.com/a/47558246
possible better answer: http://stackoverflow.com/a/47558246
answer count: 2
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/20166749
has comment: http://stackoverflow.com/comment/81973673
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81973833
has body: I m fairly new to python and having a hard time solving this problem, I have a dictionary in format: {'tag1_batch1_st': OrderedDict([(0.0, '59.83163071'), (1.0, '18.94903946'), (2.0, '48.38692856'), (3.0, '0.05321884'), (4.0, '4.20608902'), (5.0, '01.66112137'), (6.0, '0.59775162'), (7.0, '37.17335892'), (8.0, '0.78234863'), (9.0, '1.67506027')]), 'tag_batch_st ': OrderedDict([(0.0, '58.83163071'), (1.0, '48.94903946'), (2.0, '38.38692856'), (3.0, '45.05321884'), (4.0, '40.20608902'), (5.0, '38.66112137'), (6.0, '37.59775162'), (7.0, '37.17335892'), (8.0, '36.78234863'), (9.0, '36.67506027')])} I want to convert it into a list like this: [{'tag1_batch1_st': '59.83163071', 'num': 0.0, 'tag_batch_st': '58.83163071'}, ...... ] I know, I can use for loop and iterate over the dictionary and create the list, but any approach which would require less iterations and methods like groupby() would be helpful. Thanks

http://stackoverflow.com/a/47459306
answers question: http://stackoverflow.com/q/47459181
score: 0
has body: You can use a dict as a cache, with the file name as a key and the timestamp is the data. Since your list content is only the file name, you need to get the timestamp: cache = dict((file, os.path.getmtime(file)) for file in list_content) Then when you read your file again, you can compare the timestamps and if they are different, you can save it. if cache[file] != os.path.getmtime(file): save_data(file)
has comment: http://stackoverflow.com/comment/81875288
has comment: http://stackoverflow.com/comment/81874246
type: Answer
has comment: http://stackoverflow.com/comment/81875147
has comment: http://stackoverflow.com/comment/81873387

http://stackoverflow.com/comment/82009173
has text: I solved this with two different xlsx files. But I write this two files to another file as sheets I lose my color-format ...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47508529
score: 0

http://stackoverflow.com/comment/81994524
score: 0
comment on: http://stackoverflow.com/q/47518835
type: Comment
type: QuestionComment
has text: Each request has a unique id, are you saying that I need something in the Node web server blocking until the Python data id matches the request id?

http://stackoverflow.com/comment/81943978
has text: The symptoms may be different, but you are using `Bcast` incorrectly as explained by the answer to the referenced question. You must call `Bcast` on all ranks with the same parameters in the same order.
score: 0
comment on: http://stackoverflow.com/q/47489741
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81904119
has text: Thank you and everyone else for your comments.
comment on: http://stackoverflow.com/a/47465534
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47447506
score: 0
has comment: http://stackoverflow.com/comment/81854376
tagged with: suds
has comment: http://stackoverflow.com/comment/81850496
has title: JIRA - Add comment to issue as another user using SOAP, suds, and python
tagged with: jira
has body: I am looking for a way to add comment as another user. REST API has no such way but SOAP has according from https://community.atlassian.com/t5/Answers-Developer-Questions/Jira-REST-API-create-a-comment-as-another-user/qaq-p/481139 Fortunately, my team still has not upgraded to 7.0 and seems no plan to upgrade since we are using SOAP in some processes. from suds.client import Client client = Client('https://example.com/jira/rpc/soap/jirasoapservice-v2?wsdl') auth = client.service.login('jira-admin', 'jira-admin123') client.service.addComment(auth, 'ISSUE-123', {'author': 'sample_user', 'body': 'TEST'}) user 'jira-admin' belong to global group 'jira-administrator' but this code is not working at all. Is there any wrong with the code or user permission? Any suggestion is appreciated.
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: soap
tagged with: python

http://stackoverflow.com/a/47449899
answers question: http://stackoverflow.com/q/47449569
upvote count: 0
downvote count: 1
has body: Convert the result in Serializer validate method and return it. import time t = time.strptime(timevalue_24hour, "%H:%M") timevalue_12hour = time.strftime( "%I:%M %p", t )
score: -1
type: Answer

http://stackoverflow.com/q/47473861
has comment: http://stackoverflow.com/comment/81902243
tagged with: opencv
has answer: http://stackoverflow.com/a/47483237
score: -5
has comment: http://stackoverflow.com/comment/81903281
tagged with: python
has comment: http://stackoverflow.com/comment/81902352
favorite count: 0
type: Question
tagged with: numpy
upvote count: 0
has comment: http://stackoverflow.com/comment/81902320
downvote count: 5
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81902246
has title: Python "for item not in list" not working correctly
has body: I am working on a facial recognition project and me and my mates have been stuck on an absurdly simple problem since yesterday. Having run out of possible solutions, I have come to you for help. The basic code is as follows: list=[] while true: nbr_predicted, conf = recognizer.predict(gray[y:y+h,x:x+w]) if nbr_predicted not in list: list.append(nbr_predicted) Here nbr_predicted is an integer which corresponds to the id of the predicted person and conf is the confidence of the prediction. Let us assume that we are using a single picture for multiple predictions. The code should supposedly insert on the first iteration, and then skip further insertions. However, the code simply attempts to insert the same id again even on further iterations. I have a hunch it is due the returning value of the function recognizer.predict() but I am unable to pinpoint it. I've left out some of the finer details which I believe is not related to the problem at hand. Just in case, I will leave the full code below. import cv2,os import numpy as np from PIL import Image import pickle import MySQLdb import datetime from random import randint db = MySQLdb.connect(host="localhost", user="######", passwd="######", db="######") recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainer/trainer.yml') cascadePath = "Classifiers/face.xml" faceCascade = cv2.CascadeClassifier(cascadePath); path = 'dataSet' cam = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_SIMPLEX while True: inp = cv2.waitKey(1) if inp == ord('q'): #cam.release() cv2.destroyAllWindows() break #ret, im =cam.read() im = cv2.imread('D:\Images\pic.jpg') gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) faces=faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100), flags=cv2.CASCADE_SCALE_IMAGE) list=[] for(x,y,w,h) in faces: nbr_predicted, conf = recognizer.predict(gray[y:y+h,x:x+w]) cv2.rectangle(im,(x-50,y-50),(x+w+50,y+h+50),(225,0,0),2) print(nbr_predicted) print(conf) if(conf&gt;45): nbr_predict…
has comment: http://stackoverflow.com/comment/81902236

http://stackoverflow.com/q/47523543
tagged with: python
accepted answer: http://stackoverflow.com/a/47523596
has answer: http://stackoverflow.com/a/47524091
score: 0
tagged with: list
answer count: 2
has body: I have long lists, for example: list1 = ["a","a","b","b","c"] list2 = [1, 3, 5, 7, 9]` How can I slice the second list based on the first list (list1 is sorted by its values)? Like [[1,3],[5,7],[9]] My lists are very long so I am looking for a fast way to precess this. Thanks!
has answer: http://stackoverflow.com/a/47523596
type: Question
possible better answer: http://stackoverflow.com/a/47524091
type: AnsweredQuestion
has title: Slice list based on values in another list

http://stackoverflow.com/a/47404707
type: Answer
accepted answer of: http://stackoverflow.com/q/47404455
score: 0
has body: This line sets lastLayer equal to a tuple: lastLayer = thinking, [32000, -1] When the for loop executes a second time, it will try to access lastLayer as a tensor, but you've converted it to a tuple. So you get the error.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47404455

http://stackoverflow.com/q/47473084
tagged with: dictionary
tagged with: list-comprehension
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: list
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47473152
has body: I have two arrays: a = [0.001,0.01,0.1,1] h = [2,4,8,16,32,64] And I want to create a dictionary, where the dict keys are a tuple of the values of a and h and the dict values are an empty list. However, the way I need this done is so that each unique a has every value in h, with the desired output: d = {(0.001,2):[], (0.001,4):[], (0.001,8):[], (0.001,16):[], (0.001,32):[], (0.001,64):[], (0.01,2):[], (0.01,4):[], (0.01,8):[], (0.01,16):[], (0.01,32):[], (0.01,64):[], (0.1,2):[], (0.1,4):[], (0.1,8):[], (0.1,16):[], (0.1,32):[], (0.1,64):[], (1,2):[], (1,4):[], (1,8):[], (1,16):[], (1,32):[], (1,64):[]} The problem is, writing it out manually as I have done above is tedious. Is there anyway to do this, using zip or list comprehension? Thanks in advance
has title: Using zip and list comprehension to create a dictionary
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/zip
has answer: http://stackoverflow.com/a/47473152
tagged with: python

http://stackoverflow.com/a/53755826
type: Answer
has body: Some directions you can try. Double check your input pipeline, make sure it is not the bottleneck for the performance. In crease your batch number or layer width to make sure the GPU got enough data to consume. The most effective method is dump the profile json to have a look. My experience is in most of time the low utilization is because of lack of data for GPU to consume. Some useful links * https://www.tensorflow.org/guide/performance/datasets * https://towardsdatascience.com/howto-profile-tensorflow-1a49fb18073d
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/94364500
downvote count: 0
answers question: http://stackoverflow.com/q/47462114

http://stackoverflow.com/q/47454317
has comment: http://stackoverflow.com/comment/81884220
tagged with: python
has answer: http://stackoverflow.com/a/47465202
has comment: http://stackoverflow.com/comment/81907413
upvote count: 16
has comment: http://stackoverflow.com/comment/131305912
tagged with: video
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81864549
score: 16
linked to: http://stackoverflow.com/q/7348505
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/81871751
has body: [Update:] Yes, it is possible, now some 20 months later. See Update3 below! [/update] Is that really impossible? All I could find were variants of calling FFmpeg (or other software). My current solution is shown below, but what I really would like to get for portability is a Python-only solution that doesn't require users to install additional software. After all, I can easily play videos using PyQt's Phonon, yet I can't get simply things like dimension or duration of the video? My solution uses ffmpy (http://ffmpy.readthedocs.io/en/latest/ffmpy.html ) which is a wrapper for FFmpeg and FFprobe (http://trac.ffmpeg.org/wiki/FFprobeTips). Smoother than other offerings, yet it still requires an additional FFmpeg installation. import ffmpy, subprocess, json ffprobe = ffmpy.FFprobe(global_options="-loglevel quiet -sexagesimal -of json -show_entries stream=width,height,duration -show_entries format=duration -select_streams v:0", inputs={"myvideo.mp4": None}) print("ffprobe.cmd:", ffprobe.cmd) # printout the resulting ffprobe shell command stdout, stderr = ffprobe.run(stderr=subprocess.PIPE, stdout=subprocess.PIPE) # std* is byte sequence, but json in Python 3.5.2 requires str ff0string = str(stdout,'utf-8') ffinfo = json.loads(ff0string) print(json.dumps(ffinfo, indent=4)) # pretty print print("Video Dimensions: {}x{}".format(ffinfo["streams"][0]["width"], ffinfo["streams"][0]["height"])) print("Streams Duration:", ffinfo["streams"][0]["duration"]) print("Format Duration: ", ffinfo["format"]["duration"]) Results in output: ffprobe.cmd: ffprobe -loglevel quiet -sexagesimal -of json -show_entries stream=width,height,duration -show_entries format=duration -select_streams v:0 -i myvideo.mp4 { "streams": [ { "duration": "0:00:32.033333", "width": 1920, "height": 1080 } ], "programs": [], "format": { "duration": "0:00:32.064000" } } Video Dimensions: 1920x1080 Streams Duration: 0:00:32.033333 Format Duration: 0:00:32.064000 UPDATE after several days of experimentation: The hacho…
favorite count: 0
linked to: http://stackoverflow.com/q/31507038
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/81864114
has comment: http://stackoverflow.com/comment/81872811
has comment: http://stackoverflow.com/comment/81871608
tagged with: ffmpeg
has title: Getting video properties with Python without calling external software
has answer: http://stackoverflow.com/a/48278168
type: UnansweredQuestion

http://stackoverflow.com/a/47486297
score: 1
type: Answer
has body: I believe that the issue lies in the way that you are importing needed decorators from ddt import data, unpack from selenium import webdriver import ddt If you look at the last statement, you are importing ddt which is a module, and this is causing the error when decorating the class. You need a decorator - callable that is located inside the ddt module. I think that the solution would be to import it in the first line like this from ddt import ddt, data, unpack from selenium import webdriver
answers question: http://stackoverflow.com/q/47485710
has comment: http://stackoverflow.com/comment/81946788
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81956016

http://stackoverflow.com/a/48539909
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84101647
answers question: http://stackoverflow.com/q/47401997
has body: As I already commented using write_got instead of write_plt will make your exploit fail. While testing your exploit I found out that attaching gdb to the target process while running your exploit, I was getting weird output [+] b'input: ' [+] write is at 0x203a647663657220 [+] libcbase is at 0x203a64766355ff70 [+] system is at 0x203a6476635a5300 [+] sending system address [+] sending '/bin/sh' string [+] try to open a shell via telnet I suspect this is from the fact that you used python socket. I have experienced in CTFs that sometimes you'll have to mess up with the buffering a lot. Its better to use a library already built for this. Check out my exploit how I have used pwntools to make my life easier for buffering inputs/outputs and for parsing ELF files so that you don't have to manually copy output from gdb.
accepted answer of: http://stackoverflow.com/q/47401997
type: Answer
has comment: http://stackoverflow.com/comment/84131132
has comment: http://stackoverflow.com/comment/84106092

http://stackoverflow.com/comment/81849778
type: Comment
comment on: http://stackoverflow.com/a/47422388
score: 0
type: AnswerComment
has text: I am having one issue with quotes in the yaml file can you please help in this [link](https://stackoverflow.com/questions/47441501/remove-single-quotes-from-dict-values-while-adding-content-to-yaml-file-using-py)

http://stackoverflow.com/a/47434173
has comment: http://stackoverflow.com/comment/128646673
has comment: http://stackoverflow.com/comment/104857737
has comment: http://stackoverflow.com/comment/81829907
upvote count: 26
score: 26
type: Answer
answers question: http://stackoverflow.com/q/47432168
has body: You can define a custom sampler for the dataset loader avoiding recreating the dataset (just creating a new loader for each different sampling). class YourSampler(Sampler): def __init__(self, mask): self.mask = mask def __iter__(self): return (self.indices[i] for i in torch.nonzero(self.mask)) def __len__(self): return len(self.mask) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) sampler1 = YourSampler(your_mask) sampler2 = YourSampler(your_other_mask) trainloader_sampler1 = torch.utils.data.DataLoader(trainset, batch_size=4, sampler = sampler1, shuffle=False, num_workers=2) trainloader_sampler2 = torch.utils.data.DataLoader(trainset, batch_size=4, sampler = sampler2, shuffle=False, num_workers=2) PS: You can find more info here: http://pytorch.org/docs/master/_modules/torch/utils/data/sampler.html#Sampler
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47432168
type: AcceptedAnswer

http://stackoverflow.com/comment/83434861
score: 0
type: AnswerComment
has text: I haven't see this when you posted it, I back to this script now and come back to search info and see this. The duplex mode set to 3 works correctly. Thanks so much!
comment on: http://stackoverflow.com/a/47601776
type: Comment

http://stackoverflow.com/a/47477265
type: Answer
has comment: http://stackoverflow.com/comment/88594752
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47477122
has comment: http://stackoverflow.com/comment/91154553
has body: I think the easiest way to support various versions of Python, as well as other languages, is the asdf version manager. It allows you to set a version of Python globally, as well as in each project folder. This means that you can set your Python version to dynamically change based upon the folder you're working in. asdf version manager I haven't used Windows for almost 20 years, but I've heard that Windows 10 sports an Ubuntu-based subsystem for Linux. I don't know if asdf will work with that, but it is worth a try. Just use the instructions for setting asdf up with bash.
score: 1

http://stackoverflow.com/comment/82005454
has text: @sachindubey Added my expected output.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47524648
score: 0

flask-sqlalchemy
tags question: http://stackoverflow.com/q/47524720
tags question: http://stackoverflow.com/q/47391715
type: Tag
tags question: http://stackoverflow.com/q/47491593
tags question: http://stackoverflow.com/q/47432480
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/47393670
tags question: http://stackoverflow.com/q/47513622
tags question: http://stackoverflow.com/q/47498415
tags question: http://stackoverflow.com/q/47393181
tags question: http://stackoverflow.com/q/47428746

http://stackoverflow.com/q/47404271
has title: Using Tweepy to Obtain Most Recent Tweet
tagged with: python
has body: I was using Tweepy and wanted to get the link of the most recent tweet from a user. Here is my code: import tweepy ckey = '-----------------------------------' csecret = '-------------------------------------------------' atoken = '---------------------' asecret = '-------------------' auth = tweepy.OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) tweets = api.home_timeline() tweet = api.user_timeline(screen_name = 'realDonaldTrump', count = 100, include_rts = True)[0] link = api.get_oembed(https://twitter.com/{}/status/{}.format(tweet.user.screen_n‌ame, tweet.id)).url print(tweet.text) Here is the traceback I get: link = api.get_oembed(https://twitter.com/{}/status/{}.format(tweet.user.screen_n‌​ame, tweet.id)).url ^ SyntaxError: invalid syntax I know I have a syntax issue, but I also think there is an overarching problem with the line itself, whether it's with my parentheses or with my commands. I know my OAuth is working because when I take out that line, I get something for print(text.tweet). Thank you so much for the help.
tagged with: twitter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81762980
tagged with: tweepy
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81763209
has comment: http://stackoverflow.com/comment/81763912
type: Question
has comment: http://stackoverflow.com/comment/81764301

http://stackoverflow.com/a/47412739
type: Answer
score: 0
type: AcceptedAnswer
has body: That is not a spacing problem. What all you need to do is to save the output of the standard deviation. Then, you can access each value like this: std_arr = np.std(nums_arr, axis=0) # array which holds std of each column # now, you can access them by indexing: print(std_arr[0]) # output here is 0.5 print(std_arr[1]) # output here is 0.5 print(std_arr[2]) # output here is 1.118034
accepted answer of: http://stackoverflow.com/q/47412496
answers question: http://stackoverflow.com/q/47412496
has comment: http://stackoverflow.com/comment/81824909

http://stackoverflow.com/a/47434472
has body: You can select all column by []: s = (df.groupby(['number'])['id1', 'id2'] .apply(lambda x: pd.unique(x.values.ravel()).tolist())) print (s) number 0 [100, 200] 1 [300, 500, 400, 600] 2 [700, 800, 900, 1000] dtype: object Or: s2 = (df.groupby(['number'])['id1', 'id2'] .apply(lambda x: np.unique(x.values.ravel()).tolist())) print (s2) number 0 [100, 200] 1 [300, 400, 500, 600] 2 [700, 800, 900, 1000] dtype: object EDIT: If need output as column, first reshape by stack and then drop_duplicates: df1 = (df.set_index('number')'id1', 'id2' .stack() .reset_index(level=1, drop=True) .reset_index(name='a') .drop_duplicates()) print (df1) number a 0 0 100 5 0 200 6 1 300 7 1 500 8 1 400 9 1 600 10 2 700 13 2 800 15 2 900 17 2 1000
downvote count: 0
answers question: http://stackoverflow.com/q/47434426
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81823309
accepted answer of: http://stackoverflow.com/q/47434426
has comment: http://stackoverflow.com/comment/81823471
score: 10
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/81823108

http://stackoverflow.com/comment/109396250
has text: Even Godaddy support couldn't help me out. This worked flawlessly.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48750034
type: AnswerComment

http://stackoverflow.com/comment/90862905
type: Comment
score: 0
type: AnswerComment
has text: With the original example there is no way of having the callback executed in Alice's thread because the `alice` method will keep the thread busy. Your solution spawns two indepenent event loops (hence two threads, as before) and forces any execution of a callback to run in the loop's thread. If this is the result you want I don't see a way out of event loops for task scheduling.
comment on: http://stackoverflow.com/a/47499085

http://stackoverflow.com/a/50566414
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47518475
type: Answer
has body: This works in python generator. def main(config): if DELETE_TS: return "D" else: return "U"
downvote count: 0

http://stackoverflow.com/comment/82003229
comment on: http://stackoverflow.com/q/47523476
score: 0
has text: You'll have to say more about what these markers need to be able to do. Why are they strings?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47402505
type: Question
possible better answer: http://stackoverflow.com/a/47402561
answer count: 3
tagged with: api
has answer: http://stackoverflow.com/a/47402561
has body: Here's my function which connects to an API: def order_summary(): """Get order summary for a specific order""" # Oauth2 params headerKey = api_login() headers = {'Authorization': headerKey} # Payload params payloadOrderSum = { "domainId": 15, "domainName": "SGL", "orderId": 3018361 } # API response orderSumResp = requests.post(url + "order/summary", data=payloadOrderSum, headers=headers) print(orderSumResp.content) The API expects a JSON array as Payload Params which essentially looks like that: [ { "domainId": 0, "domainName": "string", "orderId": 0 } ] The other endpoints I coded for on this API didn't need for the params to be an array so I could just use them as is and send them as a dictionary and it worked. I've tried a couple things using the JSON library but I can't seem to get it to work. I saw that the JSonEncoder converts lists and tuples to JSON arrays but I couldn't figure it out. Not sure what other info I could provide but just ask if there are any. Thanks!
tagged with: arrays
downvote count: 0
upvote count: 1
has title: Convert Python dictionary to a JSON array
favorite count: 0
accepted answer: http://stackoverflow.com/a/47402593
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47402593
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47402591

http://stackoverflow.com/comment/81873164
type: QuestionComment
has text: You're right, thanks to both of you guys. But question: why did it work for snippets/2 without the slash?
type: Comment
comment on: http://stackoverflow.com/q/47459216
score: 1

http://stackoverflow.com/q/47523547
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82003313
answer count: 1
has title: Function with different arguments
type: Question
score: 0
tagged with: arguments
has comment: http://stackoverflow.com/comment/82003492
has comment: http://stackoverflow.com/comment/82003426
tagged with: function
has body: I am writing a function and it should be able to take different arguments in one time. How can I define this arguments of the function? def function('005=5=0002555') def function('00025:001:002325', '/') def function(date='05-0004-002294', separator='/') def function(separator='*', date='0008=006=2001') def function('21 12 2012', separator='+')
has answer: http://stackoverflow.com/a/47523706

http://stackoverflow.com/q/47460068
has comment: http://stackoverflow.com/comment/81874750
answer count: 1
linked to: http://stackoverflow.com/q/44372046
has body: The following call is activated upon a button press. def ON(): print("System Initiated") var.set("System Initiated") AC1 = circuitD.create_oval(375,155,400,180, fill= 'green') DCM = circuitD.create_oval(375,425,400,450, fill= 'green') DC2 = circuitD.create_oval(367,513,392,538, fill= 'green') DC1 = circuitD.create_oval(313,513,338,538, fill= 'green') DC3 = circuitD.create_oval(423,513,448,538, fill= 'green') DC4 = circuitD.create_oval(477,513,502,538, fill= 'green') It simply draws 6 green circles in different areas of the canvas. I would like to draw them in sequence, with a one second delay. I've tried using the time.sleep(seconds) snippet between each line. def ON(): print("System Initiated") var.set("System Initiated") AC1 = circuitD.create_oval(375,155,400,180, fill= 'green') time.sleep(seconds) DCM = circuitD.create_oval(375,425,400,450, fill= 'green') time.sleep(seconds) DC2 = circuitD.create_oval(367,513,392,538, fill= 'green') time.sleep(seconds) DC1 = circuitD.create_oval(313,513,338,538, fill= 'green') time.sleep(seconds) DC3 = circuitD.create_oval(423,513,448,538, fill= 'green') time.sleep(seconds) DC4 = circuitD.create_oval(477,513,502,538, fill= 'green') The sleep function delays the entire drawing sequence for the set amount of time, and then proceeds to draw all 6 circles at one time. It seems as though the sleep function only properly delays the shell outputs. My questions is, is there a way to delay the circles from appearing on the canvas? Or is there a way to live update the canvas after each time.sleep(seconds)? Thank you in advance.
type: Question
type: UnansweredQuestion
has title: Sequentially updating tkinter canvas
tagged with: python
linked to: http://stackoverflow.com/q/34312090
has answer: http://stackoverflow.com/a/47460241
score: 0
tagged with: tkinter
tagged with: canvas

http://stackoverflow.com/a/47584675
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47505488
has body: You should look at the new service from AWS called "Amazon Comprehend". This should address your requirements.

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

http://stackoverflow.com/q/47449350
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
has body: I have a nested JSON which I need to convert to a CSV. I have initially worked on simple JSON and able to convert it. But this has some complex nested objects for which I'm facing difficulties. Below is the JSON: { "next": "https://api.pro.live/api/v1.0/publisher/pages?api_key=ujwq8aW7MOZ6y40nXhrrqW0OxnIvNJnFzpWOcJaSWHc&amp;format=json&amp;page_number=2", "next_page": 2, "previous": null, "previous_page": null, "count": 8888, "data": [{ "id": "294225", "publisher_id": "here", "name": "Company Page", "publisher_page_id": "", "publisher_page_url": "", "state": "active", "state_description": "", "crawled_at": null, "updated_at": null, "location": { "id": "163238", "name": "Buffard Fabrice", "address": { "address_line1": "Allée de l'Abron", "address_line2": "", "house_number": "5", "city": "Gennetines", "zip_code": "03400", "sublocality": "", "state": "", "country": "FR", "coordinates": { "latitude": 46.6376484, "longitude": 3.4076838 } }, "phones": [{ "type": "main", "number": "0470421022", "country_code": "" }, { "type": "mobile", "number": "0662241230", "country_code": "" }], "urls": [{ "type": "website", "url": "http://www.fabrice-buffard.fr", "description": "", "display_url": "" }], "emails": [{ "email": "photo@fabrice-buffard.fr", "type": "contact", "description": "" }], "closed": false, "opening_hours": { "periods": [{ "open_day": "MONDAY", "open_time": "14:00", "close_day": "MONDAY", "close_time": "19:00" }, { "open_day": "TUESDAY", "open_time": "10:00", "close_day": "TUESDAY", "close_time": "12:30" }, { "open_day": "TUESDAY", "open_time": "14:00", "close_day": "TUESDAY", "close_time": "19:00" }, { "open_day": "WEDNESDAY", "open_time": "10:00", "close_day": "WEDNESDAY", "close_time": "12:30" }, { "open_day": "WEDNESDAY", "open_time": "14:00", "close_day": "WEDNESDAY", "close_time": "19:00" }, { "open_day": "THURSDAY", "open_time": "10:00", "close_day": "THURSDAY", "close_time": "12:30" }, { "open_day": "THURSDAY", "open_time": "14:00", "close_day": "THURSDAY", "…
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47449422
answer count: 1
has title: Converting a complex nested JSON to CSV or Excel using Python

http://stackoverflow.com/a/47540540
answers question: http://stackoverflow.com/q/47535063
has body: This is what I developed and it works fine. def convertNames(nameList): if nameList==[]: return [] else: head = nameList[0:1] rest = nameList[1:] head = head[0].split(' ') head.remove(head[1]) return head + convertNames(rest) print(convertNames(['Julia Truong','Chen Wu','Jeb Castro','Ron Kennedy','X Y']))
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82038610

http://stackoverflow.com/q/47477897
has comment: http://stackoverflow.com/comment/81914058
has comment: http://stackoverflow.com/comment/81912362
has comment: http://stackoverflow.com/comment/81910845
tagged with: python
has comment: http://stackoverflow.com/comment/81911499
has comment: http://stackoverflow.com/comment/81916150
has comment: http://stackoverflow.com/comment/81914455
has comment: http://stackoverflow.com/comment/81910598
has comment: http://stackoverflow.com/comment/81911180
favorite count: 0
has comment: http://stackoverflow.com/comment/81910721
has answer: http://stackoverflow.com/a/47479900
has comment: http://stackoverflow.com/comment/81911079
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81915877
has comment: http://stackoverflow.com/comment/81911040
has comment: http://stackoverflow.com/comment/81910726
has title: How to show data in rows instead of string?
has comment: http://stackoverflow.com/comment/81914547
has comment: http://stackoverflow.com/comment/81911325
has body: Right now, when I print gameuniqueteams it shows as a string. On SQL, at each row a new team gets added while I want each to show individually. At this stage, gameuniqueteams will show the following string ['Arsenal', 'Bournemouth', 'Brighton', 'Burnley', 'Chelsea'] I want it to show per row so that when I transfer it to sql each team shows in a row by itself. ['Arsenal'] ['Bournemouth'] ['Brighton'] ['Burnley'] ['Chelsea'] This is my entire code in case it helps! What should I do? #!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import sys import csv from itertools import count, cycle from _tkinter import create from setuptools.dist import sequence from email.policy import default path = r'C:\Users\sammy\Downloads\E0.csv' with open(path, "r") as csvfile: readCSV = csv.reader(csvfile, delimiter=",") firstline = 1 con = None con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'") cur = con.cursor() cur.execute("DROP TABLE teams") cur.execute("CREATE TABLE teams (HomeTeamID SERIAL PRIMARY KEY, AllTeams123 VARCHAR)") hometeams = [] awayteams = [] uniqueteams = [] allteams = [] gameuniqueteams = [] try: for row in readCSV: if firstline: firstline=0 continue HomeTeam = row[2] AwayTeam = row[3] hometeams.append(HomeTeam) awayteams.append(AwayTeam) allteams = hometeams + awayteams for x in allteams: if x not in uniqueteams: uniqueteams.append(x) gameuniqueteams = sorted(uniqueteams) for x in gameuniqueteams: print (x) gameuniqueteams = (x) data1 = (gameuniqueteams,) query1 = "INSERT INTO teams (AllTeams123) VALUES (%s);" cursor = con.cursor() cursor.execute(query1, data1) except psycopg2.DatabaseError as e: if con: con.rollback() print ("Error %s % e", e) sys.exit(1) finally: if con: con.commit() con.close()
possible better answer: http://stackoverflow.com/a/47479900
linked to: http://stackoverflow.com/q/17037566
has comment: http://stackoverflow.com/comment/81911637
has comment: http://stackoverflow.com/comment/81914542
type: Question
accepted answer: http://stackoverflow.com/a/47478831
has comment: http://stackoverflow.com/comment/81912789
has comment: http://stackoverflow.com/comment/81910782
has comment: http://stackoverflow.com/comment/81911560
answer count: 2
has comment: http://stackoverflow.com/comment/81913004
has answer: http://stackoverflow.com/a/47478831
upvote count: 0
has comment: http://stackoverflow.com/comment/81914580
linked to: http://stackoverflow.com/q/47476434
score: -2
downvote count: 2

http://stackoverflow.com/q/47536458
has title: Generating a Midi (or chart preferably) file from mp3 onsets
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82037351
type: UnansweredQuestion
has body: I am using librosa's onset function to generate onsets for an mp3. Is there away I can turn this in to Midi format?
tagged with: python
tagged with: librosa
has comment: http://stackoverflow.com/comment/82069784
answer count: 0
has comment: http://stackoverflow.com/comment/82029912
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/82023647
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47531347
type: Comment
has text: put that link static in email where user will enter OTP. and because of localStorage, token is already saved there. so when user will be on that page , that will fetch token from localstorage

http://stackoverflow.com/comment/81941118
comment on: http://stackoverflow.com/q/47492554
type: Comment
type: QuestionComment
score: 0
has text: a list. Thank you!

http://stackoverflow.com/comment/81809559
type: Comment
comment on: http://stackoverflow.com/a/47426525
type: AnswerComment
has text: Also, is there a way to do it all at once (not with a loop), when labels is an integer array?
score: 0

http://stackoverflow.com/comment/81896413
comment on: http://stackoverflow.com/q/47470825
score: 0
has text: @syam: how would the code *calling* the function get access to the intermediate results? If you are replacing the variable each iteration, the caller would not have access to it.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47390846
has answer: http://stackoverflow.com/a/47391142
downvote count: 1
tagged with: try-catch
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47391824
tagged with: exception
has body: I think this should be a bit tricky but somehow feasible, but I need help. I'd like to execute two functions from within my main() func. I'd like to be able to catch exceptions from the two separately, but still being able to execute both and get the result of at least one of them if the other raises an exception. Let's say I have: def foo(): raise TypeError def bar(): return 'bar' If I do (adapted from here): def multiple_exceptions(flist): for f in flist: try: return f() except: continue def main(): multiple_exceptions([foo, bar]) main() main() would return 'bar', but I'd like to be able to still throw the exception from foo() after all. This way, I would still have the result of one of my functions and the information on the error occurred in the other.
possible better answer: http://stackoverflow.com/a/47391142
linked to: http://stackoverflow.com/q/13874666
has title: python - move on after exception and raise it afterwards
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81735006
has comment: http://stackoverflow.com/comment/81734570
has comment: http://stackoverflow.com/comment/81734656
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47391824
score: 0
has comment: http://stackoverflow.com/comment/81734620
upvote count: 1
has comment: http://stackoverflow.com/comment/81734821

http://stackoverflow.com/a/47515194
answers question: http://stackoverflow.com/q/47515025
has body: You can use a dictionary that stores a list of the content values: label = item.find('p', {'class': 'contentLabel'}).text dictionary[label] = [i.text for i in item.findAll('span', {'class': "contentValue"})] Output: {u'Slaapkamer': [u'8 m\xb2', u'7 m\xb2']}
score: 0
type: Answer

http://stackoverflow.com/a/47482012
answers question: http://stackoverflow.com/q/47481696
has body: Given a dataframe like this: df A B 0 aaa ddd 1 bbb eee 2 ccc fff You can just use df.sum, given every column is a string column: df.sum(1) 0 aaaddd 1 bbbeee 2 cccfff dtype: object If you need to perform a conversion, you can do so: df.astype(str).sum(1) If you need to select a subset of your data (only string columns?), you can use select_dtypes: df.select_dtypes(include=['str']).sum(1) If you need to select by columns, this should do: df'A', 'B'.sum(1) In every case, the addition is not inplace, so if you want to persist your result, please assign it back: r = df.sum(1)
has comment: http://stackoverflow.com/comment/81989965
downvote count: 0
upvote count: 10
has comment: http://stackoverflow.com/comment/82031703
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/82033617
has comment: http://stackoverflow.com/comment/81989882
has comment: http://stackoverflow.com/comment/81993569

http://stackoverflow.com/comment/82051056
comment on: http://stackoverflow.com/q/47504282
score: 0
type: Comment
has text: Thanks, the stackoverflow thread you linked me to actually helped me a lot!
type: QuestionComment

http://stackoverflow.com/comment/81777328
has text: this code will work regardless of the number of images. Next step> yu should read about pygame.sprites and groups: they provide a common functionality to draw the sprites and regenerate te background.
type: Comment
comment on: http://stackoverflow.com/a/47400975
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81846592
type: Comment
comment on: http://stackoverflow.com/q/47441731
type: QuestionComment
has text: What do I need to add to inject the list into the text file?
score: 0

microphone
tag name: microphone
tags question: http://stackoverflow.com/q/47449643
type: Tag

http://stackoverflow.com/comment/81798368
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga The point is precisely that I _cannot_ copy all the attributes within `replace_object()`.
score: 0
comment on: http://stackoverflow.com/q/47421289

decode
tag name: decode
tags question: http://stackoverflow.com/q/47426198
type: Tag

http://stackoverflow.com/comment/81906547
score: 1
has text: Also, would there be duplicates within each of the arrays?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47475611

http://stackoverflow.com/comment/81987312
type: QuestionComment
comment on: http://stackoverflow.com/q/47500832
has text: @Imran I'm sorry, I don't know the frequencies that the blocks appear. I assume that they are random. I thought that the game would provide three blocks that could definitely be placed if put in the correct order and in the correct places on the board although I once got a combination of three blocks that could not be placed and the game ended.
score: 0
type: Comment

http://stackoverflow.com/comment/81734656
type: QuestionComment
score: 0
has text: What output you are getting right now ?
comment on: http://stackoverflow.com/q/47390846
type: Comment

http://stackoverflow.com/a/47520865
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47520590
has body: You could use np.ind1d or np.isin: Returns a boolean array of the same shape as element that is True where an element of element is in test_elements and False otherwise. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) &gt;&gt;&gt; B = np.array([20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]) &gt;&gt;&gt; C = np.array([3,7,13]) &gt;&gt;&gt; D = np.array([18,8]) &gt;&gt;&gt; np.in1d(A, C) &amp; np.in1d(B, D) array([False, False, True, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False], dtype=bool) &gt;&gt;&gt; indices = np.isin(A, C) &amp; np.isin(B, D) &gt;&gt;&gt; A[indices] array([ 3, 13]) &gt;&gt;&gt; B[indices] array([18, 8]) It's not clear if C and D are converted to sets, but I suppose it will be faster than your current code.
score: 3
answers question: http://stackoverflow.com/q/47520590
type: Answer
upvote count: 3

http://stackoverflow.com/comment/81863355
type: QuestionComment
comment on: http://stackoverflow.com/q/47454091
type: Comment
has text: are you running it on a server?? localhost or something?
score: 0

http://stackoverflow.com/comment/82049051
score: 0
has text: This is the output which i am getting while redirecting it to a file. What is invalid in the output and how can i correct it. Please suggest.
comment on: http://stackoverflow.com/q/47524614
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89262684
type: Comment
type: AnswerComment
has text: It is enough with just making sure that the specified dags folder exists. There doesn't have to be anything in it. The examples will start working.
comment on: http://stackoverflow.com/a/50574061
score: 0

http://stackoverflow.com/q/47467025
has answer: http://stackoverflow.com/a/47483038
tagged with: python
has title: Why does asyncio.wait_for() need a timeout?
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/47483038
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has body: Below is a simple asyncio loop that runs two background tasks. They both perform a simple count. The first one counts forever, wrapped in a try/except. The second one counts up to 5, then cancels the first one and stops the loop. There are two ways of ensuring that the cancellation is complete - asyncio.wait([a sequence of futures]) asyncio.wait_for(a single future) Both take an optional timeout. If I use the first method without a timeout, the cancellation completes and the loop stops. If I use the second method without a timeout, the future is cancelled, but the program hangs. If I add a timeout to the second one, it behaves the same as the first one. Is there a reason for this? I am using version 3.6.0. import asyncio from itertools import count async def counter1(): cnt = count(1) try: while True: print('From 1:', next(cnt)) await asyncio.sleep(1) except asyncio.CancelledError: print('counter1 cancelled') async def counter2(): cnt = count(1) for i in range(5): print('From 2:', next(cnt)) await asyncio.sleep(1) cnt1.cancel() # await asyncio.wait([cnt1]) # works # await asyncio.wait_for(cnt1) # hangs await asyncio.wait_for(cnt1, 1) # works loop.stop() loop = asyncio.get_event_loop() cnt1 = asyncio.ensure_future(counter1()) cnt2 = asyncio.ensure_future(counter2()) loop.run_forever()
type: Question
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/81903138

http://stackoverflow.com/comment/81828873
comment on: http://stackoverflow.com/a/47436911
type: Comment
score: 0
type: AnswerComment
has text: The radius will not be bound to 1, it will be user defined. How would I go about reducing the size of the second loop?

http://stackoverflow.com/comment/81751072
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47398975
has text: That's not the word you're looking for.

http://stackoverflow.com/comment/81845725
has text: maybe try `filelist = glob.glob(os.path.join(outdir, '/*{}*.sh'))`. Or `os.listdir('max/test/')`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47445170

http://stackoverflow.com/comment/81895706
has text: It seems you just copied the assignment you got and now are assigning it to us...
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47470645

http://stackoverflow.com/q/47511885
answer count: 2
has comment: http://stackoverflow.com/comment/81979587
has title: Django Image Not found using template tags
has comment: http://stackoverflow.com/comment/81979584
linked to: http://stackoverflow.com/q/39051206
has comment: http://stackoverflow.com/comment/82012107
has comment: http://stackoverflow.com/comment/82012143
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82012625
possible better answer: http://stackoverflow.com/a/47514093
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47514093
has comment: http://stackoverflow.com/comment/82014076
has comment: http://stackoverflow.com/comment/82011723
has comment: http://stackoverflow.com/comment/82012623
has body: I'm in trouble for many days now and all solutions given didn't helped me yet. The image profile I want to show doesn't appear if I use the template variable {{ userprofile.photo.url}} (the result is the Alt text) but it does work when I put the path to the image like this : /dashboard/media/dashboard/photo/profils/user.png. I've tried to debug, it seems the url is good but the result given is this : [27/Nov/2017 13:55:07] "GET /dashboard/ HTTP/1.1" 200 44757 Not Found: /media/dashboard/photos/profils/user.png [27/Nov/2017 13:55:07] "GET /media/dashboard/photos/profils/user.png HTTP/1.1" 404 2295 Here the files of the project : Structure of the project : project_dir/ dash-app/ __init__.py settings.py urls.py wsgi.py dashboard/ __init__.py admin.py app.py forms.py models.py urls.py views.py ... templates/ dashboard/ index.html ... static/ dashboard/ images/ logo9.png ... media/ dashboard/ photos/ profils/ user.png ... On the urls.py : from django.conf.urls import url from dashboard import models from dashboard import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^$', views.index, name='index'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) On the settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "dashboard", "static") #dashboard/media/ MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media", "dashboard") On the models.py : from django.core.files.storage import FileSystemStorage image_storage = FileSystemStorage( # Physical file location ROOT location='{0}/'.format(settings.MEDIA_ROOT), # Url for file base_url='{0}/dashboard/'.format(settings.MEDIA_URL), ) def image_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/dashboard/picture/<filename> return 'phot…
has comment: http://stackoverflow.com/comment/82012582
accepted answer: http://stackoverflow.com/a/63916128
type: Question
has comment: http://stackoverflow.com/comment/81982723
has answer: http://stackoverflow.com/a/63916128

http://stackoverflow.com/q/47427771
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/47431009
has answer: http://stackoverflow.com/a/47431009
type: AnsweredQuestion
score: 0
has body: The plot is only showing a white screen and I am not entirely sure why. I would like the planets to orbit around the sun at different positions, in that, I used the FuncAnimation to make it happen. from pylab import* from matplotlib.animation import * fig = plt.figure() ax = plt.axes(xlim=(-10, 10), ylim=(-10, 10), aspect=True) x0 =0 y0 = 0 r_s=.15 r_e = .15 r_m = .15 Sun, = plt.Circle((x0, y0), radius=r_s, ec='yellow', fc='yellow', lw=3) Earth, = plt.Circle((2, 4), radius=r_e, ec='green', fc='green', lw=3) Mars, = plt.Circle((1, 3), radius=r_M, ec='brown', fc='brown', lw=3) ax.add_patch(Sun) def init(): ax.add_patch(Earth) ax.add_patch(Mars) return Earth, Mars, def animate(i): theta = radians(i) x = x0*np.cos(theta) - y0*np.sin(theta) y = x0*np.sin(theta) + y0*np.cos(theta) Earth.xy = (-x, -y) Earth._angle = i Mars.xy = (x, y) Mars._angle = i return Earth, Mars, anim = animation.FuncAnimation(fig, animate, init_func=init, frames=1080, interval=25, blit=True) plt.show()
answer count: 1
type: Question
has title: Python: My plot is not showing any Circles, any clues?

http://stackoverflow.com/q/47385830
tagged with: python
score: -1
tagged with: regex
type: Question
has comment: http://stackoverflow.com/comment/81725077
accepted answer: http://stackoverflow.com/a/47385966
has answer: http://stackoverflow.com/a/47385966
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/8270092
has comment: http://stackoverflow.com/comment/81724983
upvote count: 1
has comment: http://stackoverflow.com/comment/81724848
has comment: http://stackoverflow.com/comment/81724741
favorite count: 0
has body: I have the following input: [ ['A(x) | B(x)'],['Function(x,y) | K(x)'] ] Each list within the list of list has a space before and after the character "|". How can I remove this to get the following result? [ ['A(x)|B(x)'],['Function(x,y)|K(x)'] ] I tried the following: list=[] k1=[] for i in sentence: k1="".join(i).replace(" ","") list.append(k1) result=[[i] for i in list]
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/8270092
has comment: http://stackoverflow.com/comment/81724706
has comment: http://stackoverflow.com/comment/81724699
has title: How to remove spaces from list of lists in Python?

http://stackoverflow.com/comment/82008068
has text: You should run all your app on `virtualenv`, try to install one and then you will get away from trouble! `sudo pip install virtualenv`
comment on: http://stackoverflow.com/q/47525860
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/47427393
answers question: http://stackoverflow.com/q/47427314
accepted answer of: http://stackoverflow.com/q/47427314
type: Answer
upvote count: 6
type: AcceptedAnswer
downvote count: 0
score: 6
has body: apply is usually slow. You can use In [34]: df.join(pd.DataFrame(df.props.values.tolist())) Out[34]: id props 0 1 2 3 4 0 2 [FUT, 2, SG] FUT 2 SG None None 1 6 [NFIN] NFIN None None None None 2 7 [PST, ACT, PL, MASC, HUM] PST ACT PL MASC HUM 3 8 [FUT, 3, PL] FUT 3 PL None None 4 23 [PST, 2, SG, FEM] PST 2 SG FEM None Details In [33]: df Out[33]: id props 0 2 [FUT, 2, SG] 1 6 [NFIN] 2 7 [PST, ACT, PL, MASC, HUM] 3 8 [FUT, 3, PL] 4 23 [PST, 2, SG, FEM]

http://stackoverflow.com/comment/81879712
score: 0
comment on: http://stackoverflow.com/a/47462149
type: Comment
type: AnswerComment
has text: also, I would suggest not using `input()` in python 2

http://stackoverflow.com/comment/81902838
score: 0
has text: Apologies, I have edited my answer slightly. So its easier to understand. I have now attached an Ideal Output I am looking for below my current output. Thanks Again :)!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47474013

http://stackoverflow.com/comment/81935391
comment on: http://stackoverflow.com/q/47490033
has text: @DSM thanks! I am new to SO and trying to learn how to ask.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81813949
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47429294
type: Comment
has text: My last layer is a model itself. If I call `model.pop` I will pop both Dense layers, Dropout and Flatten. I only want to pop the last Dense and Dropout. Please read the question before answering it

http://stackoverflow.com/q/47498403
tagged with: pandas
answer count: 1
type: Question
tagged with: python-3.x
has title: IndexError: index 164 is out of bounds for axis 1 with size 164
has body: I try to drop columns and rows, and reset columns and rows after it. But on the third file, I get error: IndexError: index 164 is out of bounds for axis 1 with size 164 Files in my folder are 167*164 and, after dropping, are becoming 95*95. path = r'/home/RESULTS' allFiles = sorted((glob.glob(path + "/*.csv"))) for file_ in allFiles: data = pd.read_csv(file_, header=None) data = data.astype(str) data = data.apply(lambda x: x.str.replace(',', '.')) data = data.astype(float) data = data.fillna(value=1) data.drop(data.columns[cols_to_drop],axis=1,inplace=True) data.drop(data.index[rows_to_drop], inplace=True) data = data.reset_index(drop=True) data = data.T.reset_index(drop=True).T print(file_)
tagged with: python
accepted answer: http://stackoverflow.com/a/47498483
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47498483
score: 0

http://stackoverflow.com/q/47431704
type: Question
tagged with: buffer
tagged with: benchmarking
has title: Specify read buffer size in NetCDF (Python or C)
type: UnansweredQuestion
has body: I would like to benchmark NetCDF I/O performance compared to reading a plain binary file in Python and C. For reading the binary file, I have defined different buffer sizes to read. Here is the code of the read function in Python: def parse_os_read(filename, buffersize): f = open(filename, 'rb') for loops in itertools.count(): record = f.read(buffersize) if not record: break return loops I can then call this function with different buffer sizes ranging from 64 KB to several 100 MB. I would like to implement now a comparable sequential reading benchmark for NetCDF. However, I could not identify a read function, where I can set a pre-defined buffer size. I assume the NetCDF file should have a 1D array with random floats as a data structure. Any thoughts?
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/81823052
score: 0
answer count: 0
tagged with: netcdf
has comment: http://stackoverflow.com/comment/81819480

http://stackoverflow.com/comment/81780534
comment on: http://stackoverflow.com/a/47412196
has text: @smiss According to the example, the function expects a file in `C:\tmp\file.pdf` (Windows) or `/tmp/file.pdf` (Linux)
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81807348
type: QuestionComment
has text: Try it. Maybe help.
score: 0
comment on: http://stackoverflow.com/q/47426234
type: Comment

http://stackoverflow.com/q/47466871
tagged with: printing
tagged with: sqlite
tagged with: python
type: Question
has title: Print function in python 3.4 does not print anything in the command window when running the code
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81888223
has body: I am relatively new at this. I created a database table named tuturial.db and filled it with 30 row and 4 columns of data. import sqlite3 import time import datetime import random conn = sqlite3.connect('tutorial.bd') c = conn.cursor() def create_table(): c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, Datestamp TEXT, keyword TEXT, value REAL)') def data_entry(): c.execute("INSERT INTO stuffToPlot VALUES(145123555, '2016-01-02', 'Python', 8)") conn.commit() c.close() conn.close() def dynamic_data_entry(): unix = time.time() date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')) keyword = 'Python' value = random.randrange(0,10) c.execute("INSERT INTO stuffToPlot (unix, datestamp, keyword, value) VALUES (?, ? , ?, ?)", (unix, date, keyword, value)) conn.commit() Now I am trying to print the whole selected data in rows def read_from_db (): c.execute("SELECT * FROM stuffToPlot") for row in c.fetchall(): print(row) c.close() conn.close() When I run the code I do not get anything printed in the output window I just get "press any key to continue" I also noticed that when I put the mouse on the variable row it says row&lt;unknown type&gt; does that have anything to do with the problem? I tried to print something else simple like MMM = 45 print (MMM) Then the print function works I am not sure what I am missing here. Anyone can help? Really appreciated!
has comment: http://stackoverflow.com/comment/81889546
has answer: http://stackoverflow.com/a/47467124
score: 0

http://stackoverflow.com/q/47475585
linked to: http://stackoverflow.com/q/5424716
favorite count: 0
type: Question
tagged with: python-3.x
has body: Have been stuck on this for about an hour. Currently trying to teach myself Programming using Python. I am using a textbook for the programming stuff which walks me through pseudocode and then I attempt to convert this into python to learn the syntax. While to program runs and adds as it is supposed to, it will not print what I want it to if the user enters anything but an integer. Pseudocode I am looking at: 1 Declare Count As Integer 2 Declare Sum As Integer 3 Declare Number As Float 4 Set Sum = 0 5 For (Count = 1; Count &lt;=10; Count++) 6 Write “Enter an integer: “ 7 Input Number 8 If Number != Int(Number) Then 9 Write “Your entry is not an integer.” 10 Write “The summation has ended.” 11 Exit For 12 Else 13 Set Sum = Sum + Number 14 End If 15 End For 16 Write “The sum of your numbers is: “ + Sum This is the code i have written to this point: sum = 0 for count in range(0, 10): number = int(input("Write an integer: ")) if number != int(number): print ("Your entry is not an integer.") print ("The summation has ended.") break else: sum = sum + number continue print("The sum of your numbers is: " + str(sum))
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47475641
possible better answer: http://stackoverflow.com/a/47475632
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/81905742
duplicate of: http://stackoverflow.com/q/5424716
has comment: http://stackoverflow.com/comment/81905796
has answer: http://stackoverflow.com/a/47475641
has title: Checking that user input is an int (python)
has answer: http://stackoverflow.com/a/47475632
tagged with: loops

http://stackoverflow.com/q/47463436
upvote count: 1
tagged with: decorator
linked to: http://stackoverflow.com/q/3012421
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1782843
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: I'm using the following decorator for lazy evaluation of a property (based on this and this questions): from functools import wraps def lazy_property(fn): name = '_lazy_' + fn.__name__ @property @wraps(fn) def wrapper(self): if not hasattr(self, name): setattr(self, name, fn(self)) return getattr(self, name) return wrapper Then within some class I have mixed regular and "lazy" properties: class A(object): @property def f1(self): return 1 @lazy_property def f2(self): return 2 @lazy_property def f3(self): return 3 Is there any way how I can figure out that f1 is a regular and f2 and f3 are lazy properties without calling them? For the methods, @wraps(fn) should set up the __wrapped__ attribute, but it does not happen for the properties. I need this to write some "pre-fetching" method, which will evaluate all "lazy" properties at once (i.e. cache all necessary data). Indeed the "brute force solution" would be to hardcode all the names as a list, but this would not be easy to maintain in the future development - when new lazy-or-not properties will be added and/or types of properties will be changed based on the better understanding of use-cases.
score: 1
has comment: http://stackoverflow.com/comment/81886809
has title: Checking for the wrapped property in python
downvote count: 0

http://stackoverflow.com/q/47506854
has answer: http://stackoverflow.com/a/47506941
has body: i get this error while i am trying to run my django server and i am getting the following error I don't know why and the urls file is in the myproject/test/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('wars.urls')), ] myproject/test/settings.py ROOT_URLCONF = 'test.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] in the same folder I have another folder wars which has the urls too , in myproject/wars/ursl.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^auth/$', views.authenticate_for_token, name='authenticate'), url(r'^records/all/(?P&lt;token&gt;[1-9]_[a-z]*)/$', views.records_list_all, name='records_all'), url(r'^records/(?P&lt;offset&gt;[0-9]*)/(?P&lt;limit&gt;[1-9][0-9]*)/(?P&lt;token&gt;[1-9]_[a-z]*)/(?P&lt;comp_code&gt;[0-9]{2,8})/$', views.records_list_subset, name='records_all'), url(r'^records/save/$', views.records_save, name='records_save'), url(r'^dropdown/(?P&lt;comp_code&gt;[0-9]{2,8})/(?P&lt;token&gt;[1-9]_[a-z]*)/$', views.get_dropdown_lists, name='dropdown_lists'), url(r'^approve/$', views.approve_category, name='approve_category'), url(r'^approve/delete/$', views.approve_category_delete, name='approve_category_delete'), url(r'^hide-sheet/$', views.hide_sheet, name='hide_sheet'), url(r'^hide-sheet/delete/$', views.hide_sheet_delete, name='hide_sheet_delete'), url(r'^template/download/$', views.template_download, name='template_download'), url(r'^template/upload/$', views.template_upload, name='template_upload'), url(r'^overview/$', views.Overview.as_view(), name='admin_overview'), url(r'^login/$', views.LoginView.as_…
has comment: http://stackoverflow.com/comment/81969419
downvote count: 1
favorite count: 0
type: Question
has title: Django page not found 404
has comment: http://stackoverflow.com/comment/81969432
type: UnansweredQuestion
tagged with: django
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81969480
answer count: 2
has comment: http://stackoverflow.com/comment/81969406
has answer: http://stackoverflow.com/a/47506921
upvote count: 0

http://stackoverflow.com/a/47424212
score: 0
has comment: http://stackoverflow.com/comment/81803395
has comment: http://stackoverflow.com/comment/81804435
has body: I think what you're looking for is a static analysis tool. One of the things these (can) do, is flag unused blocks of code. Typically, you can integrate it into your CI loop. A quick search for 'python static analysis' on Google gives a number of links. One curated list of tools for various languages is here. One tool under Python that immediately jumps up for unused code checking is vulture, and it seems to be actively maintained.
has comment: http://stackoverflow.com/comment/81803488
has comment: http://stackoverflow.com/comment/81804256
answers question: http://stackoverflow.com/q/47424155
type: Answer
has comment: http://stackoverflow.com/comment/81803451
has comment: http://stackoverflow.com/comment/81803425

authentication
tags question: http://stackoverflow.com/q/47400814
tags question: http://stackoverflow.com/q/47438082
tags question: http://stackoverflow.com/q/47400711
tags question: http://stackoverflow.com/q/47511216
tag name: authentication
type: Tag
tags question: http://stackoverflow.com/q/47400505
tags question: http://stackoverflow.com/q/47506698
tags question: http://stackoverflow.com/q/47405339

http://stackoverflow.com/comment/81838228
comment on: http://stackoverflow.com/a/47441492
has text: This is preferable to a list/generator expression: It's debatable, but for applying a built-in function to a list `map()` is cleaner. That being said, both will work. Also, `split()` should be equivalent or better than `split(" ")` in this case.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81852348
comment on: http://stackoverflow.com/q/47448702
type: QuestionComment
score: 0
has text: did u try by trimming at each line? as paragraph meant just extra white spaces in each line.
type: Comment

http://stackoverflow.com/a/47513719
has comment: http://stackoverflow.com/comment/82013065
score: 0
has body: for i in range(1,(len(list))):#outer loop set to iterate for no of times:length of list -1 for j in range(i-1):#loop to iterate through o to i-1 if list[i]&lt;list[j]: list[i],list[j]=list[j],list[i]
has comment: http://stackoverflow.com/comment/82036407
has comment: http://stackoverflow.com/comment/81990097
answers question: http://stackoverflow.com/q/47513274
has comment: http://stackoverflow.com/comment/81990103
has comment: http://stackoverflow.com/comment/82036787
type: Answer

http://stackoverflow.com/q/47509249
tagged with: python
score: 12
type: AnsweredQuestion
tagged with: apache-spark
has body: I have a dataframe and I want to apply a function to each row. This function depends of other dataframes. Simplified example. I have three dataframes like below: df = sc.parallelize([ ['a', 'b', 1], ['c', 'd', 3] ]).toDF(('feat1', 'feat2', 'value')) df_other_1 = sc.parallelize([ ['a', 0, 1, 0.0], ['a', 1, 3, 0.1], ['a', 3, 10, 1.0], ['c', 0, 10, 0.2], ['c', 10, 25, 0.5] ]).toDF(('feat1', 'lower', 'upper', 'score')) df_other_2 = sc.parallelize([ ['b', 0, 4, 0.1], ['b', 4, 20, 0.5], ['b', 20, 30, 1.0], ['d', 0, 5, 0.05], ['d', 5, 22, 0.9] ]).toDF(('feat1', 'lower', 'upper', 'score')) For each row of df, I want to collect the unique upper values for feat1 and feat2 from df_other_1 and df_other_2, i.e. for first row, the unique values are (1, 3, 10, 4, 20, 30). Then, I'll sort them like (30, 20, 10, 4, 3, 1) and add to the front, one number above the first one. The df would become like so: df = sc.parallelize([ ['a', 'b', 1, [31, 30, 20, 10, 4, 3, 1]], ['c', 'd', 3, [26, 25, 22, 10, 5]] ]).toDF(('feat1', 'feat2', 'value', 'lst')) Then, for each row of df and for each of the respective values of the lst, I want to calculate the sum of score from both df_other_1 and df_other_2 where each value of lst falls within upper and lower. My goal is to find the lowest value in each lst whose total score is above some threshold (e.g. 1.4). Here's how to calculate the total score. So, for the first row of df, the first value of lst is 31. In df_other_1 for feat1, it is above the highest bucket so it would get a score of 1. Same for df_other_2. So, the total score would be 1+1 =2. For the value of 10 (again for the first row), the total score would be 1 + 0.5 = 1.5. This is how the df would look like in the end: df = sc.parallelize([ ['a', 'b', 1, [31, 30, 20, 10, 4, 3, 1], [2.0, 2.0, 2.0, 1.5, 1.5, 1.1, 0.2], 4], ['c', 'd', 3, [26, 25, 22, 10, 5], [2.0, 1.5, 1.4, 1.4, 1.1], 25] ]).toDF(('feat1', 'feat2', 'value', 'lst', 'total_scores', 'target_value')) I'm actually looking to find t…
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47509582
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47509582
tagged with: user-defined-functions
upvote count: 12
has title: How to pass DataFrame as input to Spark UDF?
tagged with: pyspark

http://stackoverflow.com/q/47430784
tagged with: numpy
type: Question
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/47430828
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/47430828
linked to: http://stackoverflow.com/q/41776579
has title: Numpy concatenate arrays with interleaving
type: AnsweredQuestion
upvote count: 3
score: 3
favorite count: 0
has body: I have 4 arrays and I want to concatenate them into one single array with interleaving. How do I do this? &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.tile(0,(5,2)) &gt;&gt;&gt; b = np.tile(1,(5,2)) &gt;&gt;&gt; c = np.tile(2,(5,2)) &gt;&gt;&gt; d = np.tile(3,(5,2)) &gt;&gt;&gt; e = np.concatenate((a,b,c,d),axis=1) &gt;&gt;&gt; e array([[0, 0, 1, 1, 2, 2, 3, 3], [0, 0, 1, 1, 2, 2, 3, 3], [0, 0, 1, 1, 2, 2, 3, 3], [0, 0, 1, 1, 2, 2, 3, 3], [0, 0, 1, 1, 2, 2, 3, 3]]) This gives just the concatenation. However, my desired_output is: &gt;&gt;&gt; desired_output array([[0, 1, 2, 3, 0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3]]) I mean I know I can select the interleaved columns from e using: &gt;&gt;&gt; f = e[:, ::2] &gt;&gt;&gt; array([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]) But how do I make one big array?

http://stackoverflow.com/comment/81749948
type: Comment
type: QuestionComment
has text: I don't think this is the right move. I am dealing with huge data and want to import it to postgresql with the least interference possible.
comment on: http://stackoverflow.com/q/47398243
score: 0

http://stackoverflow.com/comment/81993259
score: 0
comment on: http://stackoverflow.com/q/47518379
type: Comment
type: QuestionComment
has text: @RafaelMarques You need to do `Popen(['python',f_path])` windows doesn't know how to run a `.py` file.

http://stackoverflow.com/a/47402632
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47402346
score: 2
has body: By using category and value_counts df.cluster.map((-df.cluster.value_counts()).astype('category').cat.codes ) Out[151]: 0 0 1 0 2 0 3 0 4 2 5 2 6 1 7 1 8 1 9 3 Name: cluster, dtype: int8
downvote count: 0

http://stackoverflow.com/comment/81786932
type: Comment
comment on: http://stackoverflow.com/q/47413640
score: 0
has text: `ffff fff8 ff82 f825 825e 25ef 5eff efff ffff fff8 ff82 f826 8260 260f 60ff 0fff ffff35ff 5fff ffff fff7 ff72 f723 7238 238f 38ff 8fff ffff fff7 ff72 f724 7241 241f 41ff 1fff ffff fff7 ff72 f724 7244 244f 44ff 4fff ffff fff7 ff72 f724 7244 244f 44ff 4fff ffff fff8 ff80 f800 8000 000f 00ff 0fff ffff fff8 ff82 f825 825e 25ef 5eff efff ffff fff8 ff82 f826 8260 260f 60ff 0fff ffff` Thats part of the result Im getting now. Its a large file as you can imagine there is no way I can post all the result here.
type: QuestionComment

http://stackoverflow.com/a/47421653
has comment: http://stackoverflow.com/comment/81799831
has comment: http://stackoverflow.com/comment/81798714
has comment: http://stackoverflow.com/comment/81799753
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81799943
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81800073
has comment: http://stackoverflow.com/comment/81799504
has comment: http://stackoverflow.com/comment/81798960
has comment: http://stackoverflow.com/comment/81798623
score: 1
has body: Unfortunately you can't do a partial text match or remove the number from the string. What you could do is iterate through the available options until you find a match. Maybe something like this: ... # Grab the select box with selenium, same as you had before cityid = Select(driver.find_element_by_id('Location_CityId')) # Iterate through the available dropdown items for option in cityid.options: # Grab the value of the current dropdown ### NOT USED -&gt; This is for getting the option value, not the text # option_value = option.get_attribute('value') option_text = option.text # Check if the city you're currently looking for matches the current dropdown if City_Name in option_text: # If it does match, click on that item option.click() # Break out of the loop since we found what we're looking for break
has comment: http://stackoverflow.com/comment/81798922
answers question: http://stackoverflow.com/q/47421541
has comment: http://stackoverflow.com/comment/81799869
has comment: http://stackoverflow.com/comment/81799929
has comment: http://stackoverflow.com/comment/81799278
has comment: http://stackoverflow.com/comment/81799862
has comment: http://stackoverflow.com/comment/81800103
accepted answer of: http://stackoverflow.com/q/47421541

http://stackoverflow.com/comment/81845690
score: 0
has text: The example via the link you shared is attempting to classify 0's and 1's, are you attempting to expand this example to more than just two classes?
comment on: http://stackoverflow.com/q/47444608
type: Comment
type: QuestionComment

http://stackoverflow.com/a/73770438
has body: There are several custom builds of Python &gt;3.44 suitable for Windows XP. A poster at reddit has provided Python 3.55 here: https://www.reddit.com/r/Python/comments/3tgi0t/python_35_x86_on_windows_xp/ Here is an XP compatible build of 3.6.15 source code only: https://alex-free.github.io/winxp_python3.6.15/ At the MSFN forums someone has provided an XP compatible build of 3.8.1350 here: https://msfn.org/board/topic/183741-python-3813-for-windows-xp-sp3/
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47516712
downvote count: 0
has comment: http://stackoverflow.com/comment/132965430
has comment: http://stackoverflow.com/comment/134181073

http://stackoverflow.com/comment/82425616
type: Comment
type: AnswerComment
has text: it's worse than that actually. you can't modify /usr/local/ without disabling system integrity protection. it has permissions higher than root.
comment on: http://stackoverflow.com/a/47721925
score: 0

http://stackoverflow.com/comment/81974212
type: Comment
type: QuestionComment
score: 5
has text: (1) Go to `mysite` directory: `cd mysite`. (2) Run django: `python manage.py runserver`. I think you need to spend a few hours learning how to use command line. Also, read the [Django tutorial](https://docs.djangoproject.com/en/1.11/intro/tutorial01/). You can 't expect to make a website using Django without at least reading the tutorial.
comment on: http://stackoverflow.com/q/47508891

http://stackoverflow.com/comment/82029764
score: 0
has text: at start assign default value to `Berufsbezeichnung` - it can be empty string (or None). If it doesn't find it then you will have this variable with empty/default string.
type: Comment
comment on: http://stackoverflow.com/q/47532710
type: QuestionComment

http://stackoverflow.com/q/47493802
has title: I cannot find the element in html code below using Selenium Robot Framework
upvote count: 0
has answer: http://stackoverflow.com/a/47496013
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81944228
has comment: http://stackoverflow.com/comment/81947894
favorite count: 0
type: Question
tagged with: robotframework
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81943542
tagged with: selenium-webdriver
has body: Below is the HTML code for the toggle element. It is a side bar menu (nbn network rollout reports> that will display two links once clicked or expanded. I already tried "Click Element" keyword using "network rollout repots" but it didn't work. nbn™ network rollout reports

http://stackoverflow.com/a/47536681
has comment: http://stackoverflow.com/comment/119559230
answers question: http://stackoverflow.com/q/47535872
downvote count: 0
has comment: http://stackoverflow.com/comment/82033602
score: 9
upvote count: 9
has body: scikit-learn will handle this easily! Code: from time import perf_counter as pc import numpy as np import scipy.sparse as sps from sklearn.decomposition import NMF """ Create sparse data """ nnz_i, nnz_j, nnz_val = np.random.choice(531000, size=45000), \ np.random.choice(315000, size=45000), \ np.random.random(size=45000) X = sps.csr_matrix((nnz_val, (nnz_i, nnz_j)), shape=(531000, 315000)) print('X-shape: ', X.shape, ' X nnzs: ', X.nnz) print('type(X): ', type(X)) # &lt;class 'scipy.sparse.csr.csr_matrix'&gt; # !!!!!!!!!! """ NMF """ model = NMF(n_components=50, init='random', random_state=0, verbose=True) start_time = pc() W = model.fit_transform(X) end_time = pc() print('Used (secs): ', end_time - start_time) print(model.reconstruction_err_) print(model.n_iter_) Output: X-shape: (531000, 315000) X nnzs: 45000 type(X): &lt;class 'scipy.sparse.csr.csr_matrix'&gt; violation: 1.0 violation: 0.2318929397542804 violation: 0.11045394409727402 violation: 0.08104138988253409 ... violation: 9.659665625799714e-05 Converged at iteration 71 Used (secs): 247.94092973091756 122.27109041 70 Remarks: Make sure you use sparse-matrices as input or you can't exploit sparsity I'm using version 0.19.1, so the multiplicative-update solver is used (>= 0.19) But the older CD-based solver should handle this too! The above is using &lt; 800 MB of memory Additional Constraints As mentioned in the comments, OP wants to add additional constraints, while still not specifying these formally. This will need a whole new implementation of some optimization-procedure including some theory-footwork (depending on the constraints). As an alternative, this can be solved by general-purpose Convex-Programming solvers. E.g. formulated by cvxpy and solved by SCS. Of course the alternating-minimization procedure needs to be done too (as the joint-problem is non-convex) and it will scale worse than this specialized sklearn-implementation. But it might work for OPs data.
has comment: http://stackoverflow.com/comment/120483351
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82033338
accepted answer of: http://stackoverflow.com/q/47535872

http://stackoverflow.com/comment/82027731
type: Comment
comment on: http://stackoverflow.com/q/47535208
score: 0
type: QuestionComment
has text: which IDE are you using???

http://stackoverflow.com/comment/81999494
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47437425
has text: @Actuary `@echo off`, `python file.py`. Copy the Python installation with all the necessary folders and place the script above along with python.exe and you script. It will now launch from the Python interpreter.
score: 0

http://stackoverflow.com/comment/81826488
has text: UTF-8 encoded and unicode strings are different in python. Each unicode character converts to two UTF-8 characters.
comment on: http://stackoverflow.com/q/47435854
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81915859
score: 0
has text: I can surely investigate with your tip, thanks for it. I'll post the answer if i can find it, or post my desparation if not... We'll see!
type: Comment
comment on: http://stackoverflow.com/q/47477664
type: QuestionComment

http://stackoverflow.com/a/55246956
has body: As for how to check your encoding, there's a simple trick here, might be of use: You can just open the file using notepad and then goto File -> Save As. Next to the Save button there will be an encoding drop down and the file's current encoding will be selected there.
type: Answer
answers question: http://stackoverflow.com/q/47393869
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/81856242
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47450635
type: Comment
has text: what is your user input and what do you want to delete? Did you read about databases and json files so far?

http://stackoverflow.com/comment/81998692
comment on: http://stackoverflow.com/a/47519795
score: 0
type: Comment
type: AnswerComment
has text: @OopsUser `df.ffill()` fill the NaN by the pervious not NaN values, `loc[~(df.Val==df.New),:]` , slice the row which Val not Equal New

http://stackoverflow.com/a/47461277
upvote count: 1
has body: Your immediate problem is that: &lt;int **&gt;(&amp;Z[0][0]) takes the address of the first element of the first row and casts it to an int**. It's actually an int* (because it's the address of an int). Therefore the memory that initializer writes to is nonsense and you get a segmentation fault. Casts are often an indication that you're doing something wrong. You just need to pass Z which is already an int**.
answers question: http://stackoverflow.com/q/47456055
has comment: http://stackoverflow.com/comment/81877983
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81878622
downvote count: 0

http://stackoverflow.com/q/47397676
tagged with: python
has comment: http://stackoverflow.com/comment/81909349
score: 0
tagged with: opencv3.0
has body: I have a project at school that asks me to detect any discontinuity on railways. The idea is taking a video of railways (it's a model, the witdh of the railways is only 3 cm) thanks to a camera, and then a program (I have to create) has to be able to detect any discontinuity on the railways. For now, I created a program able to detect horizontal lines (it can be changed easily to detect vertical lines if necessary, depending on how the video is taken). My idea is to calculate the distance between two lines in order to detect a discontinuity if the distance is too high. The problem is, my program has some difficulties to detect long lines (it detects a lot of little lines instead). Does anyone has an idea to detect all the railways with only 2 big lines instead of a lot of little lines ? I tried to look on internet to find something helpful, but this program is the only one I found. Maybe someone already has something to detect railways ? Thanks in advance for your help ! Here is the code I work on : import numpy as np import cv2 import math as m camera = cv2.VideoCapture('mavideo.mp4') while (camera.isOpened()): ret,frame1 = camera.read() frame = cv2.resize(frame1,(600,600)) edge = cv2.Canny(frame,100,200,apertureSize=3) minLineLength = 10 maxLineGap = 15 line = cv2.HoughLinesP(edge,1,np.pi/180,100,minLineLength,maxLineGap) if line is not None: for (x1,y1,x2,y2) in line[0]: if y2==y1: cv2.line(frame,(x1, y1), (x2, y2), (0,255,0),5) if line.any()==True: d = m.sqrt(m.pow((x2-x1),2)+m.pow((y2-y1),2)) print d print "Line Detected" cv2.imshow("line detection",frame) cv2.imshow('edge',edge) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break else: print "Line not detected" #'http://192.168.43.1:8080/' camera.release() cv2.destroyAllWindows() First example of the results of the code Second example of the results of the code
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81749194
has title: How can I detect a discontinuity on railways?

http://stackoverflow.com/comment/81917514
has text: What was missing above was the str() method on line 21. I also reformatted a few lines where you are concatenating "$" with "@" to give some space for aesthetic purposes. I hope this is what you are looking for..
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47481341

http://stackoverflow.com/comment/82024445
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47519255
type: Comment
has text: So I just did all of that, but I'm still getting the error "No module named 'matplotlib'". What do I do now?

http://stackoverflow.com/q/47536243
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47536318
favorite count: 0
type: Question
has title: Grouping odd and even days
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82029355
has answer: http://stackoverflow.com/a/47536318
has body: I have a pandas dataframe as the following data Out[8]: value1 Date 2015-03-31 09:53:53.800 NaN 2015-03-31 10:28:54.700 1.34 2015-03-31 10:34:35.720 NaN 2015-03-31 10:36:53.540 1.26 2015-04-01 11:37:11.620 1.44 2015-04-01 11:39:30.520 NaN 2015-04-01 11:50:25.620 1.76 2015-04-02 11:50:30.620 1.38 2015-04-02 12:31:20.220 1.76 2015-04-02 12:37:43.940 2.36 2015-04-03 12:38:45.820 1.46 2015-04-03 12:41:56.680 2.26 2015-04-04 13:04:50.740 1.16 2015-04-05 12:38:45.820 1.46 2015-04-05 12:41:56.680 2.26 2015-04-05 13:04:50.740 1.16 and I would like to compute the mean of the values belonging to the days 0-2-4 and the mean of the values belonging to the days 1-3-5 How can I use groupby on the dates to do so? df2 = data.groupby(?).agg(np.mean)
tagged with: pandas-groupby
upvote count: 2
tagged with: pandas

http://stackoverflow.com/q/47454047
type: Question
has comment: http://stackoverflow.com/comment/81869119
has comment: http://stackoverflow.com/comment/81917635
has comment: http://stackoverflow.com/comment/81928880
linked to: http://stackoverflow.com/q/47437077
tagged with: azure-blob-storage
has comment: http://stackoverflow.com/comment/81865347
tagged with: python
has title: Azure blob storage to JSON in azure function using SDK
has comment: http://stackoverflow.com/comment/81863308
type: AnsweredQuestion
score: 0
has body: I am trying to create a timer trigger azure function that takes data from blob, aggregates it, and puts the aggregates in a cosmosDB. I previously tried using the bindings in azure functions to use blob as input, which I was informed was incorrect (see this thread: Azure functions python no value for named parameter). I am now using the SDK and am running into the following problem: import sys, os.path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'myenv/Lib/site-packages'))) import json import pandas as pd from azure.storage.blob import BlockBlobService data = BlockBlobService(account_name='accountname', account_key='accountkey') container_name = ('container') generator = data.list_blobs(container_name) for blob in generator: print("{}".format(blob.name)) json = json.loads(data.get_blob_to_text('container', open(blob.name))) df = pd.io.json.json_normalize(json) print(df) This results in an error: IOError: [Errno 2] No such file or directory: 'test.json' I realize this might be an absolute path issue, but im not sure how that works with azure storage. Any ideas on how to circumvent this? Made it "work" by doing the following: for blob in generator: loader = data.get_blob_to_text('kvaedevdystreamanablob',blob.name,if_modified_since=delta) json = json.loads(loader.content) This works for ONE json file, i.e I only had one in storage, but when more are added I get this error: ValueError: Expecting object: line 1 column 21907 (char 21906) This happens even if i add if_modified_since as to only take in one blob. Will update if I figure something out. Help always welcome. Another update: My data is coming in through stream analytics, and then down to the blob. I have selected that the data should come in as arrays, this is why the error is occurring. When the stream is terminated, the blob doesnt immediately append ] to the EOF line in json, thus the json file isnt valid. Will try now with using line-by-line in stream analytics instead of array.
tagged with: azure-functions
has comment: http://stackoverflow.com/comment/81863028
has answer: http://stackoverflow.com/a/47555082
answer count: 1
accepted answer: http://stackoverflow.com/a/47555082

http://stackoverflow.com/comment/82023927
type: AnswerComment
has text: If it solves your problem, could you mark it as correct answer?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47528226

http://stackoverflow.com/comment/81940171
score: 0
comment on: http://stackoverflow.com/q/47492398
type: Comment
type: QuestionComment
has text: a function is executed when you call it. you call a function with `()`, and you clearly did that.

http://stackoverflow.com/a/47396267
type: Answer
has comment: http://stackoverflow.com/comment/81747167
answers question: http://stackoverflow.com/q/47391774
has comment: http://stackoverflow.com/comment/81746254
has comment: http://stackoverflow.com/comment/81746063
has comment: http://stackoverflow.com/comment/81745831
has comment: http://stackoverflow.com/comment/81746545
has comment: http://stackoverflow.com/comment/81747595
has body: You're looking for pickle and the loads and dumps operations. Sockets are basically byte streams. Let us consider the case you have. class ProcessData: process_id = 0 project_id = 0 task_id = 0 start_time = 0 end_time = 0 user_id = 0 weekend_id = 0 An instance of this class needs to be pickled into a data string by doing data_string = pickle.dumps(ProcessData()) and unpickled by doing data_variable = pickle.loads(data) where data is what is received. So let us consider a case where the client creates an object of ProcessData and sends it to server. Here's what the client would look like. Here's a minimal example. Client import socket, pickle class ProcessData: process_id = 0 project_id = 0 task_id = 0 start_time = 0 end_time = 0 user_id = 0 weekend_id = 0 HOST = 'localhost' PORT = 50007 # Create a socket connection. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) # Create an instance of ProcessData() to send to server. variable = ProcessData() # Pickle the object and send it to the server data_string = pickle.dumps(variable) s.send(data_string) s.close() print 'Data Sent to Server' Now your server which receives this data looks as follows. Server import socket, pickle class ProcessData: process_id = 0 project_id = 0 task_id = 0 start_time = 0 end_time = 0 user_id = 0 weekend_id = 0 HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr data = conn.recv(4096) data_variable = pickle.loads(data) conn.close() print data_variable # Access the information by doing data_variable.process_id or data_variable.task_id etc.., print 'Data received from client' Running the server first creates a bind on the port and then running the client makes the data transfer via the socket. You could also look at this answer.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81745760
downvote count: 1
score: 29
has comment: http://stackoverflow.com/comment/113145784
has comment: http://stackoverflow.com/comment/93372015
upvote count: 30
has comment: http://stackoverflow.com/comment/81746280
has comment: http://stackoverflow.com/comment/81746201
accepted answer of: http://stackoverflow.com/q/47391774

http://stackoverflow.com/comment/81795420
score: 1
type: Comment
has text: Update: powershell solution is `python $env:scripts\test.py` which unfortunately is a quite long command
comment on: http://stackoverflow.com/a/47419701
type: AnswerComment

http://stackoverflow.com/comment/81936176
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47489905
has text: @user2357112 I meant round down, thanks. By the way, what’s the difference between rounding to 0 and flooring?
score: 0

http://stackoverflow.com/a/47502441
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47501469
has body: Pocket Kings' solution is great and should be accepted. This is an example if you want to show routes for multiple drivers (admin page?) in order to avoid N+1 queries. This pre-fetches all the routes associated to the drivers and adds an attribute routes to each driver with their specific routes, so that it would eliminate the unneeded SQL queries later. from django.db.models import Prefetch drivers = Driver.objects.all() queryset = drivers.prefetch_related(Prefetch('route_set', queryset=Route.objects.filter(driver_id__in=drivers), to_attr='routes')) Template {% for driver in drivers %} {% for route in driver.routes %} &lt;p&gt;{{ route.leave_from }}&lt;/p&gt; &lt;p&gt;{{ route.destination }}&lt;/p&gt; ... {% endfor %} {% endfor %}

http://stackoverflow.com/comment/81860746
has text: Ah, gotcha. I like your suggested solution in that case @timgeb.
comment on: http://stackoverflow.com/a/47453000
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/47515312
has comment: http://stackoverflow.com/comment/81986509
has comment: http://stackoverflow.com/comment/81986850
has comment: http://stackoverflow.com/comment/81986919
favorite count: 0
tagged with: binary-tree
type: Question
accepted answer: http://stackoverflow.com/a/47515620
has body: What I'm trying to do is to get each element's level. I'm currently using this code: re = {0: [b.keys()[0]]} n = 1 for a in b: l = [] for e in s[a]: l.append(e) if l != []: re.update({n: l}) n += 1 print re That is giving me the following output: {"0": ["a"], "1": ["b"], "2": ["i"], "3": ["c", "d"], "4": ["f", "g", "h"], "5": ["e", "l"]} What I'm doing wrong here?
has comment: http://stackoverflow.com/comment/81987060
has answer: http://stackoverflow.com/a/47515620
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
tagged with: list
has title: Finding elements for each binary tree level in python
possible better answer: http://stackoverflow.com/a/47515603
answer count: 3
has answer: http://stackoverflow.com/a/47515718
has comment: http://stackoverflow.com/comment/81986441
has comment: http://stackoverflow.com/comment/81986620
has answer: http://stackoverflow.com/a/47515603
downvote count: 0
has comment: http://stackoverflow.com/comment/81986588
has comment: http://stackoverflow.com/comment/81986641

http://stackoverflow.com/comment/81724945
type: QuestionComment
has text: You should return from the recursive call: `return create_csv_name(comm, index=index)`
comment on: http://stackoverflow.com/q/47385933
score: 0
type: Comment

http://stackoverflow.com/comment/81796672
comment on: http://stackoverflow.com/q/47420926
type: Comment
type: QuestionComment
has text: Possible duplicate of [How can I find all matches to a regular expression in Python?](https://stackoverflow.com/questions/4697882/how-can-i-find-all-matches-to-a-regular-expression-in-python). You're using `search`, you need to use `findall` or `finditer`
score: 1

http://stackoverflow.com/q/47483334
linked to: http://stackoverflow.com/q/5952344
tagged with: string
duplicate of: http://stackoverflow.com/q/5952344
has comment: http://stackoverflow.com/comment/81921390
type: Question
has answer: http://stackoverflow.com/a/47483376
has title: python print string from variable name in string
type: UnansweredQuestion
has body: I want to display a text. and in the text there is a variable name, and the name of the variable is already in the previous definition. example code my_dict = {} my_dict['name']='Candra' #I want to be like this print('my name is {name}') #not like this print('my name is '+ my_dict['name'])
tagged with: python
has answer: http://stackoverflow.com/a/47483417
score: 0
answer count: 2

http://stackoverflow.com/q/47403958
tagged with: python
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81761696
downvote count: 0
has body: I wrote the following code in Python IDLE, using its editor import urllib.request print(urllib.request.urlopen('https://github.com').read().decode('utf-8')) and then saved the code as a script. After I ran the script, Python displayed the page source I want. When I changed the above code to: import urllib.request urllib.request.urlopen('https://github.com').read().decode('utf-8') and then ran the script, Python displayed nothing. This is understandable. The weird thing for me, however, is that if I run the above code (the one without print) interactively in a Python shell, Python shell can still display the page source, as you see: >>> import urllib.request >>> urllib.request.urlopen('https://github.com').read().decode('utf-8') '\n\n\n\n\n\n \n<html\n lang="en"\n \n \n ...' (output snipped) I don't understand why.
upvote count: 1
has comment: http://stackoverflow.com/comment/81761697
tagged with: read-eval-print-loop
accepted answer: http://stackoverflow.com/a/47403983
favorite count: 0
possible better answer: http://stackoverflow.com/a/47404007
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47403983
has answer: http://stackoverflow.com/a/47404007
has comment: http://stackoverflow.com/comment/81761729
score: 1
has title: Why does the Python shell output something even when there is no "print" command?

http://stackoverflow.com/q/47475255
favorite count: 0
has body: ISSUE: Not able to create named logs CODE: from google.cloud import logging client = logging.Client() # client = logging.Client.from_service_account_json('credentials.json') logger1 = client.logger("my_new_log_1") logger1.log_text("hello logger 1") logger2 = client.logger("my_new_log_2") logger2.log_text("hello logger 2") ERROR: 'module' object has no attribute 'info' This code needs to run on Google App Engine Standard
has title: In Google App Engine Standard (Python) create named logs
type: Question
downvote count: 0
tagged with: google-cloud-platform
linked to: http://stackoverflow.com/q/47223678
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47478655
answer count: 1
tagged with: google-cloud-stackdriver
tagged with: google-cloud-logging
tagged with: google-app-engine
score: 1
has comment: http://stackoverflow.com/comment/81905717
tagged with: python

http://stackoverflow.com/q/47539248
score: 0
has comment: http://stackoverflow.com/comment/82035991
has body: My Python program is having a hard time with the symbol &#10004 and I want to replace it with the word "PASS". This is what my table looks like: &#1004 and I am trying to replace that string like this: fileString = "" for elem in root.iter(): if elem.tag == 'table': for row in elem.findall('tr'): for column in row.findall('td'): fileString = fileString.text.replace('&#10004','PASS') I also tried: for elem in root.findall('td'): if elem.text == "&#10004" in elem.text: elem.string = 'Pass' But when I try and run, I get an xml.etree.ElementTree.ParseError: Not well-formed (invalid token): Line 43, column 45. FYI, fileSting is not empty, the XML file is being fed in through a separate function, I am not having any issues there. I have a feeling I am either really close or really far off.
has comment: http://stackoverflow.com/comment/82035500
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/82037170
type: Question
has comment: http://stackoverflow.com/comment/82037016
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82036769
has comment: http://stackoverflow.com/comment/82035682
tagged with: python
has title: Use Python to replace a string in a HTML table
has comment: http://stackoverflow.com/comment/82037422
has comment: http://stackoverflow.com/comment/82035800
tagged with: replace

http://stackoverflow.com/comment/81906776
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47475758
score: 0
has text: Sorry, got that wrong. Edited for reflecting your comment.

http://stackoverflow.com/q/47475795
score: 1
upvote count: 1
has title: lookup, interpolate and match between pandas dataframes
has body: new here, and this is my first ever question, I hope I can reciprocate by answering other peoples questions in the future. I have two pandas dataframes, A &amp; B, each containing float64 values, both with the same dimensions and same index and column float64 numerical entries. E.g. A 0.5 1.0 1.5 2.0 -1.947417e-15 0.015178 0.045640 0.074928 0.100943 -5.000000e-01 0.047697 0.149200 0.256133 0.359234 -1.000000e+00 0.082972 0.272634 0.494826 0.733841 -1.500000e+00 0.120121 0.417265 0.811659 1.303373 -2.000000e+00 0.155978 0.572880 1.206698 2.159998 B 0.5 1.0 1.5 2.0 -1.947417e-15 0.003859 0.018968 0.042486 0.070368 -5.000000e-01 0.003859 0.036093 0.100487 0.187447 -1.000000e+00 -0.007340 0.018968 0.107873 0.254083 -1.500000e+00 -0.029713 -0.038906 0.042486 0.178620 -2.000000e+00 -0.059926 -0.134084 -0.091504 0.032577 I would like to be able to lookup a fixed value (e.g. 0.25) in each data column in A, returning the (linearly) interpolated index value for each column (but only when the value exists in the range of the column data values - so not column 0.5 in A). Dataframe A will always have the column data monotonically increasing. Once I have the interpolated index values for each column in Dataframe A for a data value, say 0.25, then I would like to retrieve the values within Dataframe B that have the same 'coordinates', i.e. the interpolated index and equivalent column value. So for example, a lookup of 0.25 in A, then for column 1.5 would interpolate the index between 0 and -0.5, somewhere close to but greater than the value -0.5. The value returned from B would be a lookup of the index in B for column 1.5, so returning somewhere between 0.042486 and 0.100487, close to but less than 0.100487 value. I would want to return these '0.25' coordinate values in A and lookup &amp; interpolate for the equivalent values in each column in B. Slightly confusing, does it make sense? I've done a lot of searching and can find some pandas dataframe interpolation methods, but gener…
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81946838
type: Question
tagged with: interpolation
has answer: http://stackoverflow.com/a/47500253
has comment: http://stackoverflow.com/comment/81914518
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/10464738
has comment: http://stackoverflow.com/comment/81914149
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/81931799
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47484023
has text: WOW! that is a simple solution. Thank you. I thought this was going to be a lot harder but i always over complicate things so it figures :)

http://stackoverflow.com/a/47405538
answers question: http://stackoverflow.com/q/47405420
has comment: http://stackoverflow.com/comment/81764582
has comment: http://stackoverflow.com/comment/81764603
upvote count: 2
score: 0
downvote count: 2
type: Answer
has body: Regex is one way to go. You can accomplish the same using filter &gt;&gt;&gt; lst = [u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest'] &gt;&gt;&gt; list(filter(lambda s: all(c.isdigit() or c == "." for c in s), lst)) ['3.1.1', '3.2', '3.1.2', '3', '3.3.0', '3.2.2']
has comment: http://stackoverflow.com/comment/81764541
accepted answer of: http://stackoverflow.com/q/47405420
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81764566

http://stackoverflow.com/comment/81930366
comment on: http://stackoverflow.com/q/47487744
score: 0
type: Comment
has text: what is your expected output, what do you want in second column
type: QuestionComment

http://stackoverflow.com/q/47492742
downvote count: 0
tagged with: pandas
has body: I have a list of dictionaries like this [{"Key":[val1,val2,...]}, {"Key2":[val1,val2,...]}, ...] I would like to convert this to a csv format where the keys are column headers, and he values form the column values To do this I had intended to use a pandas dataframe (which exports to csv readily), but I can't work out how to get my values into the data frame. I've tried myPanda = pd.DataFrame.from_records(data) but alas, to no avail.
tagged with: http://stackoverflow.com/tag/csv
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47492761
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47492761
has title: Panda array from list of dictionaries
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81940916
type: AnsweredQuestion

http://stackoverflow.com/q/47483390
upvote count: 1
tagged with: python
has title: Delete characters in a string Python
answer count: 4
has answer: http://stackoverflow.com/a/47483427
tagged with: filepath
tagged with: replace
has answer: http://stackoverflow.com/a/47483515
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47483427
tagged with: string
downvote count: 1
has answer: http://stackoverflow.com/a/47483534
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47483836
has answer: http://stackoverflow.com/a/47483836
has body: orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf" The original string needs to be modified (copy into a new variable) to look like the new_string below. The file has thousands of lines with the same format (file path of a pdf file). new_string = "\\\\file_foo\\bar\\foo-bar.pdf" How do I modify the orig_string to look like the new string? Edit: Sorry, I forgot to mention on my original post. The '\text-to-be-deleted' is not the same. All filepath have different '\text-to-be-deleted' string. Ex. "\\\\file_foo\\bar\\path100\\foo-bar.pdf" "\\\\file_foo\\bar\\path-sample\\foo-bar.pdf" "\\\\file_foo\\bar\\another-text-be-deleted\\foo-bar.pdf" ... and so on.

http://stackoverflow.com/a/47496462
has body: You can easily use dict with tuple/list values like so: def get_ext(file_type): d = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv']} return d[file_type] print(get_ext('audio'))
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47496415
score: 4

http://stackoverflow.com/q/47464272
tagged with: tensorflow-serving
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47537080
answer count: 2
has comment: http://stackoverflow.com/comment/81907049
downvote count: 0
score: 1
upvote count: 1
tagged with: machine-learning
has title: Unknown: KeyError: 'pyfunc_0'
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81906301
has answer: http://stackoverflow.com/a/47537080
possible better answer: http://stackoverflow.com/a/47468589
has comment: http://stackoverflow.com/comment/81883713
has comment: http://stackoverflow.com/comment/81907483
tagged with: tensor
has answer: http://stackoverflow.com/a/47468589
has comment: http://stackoverflow.com/comment/81883253
has body: I am exporting a savedModel which takes a string placeholder as the input tensor. I injected a graph to preprocess this string tensor so that it can be passed into the model. However, I am using py_func to perform my python string operations on the tensor. Here input_text is the input tensor in the savedModel signature. I created another placeholder with default input_ints which is initialized with result of performing py_func on input_text. I initially had input_text as an operation (input_ints =tf.py_func(preprocess, [input_text], tf.int64)) but then tf.nn.dynamic_rnn was not accepting a tensor with unspecified shape. # Create the graph object with tf.name_scope('inputs'): input_text = tf.placeholder(tf.string, name="input_text") input_ints = tf.placeholder_with_default( tf.py_func(preprocess, [input_text], tf.int64), shape=[None, None]) def lstm_cell(): # Your basic LSTM cell lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size, reuse=tf.get_variable_scope().reuse) # Add dropout to the cell return tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob) # def create_rnn(): with tf.name_scope("Embeddings"): embedding = tf.Variable(tf.random_uniform((vocab_size, embed_size), -1, 1)) embed = tf.nn.embedding_lookup(embedding, input_ints) with tf.name_scope("RNN_layers"): cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(lstm_layers)]) initial_state = cell.zero_state(batch_size, tf.float32) with tf.name_scope("RNN_forward"): outputs, final_state = tf.nn.dynamic_rnn(cell, embed, initial_state=initial_state) with tf.name_scope('predictions'): predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid) Now using the above implementation, I can export the model properly but when restoring the model, I get the following error: 2017-11-23 17:29:14.600184: W tensorflow/core/framework/op_kernel.cc:1192] Unknown: KeyError: 'pyfunc_0' Traceback (most recent call last): File "/Users/sakibarrahman/anaconda/lib/python3.6/site-packages/…

http://stackoverflow.com/a/47416928
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/47411468
has comment: http://stackoverflow.com/comment/81795625
has comment: http://stackoverflow.com/comment/81794719
downvote count: 0
has comment: http://stackoverflow.com/comment/81795735
has body: What is happening is your worker takes in more than one task, unless you have the -Ofair flag when starting the worker https://medium.com/@taylorhughes/three-quick-tips-from-two-years-with-celery-c05ff9d7f9eb So, even if you clear out your queue, your worker will still be running with the tasks its already picked up, unless you kill the worker process itself. Edit to add If you have a task running after restart, you need to revoke the task. http://celery.readthedocs.io/en/latest/faq.html#can-i-cancel-the-execution-of-a-task
has comment: http://stackoverflow.com/comment/81794876
type: Answer

http://stackoverflow.com/q/47436107
has title: scrapy is not crawling all content
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48000883
answer count: 1
tagged with: web-crawler
tagged with: scrapy
has body: I want to crawl a website that has url in this format : www.test.com/category1/123456.html (page) www.test.com/category1/123457.html .. www.test.com/category2 www.test.com/category3 ... here is the code: class ExampleSpider(CrawlSpider): name = "test" # Spider name allowed_domains = ["test.com"] # Which (sub-)domains shall be scraped? start_urls = ["https://test.com/"] # Start with this one user_agent=["Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"] rules = [Rule(LinkExtractor(allow=(r'/[a-z-]+/[0-9]+\.html$')), callback='parse_item', follow=True)] # Follow any link scrapy finds (that is allowed). def parse_item(self, response): print('Got a response from %s.' % response.url) selector = Selector(response) title = selector.xpath('//title/text()').extract()[0] post = '' for line in selector.xpath('//div[@id="article_body"]/p/text()').extract(): post += line url = response.url print('TITLE: %s \n' % title) print('CONTENT: %s \n' % post) Results: 2017-11-22 12:19:19 [scrapy.core.engine] INFO: Closing spider (finished) 2017-11-22 12:19:19 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 132266, 'downloader/request_count': 315, 'downloader/request_method_count/GET': 315, 'downloader/response_bytes': 9204814, 'downloader/response_count': 315, 'downloader/response_status_count/200': 313, 'downloader/response_status_count/301': 2, 'dupefilter/filtered': 21126, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2017, 11, 22, 12, 19, 19, 295516), 'log_count/DEBUG': 318, 'log_count/INFO': 11, 'offsite/domains': 1, 'offsite/filtered': 312, 'request_depth_max': 4, 'response_received_count': 313, 'scheduler/dequeued': 315, 'scheduler/dequeued/memory': 315, 'scheduler/enqueued': 315, 'scheduler/enqueued/memory': 315, 'start_time': datetime.datetime(2017, 11, 22, 12, 14, 41, 591030)} 2017-11-22 12:19:19 [scrapy.core.engine] INFO: Spider closed (finished) the crawler stops after o…
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/47581628
has body: The problem has been solved, It was not the code. It was the hosting service, I had to reset the File permissions on the server and after that all works perfectly again.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47489711
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47489711

http://stackoverflow.com/q/47479480
favorite count: 0
tagged with: face-recognition
accepted answer: http://stackoverflow.com/a/47479507
type: Question
tagged with: python-3.x
upvote count: 2
has title: How to increase the size of a detected rectangle for openCV in python?
has body: I'm using openCV in Python3.6 to detect faces in an image. It works well enough and detects the face, but I'd like the rectangle to include more of the face (chin, hair, etc.) since those parts are important in recognizing the person. I'm using this code. How can I get the program to select more of the face? Here's an example of what I'm getting (censored for privacy of course)
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47479507
score: 1
has comment: http://stackoverflow.com/comment/81913907
answer count: 1
tagged with: image-processing
downvote count: 1

http://stackoverflow.com/a/47482192
downvote count: 0
upvote count: 1
has body: You can simply have a relationship between the min and the max value's index within the list to another list containing the month names. calendarMonthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] #Get the index of the min value and use that index value to get the month name. print('The month with the lowest rainfall was', min(yearly_rainfall), ', and that month is', calendarMonthNames[yearly_rainfall.index(min(yearly_rainfall))])
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47482139
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81919429
accepted answer of: http://stackoverflow.com/q/47482139

format
tags question: http://stackoverflow.com/q/47497536
tags question: http://stackoverflow.com/q/47392040
tags question: http://stackoverflow.com/q/47464891
tag name: format
tags question: http://stackoverflow.com/q/47451256
type: Tag
tags question: http://stackoverflow.com/q/47397461
tags question: http://stackoverflow.com/q/47426126
tags question: http://stackoverflow.com/q/47441224

http://stackoverflow.com/comment/82223436
comment on: http://stackoverflow.com/q/47512686
type: QuestionComment
has text: @Shai: I copied mask_extractor.py to caffe/python/caffe and added 'from .mask_extractor import MaskExtractor' and still the same error! What did I do wrong? This only happens when I run caffe from bash, not python script
type: Comment
score: 0

http://stackoverflow.com/comment/82010093
type: Comment
comment on: http://stackoverflow.com/q/47526902
score: 0
type: QuestionComment
has text: Possible duplicate of [How do I get python to read only every other line from a file that contains a poem](https://stackoverflow.com/questions/30551945/how-do-i-get-python-to-read-only-every-other-line-from-a-file-that-contains-a-po)

http://stackoverflow.com/comment/82023175
type: AnswerComment
comment on: http://stackoverflow.com/a/47531558
score: 0
type: Comment
has text: Thank you this works out perfectly

http://stackoverflow.com/a/65201840
has body: Thank you @kjhughes for this amazing answer for extracting all the comments from the document file. I was facing same issue like others in this thread to get the text that the comment relates to. I took the code from @kjhughes as a base and try to solve this using python-docx. So here is my take at this. Sample document. I will extract the comment and the paragraph which it was referenced in the document. from docx import Document from lxml import etree import zipfile ooXMLns = {'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'} #Function to extract all the comments of document(Same as accepted answer) #Returns a dictionary with comment id as key and comment string as value def get_document_comments(docxFileName): comments_dict={} docxZip = zipfile.ZipFile(docxFileName) commentsXML = docxZip.read('word/comments.xml') et = etree.XML(commentsXML) comments = et.xpath('//w:comment',namespaces=ooXMLns) for c in comments: comment=c.xpath('string(.)',namespaces=ooXMLns) comment_id=c.xpath('@w:id',namespaces=ooXMLns)[0] comments_dict[comment_id]=comment return comments_dict #Function to fetch all the comments in a paragraph def paragraph_comments(paragraph,comments_dict): comments=[] for run in paragraph.runs: comment_reference=run._r.xpath("./w:commentReference") if comment_reference: comment_id=comment_reference[0].xpath('@w:id',namespaces=ooXMLns)[0] comment=comments_dict[comment_id] comments.append(comment) return comments #Function to fetch all comments with their referenced paragraph #This will return list like this [{'Paragraph text': [comment 1,comment 2]}] def comments_with_reference_paragraph(docxFileName): document = Document(docxFileName) comments_dict=get_document_comments(docxFileName) comments_with_their_reference_paragraph=[] for paragraph in document.paragraphs: if comments_dict: comments=paragraph_comments(paragraph,comments_dict) if comments: comments_with_their_reference_paragraph.append({paragraph.text: comments}) return comments_with_t…
answers question: http://stackoverflow.com/q/47390928
type: Answer
downvote count: 0
upvote count: 14
score: 14
has comment: http://stackoverflow.com/comment/136475023

http://stackoverflow.com/q/47425520
accepted answer: http://stackoverflow.com/a/47428897
has answer: http://stackoverflow.com/a/51870885
possible better answer: http://stackoverflow.com/a/51870885
has comment: http://stackoverflow.com/comment/81806251
linked to: http://stackoverflow.com/q/30927567
type: AnsweredQuestion
tagged with: batch-file
has body: I'd like to use Windows Task Scheduler to run a python script within a virtual environment. I'd like the Scheduler to run a .bat file that will activate the virtualenv run the script These steps work together from the command line, and they work individually in a .bat, but I can't seem to get them to work together from the .bat. It seems the virtualenv is not fully activated when I try to execute the python script and confused as to why. My .bat looks like this: call workon venv cd path/to/Python/proj python -m script.py I've tried adding timeouts immediately after the call to workon and tried moving the workon to seperate .bat called from my first file, but the other lines still execute before the virtualenv is activated. Any help is greatly appreciated!
has comment: http://stackoverflow.com/comment/81836273
has answer: http://stackoverflow.com/a/73288049
tagged with: cmd
has answer: http://stackoverflow.com/a/73979877
has answer: http://stackoverflow.com/a/47428897
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/74031440
answer count: 8
downvote count: 0
has answer: http://stackoverflow.com/a/76501630
has answer: http://stackoverflow.com/a/77030698
score: 70
upvote count: 70
has title: Activate virtualenv and run .py script from .bat
tagged with: python
tagged with: virtualenv
has answer: http://stackoverflow.com/a/68138512

http://stackoverflow.com/a/47468893
has comment: http://stackoverflow.com/comment/81896182
type: Answer
has comment: http://stackoverflow.com/comment/81893604
answers question: http://stackoverflow.com/q/47468174
score: 0
has body: Python strings are immutable. You can't have for example a='10010110' and assign a[3]='1'. It is what causes the error. You need to avoid strings. Use array of bool or array of integers instead. Something like: class Chromosome: def __init__(self): self._genes = [[],[]] self._fitness = 0 self.xd = 0 self.yd = 0 xd = random.randint(0,256) self._genes[0] = [ int(xd/2**i%2) for i in reversed(range(8))] yd = random.randint(0,256) self._genes[1] = [ int(yd/2**i%2) for i in reversed(range(8))]

http://stackoverflow.com/comment/81800096
type: Comment
score: 0
type: AnswerComment
has text: okay, was too fast... that is ot doing what i want... i think i might need to go for regex
comment on: http://stackoverflow.com/a/47422344

http://stackoverflow.com/a/47477378
accepted answer of: http://stackoverflow.com/q/47477225
has comment: http://stackoverflow.com/comment/81909639
score: 0
type: AcceptedAnswer
has body: Try on the following code: headlines = driver.find_elements_by_css_selector(".title&gt;a") for headline in headlines: print(headline.text) Hope it helps you!
has comment: http://stackoverflow.com/comment/81910022
answers question: http://stackoverflow.com/q/47477225
type: Answer

http://stackoverflow.com/q/47538154
type: Question
tagged with: startup
has comment: http://stackoverflow.com/comment/82033148
tagged with: reinstall
tagged with: python
has answer: http://stackoverflow.com/a/47538375
has answer: http://stackoverflow.com/a/47538387
has comment: http://stackoverflow.com/comment/82033303
type: AnsweredQuestion
score: 0
answer count: 2
has body: It is a minor issue, but since I reinstalled python (3.6.3 on windows 10), it no longer starts using the python command in the command prompt. Instead I have to use the py -3 command now. The error: 'python' is not recognized as an internal or external command, operable program or batch file. Since it is probably the most common way to use python in commands on forums, it becomes quite annoying to change it every time. Thank you in advance.
tagged with: cmd
tagged with: windows-10
accepted answer: http://stackoverflow.com/a/47538387
has title: How to open python in cmd with the 'python' command in stead of py -3
possible better answer: http://stackoverflow.com/a/47538375

http://stackoverflow.com/a/47525057
has comment: http://stackoverflow.com/comment/82007097
score: 1
has body: You can first compare B with C and then double shift boolean mask, last invert with ~ and filter by boolean indexing: m = df['B'] != df['C'] df = df[~(m.shift(1) | m.shift(2))] print (df) A B C 0 45 0 0 1 40 0 1 4 45 1 1 5 40 1 0 8 48 0 0 9 51 0 0
type: Answer
has comment: http://stackoverflow.com/comment/82007149
has comment: http://stackoverflow.com/comment/82007632
accepted answer of: http://stackoverflow.com/q/47525011
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82008074
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47525011

http://stackoverflow.com/a/47540480
score: 2
upvote count: 2
has body: You need to return the value of data_stream_logfile in the Define_and_Collect_1_WireData function and use that to pass it to log_file(): def Define_and_Collect_1_WireData(): ... data_stream_logfile = str(temperature1) + "," + str(timestamp) return data_stream_logfile def log_file(data_stream): ... def main(): data_stream = Define_and_Collect_1_WireData() log_file(data_stream)
answers question: http://stackoverflow.com/q/47540395
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81805316
type: QuestionComment
score: 0
has text: No it's not going to be okay. This is not compatible with the underlying mathematical theory of those algorithms nor sklearn. Read sklearn's excellent documentation (the best i know) on what's expected input.
comment on: http://stackoverflow.com/q/47424458
type: Comment

http://stackoverflow.com/q/47430703
type: UnansweredQuestion
has body: I am installing FukuML-0.4.1 package for machine learning in anaconda python 3.5.3 in windows 10 64-bit OS. After successfully installing required dependencies such as cvxplot, pep8, I am getting following error for FukuML-0.4.1 installation. . src/C/base.c(360): error C2065: 'a': undeclared identifier src/C/base.c(360): fatal error C1003: error count exceeds 100; stopping compilation error: Setup script exited with error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 I appreciate if anyone can guide me to get the successful installation of the package. Thank you.
tagged with: python
has comment: http://stackoverflow.com/comment/81816675
has comment: http://stackoverflow.com/comment/81816199
score: 0
has title: Python package installation error: FukuML machine learning
answer count: 0
has comment: http://stackoverflow.com/comment/81816154
type: Question

http://stackoverflow.com/comment/81854925
score: 0
comment on: http://stackoverflow.com/q/47450037
has text: can you attached the file you are reading?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47494632
has body: I have converted my python program to exe using pyinstaller. My exe creates a temporary folder _MEIxxxxx to keep files. In the same folder there is a file which is being changed by the program, but unfortunately it is not happening. In the program I change the folder to go to above folder: os.chdir('C:\\Users\\Public') for foldername in os.listdir(): if foldername.startswith('_MEI'): myfolder = foldername os.chdir('C:\\Users\\Public'+myfolder+'\\Quiz') Thanks in advance.
accepted answer: http://stackoverflow.com/a/47494666
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47494666
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81944230
has title: python exe in windows not writng
score: -1

http://stackoverflow.com/q/47499686
answer count: 1
downvote count: 0
upvote count: 1
has title: Eventlet threads do not run in parallel
favorite count: 0
type: Question
tagged with: eventlet
tagged with: proxy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/28315657
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81982457
tagged with: concurrency
accepted answer: http://stackoverflow.com/a/47520261
has comment: http://stackoverflow.com/comment/81968787
has answer: http://stackoverflow.com/a/47520261
has body: I wrote the following code: import eventlet import requests import redis redis = redis.StrictRedis(host="localhost", port="6379", db=0) proxy_1_pool = eventlet.GreenPool(40) def fetch_items(): for _ in range(0, 400): proxy_1_pool.spawn(fetch_listing) proxy_1_pool.waitall() def fetch_listing(): logger.info("START fetch: " + str(datetime.utcnow())) url_info = redis.spop("listings_to_crawl") content = make_request(url_info) logger.info("END fetch: " + str(datetime.utcnow())) if content: do_something(content) def make_request(url_info): r = requests.get(url_info) return r.content def main(): fetch_items() Unfortunately I see that fetch_listing is being involved sequentially. It would always print: START END START END While I would expect to see: START START END END
linked to: http://stackoverflow.com/q/14180179
tagged with: multithreading

http://stackoverflow.com/comment/136796939
comment on: http://stackoverflow.com/a/67051608
has text: @Pyzard check the [3.9 Release Notes](https://www.python.org/downloads/release/python-390/), it includes PEP585. Conversely PEP585 is also labeled python-version 3.9.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47434695
accepted answer of: http://stackoverflow.com/q/47434557
answers question: http://stackoverflow.com/q/47434557
type: Answer
score: 2
upvote count: 2
has body: For first solution is easier filtered twice - first only Operational and then duplicates: df1 = df[df['C3'] == 'Operational'] df1 = df1[df1.duplicated(['C2'], keep=False)] print (df1) C1 C2 C3 C4 0 1234 1002 Operational ABC 2 7896 1002 Operational DEF What is same, but worse readable: m1 = df['C3'] == 'Operational' df1 = df[df[m1].duplicated(['C2'], keep=False) &amp; m1] print (df1) C1 C2 C3 C4 0 1234 1002 Operational ABC 2 7896 1002 Operational DEF And for second question use drop_duplicates with parameter keep='last' for get last value of duplicates in C4: df2 = df.drop_duplicates('C4', keep='last') print (df2) C1 C2 C3 C4 2 7896 1002 Operational DEF 3 4321 4005 Closed CDE 4 7781 4005 Operational ABC Or if is necesary remove consecutive dupes only: mask = df['C4'].ne(df['C4'].shift()).cumsum().duplicated(keep=False) df2 = df[~mask] print (df2) C1 C2 C3 C4 2 7896 1002 Operational DEF 3 4321 4005 Closed CDE 4 7781 4005 Operational ABC
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47424052
upvote count: 4
type: AnsweredQuestion
has title: How do I get the label position of entry widgets to update properly when changing the font size?
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/47430473
has comment: http://stackoverflow.com/comment/81806215
has answer: http://stackoverflow.com/a/47430473
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81803532
has comment: http://stackoverflow.com/comment/81803272
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81804228
has comment: http://stackoverflow.com/comment/81809865
has body: I am creating a tkinter ttk GUI and I made some radio buttons that select the GUI size. This changes, among other things, the global font size for the whole application. I made a quick script to demonstrate it. import tkinter as tk from tkinter import ttk import tkinter.font UI_SIZES = ["Tiny", "Small", "Normal", "Large", "Huge"] TINY_FONT_SIZE = 8 SMALL_FONT_SIZE = 12 NORMAL_FONT_SIZE = 16 LARGE_FONT_SIZE = 18 HUGE_FONT_SIZE = 22 root = tk.Tk() ui_size = tk.StringVar(root, "Normal") entry_text = tk.StringVar(root, "Entry Text") def text_size_callback(*_args): """change the program font size when the font_size variable changes""" font = tkinter.font.nametofont("TkDefaultFont") selected_size = ui_size.get() if selected_size == "Tiny": font.configure(size=TINY_FONT_SIZE) elif selected_size == "Small": font.configure(size=SMALL_FONT_SIZE) elif selected_size == "Normal": font.configure(size=NORMAL_FONT_SIZE) elif selected_size == "Large": font.configure(size=LARGE_FONT_SIZE) elif selected_size == "Huge": font.configure(size=HUGE_FONT_SIZE) root.option_add("*Font", font) ui_size.trace('w', text_size_callback) ui_size.set("Normal") ui_radio_group = ttk.Frame(root) ui_size_radios = [] for sizeval in UI_SIZES: ui_size_radios.append(ttk.Radiobutton( ui_radio_group, text=sizeval, variable=ui_size, value=sizeval )) text_entry = ttk.Entry(ui_radio_group, textvariable=entry_text) i = 0 for sizeradio in ui_size_radios: sizeradio.grid(row=i, column=0, sticky=tk.W) i += 1 text_entry.grid(row=2, column=1) ui_radio_group.pack() root.mainloop() This works well, except for the labels inside entries (and comboboxes). The text itself resizes but the label does not, until the text is edited. This makes the text entries look weird. Here it is on startup Then messed up after clicking tiny Then fixed after I hit backspace How can I work around this? Or, how can I do this more correctly so it works without workarounds? I'm on Windows 10, using Python 3.6.3 64-bit, if it helps. EDIT: I made an…
tagged with: ttk
has comment: http://stackoverflow.com/comment/81804707
tagged with: python
score: 4

http://stackoverflow.com/q/47473795
upvote count: 1
linked to: http://stackoverflow.com/q/47472574
has title: List, variable assignment and function in Python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81902168
has comment: http://stackoverflow.com/comment/81923484
type: Question
accepted answer: http://stackoverflow.com/a/47473892
has comment: http://stackoverflow.com/comment/81902142
tagged with: python
has answer: http://stackoverflow.com/a/47473892
possible better answer: http://stackoverflow.com/a/47473845
has comment: http://stackoverflow.com/comment/81902410
score: -1
has comment: http://stackoverflow.com/comment/81923642
has answer: http://stackoverflow.com/a/47473845
has answer: http://stackoverflow.com/a/47473851
answer count: 4
type: AnsweredQuestion
has body: I have the following code: def proc2(p): p=p+[1] y=[2,5] proc2(y) print(y) z=[2,5] z=z+[1] print(z) The output of the code is: [2, 5] [2, 5, 1] I understand that y is not modified to [2,5,1]. But, y is reassigned to a new list, which is [2,5,1], right? Then why does y still refer to the original value? If the value of z has changed, why not y? P.S. I have just asked a question which is almost the same as this one. That question has been marked as a duplicate of another question. However, I think they are a bit different. That is why I'm posting my question again. I think I must have missed something about function.
downvote count: 2
has answer: http://stackoverflow.com/a/47474073

http://stackoverflow.com/q/47419820
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/47420049
has title: Are you able to use the "+" in the output of a user input list in Python 3.x?
has body: So I am trying to get familiar with list and arrays in python and I was just wondering, can you add the "+" sign in the output of a user_input list? I am aware on calculating the total and also displaying the list but not sure if I can make it that way. example: 4 + 5 + 6 + 7 + 8 = 30
has answer: http://stackoverflow.com/a/47420049
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 4
has comment: http://stackoverflow.com/comment/81793844
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81802817
score: -3
has comment: http://stackoverflow.com/comment/81803604

http://stackoverflow.com/comment/81965155
comment on: http://stackoverflow.com/a/47503864
type: Comment
score: 0
type: AnswerComment
has text: @Sun No problem. That was just how I decided to type it up to show you the graph. Furthermore, I'm not too experienced with mplotlib, but this might help you: https://stackoverflow.com/a/12608937/4909087

http://stackoverflow.com/q/47405236
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/81764090
type: AnsweredQuestion
tagged with: urlencode
score: 0
upvote count: 1
answer count: 1
tagged with: python-requests
has answer: http://stackoverflow.com/a/47405868
has body: I'm writing a Python script to fetch Korean vocabulary pronunciation. I have a URL ready to go, and when I open the URL in Safari, it retrieves the expected JSON from the server. When I use requests to get the JSON, the call fails and no results are found. Using Charles, I can see that the URL with my original query, a Hangul word, is URL encoded after I paste the URL into Safari and hit enter. For example, the instance of 소식 in the URL string becomes %EC%86%8C%EC%8B%9D on its way out. However, when I make that same request with requests, the word is encoded as %E1%84%89%E1%85%A9%E1%84%89%E1%85%B5%E1%86%A8. Both encodings can be decoded back to the original word 소식 (using a web app to confirm). The former encoding is accepted by the server, the latter is not. Why would I be getting a different encoding from requests? Edit Query string comes into the script as 소식 query = sys.argv[1] sys.stderr.write(query) -> 소식 Interpolating the query into the URL string yields ...json/word/소식... when printing it. Going through Charles it now looks like this /json/word/%E1%84%89%E1%85%A9%E1%84%89%E1%85%B5%E1%86%A8/. Everything is default, no specified encoding.
downvote count: 1
accepted answer: http://stackoverflow.com/a/47405868
favorite count: 0
type: Question
has title: URL Encoding yields two different results? Only one works

http://stackoverflow.com/a/47502073
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47500417
has comment: http://stackoverflow.com/comment/84021357
accepted answer of: http://stackoverflow.com/q/47500417
score: 1
has body: I solved it by using max-tasks-per-child argument. Here is my solution. celery -A my_app worker -l info -c 10 --max-tasks-per-child 10 -n worker1 After running this, it can execute 10 same tasks at a time in parallel. Hope this is helpful.
type: AcceptedAnswer

http://stackoverflow.com/comment/81755221
type: Comment
type: QuestionComment
has text: I've got the answer i needed for my programme to work the way i want to the only thing wrong was my indentation
score: 0
comment on: http://stackoverflow.com/q/47400711

http://stackoverflow.com/q/47519626
answer count: 1
downvote count: 0
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47522444
accepted answer: http://stackoverflow.com/a/47522444
score: 18
tagged with: python
has body: I am trying to come up with a generalised way in Python to identify pitch rotations occurring during a set of planned spacecraft manoeuvres. You could think of it as a particular case of a shift detection problem. Let's consider the solar_elevation_angle variable in my set of measurements, identifying the elevation angle of the sun measured from the spacecraft's instrument. For those who might want to play with the data, I saved the solar_elevation_angle.txt file here. import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec from scipy.signal import argrelmax from scipy.ndimage.filters import gaussian_filter1d solar_elevation_angle = np.loadtxt("solar_elevation_angle.txt", dtype=np.float32) fig, ax = plt.subplots() ax.set_title('Solar elevation angle') ax.set_xlabel('Scanline') ax.set_ylabel('Solar elevation angle [deg]') ax.plot(solar_elevation_angle) plt.show() The scanline is my time dimension. The four points where the slope changes identify the spacecraft pitch rotations. As you can see, the solar elevation angle evolution outside the spacecraft manoeuvres regions is pretty much linear as a function of time, and that should always be the case for this particular spacecraft (except for major failures). Note that during each spacecraft manoeuvre, the slope change is obviously continuous, although discretised in my set of angle values. That means: for each manoeuvre, it does not really make sense to try to locate a single scanline where a manoeuvre has taken place. My goal is rather to identify, for each manoeuvre, a "representative" scanline in the range of scanlines defining the interval of time where the manoeuvre occurred (e.g. middle value, or left boundary). Once I get a set of "representative" scanline indexes where all manoeuvres have taken place, I could then use those indexes for rough estimations of manoeuvres durations, or to automatically place labels on the plot. My solution so far has been to: Compute the 2nd derivative of …
has title: Using numpy/scipy to identify slope changes in digital signals?
upvote count: 18
tagged with: scipy
tagged with: signal-processing
tagged with: numpy

http://stackoverflow.com/comment/81880514
type: Comment
has text: What should be the output exactly?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47462798

http://stackoverflow.com/comment/81839780
comment on: http://stackoverflow.com/q/47442154
type: QuestionComment
has text: Please don't spam the Python tag. You probably don't need Python-3.x **and** python2.7.
score: 0
type: Comment

http://stackoverflow.com/q/47474294
has answer: http://stackoverflow.com/a/47568897
has body: First off, I'm really new to the python requests module and using API in general. Chances are I made a basic mistake somewhere. I'm trying to retrieve data from the exactonline API. Some data (eg: list of projects and cost transactions) I can retrieve relatively simply, so bearer code and current division should be ok. However, when I try to request data regarding hours worked I get only Null and 0 values. I'm using requests as specified by this page: https://start.exactonline.nl/docs/HlpRestAPIResources.aspx?SourceAction=10 To be specific, I've tried these 4 functions: RecentHours HoursByDate HoursById RecentHoursByNumberOfWeeks For RecentHours I use headers = {'Authorization': 'Bearer ' + bearer_token} result = requests.get('https://start.exactonline.nl/api/v1/' + CURRENT_DIVISION + "/read/project/RecentHours", headers=headers, params=query_args) return(result.text) For HoursByWeek I use (I currently only request one piece of information because that way I'm sure I didn't make any typo's in the query_args): headers = {'Authorization': 'Bearer ' + bearer_token} query_args = {'numberOfWeeks': '15', 'select': 'AccountCode'} result = requests.get('https://start.exactonline.nl/api/v1/' + CURRENT_DIVISION + "/read/project/RecentHoursByNumberOfWeeks", headers=headers, params=query_args) return(result.text) All return status code 200, and no data. According to this page (https://support.exactonline.com/community/s/knowledge-base?language=en_GB#All-All-DNO-Content-resp-codes-error-handling) this means I don't have access rights to this information. However, when I log in without using API I can access this information, so that seems strange to me. I've also tried logging in with the account with the highest freedom, but this still returns only null information.
has comment: http://stackoverflow.com/comment/81905110
score: 0
has comment: http://stackoverflow.com/comment/81903227
linked to: http://stackoverflow.com/q/16337511
has title: Exact Online API returns null values
has comment: http://stackoverflow.com/comment/81904029
has comment: http://stackoverflow.com/comment/81903904
has comment: http://stackoverflow.com/comment/81905413
tagged with: exact-online
answer count: 1
has comment: http://stackoverflow.com/comment/81904294
type: Question
has comment: http://stackoverflow.com/comment/81904011
has comment: http://stackoverflow.com/comment/81903964
tagged with: api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81904695
has comment: http://stackoverflow.com/comment/81903953
tagged with: python
tagged with: python-requests

http://stackoverflow.com/comment/81737626
type: Comment
comment on: http://stackoverflow.com/q/47392083
score: 0
has text: @jdm that's not true. It appears that way because most homework questions are just bad. I.e. no MCVE, no own effort, unclear problem description and possibly "urgent" in the title.
type: QuestionComment

http://stackoverflow.com/q/47480045
tagged with: python
tagged with: flask
has title: Flask routing not working
score: 1
upvote count: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81921275
favorite count: 0
has answer: http://stackoverflow.com/a/47492156
type: Question
has comment: http://stackoverflow.com/comment/81914948
has comment: http://stackoverflow.com/comment/81915676
has body: It's the most basic thing to ask but @app.route('/') is not working on my Linux server. Below is the code : from flask import Flask, jsonify, request from app import models import json import time app = Flask(__name__) app.url_map.strict_slashes = True @app.route('/') def blank(): return 'Hello ABC!' @app.route('/driftking') def blank2(): return 'Hello driftking!' # dynamic route @app.route("/test/&lt;search_query&gt;") def search(search_query): return search_query @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return "POST METHOD" elif request.method == 'GET': return "GET REQUEST ARE NOT ALLOWED" if __name__ == '__main__': app.run(debug=True) app.run() Very basic app, all's working fine on local machine but not on my linux server. E.g. if I load http://xxx.xxx.xxx.xxx/projectname ---- it shows Hello ABC! If I load http://xxx.xxx.xxx.xxx/projectname/driftking -- it redirects me to http://xxx.xxx.xxx.xxx ( i.e my server's homepage) If I load http://xxx.xxx.xxx.xxx/projectname/test/search -- 404 error not found If I load http://xxx.xxx.xxx.xxx/projectname/login -- it redirects me to http://xxx.xxx.xxx.xxx ( i.e my server's homepage) 127.0.0.1 - - [24/Nov/2017 19:37:01] "POST //login HTTP/1.1" 405 - ^^This is what I get on terminal. I don't understand why I get two leading slashes everytime. But If do http://xxx.xxx.xxx.xxx/projectname/insert-any-word/login , my post req get's executed. At the same time on local machine i dont get two leading slashes // to the path and thus the request get's processed.
has comment: http://stackoverflow.com/comment/81914908
type: UnansweredQuestion

http://stackoverflow.com/q/47422672
tagged with: sql
has comment: http://stackoverflow.com/comment/81802941
upvote count: 3
has title: SQL Delete statement with nested selects
tagged with: sqlite
has body: I am trying to make a subquery in a DELETE statement in order to improve performance. The plain DELETE statement works but the subquery ones are either deleting all rows indiscriminately, or only one row per invocation. I am confused as to why the statements are not equivalent. Jump down to "What doesn't work" to see the problem statements. Upfront info I am using sqlite3 from python2 to manage a database of pictures with associated tags. The schema for the table is: CREATE VIRTUAL TABLE "files" USING fts3(fname TEXT, orig_name TEXT, tags TEXT, md5sum TEXT); Tags are organized as a comma separated list so direct string comparison in sqlite doesn't (easily) work, so I've add a helper function TAGMATCH def tag_match(tags, m): i = int(m in [i.strip() for i in tags.split(',')]) return i db.create_function('TAGMATCH', 2, tag_match) What works This does what I want/expect. It deletes all rows where the column tags contains the tag 'DELETE'. Downside is, as far as I understand, this requires a linear scan of the table. Because of the "dangers" of deleting something from the table I did want to use MATCH in case, in some hypothetical situation, a match occurs with another unintended tag ie. 'DO NOT DELETE THIS'. DELETE FROM files WHERE TAGMATCH(tags, 'DELETE') What doesn't work To speed things up I tried a trick I read in another stackoverflow post where MATCH is used to narrow down the search, then a direct string comparison is done on those results ie SELECT * FROM (SELECT * FROM table WHERE words MATCH keyword) WHERE words = keyword I tried using this trick here, but instead it deletes every row in the table. DELETE FROM files WHERE TAGMATCH(( SELECT tags FROM files WHERE tags MATCH 'DELETE'), 'DELETE') This is what I first came up with. I realize now it's not a particularly good solution, but since its effect puzzles me I'm including it. This statement only deletes one row containing the tag 'DELETE'. If invoked again, it deletes another row, and so on until all the row…
downvote count: 0
answer count: 1
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/81803868
tagged with: fts3
tagged with: python
accepted answer: http://stackoverflow.com/a/47426290
has answer: http://stackoverflow.com/a/47426290
type: AnsweredQuestion

http://stackoverflow.com/comment/81964116
score: 1
type: Comment
type: QuestionComment
has text: paste your output
comment on: http://stackoverflow.com/q/47503817

http://stackoverflow.com/q/47383588
tagged with: python
has answer: http://stackoverflow.com/a/47384928
favorite count: 0
type: Question
downvote count: 0
type: UnansweredQuestion
has title: Using a matplotlib button to alternate/switch between plots I created
answer count: 1
has body: So I've created several charts using the matplotlib library in python 3.5, but I want to be able to have the flexibility to utilize a button to alternate between the views I created within a single window. I've been trying to experiment with an example here, but have not succeeded in doing so. I was curious in how to have the flexibility to click through different views that I created. My code is sort of organized like this: def plot1(data1, 'name1'): ... ax.plot(x,y) plt.draw() def plot2(data2, 'name2'): ... ax2.plot(x,y) plt.draw() def plot3(data3, 'name3'): ... ax3.plot(x,y) plt.draw() plot1(data1,'name1') plot2(data2,'name2') plot3(data3,'name3') plt.show() Currently it will show up in three different windows. Now when I try to make this all into one view accessible via buttons, I'm unable to do so because quite frankly I'm unfamiliar with how to pass on the variables in my methods to create my desired subplots with the callback function. Is there a way to sort of structure my code to have them all run under one matplotlib window?
upvote count: 3
score: 3
tagged with: matplotlib

http://stackoverflow.com/a/47419887
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47417049
type: Answer
has body: Simplest way is use volumes against local paths: Create local path /tmp/myfiles put test-image in /tmp/myfiles Ensure that your script gets absolute path with open('/tmp/myfilesdocker/test-image.jpeg', 'r+b') as f: run container docker run -v /tmp/myfiles:/tmp/myfilesdocker python It's the easiest volume. Your local path /tmp/myfiles is mounted against the container /tmp/myfilesdockerpath. You can create the resized image in this path also. Easiest way to your hello world purpose.
accepted answer of: http://stackoverflow.com/q/47417049
score: 1

http://stackoverflow.com/a/47398609
has comment: http://stackoverflow.com/comment/81848067
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81850859
downvote count: 0
has body: What you seek to accomplish isn't as simple as you might believe. Applications draw graphics on the screen largely with the help of calls to the graphics card API. Those API's can be complicated, as they should be, because all the graphics that you see on your screen, whether it be your browser GUI, to video playback, to your Starcraft II, has to use combinations of these calls to produce the beautiful and seamless graphics you see on your screen (graphics would NOT look good without use of the GPU). However, not all manipulation of graphics has to be so complicated, and many languages/frameworks write wrappers around some of the graphics libraries that expose a simpler subset of the total functionality. Tkinter is a good example. If you don't want to import ANYTHING, you will have to make the calls to the API yourself, and you're not in for a good time. Nobody does this nowadays for personal projects because it really is quite complicated. Also, Python is a very high-level language, and although it might expose the OS's system calls that you need, you're probably better off doing it in C. Before you proceed, I suggest you read up on the fundamentals of computer graphics work. Here's a nice image that shows how OpenGL, a very popular graphics library, works.
has comment: http://stackoverflow.com/comment/81892686
has comment: http://stackoverflow.com/comment/82242040
has comment: http://stackoverflow.com/comment/81916343
has comment: http://stackoverflow.com/comment/82241065
has comment: http://stackoverflow.com/comment/82243148
has comment: http://stackoverflow.com/comment/81752917
has comment: http://stackoverflow.com/comment/82243653
accepted answer of: http://stackoverflow.com/q/47398448
score: 5
has comment: http://stackoverflow.com/comment/81751902
has comment: http://stackoverflow.com/comment/82242616
upvote count: 5
has comment: http://stackoverflow.com/comment/81892617
answers question: http://stackoverflow.com/q/47398448
has comment: http://stackoverflow.com/comment/81753040
type: Answer
has comment: http://stackoverflow.com/comment/82243956
has comment: http://stackoverflow.com/comment/82243964
has comment: http://stackoverflow.com/comment/81916330
has comment: http://stackoverflow.com/comment/81873236
has comment: http://stackoverflow.com/comment/81752992
has comment: http://stackoverflow.com/comment/82243887
has comment: http://stackoverflow.com/comment/81915775
has comment: http://stackoverflow.com/comment/82243706
has comment: http://stackoverflow.com/comment/81916263
has comment: http://stackoverflow.com/comment/81919244

http://stackoverflow.com/q/47481618
tagged with: python
tagged with: tkinter
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47481670
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47481670
answer count: 1
favorite count: 0
has title: changing value of a variable in python tkinter
has body: I have just started using python tkinter and i can't get a button to change a date in datetime. So far I have the button changing the value variables b, c, and d but it doesn't change the date. Thanks for any help. from tkinter import * import datetime window = Tk() b = int(1999) c = int(2) d = int(2) today = datetime.date.today() def changeVariable(): global b, c, d b = int(1914) print("changed b") c = int(7) print("changed c") d = int(28) print("changed d") def printVariable(): global a print(a.days) dog = datetime.date(b, c, d) a = today - dog button1 = Button(window, command = changeVariable) button1.pack() button2 = Button(window, command = printVariable) button2.pack()
type: Question
tagged with: datetime

http://stackoverflow.com/q/47386454
has title: Confused about how set in python returns values
tagged with: set
answer count: 1
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
score: -2
tagged with: python
accepted answer: http://stackoverflow.com/a/47386640
has comment: http://stackoverflow.com/comment/81725883
has comment: http://stackoverflow.com/comment/81725921
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47386640
has body: I have a code. scores = [19.0,19.0,20.0,20.0,21.0,21.0] new_scores = set(scores) print new_scores Output: set([19.0, 20.0, 21.0]) My Question: Why is the word 'set' prefixed to the output. Isn't set supposed to return directly the unique values in the list 'scores'. Also, if i use 'list(set(scores))' then i get the intended output of only the list of unique values without the prefix word 'set'
tagged with: list

http://stackoverflow.com/a/47416324
answers question: http://stackoverflow.com/q/47416270
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81786583
has body: You can use "unpacking" with assign: df_out = df.assign(**df.filter(regex = 'dt_').apply(lambda x: pd.to_datetime(x))) dt_one dt_two other_col 0 2015-01-01 2015-01-01 1 1 2016-02-02 2016-02-02 2 And info: &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 2 entries, 0 to 1 Data columns (total 3 columns): dt_one 2 non-null datetime64[ns] dt_two 2 non-null datetime64[ns] other_col 2 non-null int64 dtypes: datetime64[ns](2), int64(1) memory usage: 128.0 bytes
score: 2
upvote count: 2

http://stackoverflow.com/comment/81904695
comment on: http://stackoverflow.com/q/47474294
has text: In the Query Tool you can do 'set use-log-xml true', dito for REST, to log payload to folder (default is c:\temp) and also check the calls made in 'select * from sessionios@datadictionary'.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81907153
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47474407
has text: @dgan - The display precision is actually a formatting attribute stored in the file, so in principle it can be read. xlrd happens to not include code to read this in .xlsx files (it can read some formatting information in .xls files). I don't use OpenPyXL myself, but maybe it reads the numeric format string.

http://stackoverflow.com/comment/81835358
type: QuestionComment
has text: Using loop is considered the least optimum option in Pandas. Please look into df.replace(). You can try something like df.replace('[^a-zA-Z]', '', regex = True)
comment on: http://stackoverflow.com/q/47440165
score: 1
type: Comment

http://stackoverflow.com/comment/81803025
score: 0
type: AnswerComment
has text: Oh, if you wanted to prompt the user for a username and password then you can't do it with ngrok's HTTP basic authentication. You'd have to build the authentication into your application itself.
comment on: http://stackoverflow.com/a/47403575
type: Comment

http://stackoverflow.com/comment/81750121
type: AnswerComment
has text: Got you bro............
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47398424

http://stackoverflow.com/q/47447375
tagged with: loops
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0
has body: I would like to check how many iterations are completed per second or how many urllib requests are sent per second, but without slowing down the program at all (which time.sleep() seems to do). This is the program, for example: while True: url = urllib.request.urlopen("google.com") I would also like for the requests/per second counter to update in miliseconds, so it may print something like "2.83 requests per second" and then update to "2.93 requests per second" if the loop iterates faster.
has comment: http://stackoverflow.com/comment/81849995
tagged with: iteration
has title: How can I check the number of iterations per second without using time module?
type: Question
has comment: http://stackoverflow.com/comment/81850063
tagged with: python
has answer: http://stackoverflow.com/a/47447522
tagged with: python-3.x
score: 0
upvote count: 1

http://stackoverflow.com/q/47459065
answer count: 1
score: 6
has answer: http://stackoverflow.com/a/48577942
tagged with: pysftp
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: sftp
upvote count: 6
accepted answer: http://stackoverflow.com/a/48577942
tagged with: python
tagged with: synchronization
linked to: http://stackoverflow.com/q/48434941
tagged with: data-synchronization
has body: I am using pysftp library's get_r function (https://pysftp.readthedocs.io/en/release_0.2.9/pysftp.html#pysftp.Connection.get_r) to get a local copy of a directory structure from sftp server. Is that the correct approach for a situation when the contents of the remote directory have changed and I would like to get only the files that changed since the last time the script was run? The script should be able to sync the remote directory recursively and mirror the state of the remote directory - f.e. with a parameter controlling if the local outdated files (those that are no longer present on the remote server) should be removed, and any changes to the existing files and new files should be fetched. My current approach is here. Example usage: from sftp_sync import sync_dir sync_dir('/remote/path/', '/local/path/')
downvote count: 0
has title: How to sync only the changed files from the remote directory using pysftp?

http://stackoverflow.com/comment/81835974
comment on: http://stackoverflow.com/q/47439594
has text: No, you can't access the class itself there because the class doesn't exist as an object until after its definition has been executed.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47484753
tagged with: python-3.x
has body: sc = [] n = 6 for i in range(n): sc.append("#") scstr = ''.join(map(str, sc)) print(scstr) I tried to use the code below to reverse the output by adding padding white spaces but it prints out a distorted staircase. # print(scstr.rjust(n-i, ' ')) -- trying to print reversed staircase Please help convert the staircase from right-aligned to LEFT ALIGNED, composed of # symbols and spaces. Attached is a visual description of expected output
has answer: http://stackoverflow.com/a/47484863
score: 5
has comment: http://stackoverflow.com/comment/81924434
possible better answer: http://stackoverflow.com/a/47484858
upvote count: 5
has answer: http://stackoverflow.com/a/47484858
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/47484785
has comment: http://stackoverflow.com/comment/81924463
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81924398
has answer: http://stackoverflow.com/a/47484785
has answer: http://stackoverflow.com/a/47484859
tagged with: whitespace
has comment: http://stackoverflow.com/comment/81924473
downvote count: 0
has title: Python 3 - convert the staircase from right-aligned to LEFT ALIGNED, composed of # symbols and spaces
favorite count: 0
type: Question

http://stackoverflow.com/a/47465015
has body: Since they are distinguished by spaces and your strings themselves have spaces using the extracted text will probably not be too helpful. I would have to see the full pdf to know if this would work but try: From tabula import read_pdf df = read_pdf("grocery2.pdf") Then you can do any dataframe operations to extract different values ie. df1 = df'UPC', 'Product Description'
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47464866

http://stackoverflow.com/comment/81851045
type: QuestionComment
has text: Fixed indentation.
score: 0
comment on: http://stackoverflow.com/q/47447906
type: Comment

http://stackoverflow.com/q/47498481
tagged with: diagonal
has answer: http://stackoverflow.com/a/47498716
tagged with: python
has comment: http://stackoverflow.com/comment/81952312
has body: I am trying to get the diagonal of a matrix from a text file without using any kind of module. So the text file can have something like: [[1,2,3],[4,5,6],[7,8,9]] Here is my code so far: def diagonal(filename): with open(filename, 'r') as myfile: data=myfile.read().split() a=data[0].split() a=eval(a[0]) c=len(a[0]) d=len(a) if c==d: diagonal=[] c=len(a[0]) for i in range(d): row=[0]*c for j in range(c): row=a[i][j] diagonal.append(row) return diagonal else: return ('Error') This returns: [1, 2, 3, 4] When I want it to output: [[1,0,0],[0,5,0],[0,0,9]] Any ideas on how to make my code work? Thank you very much!
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81952240
has comment: http://stackoverflow.com/comment/81952507
answer count: 2
tagged with: matrix
has comment: http://stackoverflow.com/comment/81952637
tagged with: file
has comment: http://stackoverflow.com/comment/81952528
has comment: http://stackoverflow.com/comment/81952331
accepted answer: http://stackoverflow.com/a/47498616
has title: Diagonal of A Matrix From A Text File (No Numpy)
type: Question
has comment: http://stackoverflow.com/comment/81952648
has answer: http://stackoverflow.com/a/47498616
possible better answer: http://stackoverflow.com/a/47498716

http://stackoverflow.com/a/47384602
has body: You can skip the replace if you use ne: df[df.ne('Null').all(1)] Name Participation Homework Test Presentation Attendance 2 Carrie 82 99 96 89 92 3 Simone 100 91 88 99 90
accepted answer of: http://stackoverflow.com/q/47384535
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47384535
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/q/47386378
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81726200
favorite count: 0
has body: As i'm doing one project in that i want to send checkbox values from HTML to PYTHON and i have completed passing checkbox values from HTML to PYTHON but my problem is if i choose anyone of checkbox value it will not be send values to my database but if i choose given all values it will be sent values to my database. but i want to choose one or more values from checkbox and pass choosen values to my database but i don't know how do i do it...Please anyone help me..Thanks in advance here is my.html: UserName: Password: panchayath ward-name result here is my.py: import os from flask import Flask, request, render_template from flaskext.mysql import MySQL mysql = MySQL() app = Flask(__name__) app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'root' app.config['MYSQL_DATABASE_DB'] = 'votelist' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) APP_ROOT = os.path.dirname(os.path.abspath(__file__)) @app.route('/',methods=['GET','POST']) def main(): return render_template("ram.html") @app.route('/s', methods=['GET', 'POST']) def get_data(): print("hlo") if request.method == 'POST': print("cat") sp = request.form['well'] print(sp) t = request.form['dull'] print(t) panchayath = request.form.getlist('hello[]') print (panchayath) ward = request.form.getlist('hi[]') print (ward) result = request.form.getlist('well[]') print (result) conn = mysql.connect() cursor = conn.cursor() # cursor.execute() print ("yes") # cursor.execute("insert into try_chk3 values (%s,%s,%s)", (some_var)) # query = "CREATE TABLE saracheck( panchayath VARCHAR(40), ward VARCHAR(40),Results VARCHAR (40))" # cursor.execute(query) query = "INSERT INTO demo(username,password,panchayath,wardname,results) VALUES(%s,%s,%s, %s,%s)" a=cursor.execute(query, (sp,t,panchayath,ward,result)) print (a) print ("execuet") # cursor.execute(query,(first_name,last_name,email_id,can_pic,logo_pic)) conn.commit() return "over" if __name__ == '__main__': app.run()
type: Question
tagged with: http://stackoverflow.com/tag/html
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: checkbox
has title: How to choose one or more checkbox values and pass that data from HTML to MY-SQL using PYTHON?
downvote count: 0

http://stackoverflow.com/a/47386742
has comment: http://stackoverflow.com/comment/81728016
has body: Since you don't just have iterables of values, but dictionaries of key:value pairs, you should use a csv.DictWriter instead of a csv.writer.
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47386655
type: Answer
has comment: http://stackoverflow.com/comment/81728221

http://stackoverflow.com/comment/81949318
comment on: http://stackoverflow.com/a/47495628
has text: Thanks @furas I was able to get the entire data the txt has multiple words as well , for instance Client: Township one , Location : Pennsylvania,Newyork. Straight forward split(:) might not work out Need some regexp(). I am trying to split it
score: 0
type: AnswerComment
type: Comment

recurrent-neural-network
tags question: http://stackoverflow.com/q/47504501
tags question: http://stackoverflow.com/q/47385700
tags question: http://stackoverflow.com/q/47459225
tags question: http://stackoverflow.com/q/47491098
tags question: http://stackoverflow.com/q/47423828
tags question: http://stackoverflow.com/q/47413844
tags question: http://stackoverflow.com/q/47529792
tags question: http://stackoverflow.com/q/47470655
tags question: http://stackoverflow.com/q/47432870
tags question: http://stackoverflow.com/q/47520135
type: Tag
tag name: recurrent-neural-network
tags question: http://stackoverflow.com/q/47490393

http://stackoverflow.com/q/47474986
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47475600
tagged with: python
has title: Creating a script in Python 3 to compare two CSVs and output the similarities and differences between the two into another set of CSVs
score: 0
answer count: 2
tagged with: compare
tagged with: mysql
has body: I have two CSVs, ideally the CSVs will contain same data, in reality sometimes the content may differ here and there. Instead of manually browsing the two CSVs and find out whats same and different, I am trying to create a python script which I will run weekly that will tell me whats same and what not. Here's the logic. 1. Given 2 CSVs 2. Compare them row by row. 3. Any rows that are different between the two CSVs should be recorded into an another CSV (the entire row/s) 4. Any rows that are same between the CSVs should be recorded into another CSV (the entire row/s). This will help me visually see what the differences are and action them accordingly. Below is an example of what I am looking for. The code below is what I have so far with open('Excel 1.csv', 'r') as csvOne, open('Excel 2.csv', 'r') as csvTwo: csvOne = csvOne.readlines() csvTWO = csvTWO.readlines() with open('resultsSame.csv', 'w') as resultFileSame: for row in csvTWO: if row not in csvONE: resultFileSame.write(row) with open('resultsDifference.csv', 'w') as resultFileDifference: for row in csvTWO: if row in csvONE: resultFileDifference.write(row) I want the script to compare rows and only if there is a similarity or differences between rows output that into another set of CSVs. The above code works but it removes the columns which are in one CSV and not the other and not rows. I want to keep the columns even though if they are not in the other CSV and only show me what roles are in one or the other in separate CSVs. Please see below the results I get when I run the first code you've given, on your dataset example. If you look at the above, I can't quite seem to figure out how your getting the output that you are, as that is exactly what I want! To be honest, I don't need to print out the headers as I am comparing those as well, they can sometime end of different due to user error.
type: Question
has answer: http://stackoverflow.com/a/47504747

http://stackoverflow.com/comment/81950441
has text: @C._: I added an additional section to explain the behavior.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47497397

http://stackoverflow.com/comment/81989819
type: QuestionComment
score: 0
has text: @PatrickArtner I don't think this is a homework , and btw it is a good question.
type: Comment
comment on: http://stackoverflow.com/q/47516877

http://stackoverflow.com/comment/81954083
comment on: http://stackoverflow.com/q/47498045
score: 0
type: Comment
type: QuestionComment
has text: As for the original problem, I think the position arguments to `addstr()` are relative to the corner of screen they're sending output to, which means that each `sendPacket` thread needs to add/update information on a _different_ row for them all to visible. You could pass them the row (column isn't really needed here) position as additional arguments to the function when each thread is created.

http://stackoverflow.com/q/47422762
has title: wrong output in sorting a list of list in python
tagged with: list
linked to: http://stackoverflow.com/q/7301110
type: AnsweredQuestion
upvote count: 0
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/47422789
duplicate of: http://stackoverflow.com/q/11205254
accepted answer: http://stackoverflow.com/a/47422884
has answer: http://stackoverflow.com/a/47422789
favorite count: 0
has answer: http://stackoverflow.com/a/47422884
has comment: http://stackoverflow.com/comment/81800053
type: Question
tagged with: python
tagged with: sorting
score: -2
has body: I have this sample list of list: [[0.7578684, 'Yes, import function which lets you load items'],[1.7032554, 'Use the Test tools to edit'], [0.58279467, 'Yes, use the Designer UI Import feature to restore content from the JSON file.']] I want to sort this list in descending order based on the integer value in each list. I wrote these lines but I am getting wrong output: sorted_answer = answer.sort(key=lambda x: float(x[0]),reverse = True) print(sorted_answer) When I execute this I get None as output for sorted_answer list. What is the mistake I am making?

http://stackoverflow.com/q/47463859
favorite count: 0
type: Question
tagged with: gimp
score: 1
tagged with: python
has body: When I try to run the following python script through GIMP's gui: #!/usr/bin/env python from gimpfu import * def export_png(image, drawable, self): filename=image.name interlace=0 compression=0 bkgd=0 gama=0 off=0 phys=0 time=0 pdb.file_png_save(image, drawable, filename, raw_filename, interlace, compression, bkgd, gama, offs, phys, time) register( "python_fu_export_png", "Exports the current image as png", "Exports the current image as png", "HHP", "HHP", "2017", "&lt;Image&gt;/Image/Export as png", "*", [ (PF_IMAGE, "image", "takes current image", None), (PF_DRAWABLE,"drawable", "input layer",None), ], [], export_png ) main() I get this error: Traceback (most recent call last): File "/Applications/GIMP.app/Contents/Resources/lib/gimp/2.0/python/gimpfu.py", line 736, in response dialog.res = run_script(params) File "/Applications/GIMP.app/Contents/Resources/lib/gimp/2.0/python/gimpfu.py", line 361, in run_script return apply(function, params) TypeError: export_png() takes exactly 3 arguments (4 given) Why is that? I thought I was only passing PF_Image and PF_DRAWABLE into the function, why does it say I'm giving four arguments?
type: UnansweredQuestion
has title: TypeError: export_png() takes exactly 3 arguments (4 given)
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81882595
upvote count: 1
has answer: http://stackoverflow.com/a/47464860

http://stackoverflow.com/comment/81957955
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47492412
score: 0
has text: See my answer ;)

http://stackoverflow.com/comment/81870637
has text: my program too seldom returns the best solution (50)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47456812

http://stackoverflow.com/comment/81851930
has text: It is your decision to decide if spending a month of work (and perhaps even several, depends upon your current skills) is worthwhile. Remember [Hofstadter's law](https://en.wikipedia.org/wiki/Hofstadter%27s_law). Perhaps speak with your PhD advisor.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47448296

http://stackoverflow.com/q/47428675
tagged with: python
has answer: http://stackoverflow.com/a/47428744
type: AnsweredQuestion
has body: cookiedict = {'banana':5, 'blueberries':5, 'jerky':5} def cookies(): return input('Which of the cookies do you want to eat?') def number(): return int(input('How many cookies do you want to eat?')) cookies = cookies () number = number () while True: if cookiedict[cookies] &gt;0 &lt;=5: cookiedict[cookies] -= number print ('You ate {} of the {} cookies'.format(number,cookies)) elif cookiedict[cookies] &gt;=6: print ('Game Over!!! You ate too much!!!') break else: print ('Incorrect Input. Try again...') This is my second day. I'm using a combo of udemy course and youtube videos. You probably know what I'm trying to accomplish by looking at the code. If you eat more than the available cookies you lose. There are only 5 for each. if cookiedict[cookies] &gt;0 &lt;=5: cookiedict[cookies] -= number print ('You ate {} of the {} cookies'.format(number,cookies)) I have no idea why this does not work. It keeps outputting the print no matter what number I type in, even though I think I'm telling it to only print when greater than 0 and equal or less than 5. Also, am I doing this part correct? It seems like it shouldn't work for some reason but it is accepting input. def cookies(): return input('Which of the cookies do you want to eat?') def number(): return int(input('How many cookies do you want to eat?')) cookies = cookies () number = number () Thanks for any help. I've spent the last couple of hours playing with this and can not get it to work!!
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81811744
has comment: http://stackoverflow.com/comment/81811618
has comment: http://stackoverflow.com/comment/81811929
has answer: http://stackoverflow.com/a/47428798
possible better answer: http://stackoverflow.com/a/47428744
accepted answer: http://stackoverflow.com/a/47428798
type: Question
has title: Newbie at Python (greater than but less than; return
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81811652

http://stackoverflow.com/comment/81986275
type: Comment
comment on: http://stackoverflow.com/q/47515107
score: 0
type: QuestionComment
has text: How can i create a bar graph since it will be more informative?

http://stackoverflow.com/comment/81996294
comment on: http://stackoverflow.com/q/47519776
score: 1
type: Comment
type: QuestionComment
has text: use `print()` to check values in variables and which part of code is executed - it helps to find problem.

http://stackoverflow.com/comment/82003197
type: QuestionComment
comment on: http://stackoverflow.com/q/47523475
score: 1
has text: can you show where you have tried adding while loop ?
type: Comment

http://stackoverflow.com/comment/81997723
type: AnswerComment
type: Comment
has text: @JensB How do mean *return the list in that state*? There you have a string, not a list. Calling print on a list gives you a string showing the items in the list with the square braces as identifiers. The list remains the same, irrespective of how it's printed.
comment on: http://stackoverflow.com/a/47520536
score: 0

http://stackoverflow.com/comment/81904805
has text: I'd prefer the elif for efficiency sake; that way it will not continue to evaluate after the case is met. This also adds allot of non-pretty code due to incrementing count only when an if statement is met (however this might be a good thing depending on what the user is trying to accomplish)
comment on: http://stackoverflow.com/a/47475106
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82016016
comment on: http://stackoverflow.com/q/47472691
has text: In line 3: ids = range(data_size)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47457362
answer count: 3
has comment: http://stackoverflow.com/comment/81870079
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47457603
possible better answer: http://stackoverflow.com/a/47457603
has answer: http://stackoverflow.com/a/47457661
tagged with: python
has title: Python reading in integers from a csv file into a list
favorite count: 0
has answer: http://stackoverflow.com/a/47458032
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81869862
downvote count: 0
accepted answer: http://stackoverflow.com/a/47457661
has comment: http://stackoverflow.com/comment/81869226
has comment: http://stackoverflow.com/comment/81869327
has comment: http://stackoverflow.com/comment/81869456
has comment: http://stackoverflow.com/comment/81869701
has comment: http://stackoverflow.com/comment/81869510
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/81869422
has body: I am having some trouble trying to read a particular column in a csv file into a list in Python. Below is an example of my csv file: Col 1 Col 2 1,000,000 1 500,000 2 250,000 3 Basically I am wanting to add column 1 into a list as integer values and am having a lot of trouble doing so. I have tried: for row in csv.reader(csvfile): list = [int(row.split(',')[0]) for row in csvfile] However, I get a ValueError that says "invalid literal for int() with base 10: '"1' I then tried: for row in csv.reader(csvfile): list = [(row.split(',')[0]) for row in csvfile] This time I don't get an error however, I get the list: ['"1', '"500', '"250'] I have also tried changing the delimiter: for row in csv.reader(csvfile): list = [(row.split(' ')[0]) for row in csvfile] This almost gives me the desired list however, the list includes the second column as well as, "\n" after each value: ['"1,000,000", 1\n', etc...] If anyone could help me fix this it would be greatly appreciated! Cheers
has comment: http://stackoverflow.com/comment/81869305
tagged with: list

http://stackoverflow.com/a/47521041
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47520850
has body: You can try this: import re cards = ['4916 0636 4700 5548', '4556-0775-2249-5041', '5119 0966 3584 2334', '5108-5708-8343-5937', '1234 2345 3456 4567', '2132-3523-3211-3356', '5118-3323-1315-9900'] new_cards = [card for card in cards if re.findall('^5|^4', card)] Output: ['4916 0636 4700 5548', '4556-0775-2249-5041', '5119 0966 3584 2334', '5108-5708-8343-5937', '5118-3323-1315-9900']
type: Answer
accepted answer of: http://stackoverflow.com/q/47520850
score: 2
upvote count: 2

http://stackoverflow.com/q/47426314
tagged with: django
tagged with: python
tagged with: django-rest-framework
has title: Whats the `self` means in create(self, validated_data) method?
answer count: 1
downvote count: 1
has body: Whats the self means in create(self, validated_data) method ? I have a serializer named CloudServerPayOrderSerializer, and I want to override the create() method. class CloudServerPayOrderSerializer(ModelSerializer): class Meta: model = TradeRecord exclude = ( 'id', 'name', 'traderecord_num', 'money', 'balance', 'desc', ) def create(self, validated_data): user = getUserFormSerializer(self) ... You see, I am override the create method, and I want to get user through self. so there is a util method getUserFormSerializer. But I don't know the self here stands for what, whether it is stand for CloudServerPayOrderSerializer, if is not, I can not name the util method as getUserFormSerializer.
accepted answer: http://stackoverflow.com/a/47426369
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47426369
has comment: http://stackoverflow.com/comment/81814113
score: -1
favorite count: 0
type: Question
upvote count: 0

http://stackoverflow.com/a/47601776
accepted answer of: http://stackoverflow.com/q/47435973
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47435973
has comment: http://stackoverflow.com/comment/83434861
type: Answer
has body: Try to run this code: import win32api import win32print name = win32print.GetDefaultPrinter() #printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_ADMINISTER} printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_USE} handle = win32print.OpenPrinter(name, printdefaults) level = 2 attributes = win32print.GetPrinter(handle, level) print "Old Duplex = %d" % attributes['pDevMode'].Duplex #attributes['pDevMode'].Duplex = 1 # no flip #attributes['pDevMode'].Duplex = 2 # flip up attributes['pDevMode'].Duplex = 3 # flip over ## 'SetPrinter' fails because of 'Access is denied.' ## But the attribute 'Duplex' is set correctly try: win32print.SetPrinter(handle, level, attributes, 0) except: print "win32print.SetPrinter: set 'Duplex'" res = win32api.ShellExecute(0, 'print', 'test.pdf', None, '.', 0) win32print.ClosePrinter(handle) It works on my computer: Windows 10, Python 2.7.14, pypiwin32-220 Notes: On my computer PRINTER_ACCESS_ADMINISTER causes 'Access is denied' in OpenPrinter. On my computer SetPrinter fails with 'Access is denied'. But 'Duplex' is set correctly..
score: 2
upvote count: 2

http://stackoverflow.com/a/71993662
score: 7
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47417986
upvote count: 7
has body: The question has been answered in the other answers but it took me a while to wrap my mind around everything. Here is a complete example of the final solution: import numpy as np from scipy import interpolate from scipy.special import ndtr import matplotlib.pyplot as plt from scipy.stats import norm, gaussian_kde # create kde npts_kde = int(5e3) n = np.random.normal(loc=0, scale=1, size=npts_kde) kde = gaussian_kde(n) # grid for plotting npts_sample = int(1e3) x = np.linspace(-3, 3, npts_sample) # evaluate pdfs kde_pdf = kde.evaluate(x) norm_pdf = norm.pdf(x) # cdf and inv cdf are available directly from scipy norm_cdf = norm.cdf(x) norm_inv = norm.ppf(x) # estimate cdf cdf = tuple(ndtr(np.ravel(item - kde.dataset) / kde.factor).mean() for item in x) # estimate inv cdf inversefunction = interpolate.interp1d(cdf, x, kind='cubic', bounds_error=False) fig, ax = plt.subplots(1, 3, figsize=(6, 3)) ax[0].plot(x, norm_pdf, c='k') ax[0].plot(x, kde_pdf, c='r', ls='--') ax[0].set_title('PDF') ax[1].plot(x, norm_cdf, c='k') ax[1].plot(x, cdf, c='r', ls='--') ax[1].set_title('CDF') ax[2].plot(x, norm_inv, c='k') ax[2].plot(x, inversefunction(x), c='r', ls='--') ax[2].set_title("Inverse CDF")

http://stackoverflow.com/q/47488859
type: AnsweredQuestion
has title: How strip python
has comment: http://stackoverflow.com/comment/81932850
score: 0
has comment: http://stackoverflow.com/comment/81932813
upvote count: 1
has answer: http://stackoverflow.com/a/47489075
has answer: http://stackoverflow.com/a/47488958
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81932727
has comment: http://stackoverflow.com/comment/81933085
has comment: http://stackoverflow.com/comment/81932961
possible better answer: http://stackoverflow.com/a/47489075
accepted answer: http://stackoverflow.com/a/47489013
tagged with: python
has answer: http://stackoverflow.com/a/47489013
has comment: http://stackoverflow.com/comment/81933112
answer count: 4
has answer: http://stackoverflow.com/a/47489026
has body: I'm writing a quiz code for school. The code iterates over a text file and loads the questions and answers from it. The user will select a difficulty to do the quiz on. The number of options for answers will vary depending on the difficulty. I have split each question and possible answer in the text file with commas. from random import shuffle file = open("maths.txt" , "r") for line in file: question = line.split(",") print(question[0]) if difficulty in ("e", "E"): options = (question[1], question[2]) if difficulty in ("m", "M"): options = (question[1], question[2], question[3]) if difficulty in("h", "H"): options = (question[1], question[2], question[3], question[4]) options = list(options) shuffle(options) print(options) answer = input("Please enter answer: ") if answer in (question[1]): print("Correct!") else: print("incorrect") file.close() This is what a line of the text file would look like: Question 1. What is 4+5?,9,10,20,11 The first option (question[1]) will always be the correct answer, therefore I would like to shuffle the options. With this code the options are outputted with square brackets, newline characters and quotation marks. Does anyone know how I can strip these? I tried to use: line.split(",").strip() however this seemed to do nothing at all. Thanks

http://stackoverflow.com/comment/81995039
comment on: http://stackoverflow.com/q/47518835
type: Comment
type: QuestionComment
score: 0
has text: No i did not. However this id is really important. Can you add it to the question?

http://stackoverflow.com/a/47479931
accepted answer of: http://stackoverflow.com/q/47459016
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47459016
has body: Ok, I figured out how to do this for Python 2.7 on my own. This is what I believe to be the best solution though it may not be the only one. It allows you to set, get, and function call on attributes of Class.all. I've named the metaclass InstanceUnifier, but please comment if you think there's a better (shorter, more descriptive) name you can think of. class InstanceUnifier(type): ''' What we want: A metaclass that can give a class an array of instances and provide a static Class.all object, that, when a method is called on it, calls the same method on every instance of the class. ''' def __new__(cls, name, base_classes, dct): dct['all'] = None dct['instances'] = [] return type.__new__(cls, name, base_classes, dct) def __init__(cls, name, base_classes, dct): class Accessor(object): def __getattribute__(self, name): array = [getattr(inst, name) for inst in cls.instances] if all([callable(item) for item in array]): def proxy_func(*args, **kwargs): for i in range(len(cls.instances)): this = cls.instances[i] func = array[i] func(*args, **kwargs) return proxy_func elif all([not callable(item) for item in array]): return array else: raise RuntimeError('Some objects in class instance array for key "'+name+'" are callable, some are not.') def __setattr__(self, name, value): [setattr(inst, name, value) for inst in cls.instances] def __delattr__(self, name): [delattr(inst, name) for inst in cls.instances] cls.all = Accessor() return type.__init__(cls, name, base_classes, dct) def __call__(cls, *args, **kwargs): inst = type.__call__(cls, *args, **kwargs) cls.instances.append(inst) return inst
type: Answer

http://stackoverflow.com/q/47405339
tagged with: flask-security
tagged with: flask
type: Question
has comment: http://stackoverflow.com/comment/81764718
has title: Flask Security Login Url
has comment: http://stackoverflow.com/comment/81764682
tagged with: python
score: 0
has body: I am using Flask Security in my flask project to handle authentication. Currently, navigating to example.com/login works perfectly. However, example.com/login.html results in a template not found error. I am assuming this is because flask-security is only handling the /login with nothing appended to it. Right now I have gotten around this by adding a redirect that goes from /login.html to /login. @app.route('/login.html', methods=['GET']) def loginReRoute(): return redirect('/login') Is this the best way to account for this? Or is there an easy way to get flask-security to directly handle the login URL with .html appended? Thanks!
has comment: http://stackoverflow.com/comment/81765716
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81764439
has comment: http://stackoverflow.com/comment/81764140
tagged with: authentication

http://stackoverflow.com/comment/81885702
has text: I think you need to create level property as dict.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47465488
type: QuestionComment

http://stackoverflow.com/q/47443434
has body: I'm new to python/data science in general, trying to understand why the below isn't working: import pandas as pd url = 'https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2017-06.csv' trip_df = [] for chunk in pd.read_csv(url, chunksize=1000, nrows=10000): trip_df.append(chunk) trip_df = pd.concat(trip_df, axis='rows') It's returning a MemoryError, but I was under the impression that loading the file in chunks was a workaround for that. I'd prefer not to save the csv to my hard drive, plus I'm not entirely sure if that would help. My computer's pretty limited, only 4GB of RAM (2.9 usable). I imagine that's a factor here, but if importing the whole file isn't an option, how would I just get part of it, say 5,000 rows?
has title: Pandas - Reading Large CSV directly from URL
answer count: 3
tagged with: pandas
upvote count: 3
downvote count: 0
tagged with: url
has answer: http://stackoverflow.com/a/47443498
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/47443538
has answer: http://stackoverflow.com/a/66511264
score: 3

http://stackoverflow.com/comment/81896398
score: 1
type: Comment
has text: GZip is not a splittable codec in Hadoop. That's why you don't get a lot of partitions when you read the CSV. I don't think there's much you can do here apart from changing the type of your file or probably extracting it before you read it using Spark.
type: QuestionComment
comment on: http://stackoverflow.com/q/47470772

http://stackoverflow.com/comment/82186242
comment on: http://stackoverflow.com/q/47509597
score: 0
type: Comment
type: QuestionComment
has text: What discord api are you using for python?

http://stackoverflow.com/a/47384478
answers question: http://stackoverflow.com/q/47384271
upvote count: 1
score: 1
type: Answer
has body: I believe you meant to use your with block inside your while block so that val gets updated. Something like this: import urllib.request, json previous_value = 0 while True: with urllib.request.urlopen("https://free.currencyconverterapi.com/api/v4/convert?q=MYR_INR&amp;compact=y") as url: data = json.loads(url.read().decode()) myr_ind = data['MYR_INR'] val = myr_ind['val'] if val &gt; previous_value: previous_value = val print(val)
accepted answer of: http://stackoverflow.com/q/47384271
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47428764
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47431522
has body: If have just switched to the qutebrowser and I'm overly happy with it. The one thing that is disturbing me is that I can't get the qutebrowser to focus on the tab that I've just opened. Any idea how to do this?
type: Question
tagged with: browser
accepted answer: http://stackoverflow.com/a/47431522
has title: How to focus on newly opened tab in qutebrowser?
answer count: 1
tagged with: python

http://stackoverflow.com/q/47481191
has comment: http://stackoverflow.com/comment/81917308
has comment: http://stackoverflow.com/comment/81917418
has comment: http://stackoverflow.com/comment/84281361
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81917224
score: 10
has answer: http://stackoverflow.com/a/47481344
has comment: http://stackoverflow.com/comment/81917269
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/81917191
has comment: http://stackoverflow.com/comment/81917234
has comment: http://stackoverflow.com/comment/81917204
has title: "__init__" looks so ugly in Python. Is there another way to code this construct?
has body: I have used this in my code, but "underscore underscore init underscore underscore" looks so ugly in Python, because it is not clear at a glance as to whether these prefixes and suffixes are one, two or three characters. Is there another way to code this construct without the double underscore? For example: class MyForm(forms.Form): foo = forms.CharField() def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.bar = bar(self) Annoyingly this code does not work, so obviously the underscore plays an essential role: class MyForm(forms.Form): foo = forms.CharField() def init(self, *args, **kwargs): super(MyForm, self).init(*args, **kwargs) self.bar = bar(self) What is the purpose of this syntax?
has comment: http://stackoverflow.com/comment/81917221
has comment: http://stackoverflow.com/comment/81917442
has comment: http://stackoverflow.com/comment/81917216
has comment: http://stackoverflow.com/comment/81917333
has comment: http://stackoverflow.com/comment/81917257
has comment: http://stackoverflow.com/comment/81917399
has answer: http://stackoverflow.com/a/47481249
favorite count: 0
type: Question
upvote count: 15
answer count: 2

http://stackoverflow.com/comment/108522616
type: AnswerComment
has text: When `t="s"` as in the first row, the value is a zero based index into a shared string table. That table can be found in `xl/sharedStrings.xml`.
score: 0
comment on: http://stackoverflow.com/a/47455961
type: Comment

http://stackoverflow.com/comment/82028802
score: 0
has text: Also does anyone know how to write over an input in the file?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47535654

http://stackoverflow.com/q/47496329
has answer: http://stackoverflow.com/a/47887814
favorite count: 0
type: Question
upvote count: 4
downvote count: 0
tagged with: pylint
score: 4
has answer: http://stackoverflow.com/a/57495664
type: AnsweredQuestion
answer count: 3
has body: I'm trying to use Visual Studio Code with pylint. When I load any .py file, I get the following error in the output console: Linting with pylint failed. You could either install the 'pylint' linter or turn it off in setings.json via "python.linting.pylintEnabled = false". Error: Command failed: C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\python.exe -m pylint --msg-template='{line},{column},{category},{msg_id}:{msg}' --reports=n --output-format=text c:\Users\(...)\Desktop\Untitled-1.py Traceback (most recent call last): File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pylint\__main__.py", line 7, in &lt;module&gt; pylint.run_pylint() File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pylint\__init__.py", line 12, in run_pylint from pylint.lint import Run File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pylint\lint.py", line 43, in &lt;module&gt; import astroid File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroid\__init__.py", line 57, in &lt;module&gt; from astroid.nodes import * File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroid\nodes.py", line 30, in &lt;module&gt; from astroid.node_classes import ( File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroid\node_classes.py", line 26, in &lt;module&gt; from astroid import decorators File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroid\decorators.py", line 12, in &lt;module&gt; import wrapt File "C:\Users\(...)\AppData\Local\Programs\Python\Python36-32\lib\site-packages\wrapt\__init__.py", line 4, in &lt;module&gt; from .w…
accepted answer: http://stackoverflow.com/a/47861422
possible better answer: http://stackoverflow.com/a/47887814
has answer: http://stackoverflow.com/a/47861422
has title: Running pylint returns ModuleNotFoundError: No module named 'wrapt.wrappers'
tagged with: python

http://stackoverflow.com/comment/81767450
type: Comment
score: 0
has text: @VijeshVenugopal it is solved. When i did the collectstatic, the missing css error was solved and also there was css dependency problem which is solved now. Thanks everyone for your help.
type: QuestionComment
comment on: http://stackoverflow.com/q/47406557

http://stackoverflow.com/q/47466084
answer count: 2
upvote count: 1
has title: How to compare a dictionary and string and output a dictionary?
downvote count: 1
has answer: http://stackoverflow.com/a/47467018
favorite count: 0
has answer: http://stackoverflow.com/a/47466152
type: Question
has body: I'm new to python and trying to write code which can compare a dictionary with a string. My input dictionary and string looks like this: l = {'Python' : 'high-level language', 'PHP' : 'ssl', 'Java' : 'low-level language'} st = 'Python and Php and Java are programming languages. PYTHON and PHP and JAVA are good skills to have. python and php and java are programming languages' I want to do a case insensitive comparison between the dictionary keys and string individual words (applying split function on string) and output the following: final_output = {'Python' : 'high-level language', 'and' : 'O', 'Php' : 'ssl', 'anbd' : 'O', 'Java' : 'low-level language', 'are' : 'O', 'programming' : 'O', 'languages.' : 'O', 'PYTHON' : 'high-level language', 'and' : 'O', 'PHP' : 'ssl', 'and' : 'O', 'JAVA' : 'low-level language', 'are' : 'O', 'good' : 'O', 'skills' : 'O', 'to' : 'O', 'have.' : 'O', 'python' : 'high-level language', 'and' : 'O', 'php' : 'ssl', 'and' : 'O', 'java' : 'low-level language', 'are' : 'O', 'programming' : 'O', 'languages' : 'O'} or like list of tuples where the integrity of the sentence would be maintained (which is also important in my case) final_output = [('Python' , 'low-level language'), ('and' , 'O'), ('Php' , 'ssl'), ('and' , 'O'), ('Java' , 'low-level language'), ('are' , 'O'), ('programming' , 'O'), ('languages.' , 'O'), ('PYTHON' , 'high-level language'), ('and' , 'O'), ('PHP' , 'ssl'), ('and' , 'O'), ('JAVA' , 'low-level language'), ('are' , 'O'), ('good' , 'O'), ('skills' , 'O'), ('to' , 'O'), ('have.' , 'O'), ('python' , 'high-level language'), ('and' , 'O'), ('php' , 'ssl'), ('and' , 'O'), ('java' , 'low-level language'), ('are' , 'O'), ('programming' , 'O'), ('languages' , 'O')] I tried to achieve this by considering my inputs to compare as two lists (rather than comparison between dictionary of keys and string) and wrote the following line of code: l = ['Python', 'PHP', 'Java'] st = 'Python and Php and Java are programming languages. PYTHON an…
accepted answer: http://stackoverflow.com/a/47466152
has comment: http://stackoverflow.com/comment/81886770
tagged with: python
possible better answer: http://stackoverflow.com/a/47467018
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81887073
type: AnsweredQuestion
score: 0

unix
tags question: http://stackoverflow.com/q/47383825
tags question: http://stackoverflow.com/q/47386149
tags question: http://stackoverflow.com/q/47501453
type: Tag
tags question: http://stackoverflow.com/q/47464706
tag name: unix
tags question: http://stackoverflow.com/q/47424885

http://stackoverflow.com/q/47531879
has body: why is the list index out of range?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82020167
type: UnansweredQuestion
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/47532099
tagged with: list
tagged with: sql
has comment: http://stackoverflow.com/comment/82020233
upvote count: 0
has comment: http://stackoverflow.com/comment/82021183
downvote count: 2
answer count: 1
tagged with: file
has title: SQL - python 3 index out of range

http://stackoverflow.com/comment/82020544
has text: Note that OP's `print` acutally gives `False` in Python 2. Maybe a complete answer should touch on that fact.
comment on: http://stackoverflow.com/a/47532038
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47443177
type: Answer
answers question: http://stackoverflow.com/q/47442478
score: 0
has body: Change: data.append([a.string for a in s]) to data.append([a.text for a in s]) Outputs: Player G A Plus_Minus SOG MS BS PN PIM HT ... GV SHF \ 0 J. Armia RW 0 0 -2 0 0 1 0 0 1 ... 0 21 1 D. Byfuglien D 0 1 0 5 1 1 1 2 1 ... 1 29 2 A. Copp C 0 0 -1 1 0 1 0 0 1 ... 0 18 3 M. Dano C 0 0 -1 0 0 0 0 0 0 ... 0 14 4 N. Ehlers LW 0 0 -1 2 1 0 0 0 0 ... 0 20 5 T. Enstrom D 0 0 -2 1 1 2 0 0 1 ... 0 23 6 D. Kulikov D 0 0 1 0 0 0 0 0 1 ... 0 20 7 P. Laine RW 0 1 2 2 1 0 0 0 0 ... 1 23 8 B. Little C 0 1 0 3 2 0 0 0 0 ... 0 22 9 A. Lowry LW 0 0 0 4 1 0 0 0 3 ... 1 27 10 S. Matthias C 0 0 -1 2 0 0 0 0 2 ... 2 23 11 J. Morrissey D 0 0 -2 2 0 2 1 2 0 ... 0 20 12 T. Myers D 0 0 0 2 1 2 1 2 2 ... 1 27 13 M. Perreault C 1 0 -1 2 0 0 0 0 1 ... 0 23 14 M. Scheifele C 1 0 -1 4 0 0 0 0 0 ... 0 23 15 B. Tanev LW 0 0 -1 0 0 0 0 0 1 ... 0 15 16 J. Trouba D 0 0 -4 5 0 4 1 2 4 ... 1 30 17 B. Wheeler RW 0 0 -1 2 2 1 0 0 0 ... 0 23 see Difference between .string and .text BeautifulSoup An example: from bs4 import BeautifulSoup data = ' B. Wheeler RW ' soup = BeautifulSoup(data, 'lxml') td = soup.find("td") print (td.string) print (td.text) Outputs: None B. Wheeler RW Because you have "markup" in the "td" element.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47442478

http://stackoverflow.com/a/47480454
has comment: http://stackoverflow.com/comment/81915833
has comment: http://stackoverflow.com/comment/81915875
has comment: http://stackoverflow.com/comment/81916236
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81916117
has comment: http://stackoverflow.com/comment/81915815
has comment: http://stackoverflow.com/comment/81915992
accepted answer of: http://stackoverflow.com/q/47480320
has comment: http://stackoverflow.com/comment/81915970
has body: Depending a bit on how much of your given structure will generalize, In [50]: df_a | df_b | df_c.loc[df_a.index, df_a.columns] Out[50]: A B 0 1 1 1 1 1
has comment: http://stackoverflow.com/comment/81916174
answers question: http://stackoverflow.com/q/47480320
type: Answer

http://stackoverflow.com/q/47513816
upvote count: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47517519
tagged with: pyqt5
has answer: http://stackoverflow.com/a/47517519
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81984288
has title: Exception from QTextEdit textChanged signal
tagged with: python
tagged with: signals-slots
tagged with: qtextedit
type: AnsweredQuestion
score: 3
has body: I'm using Python3 and PyQt5 to create an application containing form elements such as QLineEdit and QTextEdit. I collect data from a QLineEdit as follows (this is working properly): self.rolAdi = QtWidgets.QLineEdit(self.centralWidget) self.rolAdi.setObjectName("rolAdi") self.rolAdi.textChanged.connect(self.textSonDurum) def textSonDurum(self, s): print("Text changed...&gt;&gt;&gt; "+s) However, the same method using a QTextEdit control doesn't work - the program stops whenever I change the content of the control: self.IP = QtWidgets.QTextEdit(self.centralWidget) self.IP.setObjectName("IP") self.IP.textChanged.connect(self.textSonDurum) def textSonDurum(self, s): print("Text changed...&gt;&gt;&gt; "+s) I researched about this problem and I found a suggestion involving using the disconnect function, but cannot find it in PyQt5. self.IP.textChanged.disconnect() Output Error: TypeError: disconnect() failed between 'textChanged' and all its connections (The full code is very long to paste it here but let me know if you need any other part).

http://stackoverflow.com/q/47448560
has body: I want to extract the (paragraph) within the html tags in Python &amp;lt;p style=&amp;quot;text-align: justify;&amp;quot;&amp;gt;&amp;lt;span style=&amp;quot;font-size: small; font-family: lato, arial, helvetica, sans-serif;&amp;quot;&amp;gt; Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive. &amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt; My code is from HTMLParser import HTMLParser from bs4 import BeautifulSoup x = """&amp;lt;p style=&amp;quot;text-align: justify;&amp;quot;&amp;gt;&amp;lt;span style=&amp; quot;font-size: small; font-family: lato, arial, helvetica, sans-serif;&amp;quot;&amp;gt; Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive. &amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt;""" p1 = HTMLParser() p1.unescape(x) bdy_soup = BeautifulSoup(p1.unescape(x)).get_text(separator=";") print(bdy_soup) this code is not returning anything please help me to do so ,, any help would be appreciated
has answer: http://stackoverflow.com/a/47448631
downvote count: 2
has comment: http://stackoverflow.com/comment/81852223
has comment: http://stackoverflow.com/comment/81852528
favorite count: 0
type: Question
tagged with: python-3.x
has title: python extract data from html tags
has comment: http://stackoverflow.com/comment/81852129
has comment: http://stackoverflow.com/comment/81852180
score: -2
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47450387
tagged with: python
duplicate of: http://stackoverflow.com/q/328356
has answer: http://stackoverflow.com/a/47448653
answer count: 4
has comment: http://stackoverflow.com/comment/81852092
has answer: http://stackoverflow.com/a/47448822
linked to: http://stackoverflow.com/q/328356
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/47464712
score: 0
type: AcceptedAnswer
has body: At first 'if' case you create Person object and you add this object to the list - at this moment your list contains instances of 'Person' class. List in Python can contain only one type of objects so when you try to invoke 'getHSalary', which is not a part of Person class, error occurs.
accepted answer of: http://stackoverflow.com/q/47464535
type: Answer
answers question: http://stackoverflow.com/q/47464535

http://stackoverflow.com/q/47436720
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47437133
tagged with: postgresql
tagged with: sql
score: 1
answer count: 1
downvote count: 0
has body: The tables are showing but all the data is showing under HY. I want row 19 to show under HY and row 20 to show under AY. For a fact, AY column is getting created but all lines say [null] #!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import sys import csv from itertools import count path = r'C:\Users\sammy\Downloads\E0.csv' with open(path, "r") as csvfile: readCSV = csv.reader(csvfile, delimiter=",") firstline = 1 con = None con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'") cur = con.cursor() cur.execute("DROP TABLE testtest1234") cur.execute("CREATE TABLE testtest1234 (HY INTEGER, AY INTEGER)") try: for row in readCSV: if firstline: firstline=0 continue new_data = row[19] newer_data = row[20] print(new_data) print(newer_data) cur.execute("INSERT INTO testtest1234 values ("+new_data+"), ("+newer_data+")") except psycopg2.DatabaseError as e: if con: con.rollback() print ("Error %s % e", e) sys.exit(1) finally: if con: con.commit() con.close() print(" ".join(row)) out=open("new_data.csv", "w") output = csv.writer(out) for row in new_data: output.writerow(row) out.close()
upvote count: 1
has title: data from python showing in one column instead of two on ppostgresqll
tagged with: eclipse
favorite count: 0
type: Question
tagged with: pydev

http://stackoverflow.com/q/47503396
has comment: http://stackoverflow.com/comment/81962672
favorite count: 0
has title: Comparing dataframe cell value to previous cell value
has answer: http://stackoverflow.com/a/47503449
answer count: 2
has comment: http://stackoverflow.com/comment/81962678
has comment: http://stackoverflow.com/comment/81963211
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47503504
possible better answer: http://stackoverflow.com/a/47503504
type: Question
has comment: http://stackoverflow.com/comment/81963100
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47503449
has body: I am trying to iterate through each row of a pandas dataframe and compare a certain cell's value to the same cell in the previous row. I imagined this could be done using .shift(), but it is returning a series instead of the cell value. I have seen some usage of groupby and iloc for accessing the value of a cell but not for iterative comparisons, and using some sort of incrementing counter method or manually storing the value of each cell and then comparing doesn't seem very efficient. Here is what I imagined would work, but no joy. for index, row in df.iterrows(): if row['apm'] &gt; df['apm'].shift(1): # do something
tagged with: pandas
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81963546

http://stackoverflow.com/a/47487023
has comment: http://stackoverflow.com/comment/81928959
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47486763
answers question: http://stackoverflow.com/q/47486763
type: Answer
has body: I think you need create dictionary for maping by all possible towns with different council and then use replace: d = {'Enniskillen':'Fermanagh', 'Clogher':'Fermanagh', 'town1':'council1', ...} PsniYear1617Cleaned['council'] = PsniYear1617Cleaned['Town'].replace(d)

http://stackoverflow.com/comment/82002597
has text: Then why is 10 in the second row in the same group as 10 in the 3rd?
comment on: http://stackoverflow.com/q/47523071
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81943009
type: QuestionComment
comment on: http://stackoverflow.com/q/47457956
type: Comment
score: 0
has text: Have you looked at mean-shift segmentation?

http://stackoverflow.com/comment/81876348
comment on: http://stackoverflow.com/q/47459474
score: 0
type: Comment
type: QuestionComment
has text: below 200 MByte, so I am able to read them completely in the memory

http://stackoverflow.com/comment/81744436
type: QuestionComment
has text: To get the full text of a longer Tweet, use the `tweet_mode=extended` parameter and check the `full_text` field on the response. It is not possible to get all the Tweets for a specific account that has been around for a number of years via the API. Each timeline request will by default return 200 characters. You can use API Cursoring (https://developer.twitter.com/en/docs/basics/cursoring) to retrieve additional pages of results, but the timeline API tops out at 3200 Tweets. If you wanted more than that, you'd need to use Twitter's enterprise full archive search product (commercial).
comment on: http://stackoverflow.com/q/47394179
score: 1
type: Comment

http://stackoverflow.com/q/47443183
favorite count: 0
type: Question
has body: I am writing a small program which needs to parse an option -h using argparse module. Thus, I have this line in my code: parser.add_argument("-h"). However, when running, python complains: argparse.ArgumentError: argument -h/--help: conflicting option string(s): -h So I wonder if there is any way to override the -h provided by default from argparse.
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47443932
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47443932
has title: Is there any way to override the --help -h argument in python argparse?
type: AnsweredQuestion
tagged with: python-2.7
tagged with: argparse
score: 1
tagged with: command-line-arguments
has comment: http://stackoverflow.com/comment/81841628

http://stackoverflow.com/a/47420443
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47420369
has body: Yes, you can do something like this import subprocess from subprocess import Popen p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder") stdout, stderr = p.communicate()
type: Answer

google-cloud-vision
tags question: http://stackoverflow.com/q/47428173
type: Tag
tags question: http://stackoverflow.com/q/47466195
tag name: google-cloud-vision

http://stackoverflow.com/a/47452821
downvote count: 0
answers question: http://stackoverflow.com/q/47452663
type: Answer
has comment: http://stackoverflow.com/comment/81864560
has body: Try to use multi-level columns: In [137]: df Out[137]: A B C 0 1 2 3 1 4 5 6 2 7 8 9 In [138]: df.columns = pd.MultiIndex.from_product([['Caption'], df.columns]) In [139]: df Out[139]: Caption A B C 0 1 2 3 1 4 5 6 2 7 8 9 In [140]: df.to_excel('c:/temp/a.xlsx') Result:
score: 3
upvote count: 3

http://stackoverflow.com/comment/81886058
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47455874
has text: @ClémentDenoix, No it's not a duplicate. I have only one spider here.

http://stackoverflow.com/a/65832270
accepted answer of: http://stackoverflow.com/q/47495285
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47495285
has comment: http://stackoverflow.com/comment/116396273
upvote count: 2
has body: Normally I do get the correct size when following the above procedures, but the results from this example really puzzles me: from tkinter import * root=Tk() labelName = Label(root, text='label') entryName = Entry(root, foreground='red') labelName.update_idletasks() entryName.update_idletasks() wl = labelName.winfo_width() we = entryName.winfo_width() print('wl, we: ', we, wl) wl = labelName.winfo_reqwidth() we = entryName.winfo_reqwidth() print('wl, we: ', we, wl) entryName.insert(0, 'entry.................sajdALSKJDASKDjsc') labelName.grid(row=0, column=0) entryName.grid(row=0, column=1) mainloop() outputs ???: wl, we: 1 1 wl, we: 124 31
type: Answer
has comment: http://stackoverflow.com/comment/116396482
score: 2

http://stackoverflow.com/a/47501456
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81965663
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81968224
accepted answer of: http://stackoverflow.com/q/47501266
answers question: http://stackoverflow.com/q/47501266
has body: in the template you can simple use the property album, for example: {% for photo in object_list %} {{ photo.album.name }} created by {{ photo.album.user.username }} {% endfor %} read for details in docs

http://stackoverflow.com/a/63318730
has comment: http://stackoverflow.com/comment/118142184
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/115228568
answers question: http://stackoverflow.com/q/47495206
upvote count: 1
downvote count: 1
has body: You can use the OS library to see all drives connected to your computer. The following code will tell you the drives name and if it was connected or disconnected. In addition the code executes the function foo() when a drive is connected. Also, when a drive is disconnected it will execute the command ham() import os.path def diff(list1, list2): list_difference = [item for item in list1 if item not in list2] return list_difference def foo(): print("New dive introduced") def ham(): print("Drive disconnected") dl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)] print(drives) while True: uncheckeddrives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)] x = diff(uncheckeddrives, drives) if x: print("New drives: " + str(x)) foo() x = diff(drives, uncheckeddrives) if x: print("Removed drives: " + str(x)) ham() drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)] This code is made for python 3.8 for windows

http://stackoverflow.com/a/47479880
downvote count: 1
has body: Adding this line to the data feed sorted out my problem: timeframe=bt.TimeFrame.Ticks If interested in the strategy result, it's here.
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/47469640
score: 1

http://stackoverflow.com/comment/81973438
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47506499
score: 0
has text: yes I'm sorry about that, I realize now that might have been a bit misleading

http://stackoverflow.com/comment/81773993
type: Comment
score: 2
type: QuestionComment
has text: use `json.loads` to read each line into a dictionary instead of trying to lamely parse your input string.
comment on: http://stackoverflow.com/q/47410264

http://stackoverflow.com/q/47411966
tagged with: python
has answer: http://stackoverflow.com/a/47412487
score: 0
has comment: http://stackoverflow.com/comment/81777659
answer count: 3
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47417443
favorite count: 0
has answer: http://stackoverflow.com/a/47412219
type: Question
tagged with: hadoop
has comment: http://stackoverflow.com/comment/81777682
has comment: http://stackoverflow.com/comment/81777729
has body: i have a python mapreduce program, which takes an input of lists like this. [0, [199705, 213905, 212829, 13457, 111686, 607393, 872608, 732377, 182538, 787881, 118319, 964795, 166968, 365009, 894771, 613260, 641339, 25337, 34115, 893819, 795572, 685695, 312904, 907582, 871031, 166572, 677524, 579547, 293532, 823144, 475466, 809697, 941561, 691401, 933961, 968512, 533541, 65023, 553086, 644441, 448130, 721938, 404353, 430226, 391164, 805168, 119856, 322218, 657328, 433268]] [1, [347154, 517159, 919812, 929796, 522835, 759868, 683323, 445616, 940315, 862788, 290265, 955975, 453456, 295093, 884128, 748140, 456509, 449460, 676630, 112028, 891628, 927525, 246077, 249585, 430901, 582551, 889207, 115453, 124599, 985059, 5141, 689344, 396875, 770571, 246748, 643185, 573140, 161546, 734303, 872849, 931835, 793428, 678324, 534229, 928903, 211030, 227042, 669851, 545325, 494357]] There are 20 lists in total. I have to output the maximum integer among all these integers, globally. This is my code. def mapper(key, value): print(key,max(value)) def reducer(key, list_of_values): print(max(list_of_values)) It gives me the output like this. It prints out the biggest integer from each list, and it does so 20 times (20 mappers). 955177 957396 968512 972704 977466 982293 982751 983684 985059 987475 988109 988774 995432 995598 996172 996581 997120 998921 999030 999657 This is the line from the 20 lists. How can i get the output of only the single biggest integer?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81777506
has title: In python map-reduce, how to print the key with max value?

http://stackoverflow.com/q/47407576
has body: I want to create dictionary from pd.DataFrame where I want id to be key and all value_x are values but excluding NaN Dataframe newdf: id name value_1 value_2 value_3 0 ant jay 10.2 3.5 4.7 1 ant ann 5.7 10.2 NaN 2 bee will 7.4 NaN NaN 3 bee dave 12.4 1.3 6.9 4 bee ed 0.8 NaN NaN 5 cat kit NaN NaN 5.2 The expected outcome (value is sorted row by row) is {ant:(10.2,3.5,4.7,5.7,10.2), bee:(7.4,12.4,1.3,6.9,0.8), cat:(5.2)} I am trying to use .to_dict() but it does work yet newdf.groupby('id').apply(newdf.iloc[:,-3:].to_dict()) or dict(zip(newdf.id, newdf.iloc[:,-3:]))
favorite count: 0
has comment: http://stackoverflow.com/comment/81768286
has title: Dictionary from DataFrame: key from one column, values from multiple rows and columns excluding NaN
type: Question
has comment: http://stackoverflow.com/comment/81768742
downvote count: 0
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81768319
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47407665
score: 1
has comment: http://stackoverflow.com/comment/81768393
answer count: 1
has answer: http://stackoverflow.com/a/47407665
upvote count: 1

http://stackoverflow.com/a/47431522
score: 2
accepted answer of: http://stackoverflow.com/q/47428764
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Stack Overflow is about programming, and not the right place for qutebrowser questions. See getting help in the qutebrowser documentation for better places to get help. qutebrowser usually does focus newly opened tabs by default, unless you have tabs.background set. You might be running into this issue, or it might be something different - difficult to say more without knowing what link you're opening where, and how.
answers question: http://stackoverflow.com/q/47428764
type: Answer
has comment: http://stackoverflow.com/comment/81821411

http://stackoverflow.com/a/47436889
has comment: http://stackoverflow.com/comment/81830071
has comment: http://stackoverflow.com/comment/81829055
has comment: http://stackoverflow.com/comment/81828755
has comment: http://stackoverflow.com/comment/81828763
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81830343
has comment: http://stackoverflow.com/comment/81828820
has body: As they say use Series.ewm, Here series is referring to the column in your actual dataframe EMA = df['Close'].ewm(span=n,min_periods=n-1).mean().rename('EMA_' + str(n))
has comment: http://stackoverflow.com/comment/81829474
answers question: http://stackoverflow.com/q/47436867
score: 3
has comment: http://stackoverflow.com/comment/81831258
type: Answer

http://stackoverflow.com/comment/81881099
comment on: http://stackoverflow.com/q/47463064
score: 1
type: Comment
type: QuestionComment
has text: `text1 = csv.reader(file1)` - You made a csv reader , why aren't you using it?

http://stackoverflow.com/comment/82015389
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47529120
has text: Not sure about your need, but if this concerns translations from, say, English, would naming the files like `<sentence>_<language>` (e.g. `I don't know_de_DE`) be ok for you?
score: 2

http://stackoverflow.com/comment/81746545
type: Comment
comment on: http://stackoverflow.com/a/47396267
type: AnswerComment
has text: @SudheeshSinganamalla will keep that in mind. Thanks again :)
score: 1

http://stackoverflow.com/comment/103869289
comment on: http://stackoverflow.com/q/47495285
type: Comment
type: QuestionComment
score: 2
has text: Bryan, this seems unfair. If you call widget.winfo_height() when the widget is created, you just get '1'. But if ypu call widget.update() first, it gives the right answer.

http://stackoverflow.com/q/47532462
tagged with: keyboard-events
has title: pynput reject input when terminal not focused
has body: I have a python graphical application that runs in a terminal and accepts keyboard input using the pynput module. The issue I am having is that pynput accepts input all the time, even when the terminal running the application is not in focus by my window manager. This makes it difficult to shift focus to another task without accidentally typing into the application. Ideally, I would like to be able to either: Have pynput reject input when the terminal is not in focus OR Have some way of determining when the application gains/loses focus (so I can simulate #1 myself) I have searched the pynput documentation, but I cannot find a solution. Any advice on how to accomplish this is appreciated. I am using Linux.
tagged with: user-input
has comment: http://stackoverflow.com/comment/82022323
type: Question
upvote count: 4
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/72195104
tagged with: python
has comment: http://stackoverflow.com/comment/82022478
favorite count: 0
score: 4
tagged with: python-2.7

http://stackoverflow.com/q/47537821
has comment: http://stackoverflow.com/comment/82033720
possible better answer: http://stackoverflow.com/a/51717621
has answer: http://stackoverflow.com/a/51717621
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/47540934
answer count: 2
has body: In TensorFlow I'd like to apply one of the "fake" quantization functions to one of my tensors. Concretely I'm interested in using this function: fake_quant_with_min_max_args( inputs, min=-6, max=6, num_bits=8, narrow_range=False, name=None ) It works just fine out of the box. Ideally I would like to adjust the min and max arguments depending on the input tensor. Concretely, I want to use the 99.7% rule to define that range. In other words, I want to use the range of values that, if representing the input tensor as a 1-dimensional vector, 99.7% of its elements will lie between the [mean-3*std, mean + 3*std] range. For this purpose I do the following: def smartFakeQuantization(tensor): # Convert the input tensor to a 1-d tensor t_1d_data = tf.reshape(tensor,[tf.size(tensor), 1]) # get the moments of that tensor. Now mean and var have shape (1,) mean, var = tf.nn.moments(t_1d_data, axes=[0]) # get a tensor containing the std std = tf.sqrt(var) &lt; some code to get the values of those tensors at run-time&gt; clip_range = np.round([mean_val - 3*std_val, mean_val + 3*stdstd_val], decimals=3) return tf.fake_quant_with_min_max_args(tensor, min=clip_range[0], max=clip_range[1]) I know that I could evaluate any tensor in the graph by doing: myTensor.eval() or mySession.run(myTensor) but if I add those kind of lines in side my function above it will crash when executing the graph. I'll get an error of the form: tensor &lt;...> has been marked as not fetchable. Probably steps I'm following are not the correct ones for the "graph" nature of TensorFlow. Any ideas how this could be done? Summarising, I want to use the value of a tensor at run-time to modify another tensor. I'd say this problem is more complex than what can be done with tf.cond().
tagged with: quantization
accepted answer: http://stackoverflow.com/a/47540934
tagged with: tensorflow
type: Question
has title: Use tensor's value to modify another tensor at run-time
type: AnsweredQuestion

http://stackoverflow.com/q/47436398
type: AnsweredQuestion
upvote count: 0
has title: How to use decorator in my package
tagged with: decorator
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81828268
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81827137
type: Question
has answer: http://stackoverflow.com/a/47436564
tagged with: package
has comment: http://stackoverflow.com/comment/81960243
has comment: http://stackoverflow.com/comment/81960280
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81962139
accepted answer: http://stackoverflow.com/a/47436564
has body: I want to use original decorator in my original package (ex.'with_error_handler' in 'mypackage') and execute some function. But it returns function object or error massage that too given arguments. In my package: def with_error_handler(func): import traceback from functools import wraps from decorator import decorator @decorator @wraps(func) def error_handler(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: strError = traceback.format_exc() + __file__ + '(' + str(args) + str(kwargs) + ')' print(strError) return error_handler And I want to execute below code. import mypackage @mypackage.with_error_handler def divnum(num): print(1/num) @mypackage.with_error_handler def divone(): print(1/1) if __name__ == '__main__': divnum(2) divone() These result is here &gt;&gt;&gt;divnum(2) ･･･with_error_handler() takes 1 positional argument but 2 were given &gt;&gt;&gt;divone() ･･･&lt;function __main__.divone&gt; Why these error is occured? How to fix it?
tagged with: wrapper
has comment: http://stackoverflow.com/comment/81827317

http://stackoverflow.com/comment/81999057
type: Comment
comment on: http://stackoverflow.com/q/47520872
type: QuestionComment
score: 0
has text: thank you anyway @PatrickArtner. I have just posted a sample of the xhtml file

http://stackoverflow.com/comment/81877028
has text: This will remove regardless the column, need to remove only if coulumn A has them
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47460459

http://stackoverflow.com/comment/82033510
comment on: http://stackoverflow.com/q/47537955
has text: You should've put your patterns to original answer, but it's seen from code that there is no [captured parameters](https://docs.djangoproject.com/en/1.11/topics/http/urls/#captured-parameters). I suggest you to pay attention to https://docs.djangoproject.com/en/1.11/intro/tutorial03/#writing-more-views
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47459944
upvote count: 7
score: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47459824
has comment: http://stackoverflow.com/comment/81874725
has comment: http://stackoverflow.com/comment/81874492
has comment: http://stackoverflow.com/comment/81874786
type: Answer
has comment: http://stackoverflow.com/comment/81875062
accepted answer of: http://stackoverflow.com/q/47459824
has body: If need lens of characters: df = (all_works_by_speaker_df.groupby('title')['scene_text'] .apply(lambda x: np.mean(x.str.len())) .reset_index(name='mean_len_text')) print (df) title mean_len_text 0 All's Well That Ends Well 48.4 If need lens of words use Vaishali's solution.
downvote count: 0

http://stackoverflow.com/q/47433921
type: AnsweredQuestion
tagged with: suds
has body: I am trying to use suds (version 0.6) to connect to a web service, from suds.client import Client client = Client(SOAP_URL, timeout=10) now I sometimes get timeout error, so I am wondering how to catch all errors using suds when connecting to a web service, and so then in the catch block I can reconnect the web service.
downvote count: 0
has title: python how to catch suds web service soap errors
duplicate of: http://stackoverflow.com/q/2085128
score: 1
upvote count: 1
tagged with: web-services
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: soap
tagged with: python
has answer: http://stackoverflow.com/a/47433965
accepted answer: http://stackoverflow.com/a/47433965
linked to: http://stackoverflow.com/q/2085128

http://stackoverflow.com/comment/81954663
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47499575
has text: good one @dimitris_ps. But my requirement is I have to compare the value of Col1 in DF2 with the country_map keys and fetch the corresponding country_map values which will be put in Col2 in DF2. Please note that the values of Col1 in DF2 is duplicated. So wherever the same value is present, the corresponding integer should be same
type: Comment

http://stackoverflow.com/comment/81882188
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47463612
has text: Python has a REPL -- enter it in as you would any experiment in python.
type: Comment

http://stackoverflow.com/comment/81726262
has text: This github gist is pretty cool about doing things in a 'pythonic' way. [Transforming Code into Beautiful, Idiomatic Python](https://gist.github.com/JeffPaine/6213790)
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47386541

http://stackoverflow.com/q/47459949
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68373998
has answer: http://stackoverflow.com/a/47541112
downvote count: 0
has answer: http://stackoverflow.com/a/47541172
has comment: http://stackoverflow.com/comment/108650399
has title: Drop few rows of a pandas dataframe using lambda
favorite count: 0
has answer: http://stackoverflow.com/a/61419135
has comment: http://stackoverflow.com/comment/81885890
has answer: http://stackoverflow.com/a/47541306
has body: I'm currently facing a problem with method chaining in manipulating data frames in pandas, here is the structure of my data: import pandas as pd lst1 = range(100) lst2 = range(100) lst3 = range(100) df = pd.DataFrame( {'Frenquency': lst1, 'lst2Tite': lst2, 'lst3Tite': lst3 }) the question is get entries(rows) if the frequency is less than 6, but it needs to be done in method chaining. I know using a traditional way is easy, I could just do df[df["Frenquency"]&lt;6] to get the answer. However, the question is about how to do it with method chaining, I tried something like df.drop(lambda x:x.index if x["Frequency"] &lt;6 else null) but it raised an error "[&lt;function &lt;lambda&gt; at 0x7faf529d3510&gt;] not contained in axis" Could anyone share some light on this issue?
tagged with: pandas
has comment: http://stackoverflow.com/comment/81885927
has comment: http://stackoverflow.com/comment/81874728
score: 10
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81874743
tagged with: lambda
upvote count: 10
has comment: http://stackoverflow.com/comment/82039749
type: Question

http://stackoverflow.com/q/47461470
has body: I have an edit function where I edit certain data. The form (I use flask_wtf) is the same, so I can use: form.populate_obj(build) Now I see all old values and can edit them, but some fields do not have a value. These fields are null in the DB. Often I dont need to edit them so I simply ignore them. And here is the problem, if I submit the edit form all values which should remain null become an empty string "" Here is a precise example: Thats an entry where I want only to edit date_added. I ignore bandits and additional_info. After submit I expect that bandits and additional_info still are null, but they change: Of course I could rewrite the whole code and use the same logic where I add these values to the DB, but I feel like there should be a better solution.
has answer: http://stackoverflow.com/a/47717762
type: Question
accepted answer: http://stackoverflow.com/a/47717762
tagged with: python
tagged with: flask
type: AnsweredQuestion
score: 0
answer count: 1
has title: Flask form.populate_obj() keep null values

http://stackoverflow.com/comment/81962425
type: AnswerComment
score: 0
type: Comment
has text: Just updated the answer, do you mean something like that?
comment on: http://stackoverflow.com/a/47503230

http://stackoverflow.com/comment/81735875
type: Comment
type: QuestionComment
has text: @adamsorbie also, if you need more help, post the full code and data if it is possible.
comment on: http://stackoverflow.com/q/47390313
score: 0

http://stackoverflow.com/q/47498713
type: Question
has comment: http://stackoverflow.com/comment/81952764
accepted answer: http://stackoverflow.com/a/47498825
has comment: http://stackoverflow.com/comment/81952597
tagged with: function
has comment: http://stackoverflow.com/comment/81952781
tagged with: square-root
tagged with: python
has comment: http://stackoverflow.com/comment/81952669
tagged with: epsilon
has comment: http://stackoverflow.com/comment/82048879
possible better answer: http://stackoverflow.com/a/47498803
type: AnsweredQuestion
has title: getting the accuracy of epsilon
score: 0
has comment: http://stackoverflow.com/comment/81952643
has answer: http://stackoverflow.com/a/47498825
has answer: http://stackoverflow.com/a/47498803
answer count: 2
has comment: http://stackoverflow.com/comment/81952826
upvote count: 1
downvote count: 1
has body: I'm trying to make a function that finds the square root of a number, without the square root command. That gets the answer to an accuracy of epsilon without any libraries, I have the basic code now def mySqrt(b, e) : sqrt = b**.5 I've tried many different approaches to this but I can't figure out how to implement in epsilon e
has comment: http://stackoverflow.com/comment/82048800
favorite count: 0

http://stackoverflow.com/comment/81884266
comment on: http://stackoverflow.com/q/47464706
type: QuestionComment
type: Comment
score: 0
has text: If you mean using os.listdir without os.isfile, it will also append the subdir names to the list

http://stackoverflow.com/a/47520979
accepted answer of: http://stackoverflow.com/q/47520885
downvote count: 0
upvote count: 2
has body: We using strftime df.index=df.index.strftime('%m/%d/%Y') df Out[300]: val 01/04/2016 BBG.XTKS.9716.S 01/04/2016 BBG.XTKS.9065.S 01/04/2016 BBG.XTKS.7966.S 01/04/2016 BBG.XTKS.3774.S 01/04/2016 BBG.XTKS.5110.S
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47520885
type: Answer
score: 2

http://stackoverflow.com/q/47509358
score: 1
accepted answer: http://stackoverflow.com/a/47509433
has answer: http://stackoverflow.com/a/47509433
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has title: Mixin fields not existing on Django migrations
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: django-migrations
has body: Let's say I have this mixing: class Test(object): ...some logic... class TestMixin(models.Model): db_field = django database field test = Test() # not a database field class Meta: abstract = True class Foo(TestMixin, models.Model): ... more db fields ... I am having a strange issue here. If I inspect Foo through django shell I can see both fields, db_field and test But if I create this migration: from __future__ import unicode_literals from django.db import migrations def custom_operation(apps, schema_editor): Foo = apps.get_model('django_app', 'Foo') stuffs = Foo.objects.all() for stuff in stuffs: print stuff.test # this doesnt exist class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.RunPython(custom_operation), ] And if I add a breakpoint at Test() __init__ it gets called through the shell or Django but not when running the migration. Which is the differente between with using the model through the migration?
has comment: http://stackoverflow.com/comment/81974924
tagged with: django-models
tagged with: python

http://stackoverflow.com/a/47504747
answers question: http://stackoverflow.com/q/47474986
has body: Here is the modified version of your code. with open('excel1.csv', 'r') as csvOne, open('excel2.csv', 'r') as csvTwo: csvONE = csvOne.readlines() csvTWO = csvTwo.readlines() with open('resultsDifference.csv', 'w') as resultFileDifference: # Write the header to difference file. # Because, the headers are same for 2 input CSVs, the header row will be obviously into resultsSame.csv resultFileDifference.write(csvONE[0]) for row in csvTWO: if row not in csvONE: resultFileDifference.write(row) with open('resultsSame.csv', 'w') as resultFileSame: for row in csvTWO: if row in csvONE: resultFileSame.write(row)
has comment: http://stackoverflow.com/comment/81973893
has comment: http://stackoverflow.com/comment/81970634
score: 0
has comment: http://stackoverflow.com/comment/81973777
type: Answer

http://stackoverflow.com/comment/81950998
has text: All you have to do is put a `\n` instead of a `\ `
score: 0
comment on: http://stackoverflow.com/q/47497832
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81926078
score: 2
has text: please post your code
comment on: http://stackoverflow.com/q/47485638
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47397692
has comment: http://stackoverflow.com/comment/81771664
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81772043
type: Answer
answers question: http://stackoverflow.com/q/47396789
score: 0
accepted answer of: http://stackoverflow.com/q/47396789
has comment: http://stackoverflow.com/comment/81773304
has body: According to pandas documentation https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html pd.read_html returns the list of dataframes (one dataframe for each table). So, you need to choose which one you want to group. Like: # for the first one: df = pd.read_html(str(table))[0]
has comment: http://stackoverflow.com/comment/81771548
has comment: http://stackoverflow.com/comment/81772829

http://stackoverflow.com/comment/82012929
type: AnswerComment
comment on: http://stackoverflow.com/a/47527692
has text: This while true will never end, so this answer is not really useful :/
type: Comment
score: 0

http://stackoverflow.com/q/47421930
answer count: 0
tagged with: arrays
has body: I am new to PYPY and trying to use it with large arrays being worked on in a large iteration for loop. What libraries can I use to optimize for large arrays and are there any other optimizing techniques I should be aware of? PLEASE NOTE THE *****SIMPLE CODE***** BELOW does not show that the print1-print10 variables CHANGE ON EVERY ITERATION. I am trying to keep things simple given that my question is ONLY about optimization techniques. The code below is simple: 10 large arrays get merged in a for loop 28,000 times and all the numbers that fall out 3 times over all 10 arrays are calculated on every iteration. This is super slow, would take hours, to loop to 28000. print1=range(0,200000) print2=range(100000,325000) print3=range(180000,300000) print4=range(0,250000) print5=range(0,100000) print6=range(170000,300000) print7=range(160000,300000) print8=range(150000,300000) print9=range(140000,300000) print10=range(130000,300000) task_id=0 for x in range(0, 28800): print x result= print1 + print2 + print3 + print4 + print5 + print6 + print7 + print8 + print9 + print10 from collections import Counter countresult=Counter(result) u = [ m for m,n in countresult.iteritems() if n == 3 ] print str(u) + "this is countsum"
tagged with: pypy
has comment: http://stackoverflow.com/comment/81798344
has comment: http://stackoverflow.com/comment/81824525
type: Question
has title: Optimisation techniques for large arrays in PYPY
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81824454
has comment: http://stackoverflow.com/comment/81847316
tagged with: large-data
score: 0

http://stackoverflow.com/comment/81895944
has text: The problem is the data is not organised (pulling from a huge database), and I was going to instruct. If you find AB data plot in subplot 3 of figure 1, if you find BA data plot in Fig2-subplot1, but if there is an instance of AB again go back to Fig1-subplot 3 etc. I get your point though `figure` and `axisArr` are instances, once the same name used the previous reference to that instance is lost. At least I know what the problem is, thanks for taking the time!
comment on: http://stackoverflow.com/a/47462533
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81940323
type: Comment
score: 0
type: AnswerComment
has text: Okay, so how would I do it so it can randomly select an item from the `system_list`, then correlate that to `system_list_damaged`?
comment on: http://stackoverflow.com/a/47492483

http://stackoverflow.com/q/47467658
has title: Flask: why app.route() decorator, should always be the outermost?
type: Question
score: 5
upvote count: 5
tagged with: python
tagged with: flask
tagged with: python-decorators
linked to: http://stackoverflow.com/q/25288773
accepted answer: http://stackoverflow.com/a/47467689
has answer: http://stackoverflow.com/a/47467689
linked to: http://stackoverflow.com/q/28204071
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/28575234
downvote count: 0
tagged with: decorator
answer count: 1
linked to: http://stackoverflow.com/q/739654
favorite count: 0
has body: Say, I have a hand-crafted @login-required decorator: from functools import wraps def login_required(decorated_function): """Decorator to check if user is logged in.""" @wraps(decorated_function) def wrapper(*args, **kwargs): if False: # just to check it's working return decorated_function(*args, **kwargs) else: flash('You need to login, to access this page') return redirect(url_for('login')) return wrapper and a function, decorated with @app.route() and @login_required (endpoint for login omitted for brevity): @app.route('/') @login_required def index(): return "Hello!" Now, if I try to access /, as expected, it won't let me and will redirect to the login page. Though, if I swipe the the order of the decorators i.e.: @login_required @app.route('/') def index(): return "Hello!" then I am able to access /, even though I shouldn't be. I am aware that Flask documentation on the subject states: When applying further decorators, always remember that the route() decorator is the outermost. I have also seen other questions on the same issue. What I'm curious about is not what is the proper way to do it (@app.route() decorator must be outermost - got it), but rather why it is working this way (i.e. what is the mechanics behind it). I took a look at @app.route() source code: def route(self, rule, **options): def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator This answer, helped me to understand mechanism of decorators, more or less. Though, I have never seen function just returned (without calling it) before, so I did a little experiment myself (which turned out to be workable, of course): def my_decorator(): def decorator (function): return function return decorator @my_decorator() def test(): print('Hi') test() So, I would like to understand: Why order of decorators matter in the exact case above and for @app.route() and other decorators in general (which is the same answer, I guess)? What co…

http://stackoverflow.com/comment/81804121
score: 0
type: AnswerComment
has text: The Rolling Stones also have spaces and it works: http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=therollingstones&api_key=b088cbedecd40b35dd89e90f55227ac2&format=json. Do you know why?
comment on: http://stackoverflow.com/a/47423199
type: Comment

http://stackoverflow.com/q/47438718
score: 0
tagged with: pyzmq
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81859489
has body: I'm working on a relatively simple Python / ZeroMQ based work distribution system, using REQ/ROUTER sockets. The system is distributed and worker nodes are geographically distributed on different continents. The ROUTER, responsible for distributing work, .bind()-s a ROUTER socket. Workers .connect() to it over TCP using a REQ socket. In the process of setting up a new worker node, I've noticed that while smaller messages (up to 1kB) do the trip with no issues, replies of ~2kB and up, sent by the ROUTER-end are never received by the worker into their REQ-socket - when I call recv(), the socket just hangs. The worker code runs inside Docker containers, and I was able to work around the issue when running the same image with --net=host - it seems to not happen if Docker is using the host network. I'm wondering if this is something in the network stack configuration on the host machine or in Docker, or maybe something that can be prevented in my code? Here is a simplified version of my code that reproduces this issue: Worker import sys import zmq import logging import time READY = 'R' def worker(connect_to): ctx = zmq.Context() socket = ctx.socket(zmq.REQ) socket.connect(connect_to) log = logging.getLogger(__name__) while True: socket.send_string(READY) log.debug("Send READY message, waiting for reply") message = socket.recv() log.debug("Got reply of %d bytes", len(message)) time.sleep(5) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) worker(sys.argv[1]) Router import sys import zmq import logging REPLY_SIZE = 1024 * 8 def router(bind_to): ctx = zmq.Context() socket = ctx.socket(zmq.ROUTER) socket.bind(bind_to) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) log = logging.getLogger(__name__) while True: socks = dict(poller.poll(5000)) if socks.get(socket) == zmq.POLLIN: message = socket.recv_multipart() log.debug("Received message of %d parts", len(message)) identity, _ = message[:2] res = handle_message(message[2:]) log.debug("Sending %d …
type: UnansweredQuestion
tagged with: zeromq
has title: ZeroMQ REQ .recv() hangs with messages larger than ~1kB if run inside Docker
has answer: http://stackoverflow.com/a/47452717
tagged with: python
tagged with: docker

http://stackoverflow.com/comment/81986249
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47515196
has text: I don't think it's ugly and I will punish you with an upvote.
type: Comment

http://stackoverflow.com/comment/81837247
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47441162
has text: Mixing them won't create a new paradigm?
score: 0

http://stackoverflow.com/comment/81981879
has text: Hadn't seen them before! Thanks!
comment on: http://stackoverflow.com/q/47397341
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82058595
comment on: http://stackoverflow.com/a/47523913
has text: Sorry for the delayed response but thanks so much the second option solved my problem. So for the url I hard coded the login page and then the pertinent login data as shown above and boom works like a charm. Thanks for your help!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82038750
type: QuestionComment
comment on: http://stackoverflow.com/q/47540609
type: Comment
score: 0
has text: Can you share some sample input and the output you'd like to get for it?

graph
tags question: http://stackoverflow.com/q/47469094
tags question: http://stackoverflow.com/q/47501336
tags question: http://stackoverflow.com/q/47512989
tags question: http://stackoverflow.com/q/47490284
tags question: http://stackoverflow.com/q/47540218
tag name: graph
type: Tag
tags question: http://stackoverflow.com/q/47494757
tags question: http://stackoverflow.com/q/47402177
tags question: http://stackoverflow.com/q/47419410
tags question: http://stackoverflow.com/q/47521187

http://stackoverflow.com/q/47499142
upvote count: 6
has comment: http://stackoverflow.com/comment/81953943
has comment: http://stackoverflow.com/comment/81954976
type: Question
has comment: http://stackoverflow.com/comment/81954714
has body: I am following the excellent talk on Pandas and Scikit learn given by Skipper Seabold. I am utilizing his cleaned data set that originates from UCI adult names. Upon running this code and generating the tree image via graphviz, we can observe there are value data on each node in the tree. import pandas as pd from sklearn.tree import DecisionTreeClassifier, export_graphviz dta = pd.read_csv("data/adult.data.cleaned.csv") for col in dta: if not dta[col].dtype.kind == "O": continue if dta[col].str.contains("\?").any(): dta.ix[dta[col].str.contains("\?"), col] = "Other" test.ix[test[col].str.contains("\?"), col] = "Other" dta.income.replace({"&lt;=50K": 0, "&gt;50K": 1}, inplace=True) test.income.replace({"&lt;=50K": 0, "&gt;50K": 1}, inplace=True) y = dta.pop("income") y_test = test.pop("income") X_train = pd.get_dummies(dta) X_test = pd.get_dummies(test) X_test[X_train.columns.difference(X_test.columns)[0]] = 0 dtree = DecisionTreeClassifier(criterion='entropy', random_state=0, max_depth=6) dtree.fit(X_train, y) export_graphviz(dtree, feature_names=X_train.columns) What do the value properties represent? EDIT: Meaning in every node there is a value=[x, y] property
answer count: 1
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/81954751
tagged with: scikit-learn
tagged with: decision-tree
tagged with: python
has comment: http://stackoverflow.com/comment/81953821
favorite count: 0
accepted answer: http://stackoverflow.com/a/47499717
type: AnsweredQuestion
has title: What is the meaning of the value property in a generated scikit learn decision tree?
has answer: http://stackoverflow.com/a/47499717
has comment: http://stackoverflow.com/comment/81954321

lerp
type: Tag
tags question: http://stackoverflow.com/q/47443037
tag name: lerp

http://stackoverflow.com/a/47399466
answers question: http://stackoverflow.com/q/47399102
type: Answer
has body: This will add the months to your list and then sort the monthlists # remove the leading empty '' from calendar.month_name list monthnames = [x for x in calendar.month_name if x != ''] # scan dicts for missing monts, if found, append tuple (monthname,0) to list for part in my_dict: print(part) for month in monthnames: if not month in [x[0] for x in my_dict[part]]: my_dict[part].append( (month,0) ) # modified https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value # interrate through dict, assign sorted dict, use indexlookup into monthlist for sorting for part in my_dict: my_dict[part] = sorted(my_dict[part], key=lambda x: monthnames.index(x[0])) print(my_dict) Output: {'Red Truck' : [('January', 2325185) ,( 'February', 209794) ,( 'March', 201874) ,( 'April', 19291) ,( 'May', 18705) ,( 'June', 0) ,( 'July', 22697) ,( 'August', 22796) ,( 'September', 0) ,( 'October', 0) ,( 'November', 0) ,( 'December', 0)], 'Witch Broom' : [('January', 0) ,( 'February', 350) ,( 'March', 3520) ,( 'April', 0) ,( 'May', 0) ,( 'June', 0) ,( 'July', 0) ,( 'August', 0) ,( 'September', 0) ,( 'October', 2703) ,( 'November', 2221) ,( 'December', 664)], 'Police Car' : [('January', 2037) ,( 'February', 2620) ,( 'March', 1480) ,( 'April', 15630) ,( 'May', 0) ,( 'June', 0) ,( 'July', 40693) ,( 'August', 2329) ,( 'September', 0) ,( 'October', 0) ,( 'November', 0) ,( 'December', 0)], 'Green Car' : [('January', 340) ,( 'February', 2589) ,( 'March', 12750) ,( 'April', 114470) ,( 'May', 0) ,( 'June', 0) ,( 'July', 4935) ,( 'August', 1632) ,( 'September', 61) ,( 'October', 0) ,( 'November', 0) ,( 'December', 3409)], 'Zamboni' : [('January', 256) ,( 'February', 426690) ,( 'March', 589) ,( 'April', 4740) ,( 'May', 880) ,( 'June', 0) ,( 'July', 1016) ,( 'August', 106) ,( 'September', 539) ,( 'October', 598) ,( 'November', 539) ,( 'December', 470)]}
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47510441
has answer: http://stackoverflow.com/a/47510637
has comment: http://stackoverflow.com/comment/81977069
score: 2
type: AnsweredQuestion
answer count: 3
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47510520
has title: Changing an array size from 1D to 2D in a selective way
accepted answer: http://stackoverflow.com/a/47510627
linked to: http://stackoverflow.com/q/47477945
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47510627
tagged with: multidimensional-array
has body: I need to change my array from the following Array = np.array([x1,y1,z1,x2,y2,z2......]) to Array = [[x1,x2,x3......] [y1,y2,y3,.....] [z1,z2,z3,.....]] Is this possible if so how ? Thanks
possible better answer: http://stackoverflow.com/a/47510520
duplicate of: http://stackoverflow.com/q/47477945
tagged with: python

http://stackoverflow.com/comment/81929918
comment on: http://stackoverflow.com/q/47487498
has text: please post the code you've tried.
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81858441
type: Comment
has text: I just edited my post. could you please put a sample websocket server code that receives limited message length?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47438051

http://stackoverflow.com/a/47501484
score: 0
type: Answer
has body: My naive understanding is that Pool simply processes the input list in sequence, sending the first ‘n’ elements to the pool, and then after the first process becomes available again, that one gets the next element, until there are no more elements. Finally it waits for all elements to finish before returning. You should do an experiment with a list: [2,2,2,5,2,2,2] and a function: def f(x): sleep(x) return x * x
has comment: http://stackoverflow.com/comment/81958715
has comment: http://stackoverflow.com/comment/81958763
answers question: http://stackoverflow.com/q/47501372

http://stackoverflow.com/a/47495053
answers question: http://stackoverflow.com/q/47493880
has comment: http://stackoverflow.com/comment/81955015
type: Answer
score: 0
has body: Have you tried writing: import pandas as pd df=pd.read_csv(file,encoding='utf-8')

http://stackoverflow.com/q/47433627
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81821559
linked to: http://stackoverflow.com/q/23621833
tagged with: python
linked to: http://stackoverflow.com/q/588004
duplicate of: http://stackoverflow.com/q/23621833
has body: I need to check to see if a shape is a cube (or could be). I have the total volume and length of one side. I begin by checking to see if the volume and side are both greater than 0, and then if the cubed root of the volume is equal to the side. The problem I have is that the cubed root of 125 returns as 4.999999999 using the following code. Rounding the number would make it inaccurate in other cases (4.6 would also become 5). I'm new to Python, as far as I can tell there's no built in cube root like Javascripts Math.cbrt(). def is_cube(volume, side): if volume &lt;= 0 or side &lt;= 0: return False elif volume ** (1/3) != side: return False else: return True I feel like I'm missing something very obvious. I know division in Python 3 will always give me a floating number, but 125 is a perfect cube.
has answer: http://stackoverflow.com/a/47433671
type: Question
possible better answer: http://stackoverflow.com/a/47435518
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81822038
has answer: http://stackoverflow.com/a/47435518
score: 0
has title: Finding cube root of perfect cube python3
accepted answer: http://stackoverflow.com/a/47433671

http://stackoverflow.com/a/51587987
answers question: http://stackoverflow.com/q/47441950
has body: using concatenate_videoclips might help. I use the code below and it works just fine. clips = [ImageClip(m).set_duration(1/25) for m in file_list_sorted] concat_clip = concatenate_videoclips(clips, method="compose") concat_clip.write_videofile("test.mp4", fps=25)
score: 0
type: Answer

http://stackoverflow.com/a/47428269
score: 0
has body: Something like this: def nothree(nt): sum = 0 for n in nt: if n == 3: break sum += n return sum If there is 3 in list, it will break the loop and return sum of numbers before 3 was reached. If there is no 3 in list, the sum will be sum of the list. And finally, if there is no numbers in list, sum will be 0.
type: Answer
answers question: http://stackoverflow.com/q/47428190

http://stackoverflow.com/q/47404943
has comment: http://stackoverflow.com/comment/81808292
has comment: http://stackoverflow.com/comment/81799151
tagged with: python
has answer: http://stackoverflow.com/a/47422389
tagged with: graphviz
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/30194104
type: Question
has title: How can I make my node text bold using attributes of the nodes when trying to draw graph structure using pydot and graphviz?
type: UnansweredQuestion
tagged with: pydot
has body: I have created a node using pydot and GraphViz as follows: import pydot graph = pydot.Dot(graph_type = 'digraph') a = pydot.Node("First Node", style = "filled", color = "red") graph.add_node(a) I want text of node a to be bold. How can I do it? Is there any attribute of the node like style, color? Thank you. Edit: If I need to add \n in the middle of the text, can I simply put \n in the middle as shown: <First\nNode>

http://stackoverflow.com/q/47400696
type: Question
has title: Python reading csv with 13 digit ISBN number converts into scientific notation
accepted answer: http://stackoverflow.com/a/47400747
tagged with: pandas
has answer: http://stackoverflow.com/a/47400747
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: sql-server
linked to: http://stackoverflow.com/q/45667144
tagged with: http://stackoverflow.com/tag/csv
score: 1
linked to: http://stackoverflow.com/q/47402225
tagged with: python
has body: I have a python program which give me around 200 csv files with 25 records each. I want to merge these 200 files into one file csv and load it in SQL server. (I am assuming this is good way to load) My final aim is to have one csv file with all the data of 200 csv and load the data on SQL server as well. All the files have same columns. One of the column contains ISBN-13 book number. When I merge the file through the following code, the ISBN-13 number gets converted into scientific notation (9780981454221 gets converted to 9.78098145422e+12) and I am losing information. (like the last digit) Is there any way to avoid this. Here is my code and sample data import pandas as pd import os import csv import glob os.chdir("//network/My Folder/") df=pd.DataFrame() for files in glob.glob("*.csv"): print files df = pd.concat([df,pd.read_csv(files)],axis=0) df.to_csv("test.csv", sep=',', encoding='utf-8',index=False) Data in csv file Book ISBN-13 Book_1 9780262527132 Book_2 9780071495844 Book_3 9780679734031 Book_4 9781621840862 Book_5 9781614271352 I am new to Python and DB. Any suggestions would be appreciated. Thank you in advance!

http://stackoverflow.com/comment/81880226
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47460326
has text: Yes, I included sample project structure which visualize my project structure. In my opinion it is clear what is written here. I wrote even which line causes the error.
type: Comment

http://stackoverflow.com/comment/81891297
type: Comment
type: QuestionComment
has text: `I have to use awk print inside python script.`. No you don't. There's nothing here that you couldn't do in Python.
comment on: http://stackoverflow.com/q/47468423
score: 3

http://stackoverflow.com/q/47485759
score: 1
tagged with: python
type: Question
has body: I found some questions that are similar but did not quite solve my problem (e.g. PATH issue with pytest 'ImportError: No module named YadaYadaYada') My project is structured as follows: MyApp | +--MyApp | | | +--__init__.py | +--app.py | +--config.py | +--tests | +--__init__.py +--test_app.py in my test_app.py I import app.py, which works just fine. from MyApp import app but within app.py I import config.py like this. import config With this setup I can run the app module, but pytest fails to import 'config' and raises: ImportError: No module named 'config' pytest succeeds when I change the import statement in app.py to: from MyApp import config However, an error is raised when I try to run the app: ImportError: No module named 'MyApp' From reading other questions I'm confident that there is something wrong with the PYTHONPATH, I just could not figure out how to fix this.
type: UnansweredQuestion
tagged with: pythonpath
answer count: 1
downvote count: 0
upvote count: 1
tagged with: flask
has title: pytest 'No module named ...' for import within the tested module
favorite count: 0
has answer: http://stackoverflow.com/a/47486080
tagged with: importerror
linked to: http://stackoverflow.com/q/4757178
linked to: http://stackoverflow.com/q/10253826
tagged with: pytest

http://stackoverflow.com/comment/82012376
type: QuestionComment
has text: There are too many tags on your question: do you want to get this using java or python?
comment on: http://stackoverflow.com/q/47526788
score: 0
type: Comment

http://stackoverflow.com/comment/81974735
type: AnswerComment
has text: For example:::: 1 2 1 2 2 2 2 2 3 4 3 4 3 4 3 4 5 1 6 1 8 1 9 1 10 1 11 1 13 2 13 2 16 2 16 2 17 4 17 4
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47509337

exponential
tags question: http://stackoverflow.com/q/47443357
type: Tag
tag name: exponential

http://stackoverflow.com/comment/82026444
comment on: http://stackoverflow.com/a/47533696
type: Comment
type: AnswerComment
has text: Sorry maybe I wasn't that clear, I don't want all "C" element texts, only the specific one with absolute path /A/B/C. I've edited the question to emphasis that more.
score: 0

http://stackoverflow.com/a/47539249
downvote count: 0
has comment: http://stackoverflow.com/comment/82035502
accepted answer of: http://stackoverflow.com/q/47538292
has comment: http://stackoverflow.com/comment/82035564
has body: The doc says DEFAULT_PAGINATION_CLASS and PAGE_SIZE are None by default. So you don't have to specify that unless you want. Just remove the DEFAULT_PAGINATION_CLASS from the REST_FRAMEWORK and all good to go.
type: Answer
answers question: http://stackoverflow.com/q/47538292
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/47439511
type: Answer
upvote count: 3
score: 3
downvote count: 0
has body: Use the configparser library. import configparser config = configparser.ConfigParser() config.read('config.ini')
answers question: http://stackoverflow.com/q/47439393

http://stackoverflow.com/q/47435152
has comment: http://stackoverflow.com/comment/81825683
has body: Lets say I have a dataframe like df = pd.DataFrame({'A':[1,2,3,4],'B':[1,3,4,7]}) A B 0 1 1 1 2 3 2 3 4 3 4 7 When I assign some data to transpose of a dataframe, there is no error i.e df.T['C'] = 3 There is no change in the dataframe after running this. But the question is where is the data being stored ? Why did't it give any error? I was expecting an error for this kind of assignment or an output like A B 0 1 1 1 2 3 2 3 4 3 4 7 C 3 3 Neither is happening when I did df.T['C'] = 3 Edit: as @Zero mention we might have to do df = df.T.assign(C=3).T # Which is like df.loc['C',:] = 3
favorite count: 0
linked to: http://stackoverflow.com/q/7601823
type: Question
has answer: http://stackoverflow.com/a/47436045
has title: Why do we lose data when assigned to transpose of dataframe?
has comment: http://stackoverflow.com/comment/81824799
linked to: http://stackoverflow.com/q/9449489
tagged with: transpose
has comment: http://stackoverflow.com/comment/81824811
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47435389
has comment: http://stackoverflow.com/comment/81825096
has comment: http://stackoverflow.com/comment/81825652
has comment: http://stackoverflow.com/comment/81825732
has answer: http://stackoverflow.com/a/47435389
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47436045
score: 3
has comment: http://stackoverflow.com/comment/81826082
has comment: http://stackoverflow.com/comment/81825600
answer count: 3
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/47484806
tagged with: dataframe

http://stackoverflow.com/comment/81885181
comment on: http://stackoverflow.com/a/47464928
has text: You are right. Looks like might code didn't work because of the white space characters. I removed them and it is working fine.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81831559
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47438313
has text: Have you tried using the `predict` method that's part of the `MultinomialNB` class? http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html. You already have it trained based on the titles and the output is the category. To use Naive Bayes on test data, do the same transformation of features that you did for training, then submit it into the Naive Bayes classifier.
type: Comment

http://stackoverflow.com/q/47449110
has title: Buffer Overflow Exploit Issue
has comment: http://stackoverflow.com/comment/81854056
has comment: http://stackoverflow.com/comment/81854173
answer count: 0
has body: I am trying to complete a a buffer overflow that involves overwriting a function pointer. The vulnerable C program is as follows: #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; void win() { printf("code flow successfully changed\n"); } int main(int argc, char **argv) { volatile int (*fp)(); char buffer[64]; fp = 0; gets(buffer); if(fp) { printf("calling function pointer, jumping to 0x%08x\n", fp); fp(); } } I've already run gdb on the program and found that the size of "buffer" is 72 bytes and the function address is 0x555546ca. So, I pipe in python3.6 -c "print('A' * 72 + '\xca\x46\x55\x55')" | ./stack3 and get a weird result: calling function pointer 0x55468ac3 Segmentation fault (core dumped) After examining memory, I found that the buffer was filled properly with 0x41s, but the next two words (fp*) were 0x55468ac3 and 0x00000055. I cannot understand why the data is obscured in this way.
score: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: buffer-overflow
has comment: http://stackoverflow.com/comment/81853272
favorite count: 0
has comment: http://stackoverflow.com/comment/81854249
type: Question
tagged with: python

http://stackoverflow.com/comment/81884754
has text: use `print()` to check what you have in variables and which part of code is executed. It helps to find problem.
comment on: http://stackoverflow.com/q/47464814
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82014339
score: 1
has text: Are you on windows or linux (unix)?
type: QuestionComment
comment on: http://stackoverflow.com/q/47528906
type: Comment

http://stackoverflow.com/q/47478016
tagged with: stack
answer count: 1
linked to: http://stackoverflow.com/q/47476716
type: Question
has title: How to connect random number generation to an item to print in python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47478902
accepted answer: http://stackoverflow.com/a/47478902
tagged with: python
has body: I am using this code below to generate a number between 1 to 10 continuously until it generates either 9 or 10 before it stops import random while True: rand = random.randint(1, 10) print(rand) if rand &gt; 8: break https://stackoverflow.com/a/47477745/9003921 I want to display another item if it generates a number from 1 to 8 for example if it generates the number 3 I want it to print out a name in order from a stack data structure. If it generates the numbers 9 or 10 it would break. An example of the stack data structure Mary Peter Bob John Kim The stack code I'm using is class Stack: def __init__(self): self.container = [] def isEmpty(self): return self.size() == 0 def push(self, item): self.container.append(item) def peek(self) : if self.size()&gt;0 : return self.container[-1] else : return None def pop(self): return self.container.pop() def size(self): return len(self.container) However, I'm not sure how to proceed from here
type: AnsweredQuestion
score: 0
tagged with: random

http://stackoverflow.com/comment/82027534
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47525123
type: AnswerComment
has text: Yes, it is and probably should work that way , in case it doesn't minor tweaking will help you to implement the function on you own, accept the answer if it works.

http://stackoverflow.com/comment/81743546
has text: result is - >> unknown error: Cannot read property 'setAttribute' of null when I removed .setAttribute error changed to NoSuchElementException. here is a webpage, complete link --> https://drive.google.com/drive/folders/19NxS2AwJdvAtu4Flm90P2kEsSuQlZd_2
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47394364
type: Comment

http://stackoverflow.com/q/47492296
type: Question
tagged with: python
has body: I have installed PyQt4 for python3 on Ubuntu 16.04LTS using these instructions: https://gist.github.com/0x414A/8b64178e69d9f8331938 I experience no problems importing PyQt4 but when I try to import QtGui from PyQt4, I receive the following error: &gt;&gt;&gt; from PyQt4 import QtGui Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: /home/yorka/Documents/BasicGUI/venv/lib/python3.5/site-packages/PyQt4/QtCore.so: undefined symbol: PyString_Type Any help is greatly appreciated.
has title: Problems importing QtGui from PyQt4
type: AnsweredQuestion
tagged with: python-3.x
score: 0
tagged with: pyqt4
answer count: 1
tagged with: ubuntu
has answer: http://stackoverflow.com/a/47848257
accepted answer: http://stackoverflow.com/a/47848257

http://stackoverflow.com/comment/82029647
comment on: http://stackoverflow.com/a/47535806
score: 0
type: AnswerComment
has text: Thanks for your edit. i edited my question too, cf. the "I have thinking of making a "script" that..." part
type: Comment

http://stackoverflow.com/q/47500214
has comment: http://stackoverflow.com/comment/81956195
favorite count: 0
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/47500426
has title: How to get discord.py bot to DM a specific user
upvote count: 5
has answer: http://stackoverflow.com/a/73338279
tagged with: python
has body: I have searched around a lot for this answer, and I haven't found it. I want to use a suggestion command, that whenever someone uses it to suggest an idea, it DMs me, and me only.
answer count: 4
accepted answer: http://stackoverflow.com/a/47500426
possible better answer: http://stackoverflow.com/a/49593430
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49593430
score: 4
has answer: http://stackoverflow.com/a/76326979
downvote count: 1

http://stackoverflow.com/q/47482493
has comment: http://stackoverflow.com/comment/81994527
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82001853
has comment: http://stackoverflow.com/comment/82034988
tagged with: opencv
score: 0
has body: Im using the following code to do realtime inference from mobilenet os.environ["CUDA_VISIBLE_DEVICES"] = '0' camera = cv2.VideoCapture(0) camera.set(3, 1280) camera.set(4, 1024) # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile('tf_model/output_labels.txt')] gpu_options = tf.GPUOptions(allow_growth=True,per_process_gpu_memory_fraction=0.9) sess_config = tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False,allow_soft_placement = True) sess_config.gpu_options.per_process_gpu_memory_fraction = 0.9 sess_config.gpu_options.allow_growth=True def grabVideoFeed(): grabbed, frame = camera.read() return frame if grabbed else None def initialSetup(): with tf.device('/gpu:0'): with tf.gfile.FastGFile('tf_model/output_graph.pb', 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') initialSetup() with tf.Session(config= sess_config) as sess: softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') while True: frame = grabVideoFeed() //do the rest of classification Though I have tried to use gpu, it is still not using the entire gpu. gpu usage is only 8%. how can I be able to sort this out?
has title: Using entire gpu during realtime inference
tagged with: gpu
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/82034283
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47386932
has text: Does your hosts file have QGMAC.locall instead of QGMAC.local? Maybe that is a typo and it should be QGMAC.local.
score: 0

http://stackoverflow.com/q/47398885
linked to: http://stackoverflow.com/q/432112
tagged with: python
has comment: http://stackoverflow.com/comment/81751142
has comment: http://stackoverflow.com/comment/81751127
has comment: http://stackoverflow.com/comment/81750952
has comment: http://stackoverflow.com/comment/81750971
has body: I have a data similar to, import numpy as np A = np.array( [['1','2','3'], ['a','3','5']] ) Now I want to identify the cell address of 'a'. I have tried the following code for that purpose, for i in range(0,2): for j in range(0,3): if (type(float(A[i,j])) == float): print(str(i)+str(j)) since, 'a' can't be converted into floating point it shows the following error. 00 01 02 Traceback (most recent call last): File "", line 3, in if (type(float(A[i,j])) == float): ValueError: could not convert string to float: 'a' Please help. Thank you in advance.
has title: Identify the strings in python array
has comment: http://stackoverflow.com/comment/81751174
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/432112
has comment: http://stackoverflow.com/comment/81751180
answer count: 1
accepted answer: http://stackoverflow.com/a/47399084
has answer: http://stackoverflow.com/a/47399084
has comment: http://stackoverflow.com/comment/81751141
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81751204
has comment: http://stackoverflow.com/comment/81751070
has comment: http://stackoverflow.com/comment/81751089

http://stackoverflow.com/comment/81753815
type: Comment
type: QuestionComment
has text: Possible duplicate of [Tkinter Label does not show Image](https://stackoverflow.com/questions/13148975/tkinter-label-does-not-show-image)
score: 2
comment on: http://stackoverflow.com/q/47399690

http://stackoverflow.com/q/47462649
has answer: http://stackoverflow.com/a/47464639
tagged with: python
has comment: http://stackoverflow.com/comment/81884070
has comment: http://stackoverflow.com/comment/81882739
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: tumblr
has title: Tags get split when reblogging a post using pytumblr
type: Question
has comment: http://stackoverflow.com/comment/81883956
tagged with: pytumblr
tagged with: split
has body: When I reblog a post using pytumblr, any tags I pass to the reblog() function are split into their constituent letters. For example, the following function call: client.reblog(blogName, id=post['id'], reblog_key=post['reblog_key'], state='published', tags='anagram', comment=reblogComment) puts the following tags on the post: #a #n #g #r #m (Note: according to the Tumblr API, tags are to be supplied comma-delineated.) Does anyone know how to fix this? Thanks!
accepted answer: http://stackoverflow.com/a/47464639

while-loop
tags question: http://stackoverflow.com/q/47436776
tags question: http://stackoverflow.com/q/47443765
tags question: http://stackoverflow.com/q/47409308
tags question: http://stackoverflow.com/q/47495596
type: Tag
tags question: http://stackoverflow.com/q/47386647
tags question: http://stackoverflow.com/q/47482688
tags question: http://stackoverflow.com/q/47490230
tags question: http://stackoverflow.com/q/47451559
tags question: http://stackoverflow.com/q/47389632
tags question: http://stackoverflow.com/q/47463118
tags question: http://stackoverflow.com/q/47462735
tags question: http://stackoverflow.com/q/47524047
tags question: http://stackoverflow.com/q/47523179
tags question: http://stackoverflow.com/q/47413100
tags question: http://stackoverflow.com/q/47443233
tags question: http://stackoverflow.com/q/47409940
tags question: http://stackoverflow.com/q/47400055
tags question: http://stackoverflow.com/q/47438901
tags question: http://stackoverflow.com/q/47440203
tag name: while-loop
tags question: http://stackoverflow.com/q/47446804
tags question: http://stackoverflow.com/q/47502985
tags question: http://stackoverflow.com/q/47405018

http://stackoverflow.com/comment/81868152
comment on: http://stackoverflow.com/a/47456679
has text: Using `deque` seems to be just a tiny bit faster than the plain loop proposed by the OP; with a `consume.generator` function which yields the first 1000 numbers, running `for _ in consume.generator(): pass` takes 71.8 usec per loop for me, `deque(consume.generator(), maxlen=0)` takes 67.4 (according to `timeit`).
score: 2
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47402954
downvote count: 3
tagged with: python
tagged with: lowercase
has title: PYTHON Sort only lowercase letters in place and don't sort numbers
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47403745
score: -2
has comment: http://stackoverflow.com/comment/81759665
upvote count: 1
tagged with: sorting
has answer: http://stackoverflow.com/a/47403651
has body: I have to write a code where the user inputs numbers, lowercase letters and uppercase letters. They must then be sorted and printed. The tricky part is that the numbers must stay where they are inputted and must not be sorted. The lowercase letters must be sorted but only stay in places where lower cases were originally inputted. The UPPERCASE letters must also be sorted but only stay in places where UPPERCASE were originally inputted. I know that sounds confusing but here's and example: The input string: asDaA34sFcCdWt61 The output string should be: aaAcC34dDsFsWt61 Here's what I have so far: x = input("Enter the variables to be sorted: ") z = list(x) z.sort() print(z) I have tried everything within my knowledge to no luck. Please help; I am an amateur at best and could use lots of help.
has comment: http://stackoverflow.com/comment/81760193
tagged with: uppercase
has comment: http://stackoverflow.com/comment/81759705

http://stackoverflow.com/a/54830110
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/47433414
score: 7
has comment: http://stackoverflow.com/comment/118450792
type: Answer
has body: The ARN should be deterministic given the prefix (if any, and the name). iam = session.client('iam') sts = session.client('sts') # Slow and costly if you have many pages paginator = iam.get_paginator('list_policies') all_policies = [policy for page in paginator.paginate() for policy in page['Policies']] [policy_1] = [p for p in all_policies if p['PolicyName'] == policy_name] # Fast and direct account_id = sts.get_caller_identity()['Account'] policy_arn = f'arn:aws:iam::{account_id}:policy/{policy_name}' policy_2 = iam.get_policy(PolicyArn=policy_arn)['Policy'] # They're equal except with the direct method you'll also get description field all(policy_1[k] == policy_2[k] for k in policy_1.keys() &amp; policy_2.keys())

http://stackoverflow.com/q/47406906
tagged with: object-detection
upvote count: 2
has comment: http://stackoverflow.com/comment/91878921
score: 2
type: UnansweredQuestion
has title: tensorflow object detection trained model not working
answer count: 1
downvote count: 0
has body: I trained my dataset for tensorflow object detection using both ssd and faster r-cnn model.There were 220 train and 30 test images in my dataset. I trained the model for 200k steps and got loss under 1.But when i tested my trained model on video it was detecting and labelling almost everything in the video. Can anyone tell me why is that happening? Thank you
has comment: http://stackoverflow.com/comment/81777267
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81777375
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/81776821
has answer: http://stackoverflow.com/a/47412501
tagged with: python

http://stackoverflow.com/comment/81883992
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47464507
has text: @Os9008 in what way is my answer different from your "specification" besides the missing "the" in the function name?
score: 0

http://stackoverflow.com/comment/81970511
comment on: http://stackoverflow.com/q/47507362
has text: Sorting with a key means sorting using the value given by the key function as the indication of where to place the item. In this case, `0` is before `1`, so all the items that produce key `0` will be placed earlier than all the items that produce key `1`.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81799030
has text: I see. My posted solution here assumes generic case. Would like to hear how it performs on your actual dataset.
score: 0
comment on: http://stackoverflow.com/q/47417474
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82009068
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47525926
has text: this solution was faster in a 10000 run loop. But it had an error while testing for another array: `nb_min = min([a[nb] for nb in nb_idx if a[nb] > value])` `ValueError: min() arg is an empty sequence`

sockets
tags question: http://stackoverflow.com/q/47455977
tags question: http://stackoverflow.com/q/47455452
tags question: http://stackoverflow.com/q/47516543
tags question: http://stackoverflow.com/q/47539028
tags question: http://stackoverflow.com/q/47435650
tags question: http://stackoverflow.com/q/47394745
tags question: http://stackoverflow.com/q/47426618
tags question: http://stackoverflow.com/q/47502337
tags question: http://stackoverflow.com/q/47459662
tags question: http://stackoverflow.com/q/47383825
tags question: http://stackoverflow.com/q/47503499
tags question: http://stackoverflow.com/q/47477492
tag name: sockets
tags question: http://stackoverflow.com/q/47530959
tags question: http://stackoverflow.com/q/47391774
tags question: http://stackoverflow.com/q/47501298
tags question: http://stackoverflow.com/q/47518835
tags question: http://stackoverflow.com/q/47495910
tags question: http://stackoverflow.com/q/47422338
tags question: http://stackoverflow.com/q/47535998
tags question: http://stackoverflow.com/q/47409170
tags question: http://stackoverflow.com/q/47493930
tags question: http://stackoverflow.com/q/47436349
tags question: http://stackoverflow.com/q/47395772
tags question: http://stackoverflow.com/q/47473750
tags question: http://stackoverflow.com/q/47505625
tags question: http://stackoverflow.com/q/47440140
type: Tag
tags question: http://stackoverflow.com/q/47500377
tags question: http://stackoverflow.com/q/47460889
tags question: http://stackoverflow.com/q/47404652

http://stackoverflow.com/comment/81769541
comment on: http://stackoverflow.com/q/47408081
type: Comment
score: 0
type: QuestionComment
has text: use `{% empty %} No data {% endfor %}` instead of `{% endfor %}` or set breakpoints, it is likely that you don't have any data.

http://stackoverflow.com/q/47421289
has answer: http://stackoverflow.com/a/47421462
has body: I was trying to assign a Python object to another in-place using a member function such as replace_object() below. However, as you can see, object_A remains unchanged and the only way to copy object_B is to create an entirely new object object_C, which defeats the purpose of in-place assignment. What is going on here and how can I make the assignment in-place? class some_class(): def __init__(self, attribute): self.attribute = attribute def replace_object(self, new_object): self = new_object # Does this line even have any effect? self.attribute = new_object.attribute self.new_attribute = 'triangle' return self object_A = some_class('yellow') print(object_A.attribute) # yellow object_B = some_class('green') object_C = object_A.replace_object(object_B) print(object_A.attribute) # yellow print(object_C.attribute) # green #print(object_A.new_attribute) # AttributeError! print(object_B.new_attribute) # triangle print(object_C.new_attribute) # triangle I also tried to play around with deep copies using copy.copy(), but to no avail. An interesting twist to this is that if I replace object_C = object_A.replace_object(object_B) with object_A = object_A.replace_object(object_B) then I get what I want. But why can't the same result be achieved by the statement self = new_object statement within replace_object()? PS: I have a very good reason to do this in-place assignment, so although it may not be best practice in general, just go along with me here.
type: Question
score: 2
linked to: http://stackoverflow.com/q/243836
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81813135
has comment: http://stackoverflow.com/comment/81798129
upvote count: 2
has comment: http://stackoverflow.com/comment/81799018
accepted answer: http://stackoverflow.com/a/47421462
answer count: 1
has comment: http://stackoverflow.com/comment/81813414
downvote count: 0
has comment: http://stackoverflow.com/comment/81797485
favorite count: 0
linked to: http://stackoverflow.com/q/390250
type: AnsweredQuestion
has title: Assigning an (OOP) object to another
tagged with: oop
has comment: http://stackoverflow.com/comment/81797047
has comment: http://stackoverflow.com/comment/81798368
has comment: http://stackoverflow.com/comment/81814037
has comment: http://stackoverflow.com/comment/81797005
tagged with: python

http://stackoverflow.com/q/47511452
upvote count: 0
has comment: http://stackoverflow.com/comment/81979099
has title: How to get the text present on a webpage using python?
type: UnansweredQuestion
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47570973
has comment: http://stackoverflow.com/comment/81979588
has body: import urllib3 from bs4 import BeautifulSoup url = 'http://www.thefamouspeople.com/singers.php' http = urllib3.PoolManager() response = http.request('GET', url) print(response.data) I am using python version 3.5.2 I am unable to install urllib or urllib2 to use urlopen function.Getting the output as "No suitable versions found". The output I am getting for above code is the source code that we get when we do "Inspect source code". I want the output as: The last natural blondes will die out within 200 years, scientists believe. A study by experts in Germany suggests people with blonde hair are an endangered species and will become extinct by 2202. Researchers predict the last truly natural blonde will be born in Finland - the country with the highest proportion of blondes. The frequency of blondes may drop but they won't disappear Prof Jonathan Rees, University of Edinburgh But they say too few people now carry the gene for blondes to last beyond the next two centuries. The problem is that blonde hair is caused by a recessive gene. In order for a child to have blonde hair, it must have the gene on both sides of the family in the grandparents' generation. Dyed rivals The researchers also believe that so-called bottle blondes may be to blame for the demise of their natural rivals. They suggest that dyed-blondes are more attractive to men who choose them as partners over true blondes. Tory MP Ann Widdecombe Bottle-blondes like Ann Widdecombe may be to blame But Jonathan Rees, professor of dermatology at the University of Edinburgh said it was unlikely blondes would die out completely. "Genes don't die out unless there is a disadvantage of having that gene or by chance. They don't disappear," he told BBC News Online. "The only reason blondes would disappear is if having the gene was a disadvantage and I do not think that is the case. "The frequency of blondes may drop but they won't disappear." See also: 28 Mar 01 | Education What is it about blondes? 09 Apr 99 | Health …
linked to: http://stackoverflow.com/q/328356
tagged with: python
has comment: http://stackoverflow.com/comment/81979642
has comment: http://stackoverflow.com/comment/81978815
favorite count: 0
score: -1
tagged with: data-extraction
has comment: http://stackoverflow.com/comment/81979091
type: Question
has comment: http://stackoverflow.com/comment/81978636

http://stackoverflow.com/comment/117012123
score: 1
has text: @N.BalgopalPatro this fork worked for me, Thanks Man :)
comment on: http://stackoverflow.com/a/56818296
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47470098
score: 0
has body: Already found a solution. First of all we create new one image with all tools in it. Modify yml pipeline file image: hardtyz/jre-mvn-py3 pipelines: branches: master: - step: caches: - maven - node script: - mvn clean install - export AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY - export AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID - export AWS_DEFAULT_REGION=AWS_DEFAULT_REGION - python3 beanstalk_deploy.py And modify python script. Just update variables in head of script with your values. from __future__ import print_function import sys from time import strftime, sleep import boto3 from botocore.exceptions import ClientError VERSION_LABEL = strftime("%Y%m%d%H%M%S") BUCKET_KEY = VERSION_LABEL + '-bitbucket_builds.jar' BUCKET_NAME = 'your_bucket_name' APP_NAME='AppName' ENV_NAME='AppName-env' ARTIFACT_PATH='./core/target/core-0.0.1-SNAPSHOT.jar' def upload_to_s3(artifact): """ Uploads an artifact to Amazon S3 """ try: client = boto3.client('s3') except ClientError as err: print("Failed to create boto3 client.\n" + str(err)) return False try: client.put_object( Body=open(artifact, 'rb'), Bucket=BUCKET_NAME, Key=BUCKET_KEY ) except ClientError as err: print("Failed to upload artifact to S3.\n" + str(err)) return False except IOError as err: print("Failed to access artifact in this directory.\n" + str(err)) return False return True def deploy_new_version(): """ Deploy a new version to AWS Elastic Beanstalk """ try: client = boto3.client('elasticbeanstalk') except ClientError as err: print("Failed to create boto3 client.\n" + str(err)) return False try: response = client.update_environment( ApplicationName=APP_NAME, EnvironmentName=ENV_NAME, VersionLabel=VERSION_LABEL, ) except ClientError as err: print("Failed to update environment.\n" + str(err)) return False print(response) return True def main(): if not upload_to_s3(ARTIFACT_PATH): sys.exit(1) if not create_new_version(): sys.exit(1) # Wait for the new version to be consistent before deploying sleep(5) if not deploy_new_version…
accepted answer of: http://stackoverflow.com/q/47459317
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47459317

http://stackoverflow.com/q/47471945
type: UnansweredQuestion
has title: Rolling Window, Dominant Frequency Numpy Accelerometer Data
tagged with: python
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47473543
tagged with: fft
has body: Want to calculate dominant frequency, secondary dominant frequency from X,Y,Z accelerometer data stored in flat CSV files (million rows+) e.g. data I'm trying to use scipy although aware of numpy - either would do. I've converted my X, Y, Z to SMV format (single magnitude vector) and want to apply the fourier transform to this, and then get the frequencies using fftfreq - the bit that defeats me is the n and timestep. I have my sample rates, the hertz, and the size of rolling window I want to look at (10 rows of data) but not quite sure how to apply this to script below: #The three-dimension data collected (X,Y,Z) were transformed into a #single-dimensional Signal Magnitude Vector SMV (aka The Resultant) #SMV = x2 + Y2 + Z2 X2 = X['X']*X['X'] Y2 = X['Y']*X['Y'] Z2 = X['Z']*X['Z'] #print X['X'].head(2) #Confirmed worked #print X2.head(2) #Confirmed worked combine = [X2,Y2,Z2, Y] parent = pd.concat(combine, axis=1) parent['ADD'] = parent.sum(axis=1) #Sum X2,Y2,Z2 sqr = np.sqrt(parent['ADD']) #Square Root of Sum Above sqr.name = 'SMV' combine2 = [sqr, Y] #Reduce Dataset to SMV and Class parent2 = pd.concat(combine2, axis=1) print parent2.head(4) "************************* Begin Fourier ****************************" from scipy import fftpack X = fftpack.fft(sqr) f_s = 80 #80 Hertz samp = 1024 #samples per segment divided by 12.8 secs signal length n = X.size timestep = 10 freqs = fftpack.fftfreq(n, d=timestep)
type: Question
tagged with: numpy
tagged with: accelerometer
tagged with: frequency

http://stackoverflow.com/q/47397323
upvote count: 4
type: AnsweredQuestion
has title: How can I get an access to url paramaters in django rest framework permission class?
accepted answer: http://stackoverflow.com/a/47409059
answer count: 1
downvote count: 0
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/47409059
favorite count: 0
type: Question
tagged with: url-parameters
has body: I have a view: class DealsView(APIView): permission_classes = (IsAuthenticated, IsOwnerOrCuratorOrDirectorOrNotAllowed, ) def get(self, request, user_pk): ... But in order to check the permissions correctly I need to pass user_pk url argument to permission: class IsOwnerOrCuratorOrDirectorOrNotAllowed(permissions.BasePermission): def has_permission(self, request, view): ... By default it doesn't have any arguments except self, request, and view. How can I go through it?
tagged with: django
tagged with: python
score: 4
tagged with: permissions
has comment: http://stackoverflow.com/comment/81747861

http://stackoverflow.com/q/47489741
has comment: http://stackoverflow.com/comment/82084967
has title: Broadcasting from processes if a condition is met in MPI
has body: I am new to MPI and and I'm trying to broadcast from one of the processes if a condition is met. The problem is that I don't see broadcasted messages on other processes when I try to print it out. When a process passes the second if condition it broadcasts a numpy array. In my code, processes 0, 1, 3, 5, 7 pass the second if condition. Here's the code: import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() rand_num=np.empty(5,dtype='float') bands = [(0, 65), (66, 132), (133, 198), (199, 264), (265, 330), (331, 396), (397, 462), (463, 529)] volts = {'map1':[478], 'map2':[346], 'map3':[213], 'map4':[81], 'map5':[34]} for items in volts.keys(): if(len(volts[items])!=0): neur_id = volts[items][0] if neur_id in range(bands[comm.rank][0],bands[comm.rank][1]): rand_num = np.array([comm.rank for i in range(0,5)],dtype='float') comm.Bcast(rand_num, root=comm.rank) comm.Barrier() #hoping to stop other processes from proceeding. print 'data and rank',rand_num,comm.rank I was expecting the output to look like: data and rank [ 0. 0. 0. 0. 0.] 0 data and rank [ 1. 1. 1. 1. 1.] 0 data and rank [ 3. 3. 3. 3. 3.] 0 data and rank [ 5. 5. 5. 5. 5.] 0 data and rank [ 7. 7. 7. 7. 7.] 0 data and rank [ 0. 0. 0. 0. 0.] 1 data and rank [ 1. 1. 1. 1. 1.] 1 data and rank [ 3. 3. 3. 3. 3.] 1 data and rank [ 5. 5. 5. 5. 5.] 1 data and rank [ 7. 7. 7. 7. 7.] 1 data and rank [ 0. 0. 0. 0. 0.] 2 data and rank [ 1. 1. 1. 1. 1.] 2 data and rank [ 3. 3. 3. 3. 3.] 2 data and rank [ 5. 5. 5. 5. 5.] 2 data and rank [ 7. 7. 7. 7. 7.] 2 data and rank [ 0. 0. 0. 0. 0.] 3 data and rank [ 1. 1. 1. 1. 1.] 3 data and rank [ 3. 3. 3. 3. 3.] 3 data and rank [ 5. 5. 5. 5. 5.] 3 data and rank [ 7. 7. 7. 7. 7.] 3 data and rank [ 0. 0. 0. 0. 0.] 4 data and rank [ 1. 1. 1. 1. 1.] 4 data and rank [ 3. 3. 3. 3. 3.] 4 data and rank [ 5. 5. 5. 5. 5.] 4 data and rank [ 7. 7. 7. 7. 7.] 4 data and rank [ 0. 0. 0. 0. 0.] 5 data and rank [ 1. 1. 1. 1. 1.] 5 data and rank [ 3. 3. 3. 3. 3.] 5 da…
tagged with: numpy
score: 0
duplicate of: http://stackoverflow.com/q/20030922
answer count: 0
has comment: http://stackoverflow.com/comment/81943978
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82117646
linked to: http://stackoverflow.com/q/6653084
tagged with: mpi
tagged with: python
has comment: http://stackoverflow.com/comment/81985048
has comment: http://stackoverflow.com/comment/81942811
linked to: http://stackoverflow.com/q/20030922
tagged with: mpi4py

http://stackoverflow.com/comment/81757255
type: AnswerComment
comment on: http://stackoverflow.com/a/47397737
has text: What would be better? To write to a variable in the if statements and return this at the bottom of the function, or to return in every if-block like I tried to do now?
type: Comment
score: 0

http://stackoverflow.com/q/47534067
tagged with: python-3.x
has body: First, I am a beginner with kivy, and not very experienced in Python either. The following program is strictly meant to educate myself in kivy basics, nothing more. The program is a game where the user controls a gun turret. He shots at objects that bounce around in the program window, while points and time used are shown in the bar below. (Currently occupied by a button.) The keys that turn the turret are "A" and "D", while "P" is for shooting. The problem I am currently having is this: I need to generate additional projectile graphics every time the user press "P". At a later stage I will also need to generate and remove target objects graphics when they get hit by a shot, which I guess will involve the same technique. How should I go about to generate additional canvas´ and\or ellipse objects? (the graphical representation of each shot) My Python code: from kivy.config import Config Config.set('graphics', 'width', '800') Config.set('graphics', 'height', '900') Config.set('graphics','resizable',0) from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.uix.relativelayout import RelativeLayout from kivy.properties import NumericProperty from kivy.properties import ReferenceListProperty from kivy.properties import BooleanProperty from kivy.properties import ListProperty from kivy.clock import Clock import math from kivy.core.window import Window class MainScreen(BoxLayout): #Contains the whole program #Turret rotation: the_angle = NumericProperty(0) #Projectile vector: the_pos_x = NumericProperty(0) the_pos_y = NumericProperty(0) the_pos = ReferenceListProperty(the_pos_x, the_pos_y) #Shots data: shot_fired = BooleanProperty(False) shot_count = NumericProperty(0) angle_list = ListProperty([]) pos_list_x = ListProperty([]) pos_list_y = ListProperty([]) def update(self, dt): if self.shot_fired == True: self.shot_count += 1 self.angle_list.ap…
has comment: http://stackoverflow.com/comment/82025486
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82026725
tagged with: python
tagged with: kivy
tagged with: kivy-language
score: 0
has comment: http://stackoverflow.com/comment/82025836
tagged with: canvas
answer count: 0
has comment: http://stackoverflow.com/comment/82026362
has title: Generate a new canvas for every new keypress (shooting gun turret)
type: Question

http://stackoverflow.com/q/47404305
has comment: http://stackoverflow.com/comment/81764102
has body: I have a python script which is part of a C++ build system -- it reads C++ files and uses libclang to extract some metadata which gets stored as json somewhere. We use this tool a lot with some very large files. We would like to be able to use it with ccache. To do that, the python script needs to "look like" gcc on the command line, close enough that ccache can just think of it as some highly nonstandard c compiler that happens to produce json instead of object code. (We are already passing it a lot of c-compiler flags anyways that need to go through to libclang.) Because we had to change the way it was parsing its arguments, I changed it away from using argparse because I didn't know how to do what I needed using argparse. The question is whether there's a clever way I didn't think of / didn't know about to do this more pythonically. The tool needs to parse an input filepath and an output filepath from the command line. The output filepath is signaled using -o, and the input filepath can be signaled using -c. (Sort of like how gcc works...) All other flags should be collected in another list, which will be forwarded to libclang. Example: ./args.py foo bar -o baz -c qaz input: qaz output: baz parser_args: ['foo', 'bar'] ./args.py foo bar -c qaz -o baz input: qaz output: baz parser_args: ['foo', 'bar'] The wrinkle is that it also needs to support a strange ordering in which the -o option appears between -c and the parameter to -c. ./args.py foo bar -c -o baz qaz input: qaz output: baz parser_args: ['foo', 'bar'] Here is the parser that I whipped up in naive (admittedly C-ish) python: #!/usr/bin/env python import sys def help(): print """ This tool takes command line arguments in a way compatible with gcc. This is so that it can be compatible with ccache. Pass with -c the path to the rtdv file. Pass with -o the output path to the json file. All other args are forwarded to libclang. To accomodate ccache, the following syntax is also allowed: -c -o output input """ def…
tagged with: argparse
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81762872
has comment: http://stackoverflow.com/comment/81762853
tagged with: python
has comment: http://stackoverflow.com/comment/81762831
score: 2
answer count: 0
upvote count: 2
downvote count: 0
has title: How to allow "interleaved" option-value pairs in python argparse parsers?
has comment: http://stackoverflow.com/comment/81763482
has comment: http://stackoverflow.com/comment/81763104
has comment: http://stackoverflow.com/comment/81762900
favorite count: 0
type: Question

http://stackoverflow.com/comment/81927006
type: Comment
comment on: http://stackoverflow.com/a/47485957
score: 0
has text: i am using python 3 so please can you suggest me how can i use it?
type: AnswerComment

http://stackoverflow.com/q/47419745
type: AnsweredQuestion
upvote count: 5
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47466633
tagged with: python
has title: Django ManyToMany field as json format
answer count: 4
has body: I'm trying to get data as json format. I've one ManyToMany field which is returning just id. But I need that contents too. Here is my models.py class Pricing(models.Model): name = models.CharField(max_length = 100) price = models.CharField(max_length = 100) def __str__(self): return self.name+' and '+self.price class Service(models.Model): name = models.CharField(max_length=100) price = models.ManyToManyField(Pricing, blank=True) def __str__(self): return self.name And also the views.py which is returning json format data def all_service_json(request, name): data = serializers.serialize("json", Service.objects.filter(name__icontains=name)) return HttpResponse(data) Now Getting the output like below [ { "model": "myapp.service", "pk": 2, "fields": { "name": "Service name", "price": [1, 2] } } ] But want like below [ { "model": "myapp.service", "pk": 2, "fields": { "name": "Service name", "price": { 1: "Price 1", 2: "Price 2" } } } ]
has answer: http://stackoverflow.com/a/67592000
type: Question
score: 5
possible better answer: http://stackoverflow.com/a/47466633
has answer: http://stackoverflow.com/a/69663224
downvote count: 0
accepted answer: http://stackoverflow.com/a/47420239
tagged with: django
has answer: http://stackoverflow.com/a/47420239
favorite count: 0

http://stackoverflow.com/a/47421259
score: 0
type: Answer
has body: Python 3.6 is not fully update all packages . It is more better use Python 3.5 For Python you can use it in command interpreter .... pip install 'your desire package name' For Anaconda ... conda install 'your desire package name'
answers question: http://stackoverflow.com/q/47393549

http://stackoverflow.com/q/47516286
score: 1
downvote count: 1
tagged with: append
favorite count: 0
has comment: http://stackoverflow.com/comment/81988707
type: Question
upvote count: 2
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47516381
has comment: http://stackoverflow.com/comment/81988618
has answer: http://stackoverflow.com/a/47516404
possible better answer: http://stackoverflow.com/a/47516404
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/81988783
type: AnsweredQuestion
has title: Append arrays of different dimensions to get a single array
answer count: 2
has answer: http://stackoverflow.com/a/47516381
has body: l have three vectors (numpy arrays), vector_1, vector_2, vector_3 as follow : Dimension(vector1)=(200,2048) Dimension(vector2)=(200,8192) Dimension(vector3)=(200,32768) l would like to append these vectors to get vector_4 : Dimension(vector4)= (200,2048+8192+32768)= (200, 43008) Add respectively vector1 then vector2 then vector3 l tries the following : vector4=numpy.concatenate((vector1,vector2,vector3),axis=0) ValueError: all the input array dimensions except for the concatenation axis must match exactly and vector4=numpy.append(vector4,[vector1,vector2,vectors3],axis=0) TypeError: append() missing 1 required positional argument: 'values'
has comment: http://stackoverflow.com/comment/81988715

http://stackoverflow.com/q/47392553
has comment: http://stackoverflow.com/comment/81738538
has comment: http://stackoverflow.com/comment/81738624
answer count: 1
tagged with: python
tagged with: youtube-api
has comment: http://stackoverflow.com/comment/81738649
has comment: http://stackoverflow.com/comment/81738752
has answer: http://stackoverflow.com/a/47451875
accepted answer: http://stackoverflow.com/a/47451875
has comment: http://stackoverflow.com/comment/81738938
type: AnsweredQuestion
score: 0
has body: I am going through this getting-started tutorial for Youtube v3 API interaction. I've created new sandbox project and used (copy/paste) the provided code there. Went on our GCE project, created credentials and pasted it into my sandbox project. I keep getting the response from youtube service, saying that Credentials are Invalid. ... File ".../python-sandbox/googleapiclient/http.py", line 842, in execute raise HttpError(resp, content, uri=self.uri) HttpError: &lt;HttpError 401 when requesting https://www.googleapis.com/youtube/v3/channels?alt=json&amp;part=snippet%2CcontentDetails%2Cstatistics&amp;forUsername=GoogleDevelopers returned "Invalid Credentials"&gt; What am I missing / doing wrong? Is this because the Credentials are created from different project than used on?
has title: Cannot get valid Credentials for Youtube v3 API
has comment: http://stackoverflow.com/comment/81738974
tagged with: youtube-data-api
type: Question

http://stackoverflow.com/comment/81792294
score: 4
type: Comment
has text: There can't be a trick -- Python float simply cannot represent both N and N+1 for sufficiently large values of N. The only "trick" might be to use a different data type: `int` or `decimal.Decimal` for example.
type: QuestionComment
comment on: http://stackoverflow.com/q/47419036

http://stackoverflow.com/comment/82007536
comment on: http://stackoverflow.com/q/47525680
type: Comment
type: QuestionComment
has text: You need to describe the question more if you would like somebody to be able to reproduce the problem in a way that they can provide an answer to you.
score: 0

http://stackoverflow.com/a/47417255
downvote count: 0
score: 1
upvote count: 1
has body: you need to reference the field in the other table. dep = Dependent.objects.first() dep.primarystudentid.name # This would be the name in your str example def __str__(self): return "{0}".format(self.primarystudentid.name) just worth noting that this can easily cause a lot of extra queries to be generated.
answers question: http://stackoverflow.com/q/47417158
type: Answer

http://stackoverflow.com/a/47453027
downvote count: 0
has comment: http://stackoverflow.com/comment/81862998
has comment: http://stackoverflow.com/comment/81861143
score: 3
has comment: http://stackoverflow.com/comment/81864288
has comment: http://stackoverflow.com/comment/81860813
type: Answer
has comment: http://stackoverflow.com/comment/81861046
has comment: http://stackoverflow.com/comment/81860883
has body: You have an error in your code. Try this out: labels = decode_predictions(yhat)[0] # retrieve the most likely result, e.g. highest probability for i in range(0,5): label = labels[i] #print('%s (%.2f%%)' % (label[1], label[2] * 100)) print('%s (%.2f%%)' % (label[1], float(label[2]) * 100))
has comment: http://stackoverflow.com/comment/81863326
answers question: http://stackoverflow.com/q/47451919
has comment: http://stackoverflow.com/comment/81863217
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47451919

http://stackoverflow.com/a/47478059
accepted answer of: http://stackoverflow.com/q/47477109
score: 2
answers question: http://stackoverflow.com/q/47477109
has body: 1 - I think it's a good option store as "America/Sao_Paulo". I do not think there is a numerical ID for time zones. 2 - The size consumed by a CharField is related to your database engine. Most databases only consumes the space required to store the text value. There is no difference in terms of space to set 32 or 320 characters (I think 64 is a good size). 3 - Use the third normal form: create a timezone table, then uses fks to link it: class MytimezoneTable(models.Model): tz_name = models.CharField(choices=ALL_TIMEZONES, max_length=64) class Snippet(models.Model): tz = models.ForeignKey(MyTimezoneTable)
upvote count: 2
downvote count: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81940367

http://stackoverflow.com/comment/81929772
has text: @pshep123 - Dose Google-able means I can solve this problem googling?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47487221
score: 0

http://stackoverflow.com/comment/81880449
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47462524
has text: whichever way you choose to go, make an attempt by yourself based on the hints you now have, if you have problems post that code in your original question and you will get help from someone.
type: Comment

http://stackoverflow.com/a/47498538
score: 2
has comment: http://stackoverflow.com/comment/81953781
has body: The best practice to keep it 'clean' is to use virtual environments. You can use conda to do it. From terminal run: conda create -n envs_name python=3.6 for example. After that you need to activate it, this is like saying "do the following only in my virtual environment and not on the global one": source activate envs_name pip install keras pip install tensorflow pip install ipykernel The ipykernel let's you manage your environments inside Jupyter. It's really easy and convenient.
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47493806
type: Answer

http://stackoverflow.com/comment/81752470
type: QuestionComment
comment on: http://stackoverflow.com/q/47399561
score: 1
has text: use a `try-except`?
type: Comment

http://stackoverflow.com/a/47431398
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47385053
downvote count: 0
answers question: http://stackoverflow.com/q/47385053
has comment: http://stackoverflow.com/comment/81824913
upvote count: 2
has body: From the pretty print for your document, information is nested in req. In your template, use: {{ req.req.Question }} {{ req.req.JobDetailLink }} {{ req.req.JobDescription }} Or better still write a projection to unnest those attributes then you can use your current template the way it is. projection = { 'Question': '$req.Question', 'JobDetailLink': '$req.JobDetailLink', 'JobDescription': '$req.JobDescription', } cursor = db.find({}, projection)
type: AcceptedAnswer

http://stackoverflow.com/q/47419211
has title: import data from pydev to postgresqll
tagged with: python
type: UnansweredQuestion
tagged with: eclipse
has answer: http://stackoverflow.com/a/47420030
tagged with: sql
downvote count: 0
score: 1
has body: I am trying to move data from pydev on eclipse to postgresql using pgadmin4. Why is my code printing "Error %s % e"? In postgres, the testtest123 table is getting created but the data is not being uploaded there. Many thanks! #!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import sys import csv from itertools import count path = r'C:\Users\sammy\Downloads\E0.csv' with open(path, "r") as csvfile: readCSV = csv.reader(csvfile, delimiter=",") for row in readCSV: new_data = [ row[19]] print (new_data) con = None try: con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'") cur = con.cursor() cur.execute("CREATE TABLE testtest123 (HY INTEGER PRIMARY KEY)") cur.execute("INSERT INTO testtest123(new_data)") cur.execute("SELECT * FROM testtest123;") con.commit() except psycopg2.DatabaseError as e: if con: con.rollback() print ("Error %s % e") sys.exit(1) finally: if con: con.close() print(" ".join(row)) out=open("new_data.csv", "w") output = csv.writer(out) for row in new_data: output.writerow(row) out.close()
upvote count: 1
answer count: 1
favorite count: 0
tagged with: postgresql
tagged with: pydev
type: Question

http://stackoverflow.com/q/47424319
score: 0
possible better answer: http://stackoverflow.com/a/47424477
tagged with: tkinter-canvas
has body: I am trying to get a live matplotlib graph working in Tkinter while using a class structure. I am using the code from this stackoverflow question which successfully runs a matplotlib graph in Tkinter(does not use class structure). Every time I try to run the code I altered I am given a TypeError: __init__ takes exactly 2 arguments (1 given) I know this TypeError type question has been asked before. I tried to use this but the answer provided did not solve my problem. The line of code that seems to be the problem is: ani = animation.FuncAnimation(Window().fig, Window().animate(), interval=1000, blit=Fals I have tried altering how I call fig and animate but nothing seems to work. import Tkinter as Tk from matplotlib import pyplot as plt import matplotlib.animation as animation from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg xar = [] yar = [] class Window: def __init__(self,master): frame = Tk.Frame(master) fig = plt.figure(figsize=(14, 4.5), dpi=100) self.ax = fig.add_subplot(1,1,1) self.ax.set_ylim(0, 100) self.line, = self.ax.plot(xar, yar) self.canvas = FigureCanvasTkAgg(fig,master=master) self.canvas.show() self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1) frame.pack() def animate(self,i): yar.append(99-i) xar.append(i) self.line.set_data(xar, yar) self.ax.set_xlim(0, i+1) root = Tk.Tk() ani = animation.FuncAnimation(Window().fig, Window().animate(),interval=1000, blit=False) app = Window(root) root.mainloop()
has title: Trying to run live matplotlib graph in Tkinter while using classes. Cannot resolve TypeError
has comment: http://stackoverflow.com/comment/81803667
has answer: http://stackoverflow.com/a/47424477
linked to: http://stackoverflow.com/q/42192133
type: Question
has comment: http://stackoverflow.com/comment/81803797
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/30086384
accepted answer: http://stackoverflow.com/a/47424614
type: AnsweredQuestion
tagged with: python-2.7
tagged with: tkinter
answer count: 2
has comment: http://stackoverflow.com/comment/81803865
has answer: http://stackoverflow.com/a/47424614

http://stackoverflow.com/comment/81862272
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47452422
type: AnswerComment
has text: So you're telling me that Scipy is perfectly fine converging to an incorrect root and then claiming it is correct? Great.

mime-message
type: Tag
tags question: http://stackoverflow.com/q/47477724
tag name: mime-message

http://stackoverflow.com/q/47425221
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/81805509
has comment: http://stackoverflow.com/comment/81805685
has title: Python Seemingly Unavoidable IndexError and UnboundLocalError
favorite count: 0
has comment: http://stackoverflow.com/comment/81806095
tagged with: index-error
tagged with: python
has body: I am automating a process of importing data into a CSV from my website. The traceback can be seen below. I am getting a NameError stating that mobile and office are not defined within the if/elif conditions. EDIT: Assume a blank Book1.csv from selenium import webdriver import time import csv from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("undisclosable") driver.find_element_by_xpath("//input[@name='rad_region' and @value='far']").click() time.sleep(2) driver.find_element_by_xpath("//input[@name='rad_georegion' and @value='east']").click() time.sleep(2) driver.find_element_by_xpath("//input[@name='rad_manage' and @value='No']").click() time.sleep(2) driver.find_element_by_xpath('//*[@id="ModalPopupDiv"]/div/div[3]/div[1]/a').click() class Search(): with open(r'Book1.csv', 'r+', encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile) next(csvreader) while True: for row in csvreader: WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "searchKeyword"))) WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "go"))) driver.find_element_by_id('searchKeyword').clear() time.sleep(1) driver.find_element_by_id('searchKeyword').send_keys(row) time.sleep(1) driver.find_element_by_id('go').click() time.sleep(1) writer = csv.writer(csvfile) tobesplit = str(driver.find_element_by_class_name('snippetContact').text) emailandphone = tobesplit.split(" | ") try: email = emailandphone[0] office = emailandphone[1] mobile = emailandphone[2] writer.writerow([None, email, office, mobile]) except UnboundLocalError: if mobile not in emailandphone: writer.writerow([None, email, office]) elif office not in emailandphone: writer.writerow([None, email]) Here is the stacktrace: Traceback (most recent call last): File "C:/Users/s995648.CS/PycharmProjects/untitled/auto", line 39, in Search office = e…
type: Question
has comment: http://stackoverflow.com/comment/81805851
linked to: http://stackoverflow.com/q/25666853
upvote count: 0
has comment: http://stackoverflow.com/comment/81805491
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81806339
score: -2
has answer: http://stackoverflow.com/a/47441357

http://stackoverflow.com/comment/81833116
has text: When you get to a resolution, please remember to up-vote useful things and accept your favourite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47425676
type: QuestionComment

http://stackoverflow.com/comment/81916889
type: Comment
has text: thanks, trying df.columns=['new','new1','new3'] df['new']=performanceData.groupby(['Year','Month'],as_index=False)['total_pnl_pos'].sum() df['new1']=performanceData.groupby(['Year','Month'],as_index=False)['total_pnl_pos'].mean() df['new3']=performanceData.groupby(['Year','Month'],as_index=False)['total_pnl_pos'].std() but get error AttributeError: 'list' object has no attribute 'name'
type: AnswerComment
comment on: http://stackoverflow.com/a/47480733
score: 0

http://stackoverflow.com/q/47398937
has comment: http://stackoverflow.com/comment/81752587
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/81752544
tagged with: pandas-styles
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81752301
has comment: http://stackoverflow.com/comment/81752365
tagged with: pandas
has body: Here's a styler object with a background gradient: I'm just looking for anyway to save it as is. Have tried using .render() but not sure what to do with that HTML code, and from reading other questions on the subject it seems there is no current way to save these. Is there a hackish way to do it? Here is the array: array([[ 0.264 , 0.271 , 0.285 , 0.289 , 0.329 ], [ 0.053 , 0.051 , 0.045 , 0.038 , 0.031 ], [ 0.006 , 0.007 , 0.009 , 0.01 , 0.01 ], [-3.98650106, -3.95728537, -3.99767582, -4.20624136, -3.54186842], [-3.22600677, -2.87623307, -2.03420988, -1.54443176, -1.41006671]]) and the line of code I have: df.style.background_gradient(cmap='RdYlGn',low=.09,high=.18,axis=1)
answer count: 1
has answer: http://stackoverflow.com/a/47399733
accepted answer: http://stackoverflow.com/a/47399733
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81752321
has title: Saving pandas styler object in anyway
has comment: http://stackoverflow.com/comment/81752382
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/81946647
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47495790
has text: understanding lambda is not easy for a lot of people. Ok matter of taste.

http://stackoverflow.com/comment/82042304
comment on: http://stackoverflow.com/q/47538283
score: 0
type: Comment
type: QuestionComment
has text: Where do you find this code? I see from other questions that you are doing image work. Is this part of some module. The indexing looks like `numpy`, but the `.a` attribute or property doesn't look right - unless it is a `recarray`.

http://stackoverflow.com/comment/81726142
score: 0
type: Comment
type: QuestionComment
has text: you need to pass data from backend to frontend. See this discussion: https://forum.vuejs.org/t/passing-data-from-a-backend-framework-rails-to-a-vue-component/16324
comment on: http://stackoverflow.com/q/47386118

http://stackoverflow.com/a/47455626
answers question: http://stackoverflow.com/q/47455539
type: Answer
has body: You need to use filter() instead of map(), for filtering out values from iterable in your case it's list, something like this def check_for_value(input): if input==b: return True result=filter(check_for_value,a ) print result you can find more about filter here
score: 0

http://stackoverflow.com/comment/81799313
comment on: http://stackoverflow.com/a/47421495
score: 0
type: Comment
has text: I've just edited my main question so hopefully helps
type: AnswerComment

http://stackoverflow.com/a/47500403
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47499877
type: Answer
has body: You could leverage the newer regex module and some programming logic: import pandas as pd, regex as re # your df here rx = re.compile(r'(?:\G(?!\A)|^[^()]*\()([^();]+);?') def getter(col): # default empty dict empty = {'column1': '', 'column2': '', 'column3': ''} # generate results with a comprehension matches = {'column{}'.format(idx): val for idx, val in enumerate(rx.findall(col), 1)} return pd.Series(dict(empty, **matches)) df"column1", "column2", "column3" = df["device"].apply(getter) print(df"column1", "column2", "column3") This yields for your example column1 column2 \ 0 iPhone CPU iPhone OS 10_3_1 like Mac OS X 1 Macintosh Intel Mac OS X 10.6 2 Linux Android 6.0.1 column3 0 1 rv:48.0 2 SAMSUNG SM-G903F Build/MMB29K Explanation While surely not perfect, the idea is to match ; inside ( and ). Here, \G is needed which matches where the last match stopped: (?: # non-capturing group \G(?!\A) # match where the last match stopped, not the beginning | # or ^[^()]*\( # find the first ( ) ( # capture group 1 [^();]+ # anything not (, ) or ; at least once ) ;? # semicolon optionally Afterwards, the function getter returns a new pd.Series() which will be saved in df. The logic inside getter() overwrites an empty dict. See a demo on regex101.com.
downvote count: 0

http://stackoverflow.com/comment/82025401
type: AnswerComment
comment on: http://stackoverflow.com/a/47533709
score: 0
type: Comment
has text: Its work now under his flow: `data = json.loads(response.read().decode('utf-8', 'ignore')) output_json.write(str(data))` . But its still not in the useful formation. How can I extract or load the data from this response data? Thank you!

http://stackoverflow.com/comment/81772562
score: 0
type: Comment
type: QuestionComment
has text: FYI, I edited my answer with an answer to your bonus question.
comment on: http://stackoverflow.com/q/47407887

http://stackoverflow.com/comment/81822416
has text: def searchnew(request): if request.method == 'POST': name = request.POST.get('name') loc = request.POST.get('location') d = { 'name': name, 'loc' : loc, } return render(request,"searchnew.html",d) else: name = request.GET.get('name') na = { 'name': name, } return render(request,"searchnew.html",na)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47433253
type: Comment

http://stackoverflow.com/comment/81885319
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/47465305
type: Comment
has text: String is a class. Strings can have methods just like any other class.

http://stackoverflow.com/comment/82013165
comment on: http://stackoverflow.com/a/47527622
type: Comment
has text: under form_class I wrote: form_class = HomeForm And the : for post in posts: Do I need to write it in the post function or in the PostEdit class? And the template render I should write it in the modal in the serverlist.html?
score: 0
type: AnswerComment

http://stackoverflow.com/a/47451354
has body: There's no problem serving the django backend and the angular frontend from different domains, but you do have to set up CORS correctly for it to work. To configure that, you'll have to setup Django to return the CORS headers and allow the domain where your frontend lives. These might be helpful: https://github.com/ottoyiu/django-cors-headers http://www.django-rest-framework.org/topics/ajax-csrf-cors/
type: Answer
answers question: http://stackoverflow.com/q/47450990
score: 0

http://stackoverflow.com/comment/81935298
has text: ah!! Got it!! That is what it means! They really should have put an example there so beginners like me can understand...
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47490027
type: AnswerComment

http://stackoverflow.com/comment/82022456
comment on: http://stackoverflow.com/a/47531970
has text: @MaxU yes i tried 'A' and i got PeriodIndex(['3962', '3963', '3964', '3965'], dtype='period[A-DEC]', freq='A-DEC') which gives year 3962 instead of 1992. Perhaps its my pandas version, i'm using pandas 0.18.1
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47504346
score: 1
type: Answer
has body: Hello I found a GitHub Repo without any Error Here I posting the URL of that repo https://github.com/badcoder28/djangular2
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47450990

http://stackoverflow.com/q/47413713
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81781618
has answer: http://stackoverflow.com/a/51228867
tagged with: python
has title: import error on python script
upvote count: 2
score: 1
answer count: 1
has body: I have a python script that has these import lines: import os import sys import SA_auth_keys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream from tweepy import API from tweepy import Cursor from tweepy.error import RateLimitError, TweepError from optparse import OptionParser import ast When trying to run the script I have this Error: Traceback (most recent call last): File "2_From_IDs_To_JSON.py", line 23, in &lt;module&gt; import SA_auth_keys ImportError: No module named SA_auth_keys How can I run the script?
has comment: http://stackoverflow.com/comment/81781394
downvote count: 1
tagged with: import
favorite count: 0

http://stackoverflow.com/q/47476434
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81909229
has title: how to show data per row instead of string
tagged with: python
has comment: http://stackoverflow.com/comment/81908022
score: 0
linked to: http://stackoverflow.com/q/42819228
answer count: 0
has body: I am new to coding and need help with my first big task, linking data from csv to postgresql using python. The code seems to function but when I look at it using postgresql, for each row it appends the previous row. Focusing on the table teams, considering I have 20 teams I want to have 20 rows with each team on a different row and with a different ID. At this stage, considering I have 110 games, after 10 games the data just repeats itself in different rows. What's the solution? Thanks! #!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import sys import csv from itertools import count, cycle from _tkinter import create from setuptools.dist import sequence from email.policy import default path = r'C:\Users\sammy\Downloads\E0.csv' with open(path, "r") as csvfile: readCSV = csv.reader(csvfile, delimiter=",") firstline = 1 con = None con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'") cur = con.cursor() cur.execute("DROP TABLE games") cur.execute("DROP TABLE teams") cur.execute("DROP TABLE referees") cur.execute("CREATE TABLE teams (HomeTeamID SERIAL PRIMARY KEY, AllTeams123 VARCHAR)") cur.execute("CREATE TABLE referees (RefereeID SERIAL PRIMARY KEY, RefereeName VARCHAR)") cur.execute("CREATE TABLE games (GAMEID SERIAL PRIMARY KEY, HomeTeamID INTEGER, FOREIGN KEY (HomeTeamID) REFERENCES teams(HomeTeamID), HomeTeam VARCHAR, AwayTeamID VARCHAR, AwayTeam VARCHAR, FTHG INTEGER, ATHG INTEGER, FTR VARCHAR, RefereeID INTEGER, FOREIGN KEY (RefereeID) REFERENCES referees(RefereeID), RefereeName VARCHAR, HY INTEGER, AY INTEGER)") hometeams = [] awayteams = [] uniqueteams = [] uniquereferees = [] allreferees = [] allteams = hometeams + awayteams gameuniqueteams = sorted(uniqueteams) gameuniquereferees = sorted(uniquereferees) try: for row in readCSV: if firstline: firstline=0 continue game1 = row[2] game2 = row[3] HomeTeam = row[2] AwayTeamID = row[3] AwayTeam = row[3] FTHG = row[4] ATHG = row[5] FTR = row[6] RefereeID = row[10] Refe…
has comment: http://stackoverflow.com/comment/81908619
tagged with: sql
has comment: http://stackoverflow.com/comment/81908213
type: Question
tagged with: postgresql
tagged with: pydev

mixed-models
tag name: mixed-models
tags question: http://stackoverflow.com/q/47502398
type: Tag

http://stackoverflow.com/q/47389130
score: 0
has answer: http://stackoverflow.com/a/47389304
accepted answer: http://stackoverflow.com/a/47389304
type: Question
has body: I am working on Selenium with Python. I am writing a code which will fetch the data from an excel file and punch the same data on the WebPortal. But I am getting the error: TypeError: object of type 'Cell' has no len() Below is the code: for X in range(1,rowCount): for Y in range(0,colCount): cellData = worksheet.cell(X,Y) driver.find_element_by_id("XYZ").send_keys(cellData)
has title: Python - TypeError: object of type 'Cell' has no len()
answer count: 1
tagged with: selenium
tagged with: python
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/a/47420405
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47420375
type: Answer
has body: It's because it's actually a list. You can get that element out with this: played=int(played[0])
answers question: http://stackoverflow.com/q/47420375
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47513790
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47503566
score: 0
has body: After more playing, and finally looking at the CPython source (https://github.com/python/cpython/blob/master/Objects/methodobject.c) it became obvious that using PyMethod_New(PyObject *func, PyObject *self) and setting this return was not correct. The PyCFunction call accepts two arguments, the latter being the instance to use for self. So in my example, changed to the following we have success: pCompObj = PyObject_GetAttrString(pModule, "CompObj"); pCompObjInst = PyObject_CallFunction(pCompObj, NULL); cfunc = PyCFunction_New(&amp;override_method, pCompObjInst); PyObject_SetAttrString(pCompObjInst, "my_function", cfunc); Py_DECREF(cfunc); So this seems to be what I'm intending to do, however, anyone much more versed in the Python C API can follow up with a "more correct" answer.
type: Answer
accepted answer of: http://stackoverflow.com/q/47503566

http://stackoverflow.com/comment/81895024
type: Comment
type: QuestionComment
score: 0
has text: can you tell what is line ?
comment on: http://stackoverflow.com/q/47470180

http://stackoverflow.com/comment/81756953
score: 0
has text: Basically, it looks like they actually have the same structure but, for instance, 'x' is replaced by 'arange-367e8f921d6d8...'.
comment on: http://stackoverflow.com/a/47401613
type: Comment
type: AnswerComment

export-to-csv
tags question: http://stackoverflow.com/q/47437109
tags question: http://stackoverflow.com/q/47441025
tags question: http://stackoverflow.com/q/47531292
tag name: export-to-csv
tags question: http://stackoverflow.com/q/47441224
type: Tag

http://stackoverflow.com/q/47531936
has title: How to decode non-b-prefixed string like '\xd0\xbc' stored in variable in python3?
upvote count: 2
accepted answer: http://stackoverflow.com/a/47532497
tagged with: python-3.5
possible better answer: http://stackoverflow.com/a/47532487
has answer: http://stackoverflow.com/a/47532497
tagged with: python
has answer: http://stackoverflow.com/a/47532487
type: AnsweredQuestion
score: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have some variable from API. For example: a == '\xd0\xbc' I need to get variable b by decoding a: b == 'М' But I can't write in code something like this: a = b'\xd0\xbc' b = a.decode() because this text (\xd0\xbc) is already in the variable.
answer count: 2

http://stackoverflow.com/q/47415876
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81789010
duplicate of: http://stackoverflow.com/q/2828059
tagged with: arrays
tagged with: sorting
type: Question
has comment: http://stackoverflow.com/comment/81785668
type: UnansweredQuestion
has body: I've got the following array of arrays: array([[ 0.04497471, -3. ], [ 0.0449076 , -2. ], [ 0.0448405 , -1. ], [ 0.04463641, 1. ], [ 0.0445693 , 2. ], [ 0.04450219, 3. ]]) (this example is already sorted) I want to sort it so the first column is ordered in descending order, while maintaining the figure in the second column with its partner. I've tried using np.sort(a, axis=0), but it treats the columns separately. How do I get it to maintain the rows?
tagged with: python
linked to: http://stackoverflow.com/q/2828059
has title: How do I sorting a 2D numpy array?
tagged with: numpy

http://stackoverflow.com/a/47523569
type: Answer
score: 0
has body: Here is another solution: def createGrid(filename): myFile = open(str(filename),"r") myGrid = [] for line in myFile: myGrid.append(list(line.strip())) return myGrid print createGrid("input.txt") output: [['h', 'e', 'l', 'l', 'o'], ['g', 'o', 'o', 'd', 'b', 'y', 'e']]
answers question: http://stackoverflow.com/q/47523319

http://stackoverflow.com/comment/81834945
type: Comment
type: AnswerComment
score: 0
has text: Thank you. Actually, this function worked fine with gnuplot fitting, and I am supposed to use it, though it becomes infinitly small for x -> a If I am not mistaken, the "NaN" seems to be a number below 1e-13. Is there a way to overcome this limitation ?
comment on: http://stackoverflow.com/a/47439327

http://stackoverflow.com/comment/82001563
has text: @zindarod Sure, I have added a sample image.
score: 0
comment on: http://stackoverflow.com/q/47522403
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47489625
has comment: http://stackoverflow.com/comment/81936495
has comment: http://stackoverflow.com/comment/81934964
has comment: http://stackoverflow.com/comment/81935870
has body: You could try using array slicing: plt.plot(f.f[0,][1:], label='Canal 1', color='r', linewidth=0.75, linestyle="-") plt.plot(f.f[1,][:-1], label='Canal 3', color='b', linewidth=0.75, linestyle="-") Edit: Because of the nature of the data, slicing off more than just the first/last data points is appropriate, as @Dascienz suggests in the comments. Something like this, where the first and last 50 data points are sliced off from both series: plt.plot(f.f[0,][50:-50], label='Canal 1', color='r', linewidth=0.75, linestyle="-") plt.plot(f.f[1,][50:-50], label='Canal 3', color='b', linewidth=0.75, linestyle="-")
downvote count: 0
has comment: http://stackoverflow.com/comment/81935996
has comment: http://stackoverflow.com/comment/81934715
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81952225
has comment: http://stackoverflow.com/comment/81935066
has comment: http://stackoverflow.com/comment/81934447
has comment: http://stackoverflow.com/comment/81934832
has comment: http://stackoverflow.com/comment/81935008
accepted answer of: http://stackoverflow.com/q/47489580
has comment: http://stackoverflow.com/comment/81973306
has comment: http://stackoverflow.com/comment/81958462
has comment: http://stackoverflow.com/comment/81935034
has comment: http://stackoverflow.com/comment/81936246
answers question: http://stackoverflow.com/q/47489580
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81934485

http://stackoverflow.com/comment/81982162
score: 2
comment on: http://stackoverflow.com/q/47513188
type: QuestionComment
has text: Can you post the traceback? I got the impression that the error is happening somewhere else
type: Comment

scroll
type: Tag
tags question: http://stackoverflow.com/q/47532769
tag name: scroll

http://stackoverflow.com/comment/81910773
has text: The line `questionList = ([NBAquestions(), MLBquestions(), NHLquestions(), NFLquestions()]` calls each function. You can use strings instead of calling functions like `questionList = (["NBAquestions", "MLBquestions", "NHLquestions", "NFLquestions"]`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47477868

http://stackoverflow.com/q/47398510
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/47398629
accepted answer: http://stackoverflow.com/a/47398629
has title: Ordering a dataframe using value_counts
type: Question
has body: I have a dataframe in which under the column "component_id", I have component_ids repeating several times. Here is what the df looks like: In [82]: df.head() Out[82]: index molregno chembl_id assay_id tid tid component_id 0 0 942606 CHEMBL1518722 688422 103668 103668 4891 1 0 942606 CHEMBL1518722 688422 103668 103668 4891 2 0 942606 CHEMBL1518722 688721 78 78 286 3 0 942606 CHEMBL1518722 688721 78 78 286 4 0 942606 CHEMBL1518722 688779 103657 103657 5140 component_synonym 0 LMN1 1 LMNA 2 LGR3 3 TSHR 4 MAPT As can be seen, the same component_id can be linked to various component_synonyms(essentially the same gene, but different names). I wanted to find out the frequency of each gene as I want to find out the top 20 most frequently hit genes and therefore, I performed a value_counts on the column "component_id". I get something like this. In [84]: df.component_id.value_counts() Out[84]: 5432 804 3947 402 5147 312 3 304 2693 294 75 282 Name: component_id, dtype: int64 Is there a way for me to order the entire dataframe according to the component_id that is present the most number of times? And also, is it possible for my dataframe to contain only the first occurrence of each component_id? Any advice would be greatly appreciated!

http://stackoverflow.com/q/47503534
has body: I'm trying to draw the animation of several 3DScatter with matplotlib. I succeeded to draw all the points but I'm struggling with the colors. Even if I'm calling the function set_color(..) nothing is changed. Here is what I'm currently doing, to_plot is an array of size total with (5120, 3) float elements and colors is an array of size total with (5120,) elements (equal to 'r' or 'b'): import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D import matplotlib.patches as mpatches total = 10 num_whatever = 100 # old = 5120 to_plot = [np.random.rand(num_whatever, 3) for i in range(total)] colors = [['r' if i%2==0 else 'b' for i in range(num_whatever)] for i in range(total)] red_patch = mpatches.Patch(color='red', label='Men') blue_patch = mpatches.Patch(color='blue', label='Women') fig = plt.figure() ax3d = Axes3D(fig) scat3D = ax3d.scatter([],[],[], s=10) ttl = ax3d.text2D(0.05, 0.95, "", transform=ax3d.transAxes) def update_plot(i): print i, to_plot[i].shape ttl.set_text('PCA on 3 components at step = {}'.format(i*20)) scat3D._offsets3d = np.transpose(to_plot[i]) scat3D.set_color(colors[i]) return scat3D, def init(): scat3D.set_offsets([[],[],[]]) ax3d.set_xlim(-1.,2.) ax3d.set_ylim(-0.5,0.7) ax3d.set_zlim(-1.,0.75) plt.style.use('ggplot') plt.legend(handles=[red_patch, blue_patch]) ani = animation.FuncAnimation(fig, update_plot, init_func=init, blit=False, interval=100, frames=xrange(total)) # ani.save(os.path.join(config.workdir, 'gif', 'bins','anim.gif'), writer="imagemagick") plt.plot()
tagged with: python
has comment: http://stackoverflow.com/comment/81963352
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/81963214
has comment: http://stackoverflow.com/comment/81963008
tagged with: matplotlib
downvote count: 0
favorite count: 0
has title: How to dynamically change point colors in scatter3d animation with matplotlib?
type: Question
has answer: http://stackoverflow.com/a/57683648
has comment: http://stackoverflow.com/comment/81963289
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47542896

http://stackoverflow.com/comment/82473347
type: Comment
score: 0
type: AnswerComment
has text: I went with the second solution as the real file contained some more fields last one not being date. That value was sometimes empty as well making it difficult using the first solution.
comment on: http://stackoverflow.com/a/47535378

http://stackoverflow.com/comment/82026506
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47534128
has text: Yes it contains a single line of text. There are 30,000 or so keys. But I think I do not have to read in chunks, and get away with reading at once.
type: Comment

http://stackoverflow.com/q/47457407
accepted answer: http://stackoverflow.com/a/47457850
tagged with: matlab
has body: Generally we interpolate key colors to make a colormap. Can we do the reverse, getting the key colors (approximately) from a colormap? I convert the colormap to a gray scale, divide the gray vector into piecewise line segments, retain the key points and return the colors at the key index. But it doesn't work well for vivid colormaps.
type: AnsweredQuestion
tagged with: matplotlib
downvote count: 2
answer count: 1
tagged with: matlab-figure
has comment: http://stackoverflow.com/comment/81869316
score: -1
favorite count: 0
type: Question
tagged with: colormap
has answer: http://stackoverflow.com/a/47457850
upvote count: 1
tagged with: python
has title: How to recover key colors from a colormap?

http://stackoverflow.com/a/47408282
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47408001
score: 4
has comment: http://stackoverflow.com/comment/81770388
has comment: http://stackoverflow.com/comment/81770189
type: Answer
upvote count: 4
has body: For complex annotations, you will need to specify annotation name as well, so in my mind it will look like this: Publisher.objects.filter(Book__price=150).\ annotate(particular_date = F('Book__date')).all()
answers question: http://stackoverflow.com/q/47408001
has comment: http://stackoverflow.com/comment/81777569

http://stackoverflow.com/comment/81749796
type: Comment
has text: Pandas is being updated current version is 0.21 which version is specified in the book? Maybe developers realized that sorted assignemnt might be an easy and proper way of assigning data and leads to less ambuguity.
type: AnswerComment
comment on: http://stackoverflow.com/a/47391909
score: 0

http://stackoverflow.com/comment/81853208
type: QuestionComment
has text: did u install django as sudo?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47449099

http://stackoverflow.com/q/47460168
answer count: 2
has title: Pandas data frame removing rows with 'nan' by column name
tagged with: pandas
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/46610007
has answer: http://stackoverflow.com/a/47460275
has body: After reading excel via pandas read_excel end up with rows with that has type string 'nan'. I tried to drop them using all the available method discussed here but seems like it doesn't work: Here are the attempts: df.dropna(subset=['A'], inplace=True) I thought this would work, it reduced the number of rows from the data frame without removing rows that has 'nan' df = df[df.A.str.match('nan') == False]
tagged with: python
has answer: http://stackoverflow.com/a/47460459
has comment: http://stackoverflow.com/comment/81875267
score: 0

http://stackoverflow.com/comment/81746179
has text: Thank you I will try like that
comment on: http://stackoverflow.com/a/47395674
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47404652
tagged with: python
has body: I want my django app to communicate by using a TCP/IP socket with a remote computer and I would like that socket to be available at all times. I would like to use the library tornado. Since I'm only familiar with writing views and models and such, I'm not entirely sure where to fit that into my codebase. I was thinking about writing a management command that would run the tornado's server (see http://tornado.readthedocs.io/en/latest/tcpserver.html), but how could I call .stop() on my server once the management command quits? I wouldn't want it to spawn any threads that wouldn't exit upon my management command exiting, or end up with multiple open sockets, because I just want one. Ofcourse I would also like the listener to reside somewhere in my django program and have access to it, not only within the management command code. I was thinking about importing a class from django's settings. Am I thinking in the right direction, or is there a different, better approach? EDIT: As to why would I want to do this: I've got a microcontroller I want to communicate with, and I wouldn't want to go implementing/parsing HTTP on it, and I would also like to periodically send some indication of the connection being alive, and HTTP doesn't seem like the way to go
tagged with: tornado
has answer: http://stackoverflow.com/a/47411136
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81770337
score: 1
tagged with: tcp
linked to: http://stackoverflow.com/q/2180415
answer count: 1
has comment: http://stackoverflow.com/comment/81799294
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81800687
has title: Django TCP server with tornado
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81881769
tagged with: sockets
linked to: http://stackoverflow.com/q/43348971
tagged with: django

http://stackoverflow.com/q/47452952
tagged with: mysql
type: Question
possible better answer: http://stackoverflow.com/a/47453021
downvote count: 5
score: -2
has answer: http://stackoverflow.com/a/47453004
tagged with: python
has answer: http://stackoverflow.com/a/47454179
favorite count: 0
has title: how to convert multiple strings into list using python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/47453021
answer count: 3
accepted answer: http://stackoverflow.com/a/47453004
has comment: http://stackoverflow.com/comment/81861925
has body: I want to convert the strings into list using python. here is the values of a column View of the db table here is my string: THERPET BASTHI BERIGAI ASTC-HUDCO KRISHNA-NAGAR TANK-STREET I tried to print as list results = cursor.fetchall() print list(results) But the output is [(u'THERPET BASTHI BERIGAI ASTC-HUDCO',), (u'KRISHNA-NAGAR TANK-STREET',)] Expected output is: THERPET BASTHI BERIGAI ASTC_HUDCO KRISHNA-NAGAR TANK-STREET

web-scraping
tags question: http://stackoverflow.com/q/47482206
tags question: http://stackoverflow.com/q/47414551
tags question: http://stackoverflow.com/q/47475790
tags question: http://stackoverflow.com/q/47480680
tags question: http://stackoverflow.com/q/47441374
tags question: http://stackoverflow.com/q/47446703
tags question: http://stackoverflow.com/q/47481281
tags question: http://stackoverflow.com/q/47496680
tags question: http://stackoverflow.com/q/47442953
tags question: http://stackoverflow.com/q/47509065
tags question: http://stackoverflow.com/q/47502307
tags question: http://stackoverflow.com/q/47461571
tags question: http://stackoverflow.com/q/47447178
tags question: http://stackoverflow.com/q/47516722
tag name: web-scraping
tags question: http://stackoverflow.com/q/47429673
tags question: http://stackoverflow.com/q/47417326
tags question: http://stackoverflow.com/q/47386675
tags question: http://stackoverflow.com/q/47399985
tags question: http://stackoverflow.com/q/47471876
tags question: http://stackoverflow.com/q/47457836
tags question: http://stackoverflow.com/q/47424751
tags question: http://stackoverflow.com/q/47397809
tags question: http://stackoverflow.com/q/47476608
tags question: http://stackoverflow.com/q/47482291
tags question: http://stackoverflow.com/q/47461142
type: Tag
tags question: http://stackoverflow.com/q/47446494
tags question: http://stackoverflow.com/q/47391092
tags question: http://stackoverflow.com/q/47463351
tags question: http://stackoverflow.com/q/47490964
tags question: http://stackoverflow.com/q/47502931
tags question: http://stackoverflow.com/q/47427271
tags question: http://stackoverflow.com/q/47385010
tags question: http://stackoverflow.com/q/47399486
tags question: http://stackoverflow.com/q/47468160
tags question: http://stackoverflow.com/q/47468975
tags question: http://stackoverflow.com/q/47433060
tags question: http://stackoverflow.com/q/47455874
tags question: http://stackoverflow.com/q/47426435
tags question: http://stackoverflow.com/q/47475024
tags question: http://stackoverflow.com/q/47447024
tags question: http://stackoverflow.com/q/47522957
tags question: http://stackoverflow.com/q/47461617
tags question: http://stackoverflow.com/q/47421419
tags question: http://stackoverflow.com/q/47532500
tags question: http://stackoverflow.com/q/47487029
tags question: http://stackoverflow.com/q/47384740
tags question: http://stackoverflow.com/q/47394281
tags question: http://stackoverflow.com/q/47532769
tags question: http://stackoverflow.com/q/47407044
tags question: http://stackoverflow.com/q/47383106
tags question: http://stackoverflow.com/q/47404561
tags question: http://stackoverflow.com/q/47533805
tags question: http://stackoverflow.com/q/47434292
tags question: http://stackoverflow.com/q/47458816
tags question: http://stackoverflow.com/q/47489195
tags question: http://stackoverflow.com/q/47417332
tags question: http://stackoverflow.com/q/47438699
tags question: http://stackoverflow.com/q/47520524
tags question: http://stackoverflow.com/q/47461823
tags question: http://stackoverflow.com/q/47499847
tags question: http://stackoverflow.com/q/47500449
tags question: http://stackoverflow.com/q/47433490
tags question: http://stackoverflow.com/q/47458841
tags question: http://stackoverflow.com/q/47426051
tags question: http://stackoverflow.com/q/47418322
tags question: http://stackoverflow.com/q/47495643
tags question: http://stackoverflow.com/q/47531812
tags question: http://stackoverflow.com/q/47490779
tags question: http://stackoverflow.com/q/47387035
tags question: http://stackoverflow.com/q/47453010

http://stackoverflow.com/comment/81837610
comment on: http://stackoverflow.com/a/47441272
has text: You've changed the meaning of the statement with those parens. As written by the OP, the `as mock_yaml` belongs only to the second `mock.patch()`.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81991207
has text: shutil.copy worked! thank you
comment on: http://stackoverflow.com/q/47512856
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81883448
comment on: http://stackoverflow.com/q/47464317
score: 0
has text: @ElisByberi I don't see why you wouldn't just read it but I'll upload the code in one moment
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81843677
has text: Your last function needs to be indented, presumably...
score: 0
comment on: http://stackoverflow.com/q/47444179
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81733644
comment on: http://stackoverflow.com/q/47389033
score: 0
type: Comment
has text: @KenSyme And one more thing you told me to use `.status_code` and check the response, but when I print them they are all `200`. This is because I am redirected to another page. Do you have any other method similar to this. This is way faster than before.
type: QuestionComment

http://stackoverflow.com/q/47428758
type: Question
answer count: 2
has title: Performing joins in Pandas
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47429223
downvote count: 0
tagged with: database
tagged with: python
has answer: http://stackoverflow.com/a/47429675
score: 3
tagged with: pandas
tagged with: sql
upvote count: 3
has body: I am familiar with performing joind in pandas pd.merge(A,B,on='key',how='inner') But how do I write a query in pandas for these 3 given joins as they require a IF NULL
favorite count: 0

http://stackoverflow.com/a/47460962
score: 1
has body: Given the simple input format as described in the question, the implementation can be simplified (and corrected): Initialize oneNum with zeros For each line in the file Find the index of "1" Translate the index to list position: since the possible indexes are 0, 2, 4, 6, 8, we can simply divide by 2 to translate to 0, 1, 2, 3, 4 Increment the value at the correct index in oneNum Like this: with open("test file.txt") as file: oneNum = [0] * 5 for line in file: index = line.find("1") // 2 oneNum[index] += 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47460850
type: Answer
accepted answer of: http://stackoverflow.com/q/47460850
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47487308
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47498279
has title: Python Kivy Unable to get a Window, abort
has body: This is my first post here. I am a beginner at programming with Python so please be specefic with your awnsers :) So when I try to run a simple script to create a window it gives the error 'Unable to get a Window, abort' I looked at other posts and tried to apply the sulutions given there but nothing seems to work. I am running it on windows 10 through Pycharm. this is the code im trying to run: from kivy.app import App class app(App): pass if __name__ == '__main__': App().run()
score: 0
has comment: http://stackoverflow.com/comment/81930426
has comment: http://stackoverflow.com/comment/81929817
linked to: http://stackoverflow.com/q/40697876
answer count: 1
has comment: http://stackoverflow.com/comment/81948974
type: Question

http://stackoverflow.com/comment/81951673
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47498206
has text: @sam-pyt It won't? I think it does!

http://stackoverflow.com/comment/82010662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47526363
score: 0
has text: Wow thanks guys. I'll just edit my question again to make it clearer.

http://stackoverflow.com/q/47528876
has comment: http://stackoverflow.com/comment/82014604
answer count: 2
has answer: http://stackoverflow.com/a/47528976
has body: vowel = "aeiou" for i in range(0:len(s)): if s[i] in vowel == True count += 1 print("Number of vowels: "+str(count)) The above code doesn't throw any errors in Spyder. I am taking an online course, s is a predefined variable which contains a string. Here I defined s as "big black car" I have to count the vowels in the string. When I press enter after typing the code in, I am moved to the next line, nothing happens, I am prompted for more input. What am I doing wrong?
possible better answer: http://stackoverflow.com/a/47529214
has comment: http://stackoverflow.com/comment/82014346
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47529214
has comment: http://stackoverflow.com/comment/82014565
favorite count: 0
has comment: http://stackoverflow.com/comment/82014098
type: AnsweredQuestion
has title: Vowel counter script not executing
has comment: http://stackoverflow.com/comment/82014428
score: 1
has comment: http://stackoverflow.com/comment/82014230
tagged with: python
has comment: http://stackoverflow.com/comment/82014495
accepted answer: http://stackoverflow.com/a/47528976
type: Question

http://stackoverflow.com/comment/82037398
comment on: http://stackoverflow.com/q/47539919
has text: `final.sort_values(['test','count'], ascending=[True,False])`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/81725659
comment on: http://stackoverflow.com/q/47386309
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Maybe I'm too often changing the concept., but I'm a bit pissed off this project heh :) But I think this way will be good because I was not able to get all the combinations between the sub-lists.
score: 0

http://stackoverflow.com/comment/81755419
comment on: http://stackoverflow.com/a/47400582
score: 0
type: Comment
has text: Nice alternative!
type: AnswerComment

http://stackoverflow.com/comment/81904110
comment on: http://stackoverflow.com/a/47473730
type: Comment
has text: It does indeed. When I replace the case by case test with your any(statement) the code breaks for very large ints: it returns `float('inf')` instead. I have no clue why, but I've been in front of my screen for far too long to look into it for now.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82021233
comment on: http://stackoverflow.com/q/47525204
type: Comment
has text: Do you want filter columns in `read_csv` ?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81750177
score: 0
comment on: http://stackoverflow.com/q/47398318
type: QuestionComment
has text: You can set Maya to echo every command (also those performed by mouse actions) to the console. If you know how to do this with a mouse, let it echo those actions to the console.
type: Comment

http://stackoverflow.com/q/47494941
tagged with: python
tagged with: qslider
possible better answer: http://stackoverflow.com/a/47495047
favorite count: 0
type: Question
has body: I am making a gui with multiple QSlider in a scrollarea, for some of my sliders i need an interval of 10 and not 1. When i open the gui the ticks are correct and have a jump of 10, but when i return the current value i can still get values that are between the ticks, for example: slider = QtGui.QSlider(QtCore.Qt.Horizontal) slider.setMaximum(90) slider.setMinimum(10) slider.setTickInterval(10) slider.setTickPosition(QtGui.QSlider.TicksBelow) slider.valueChanged.connect(self.slider_value_change) The function is just: def slider_value_change(self,value): print(value) This code will return 10,11,12,13... instead of 10,20... Is there a way to keep the value so it will only return the tick values? Also is there a way to add a lable to the tick with its value?
has answer: http://stackoverflow.com/a/47495047
answer count: 2
linked to: http://stackoverflow.com/q/27661877
downvote count: 0
has answer: http://stackoverflow.com/a/47500102
tagged with: user-interface
tagged with: pyqt4
accepted answer: http://stackoverflow.com/a/47500102
type: AnsweredQuestion
has title: Python PyQt4 QSlider Interval bigger than 1
linked to: http://stackoverflow.com/q/11132597
upvote count: 1
score: 1

http://stackoverflow.com/comment/81933085
type: QuestionComment
score: 0
has text: I find the question title amusing.
type: Comment
comment on: http://stackoverflow.com/q/47488859

timer
tag name: timer
tags question: http://stackoverflow.com/q/47494410
type: Tag

http://stackoverflow.com/comment/81978768
type: Comment
has text: It is good to minimize the use of globals, but having a couple of _mutable_ globals that you only mutate and _never_ assign to isn't so bad. With those, you don't need a `global` statement in the functions that mutate the global variable's contents, that's only needed if you want to perform an assignment to a global name.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47511463

http://stackoverflow.com/q/47515268
has comment: http://stackoverflow.com/comment/81989312
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47515403
has answer: http://stackoverflow.com/a/47515429
has comment: http://stackoverflow.com/comment/81986443
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81986382
has body: I'm new to programming and I'm having a hard time understanding how to ask the user if they want to run it again? def pigLatin(word): """ Function that converts word into Pig Latin form """ # Checking for starting letter as vowel if word[0] in ['a','e','i','o','u']: return word + "way" # Checking for vowel index for i in range(1, len(word)): # Checking for vowels(including y) if word[i] in ['a','e','i','o','u','y']: # Updating vowel index vowelIndex = i; break; # Forming pig lating word return word[vowelIndex:] + word[0:vowelIndex] + "ay"; def removePunctuation(text): """ Removes punctuation from text """ # List of punctuation characters punctuations = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"] # Iterating over punctuations for ch in punctuations: # Replacing punctuations text = text.replace(ch, "") # Returning text return text def main(): """ Main function """ # Reading line of text text = input("\n Enter a line of text: ") # Removing punctuation text = removePunctuation(text) # Converting to lower case text = text.lower() print("\n\n Pig Latin form: \n"); # Iterating over words for word in text.split(" "): # Converting word to Pig Latin form word = pigLatin(word) # Printing word print(word, end = " "); print("\n"); # Calling main function main() How exactly would I add a loop that asks the user to continue or not? I'm new to programming and im very confused. I also don't understand how to add the English form of the sentence before the pig latin form?? can someone please help!
downvote count: 1
has title: loop in python and converting strings
has comment: http://stackoverflow.com/comment/81987207
has comment: http://stackoverflow.com/comment/81986430
has comment: http://stackoverflow.com/comment/81987198
has comment: http://stackoverflow.com/comment/81986403
has comment: http://stackoverflow.com/comment/81987184
tagged with: python
score: -1

http://stackoverflow.com/comment/82100758
type: Comment
has text: That doesn't make them more portable, as the rules are so vague that you can't even be sure your bitfields will appear in the order you declare them in. When you care about representation, bitfields aren't your friend. They're merely a convenience for *local objects only*.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47566864

http://stackoverflow.com/a/47540299
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47539880
type: Answer
answers question: http://stackoverflow.com/q/47539880
score: 0
has body: As mentioned above, you can use itertools.product() And since you don't know number of lists you can pass list of lists as an argument: import itertools lists = [ ['a','b','c'], ['1','2'] ] ["".join(x) for x in itertools.product(*lists)] Result: ['a1', 'a2', 'b1', 'b2', 'c1', 'c2']

http://stackoverflow.com/comment/81728563
has text: I'll be happy if you can share such example, instead of -1, since I've been looking for that answer for almost a day @BryanOakley
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47387713

http://stackoverflow.com/q/47487616
answer count: 2
linked to: http://stackoverflow.com/q/606191
accepted answer: http://stackoverflow.com/a/47487651
tagged with: encryption
has answer: http://stackoverflow.com/a/47487651
has title: Encryption not working properly
has body: i have this piece of code for encryption. from cryptography.fernet import Fernet key = Fernet.generate_key() f = Fernet(key) token = f.encrypt(b"something cool") k = f.decrypt(token) print(k) ` This is the output b'something cool' According to the example on the website, that "b" should've gone. I'm very new at this and would like to know or understand how exactly the solution works. Thanks
has answer: http://stackoverflow.com/a/47487779
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81930184
has comment: http://stackoverflow.com/comment/81930130
tagged with: python
has comment: http://stackoverflow.com/comment/81930289
tagged with: cryptography
has comment: http://stackoverflow.com/comment/81930169
possible better answer: http://stackoverflow.com/a/47487779
type: Question

http://stackoverflow.com/q/47457069
has title: Why does beautiful soup not properly parse element named "area"?
answer count: 1
downvote count: 0
has body: I'm writing a python script that uses beautiful soup to parse xml documents. Some of the documents contain elements named "area". For some reason I cannot for the life of me properly parse these elements. They always come out as empty elements. Here is a minimal example of what is happening: #!/usr/bin/python3.5 from bs4 import BeautifulSoup xml = """"" <?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?> foo bar """"" soup = BeautifulSoup (xml, "lxml") print ("\n#### soup ####\n") print (soup) print ("\n#### areax ####\n") areaxs = soup.find_all ("areax") for areax in areaxs: print (areax) print ("\n### area ###\n") areas = soup.find_all ("area") for area in areas: print (area) Output: #### soup #### "" <?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?> foo bar #### areax #### foo ### area ### Is the element name "area" protected in any way or is there something else wrong with how I'm parsing it?
favorite count: 0
tagged with: parsing
accepted answer: http://stackoverflow.com/a/47457213
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/47457213
upvote count: 2
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/81778596
type: Comment
type: QuestionComment
has text: "Trying to import Json, my command is pip install json" => importing and installing are not the same thing.
comment on: http://stackoverflow.com/q/47412518
score: 1

http://stackoverflow.com/comment/81865683
has text: @J.Walker Please see the new improved version. ;)
comment on: http://stackoverflow.com/a/47454733
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47390928
has comment: http://stackoverflow.com/comment/81737449
accepted answer: http://stackoverflow.com/a/47395626
score: 10
tagged with: python
has answer: http://stackoverflow.com/a/47395626
has answer: http://stackoverflow.com/a/65201840
has answer: http://stackoverflow.com/a/51370245
has answer: http://stackoverflow.com/a/75169632
upvote count: 10
answer count: 4
has title: Extract DOCX Comments
tagged with: http://stackoverflow.com/tag/xml
tagged with: openxml
tagged with: http://stackoverflow.com/tag/docx
has body: I'm a teacher. I want a list of all the students who commented on the essay I assigned, and what they said. The Drive API stuff was too challenging for me, but I figured I could download them as a zip and parse the XML. The comments are tagged in w:comment tags, with w:t for the comment text and . It should be easy, but XML (etree) is killing me. via the tutorial (and official Python docs): z = zipfile.ZipFile('test.docx') x = z.read('word/comments.xml') tree = etree.XML(x) Then I do this: children = tree.getiterator() for c in children: print(c.attrib) Resulting in this: {} {'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}author': 'Joe Shmoe', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}id': '1', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}date': '2017-11-17T16:58:27Z'} {'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidR': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidDel': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidP': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidRDefault': '00000000', '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rsidRPr': '00000000'} {} {'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': '0'} {'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': '0'} {'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': '0'} And after this I am totally stuck. I've tried element.get() and element.findall() with no luck. Even when I copy/paste the value ('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val'), I get None in return. Can anyone help?
possible better answer: http://stackoverflow.com/a/65201840
downvote count: 0
has comment: http://stackoverflow.com/comment/81739880
favorite count: 0
tagged with: google-docs
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/47535665
type: Answer
has body: Let's call df your dataframe and say you want to remove items on column fruit df = df[~df["fruit"].isin(irrelevantList)]
score: 0
answers question: http://stackoverflow.com/q/47535547

http://stackoverflow.com/comment/81960350
score: 0
comment on: http://stackoverflow.com/a/47496537
type: Comment
type: AnswerComment
has text: @MacUsers Yeah, that's correct. I have edited the code sample

http://stackoverflow.com/q/47501177
has answer: http://stackoverflow.com/a/47501745
upvote count: 7
possible better answer: http://stackoverflow.com/a/47501357
score: 7
favorite count: 0
has answer: http://stackoverflow.com/a/47501357
has answer: http://stackoverflow.com/a/77704265
type: Question
tagged with: dataframe
tagged with: python
has body: In Python, I have a pandas dataframe. I want to filter for one value of column A. I am looking for the row, where column A is the highest value that is smaller than '5' (so if column A does have values '1', '2', '4', '7', it should be '4'). Another condition exists, too. The following statement does not work. How do I have to change it with regards to the maximum condition, so that it is working? df_new = df[(df['some_other_column'] &lt; XYZ) &amp; max(df['A'] &lt;= '5')]
tagged with: pandas
type: AnsweredQuestion
has title: Python Pandas Dataframe: Take Greatest Value Smaller Than
accepted answer: http://stackoverflow.com/a/47501745
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/81953952
comment on: http://stackoverflow.com/a/47493914
type: AnswerComment
has text: Not bad. :) I often use `dct.setdefault(key, []).append(value)` myself, but we don't really need a `dict` here because the keys are guaranteed to be in order, so we can just use a list. And by a slight change in the logic we can reduce the number of `if` tests to 1. Please see the end of my answer for a variation of your code.
score: 0
type: Comment

http://stackoverflow.com/a/47442616
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47442471
type: Answer
has body: Try this: while True: a=input("please enter a word") &lt;your code here&gt; if a!='': break Enter your code that does conversions in with the variable a.
upvote count: 1

http://stackoverflow.com/comment/81825650
type: AnswerComment
has text: I don't fully understand all the functionality, however it works flawlessly. Much appreciated!
comment on: http://stackoverflow.com/a/47431780
type: Comment
score: 0

http://stackoverflow.com/comment/81922135
type: QuestionComment
comment on: http://stackoverflow.com/q/47402765
has text: Yes, this is true, I got python 2.7.10 in R when using the library(rPython) T_T
score: 0
type: Comment

http://stackoverflow.com/q/47518786
has body: Here's my code: Board=['0','0','0','0','0','0','0','0','0'] def printBoard(): print Board[0:3] print Board[3:6] print Board[6:9] printBoard() def playerMove(): counter=0 for i in range(9): move=int(raw_input('What spot would you like to move? 0-8')) counter+=1 if(counter%2==1): Board[move]='x' else: Board[move]='o' playerMove() I am new to python, so please don't change my code to make it better or more efficient, just tell me what I need to do to change the value resulting from the input to an integer. Thanks!
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81995846
has title: Why do I get this error: ValueError: invalid literal for int() with base 10: 'def playerMove():'
has comment: http://stackoverflow.com/comment/81993972
favorite count: 0
has comment: http://stackoverflow.com/comment/81994135
type: Question
has comment: http://stackoverflow.com/comment/81994547
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81995562
score: 2
upvote count: 2
tagged with: python-2.7

http://stackoverflow.com/q/47459054
score: 13
possible better answer: http://stackoverflow.com/a/76469861
favorite count: 0
type: Question
has title: Is there a way to delete all cells at once in jupyter?
has answer: http://stackoverflow.com/a/76469861
has body: I everyday try out my solutions before answering a pandas question in stack overflow . Usually after two to three days the jupyter notebook I use will be with n number of cells. Is there a way to delete all cells at once other than creating new notebook by deleting current one? D D deletes one cell at a time.
upvote count: 13
tagged with: python
tagged with: jupyter
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68312763
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47459164
accepted answer: http://stackoverflow.com/a/47459164

http://stackoverflow.com/comment/82011753
has text: Yes, batch_size is one of the hyperparameters. Try different combinations and see what gets you the best results.
comment on: http://stackoverflow.com/a/47526001
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47417083
has comment: http://stackoverflow.com/comment/103809983
has body: You simply don't. (Late edit: except when you are creating custom training loops, only for advanced uses) Keras does backpropagation automatically. There's absolutely nothing you need to do for that except for training the model with one of the fit methods. You just need to take care of a few things: The vars you want to be updated with backpropagation (that means: the weights), must be defined in the custom layer with the self.add_weight() method inside the build method. See writing your own keras layers. All calculations you're doing must use basic operators such as +, -, *, / or backend functions. By backend, tensorflow/theano/CNTK functions are also supported. The functions you use must be differentiable (that means backpropagation will fail for functions that use constant results, for instance) This is all you need to have the automatic backpropagation working properly. If your layers don't have trainable weights, you don't need custom layers, create Lambda layers instead (only calculations, no trainable weights).
has comment: http://stackoverflow.com/comment/103007915
score: 31
has comment: http://stackoverflow.com/comment/94692185
has comment: http://stackoverflow.com/comment/81788386
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/81788456
has comment: http://stackoverflow.com/comment/94651087
accepted answer of: http://stackoverflow.com/q/47416861
type: Answer
upvote count: 32
answers question: http://stackoverflow.com/q/47416861

http://stackoverflow.com/q/47481294
linked to: http://stackoverflow.com/q/34692370
has comment: http://stackoverflow.com/comment/81917670
type: AnsweredQuestion
score: 0
tagged with: azure
tagged with: python
has comment: http://stackoverflow.com/comment/81917479
type: Question
has answer: http://stackoverflow.com/a/47501563
answer count: 2
accepted answer: http://stackoverflow.com/a/47501563
tagged with: azure-web-app-service
has comment: http://stackoverflow.com/comment/81917664
has title: How to upgrade pip in Microsoft Azure from 1.5.6 to 9.0.1?
has answer: http://stackoverflow.com/a/47487243
possible better answer: http://stackoverflow.com/a/47487243
tagged with: pip
has body: I am deploying a flask web app to Azure, and need to upgrade pip on Azure to the latest version. I have tried running D:\python34\python.exe -m pip install --upgrade pip in the Kudu console of Azure, but this didn't work, and gave me an error below. Access is denied: 'd:\\python34\\lib\\site-packages\\pip-1.5.6.dist-info\\description.rst' I really appreciate your help.

http://stackoverflow.com/comment/81918082
has text: Each time you find a letter, you need to only iterate through the *remainder* of the string for the rest of the letters
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47481607
type: QuestionComment

http://stackoverflow.com/comment/82008254
comment on: http://stackoverflow.com/q/47524816
type: QuestionComment
type: Comment
score: 0
has text: This works for me without problem with a different proxy. With your proxy I only get a connection reset, probably because the proxy restricts access. But in essence this means that the problem does not occur with a different proxy and cannot be reproduced with your specific proxy - which makes it hard to solve it.

http://stackoverflow.com/a/55925154
downvote count: 0
answers question: http://stackoverflow.com/q/47475783
score: 13
has body: In the question and in Novel's answer, first, the button is bound to the enter function using bt.config(text="ENTER",command=enter). After that, the function is bound to the enter/return key, but in fact, the button and the enter/return key are still quite independent. In the case of this question, I assume that this is not really a problem, but if you often want to change the button's command, it may be boring to also have to change the binding to the enter/return key every time. So you may think: is there a way to give the enter key automatically the same command as the button? Yes, there is! The Tkinter Button has the invoke() method, which calls the button's command and returns the command's return value: import tkinter as TK def func(): print('the function is called!') root = TK.Tk() button= TK.Button(root, text='call the function', command=func) # not func()! button.pack() button.invoke() # output: 'the function is called!' root.mainloop() We can simply bind this method to the enter key: root.bind('&lt;Return&gt;', button.invoke) # again without '()'! But wait, this gives the same problem as before: the button.invoke() method doesn't accept the event argument from the binding, but we can't (easily) change that method. The solution for that is using a lambda: root.bind('&lt;Return&gt;', lambda event=None: button.invoke()) # This time *with* '()'!!! To be complete, I will give an example below: import tkinter as TK root = TK.Tk() button= TK.Button(root) button.pack() def func1(): print('func1 is called!') button.config(text='call func2', command=func2) def func2(): print('func2 is called!') button.config(text='call func1', command=func1) root.bind('&lt;Return&gt;', lambda event=None: button.invoke()) root.mainloop() Explanation: When you press enter or click the button the first time, 'func1 is called!' will be printed. When you press enter or click the button the second time, 'func2 is called!' will be printed. The enter key should do the same as the button, al…
has comment: http://stackoverflow.com/comment/136255266
type: Answer
upvote count: 13

http://stackoverflow.com/comment/81936424
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47489554
score: 0
has text: Seems to be the rigth keyword. But if I type categoryorder='array'. How should the categoryarray look like? Is it list(range(len(num_consultants))) or num_consultants. Till now there is now effect.

http://stackoverflow.com/q/47415499
has comment: http://stackoverflow.com/comment/81787516
type: UnansweredQuestion
has body: My code functions and indentations are correct on eclipse. When running, it displays "Error %s % e" but when I go to postgresql the data doesn't upload there in anyway whatsoever. What should I do? #!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import sys con = None try: con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'") cur = con.cursor() cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price INT)") cur.execute("INSERT INTO Products VALUES(1,'Milk',5)") cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)") cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)") cur.execute("INSERT INTO Products VALUES(4,'Bread',5)") cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)") con.commit() except psycopg2.DatabaseError as e: if con: con.rollback() print ("Error %s % e") sys.exit(1) finally: if con: con.close()
has comment: http://stackoverflow.com/comment/81786195
tagged with: python
has comment: http://stackoverflow.com/comment/81786421
tagged with: postgresql
score: 0
answer count: 0
has title: pydev data not uploading on postgres
has comment: http://stackoverflow.com/comment/81785990
tagged with: eclipse
type: Question
tagged with: pydev

http://stackoverflow.com/q/47536655
accepted answer: http://stackoverflow.com/a/47537692
has comment: http://stackoverflow.com/comment/82030189
tagged with: overlapping-matches
has comment: http://stackoverflow.com/comment/82030423
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47537692
type: AnsweredQuestion
score: 0
has title: How to get this regex include overlapping occurrences, but not too much:-?
linked to: http://stackoverflow.com/q/3512471
answer count: 1
has comment: http://stackoverflow.com/comment/82030325
has comment: http://stackoverflow.com/comment/82030567
linked to: http://stackoverflow.com/q/1749437
type: Question
has body: I want to get all the occurrences of the pattern '[number]' including their context but I can't. Here is my code: import re text = 'some crap [00][0] some more' regex = r'\[[0-9]*\]' regex = '.{0,10}' + regex + '.{0,10}' occurrences = re.findall(regex, text) for occ in occurrences print(occ) What is actually wrong!? My code works just as I wish in any case except for when there are two [number] blocks with less than 10 characters in between. where my code gives me one result while I'm looking for two. If I set the regex to include the overlapping occurrences then it will give all the results for different context lengths. I can't set the context length specifically because I want to include the occurrences at the beginning and end of the string. What I actually want: I prefer a pure regex solution to get me all the occurrences of the mentioned pattern including their context. If really impossible I'd do fine with a solution that uses the positions and selects a range from the string.

http://stackoverflow.com/comment/81806101
type: QuestionComment
comment on: http://stackoverflow.com/q/47425528
has text: @spectras Can you clarify why example in question does not work? Ignore the earlier comment as SO kept incorrectly editing links for whatever reason
score: 0
type: Comment

http://stackoverflow.com/comment/82030264
type: Comment
comment on: http://stackoverflow.com/q/47536463
score: 0
has text: Thanks @wholevinski, I do have a special character in the password. Do you know any work around for this?
type: QuestionComment

http://stackoverflow.com/a/47442740
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47442632
has body: You can use templating: In "file.html": &lt;body&gt; {%for value in values%} &lt;p&gt;{{value}}&lt;/p&gt; {%endfor%} &lt;/body&gt; In app.py: (or file with routes) @app.route("/servedata") def send_data(): return flask.render_templating("file.html", values=["value1", "value2", "value3"])
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/81864946
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47454950
type: AnswerComment
has text: @ImportanceOfBeingErnest funny?

pdf-parsing
type: Tag
tags question: http://stackoverflow.com/q/47492363
tags question: http://stackoverflow.com/q/47533875
tag name: pdf-parsing

rss
type: Tag
tags question: http://stackoverflow.com/q/47540148
tag name: rss

http://stackoverflow.com/q/47443499
has answer: http://stackoverflow.com/a/47443559
has comment: http://stackoverflow.com/comment/81842036
answer count: 5
upvote count: 0
has answer: http://stackoverflow.com/a/47443581
has body: Let's say we have this data extract: ID,from,to,type,duration 1,paris,berlin,member,12 2,berlin,paris,member,12 3,paris,madrid,non-member,10 I want to retrieve the line when from = paris, and type = member. Which means in this example I have only: 1,paris,berlin,member,12 That satisfy these rules. I am trying to do this with Regex only. I am still learning and I could only get this: ^.*(paris).*(member).*$ However, this will give me also the second line where paris is a destination. The idea I guess is to: Divide the line by commas. Check if the second item is equal to 'paris' Check if the fourth item is equal to 'member', or even check if there is 'member' in that line as there is no confusion with this part. Any solution where I can use only regex?
tagged with: python
downvote count: 1
possible better answer: http://stackoverflow.com/a/47443578
type: AnsweredQuestion
has title: Regex: Capture a line when certain columns are equal to certain values
has answer: http://stackoverflow.com/a/47443578
has comment: http://stackoverflow.com/comment/81842116
has answer: http://stackoverflow.com/a/47443589
score: -1
tagged with: regex
has answer: http://stackoverflow.com/a/47443609
accepted answer: http://stackoverflow.com/a/47443559
has comment: http://stackoverflow.com/comment/81842090
favorite count: 0
type: Question

http://stackoverflow.com/q/47383044
has body: I have golf data from the PGA Tour that I am trying to clean. Originally, I had white space in front of some of the hole scores. This is what a unique count looked like: df["Hole Score"].value_counts() Out[76]: 4 566072 5 272074 3 218873 6 48596 4 38306 5 19728 2 17339 3 15093 7 7750 4232 6 3011 8 1313 2 1080 7 389 9 369 10 66 8 61 11 38 1 27 9 20 Name: Hole Score, dtype: int64 I was able to run a whitespace remover function that got rid of leading white space. However, my count values function returns the same frequency counts: df["Hole Score_2"].value_counts() Out[74]: 4 566072 5 272074 3 218873 6 48596 4 38306 5 19728 2 17339 3 15093 7 7750 4232 6 3011 8 1313 2 1080 7 389 9 369 10 66 8 61 11 38 1 27 9 20 Name: Hole Score_2, dtype: int64 For reference, this is the helper function that I used: def remove_whitespace(x): try: x = "".join(x.split()) except: pass return x df["Hole Score_2"] = df["Hole Score"].apply(remove_whitespace) My question: How do I get the unique counts to list one Hole Score per count? What could be causing the double counting?
has comment: http://stackoverflow.com/comment/81718901
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Double unique counts in python
score: 0
has comment: http://stackoverflow.com/comment/81718882
has comment: http://stackoverflow.com/comment/81718872
tagged with: pandas
has comment: http://stackoverflow.com/comment/81718904
tagged with: whitespace
type: Question

http://stackoverflow.com/comment/82017088
score: 0
comment on: http://stackoverflow.com/a/47529066
type: Comment
type: AnswerComment
has text: Using an OLS model gives different results for a,b,c,d as 0.0595,0.5877,0.3937 and the constant 0.5599

http://stackoverflow.com/a/47436109
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47435537
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47435537
type: Answer
has body: The issue here as you've properly identified is you're inadvertently averaging the daily Click to Landing values, whereas Excel is computing an average by summing up the values of Clicks and Landing Page visits per day and dividing. You can do the same thing in pandas by creating your pivot_table and summing the values per day (notice I've passed aggfunc='sum' to pivot_table). You can then apply division to find the average: df Date Reach Impressions Clicks Landing_Page Platform 0 30/05/2017 27447 27939 90 68 Facebook 1 30/05/2017 24299 24318 80 44 Facebook 2 30/05/2017 9897 10081 33 25 Facebook 3 30/05/2017 11696 11721 33 21 Facebook 4 30/05/2017 53 55 1 0 Facebook 5 31/05/2017 46632 68757 213 143 Facebook 6 31/05/2017 67478 73401 650 424 Facebook 7 31/05/2017 38831 47577 136 77 Facebook 8 31/05/2017 46834 52449 135 77 Facebook 9 31/05/2017 273 531 12 10 Facebook 10 1/06/2017 48307 72141 221 150 Facebook 11 1/06/2017 64122 79501 202 106 Facebook 12 1/06/2017 66810 71033 843 575 Facebook 13 1/06/2017 46225 50003 138 76 Facebook 14 1/06/2017 496 1043 16 15 Facebook t = df.pivot_table(index="Date", columns="Platform", values=['Clicks', 'Landing_Page'], aggfunc='sum') Clicks Landing_Page Platform Facebook Facebook Date 1/06/2017 1420 922 30/05/2017 237 158 31/05/2017 1146 731 t[('Landing_Page', 'Facebook')].div(t[('Clicks', 'Facebook')]).apply(lambda x: '{:.2%}'.format(x)) Date 1/06/2017 64.90% 30/05/2017 66.70% 31/05/2017 63.80% dtype: object

http://stackoverflow.com/q/47465218
has comment: http://stackoverflow.com/comment/81975174
type: Question
has title: Mute Pytest library output for imported library
tagged with: testing
answer count: 1
has answer: http://stackoverflow.com/a/47468571
accepted answer: http://stackoverflow.com/a/47468571
tagged with: python
has comment: http://stackoverflow.com/comment/81970485
has comment: http://stackoverflow.com/comment/81970404
has body: I'm testing a function which uses Python Wand. When I test it with an invalid input it throws a BlobError which is a custom error from the Wand library. However, it seems that there's another TypeError happening within Wand at some point when I do so, which results in a big ugly Exception ignored in... error message under the Pytest results stdout. I'm checking if Pytest raises the BlobError and that's fine, but I can't also check if it raises the TypeError, or just mute that message. So here's the Pytest test output: ================================ test session starts ================================= platform linux -- Python 3.5.2, pytest-3.2.5, py-1.5.2, pluggy-0.4.0 rootdir: /path/to/my/project/tests, inifile: collected 1 item test_split.py . ============================== 1 passed in 0.14 seconds ============================== Exception ignored in: &lt;bound method Resource.__del__ of &lt;wand.image.Image: (empty)&gt;&gt; Traceback (most recent call last): File "/my/comp/.local/share/virtualenvs/project-BRze6wfl/lib/python3.5/site-packages/wand/resource.py", line 232, in __del__ self.destroy() File "/my/comp/.local/share/virtualenvs/project-BRze6wfl/lib/python3.5/site-packages/wand/image.py", line 2767, in destroy for i in range(0, len(self.sequence)): TypeError: object of type 'NoneType' has no len() And my test is simply: with pytest.raises(wand.exceptions.BlobError): wand_split.split(PDF,TEMP, 260) So the test is working the way I want, but how do I deal with the extra Wand TypeError?
type: AnsweredQuestion
tagged with: typeerror
score: 0
tagged with: wand
tagged with: pytest

http://stackoverflow.com/a/47448056
has body: Use np.flatnonzero in conjunction with broadcasted comparison: a array([[[1, 0], [0, 2], [3, 3]], [[1, 0], [1, 3], [1, 0]], [[4, 0], [2, 3], [3, 0]]]) np.flatnonzero((a == [[1, 0], [1, 3], [1, 0]]).all(1).all(1)) array([1]) Borrowing from the other answer, you could pass multiple axes to all: np.flatnonzero((a == [[1, 0], [1, 3], [1, 0]]).all((1, 2))) array([1])
score: 2
answers question: http://stackoverflow.com/q/47447955
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47447955

http://stackoverflow.com/comment/81986806
score: 2
type: Comment
has text: Brilliant it worked! Thank you very much. Would you just be able to elaborate on index and iid just a little I'm still unsure what they exactly are. I set them to 0,1 which worked fine but that was a lucky guess.
type: AnswerComment
comment on: http://stackoverflow.com/a/47515211

http://stackoverflow.com/a/47537163
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82035126
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82034735
answers question: http://stackoverflow.com/q/47536858
has body: You can try this :- //div[@class="textA"]/ancestor::tr//*[@class="checkbox"]
has comment: http://stackoverflow.com/comment/82050573

http://stackoverflow.com/q/47506934
tagged with: pandas
has comment: http://stackoverflow.com/comment/81970082
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81970154
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47507435
has answer: http://stackoverflow.com/a/47507466
accepted answer: http://stackoverflow.com/a/47507321
has comment: http://stackoverflow.com/comment/81970771
downvote count: 1
has title: How to extract and count in certain condition in python
has answer: http://stackoverflow.com/a/47507435
has answer: http://stackoverflow.com/a/47507321
has comment: http://stackoverflow.com/comment/81969920
type: AnsweredQuestion
score: 0
has body: Assume I have two policy data like below. enroll lapse A 2010/2/1 2013/1/2 B 2012/3/1 2013/1/4 I would like to count the number who policies are ongoing at the beginning of the year. enroll lapse year A 2010/2/1 2013/1/2 2011/1/1 A 2010/2/1 2013/1/2 2012/1/1 A 2010/2/1 2013/1/2 2013/1/1 B 2012/3/1 2013/1/4 2013/1/1 and count these ongoing policies. year num 2011 1 2012 1 2013 2 I guess I must use query method. but I couldnt figure out.
answer count: 3

http://stackoverflow.com/a/47681397
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84078479
has body: I am not sure if using a customop here would be the best as it may be slow. Because SoftmaxOuput computes the gradient in the backward pass, it is not convenient to multiply losses as you want to do. However, it is not too complicated to do with the symbolic API. I have attached a toy example, hope it helps. import mxnet as mx import numpy as np import logging # learn floor function from random numbers in [-1, -1 + num_classes] n = 10000 batch_size = 128 num_classes = 10 x = (np.random.random((n,)) * num_classes) - 1 y = np.floor(x) print(x[:2]) print(y[:2]) # define graph data = mx.symbol.Variable('data') label = mx.symbol.Variable('label') class_weights = mx.symbol.Variable('class_weights') fc = mx.sym.FullyConnected(data=data, num_hidden=num_classes) fc = mx.sym.Activation(data=fc, act_type='relu') proba = mx.sym.FullyConnected(data=fc, num_hidden=num_classes) proba = mx.sym.softmax(proba) # multipy cross entropy loss by weight cross_entropy = -mx.sym.pick(proba, label) * mx.sym.pick(class_weights, label) # mask the loss to zero when label is -1 mask = mx.sym.broadcast_not_equal(label, mx.sym.ones_like(label) * -1) cross_entropy = cross_entropy * mask # fit module class_weights = np.array([np.arange(1, 1 + num_classes)]*n) data_iter = mx.io.NDArrayIter(data={'data': x, 'class_weights': class_weights}, label={'label': y}, batch_size=batch_size) mod = mx.mod.Module( mx.sym.Group([mx.sym.MakeLoss(cross_entropy, name='ce_loss'), mx.sym.BlockGrad(proba)]), data_names=[v.name for v in data_iter.provide_data], label_names=[v.name for v in data_iter.provide_label] ) logger = logging.getLogger() logger.setLevel(logging.DEBUG) mod.bind(data_shapes=data_iter.provide_data, label_shapes=data_iter.provide_label) mod.init_params() mod.fit( data_iter, num_epoch=200, optimizer=mx.optimizer.Adam(learning_rate=0.01, rescale_grad=1.0/batch_size), batch_end_callback=mx.callback.Speedometer(batch_size, 200), eval_metric=mx.metric.Loss(name="loss", output_names=["ce_loss_output"])) # s…
has comment: http://stackoverflow.com/comment/99287593
has comment: http://stackoverflow.com/comment/82404814
has comment: http://stackoverflow.com/comment/84078477
score: 3
has comment: http://stackoverflow.com/comment/82382151
type: Answer
answers question: http://stackoverflow.com/q/47427500
accepted answer of: http://stackoverflow.com/q/47427500
upvote count: 3
has comment: http://stackoverflow.com/comment/84060326

http://stackoverflow.com/a/49281276
has body: I solved the problem by clearing the keras session before each load from keras import backend as K for i in range(...): K.clear_session() model = load_model(...)
has comment: http://stackoverflow.com/comment/103101882
has comment: http://stackoverflow.com/comment/86556623
downvote count: 1
has comment: http://stackoverflow.com/comment/98018985
answers question: http://stackoverflow.com/q/47455397
upvote count: 15
type: Answer
has comment: http://stackoverflow.com/comment/98008592
has comment: http://stackoverflow.com/comment/97351474
score: 14
has comment: http://stackoverflow.com/comment/98073435

http://stackoverflow.com/comment/82002537
type: Comment
comment on: http://stackoverflow.com/a/47483966
has text: @S.Am The `sunflower` is not that `colorful`. So the range is not that accurate for other `colorful` image. I make a hsv colormap to find the range easily and accurately. Maybe it helps.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47384600
downvote count: 0
has comment: http://stackoverflow.com/comment/81722284
accepted answer: http://stackoverflow.com/a/47663067
answer count: 1
has comment: http://stackoverflow.com/comment/82237619
upvote count: 15
tagged with: gevent
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82237363
has title: Access flask.g inside greenlet
has answer: http://stackoverflow.com/a/47663067
has comment: http://stackoverflow.com/comment/81722432
tagged with: python
has body: I'm using Flask + gevent and want to access the flask.g application global inside the target function of a greenlet. I'm using the copy_current_request_context decorator and have a situation pretty similar to example given in the docs: import gevent from flask import copy_current_request_context, g @app.route('/') def index(): g.user_data = 'foobar' g.more_user_data = 'baz' @copy_current_request_context def do_some_work(): some_func(g.user_data, g.more_user_data) ... gevent.spawn(do_some_work) return 'Regular response' However, I get the following error: AttributeError: '_AppCtxGlobals' object has no attribute 'user_data' I think a new application context is pushed when the request context is copied? I set a trace in the Flask code here and that seems to be the case. So the error isn't all that surprising because the flask.g object is application context scoped as of 0.10 (see http://flask.pocoo.org/docs/0.12/api/#flask.Flask.app_ctx_globals_class). Obviously, I can just pass the user data into the target function as arguments: import gevent from flask import g @app.route('/') def index(): g.user_data = 'foobar' g.more_user_data = 'baz' def do_some_work(user_data, more_user_data): some_func(user_data, more_user_data) ... gevent.spawn(do_some_work, g.user_data, g.more_user_data) return 'Regular response' And this works just fine, but I was hoping to use flask.g if possible.
tagged with: flask
score: 15
type: AnsweredQuestion
tagged with: greenlets
has comment: http://stackoverflow.com/comment/82211025

http://stackoverflow.com/comment/81997563
comment on: http://stackoverflow.com/q/47406741
score: 3
has text: Do you have automatic formatting turned on? VS Code itself won't reformat anything, so `editor.wordWrapColumn` won't affect that as that -- along with `editor.wordWrap` -- only affect how to display long lines, not rewrite them.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81779947
comment on: http://stackoverflow.com/a/47412196
has text: This Error happens when the `file_path` is incorrect
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47504282
has body: I'm trying to call a complicated python script in a flask app, but not entirely sure on how to do it right now. If it was simple I would just copy and paste the script with a router in flask, but that would get too messy. So far I have this for my main.py. I want to call a script temp.py. from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def base(): return render_template("base.html") @app.route('/temp', methods=['GET', 'POST']) def temp(): if __name__ == "__main__": app.run(debug=True)
has comment: http://stackoverflow.com/comment/81964472
answer count: 1
tagged with: python
score: -1
has title: How to call a python script in backend in flask
type: Question
duplicate of: http://stackoverflow.com/q/89228
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/82051056
has comment: http://stackoverflow.com/comment/81964491
has answer: http://stackoverflow.com/a/47504514
tagged with: flask
favorite count: 0

http://stackoverflow.com/q/47532769
tagged with: selenium
tagged with: scroll
has answer: http://stackoverflow.com/a/47532896
tagged with: web-scraping
has body: Not able to find command for scrolling using splinter. Wherever I have searched, can find only for selenium but not splinter.
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64671067
has answer: http://stackoverflow.com/a/77950073
tagged with: python
has title: How to scroll down and up using splinter in python.
answer count: 4
score: 0
tagged with: splinter
has answer: http://stackoverflow.com/a/55697158
upvote count: 3
downvote count: 3

http://stackoverflow.com/q/47422566
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47422684
has body: So I am trying to use python's wifi module to get neary wireless networks and log into them using a password. So far this is my code just to get the networks... from wifi import Cell, Scheme Cell.all('interfacename') And I am receiving the following error... Traceback (most recent call last): File "python", line 1, in &lt;module&gt; File "/goval_modules/python3.6/pbkdf2/__init__.py", line 69 print pbkdf2(p, s, l, i).encode('base64') ^ SyntaxError: invalid syntax Can someone please help me understand why this error is appearing and how to fix it?
score: 0
answer count: 1
tagged with: wifi
has title: Syntax Error in python Wifi Module
accepted answer: http://stackoverflow.com/a/47422684
type: Question
tagged with: cell
tagged with: syntax-error
has comment: http://stackoverflow.com/comment/81799641
tagged with: python
has comment: http://stackoverflow.com/comment/81799688

http://stackoverflow.com/q/47382916
tagged with: python
score: -1
tagged with: mysql
has answer: http://stackoverflow.com/a/47383047
type: Question
has title: Syntax error when inserting strings into MySQL using PyMySQL
has comment: http://stackoverflow.com/comment/81719628
upvote count: 0
type: UnansweredQuestion
answer count: 1
has body: I frequently use pymysql to insert data into a MySQL server. When inserting strings, I usually (but not every time) receive: pymysql.err.ProgrammingError: (1064, ...) when I insert a string using the code (where refers to a varchar): cursor.execute("Insert into table (column) values (%s)", (stringVar)) Typically I have to do something like: cursor.execute("Insert into table (column) values ('"+stringVar+"')")) However, sometimes that throws the same error and I have to do something like: stringVar="'"+stringVar stringVar=stringVar+"'" cursor.execute("Insert into table (column) values ("+stringVar+")") This just isn't a feasible way to program this operation. I assume I am messing up something simple but I cannot figure out what this is. I use pymysql a lot and this error is really starting to wear on me. Any help would be much appreciated!
tagged with: pymysql
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81718576

http://stackoverflow.com/comment/81912224
type: Comment
type: QuestionComment
has text: @DanielH I checked the identation, apart from the import statements it seems that it's OK.
score: 0
comment on: http://stackoverflow.com/q/47478628

http://stackoverflow.com/q/47481814
type: Question
has body: I have installed phoenix-4.7 and it works properly with hbase (i have copied the jars the to hbase folders). Now i would like to use phoenix with pyspark and according to the documentation (see below) i need to add 2 lines to spark-defaults.conf: spark.executor.extraClassPath spark.driver.extraClassPath What exactly i should insert to be able to use it from spark? I am using HDP2.6 and python 2.6 and spark 2.0 installation guide says the following: Spark setup To ensure that all requisite Phoenix / HBase platform dependencies are available on the classpath for the Spark executors and drivers, set both ‘spark.executor.extraClassPath’ and ‘spark.driver.extraClassPath’ in spark-defaults.conf to include the ‘phoenix--client.jar’ Note that for Phoenix versions 4.7 and 4.8 you must use the ‘phoenix--client-spark.jar’. As of Phoenix 4.10, the ‘phoenix--client.jar’ is compiled against Spark 2.x. If compability with Spark 1.x if needed, you must compile Phoenix with the spark16 maven profile. error message i get when trying to write dataframe to phoenix: java.lang.ClassNotFoundException: Failed to find data source: org.apache.phoenix.spark. Please find packages at spark.apache.org/third-party-projects.html
type: UnansweredQuestion
tagged with: pyspark
has title: What lines i should add to spark-defaults.conf to be able to use phoenix from pyspark?
tagged with: python
tagged with: apache-phoenix
has comment: http://stackoverflow.com/comment/81918453
score: 0
has answer: http://stackoverflow.com/a/48126538
answer count: 1
has comment: http://stackoverflow.com/comment/81918767
tagged with: hortonworks-data-platform

http://stackoverflow.com/comment/82377034
type: Comment
score: 0
has text: Arguably, the library is broken if it doesn't allow you to capture its results to a memory buffer. Incidentally, I came across this vaguely related question: https://stackoverflow.com/questions/47381835/scipy-minimize-get-cost-function-vs-iteration
type: QuestionComment
comment on: http://stackoverflow.com/q/47517323

http://stackoverflow.com/a/47413795
downvote count: 0
answers question: http://stackoverflow.com/q/47413100
has body: You need to narrow down the possible range of numbers based on the user's "higher"/"lower" responses. So you should store the lower and upper bounds as variables, and adjust them as you get responses. Something like this: lower = 0 upper = 100 while lower &lt; upper: guess = (lower+upper)//2 print("My guess is ", guess) # Find out if the correct answer is higher or lower than this guess if the correct answer is higher: lower = guess + 1 # This gives a new lower bound if the correct answer is lower: upper = guess - 1 # This gives a new upper bound
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/47523706
has comment: http://stackoverflow.com/comment/82016786
score: 0
has body: You can use a combination of *args and **kwargs: def function(*args, **kwargs): args1 = args if args else None args2 = [kwargs.get(i) for i in ['date', 'separator']]
answers question: http://stackoverflow.com/q/47523547
type: Answer

http://stackoverflow.com/q/47457546
downvote count: 0
score: 1
upvote count: 1
has body: Trying to run following case with Celery: Example: have set of different tests (each is a dict with args to use) have 5 different environments to run those tests. I can execute one test simultaneously (multiprocessing) on 5 evns. Now trying to make in on Celery. The problem is how tests were executed, they should not overlap in one env. So one env should run only one test at the same time, but Celery with workers and queues can execute them all it total mashup. I tried to use "Canvas primitives" and add "test + evns" in loop. Like: tests_set_list = [{test1}, {test2}, {test3}] envs_list = [{alpha}, {bravo}, {charlie}, {delta}, {echo}] variant 1: In this case all tasks were added into the queue end executes just one by one, without any order, so they overlapping. """This loop create tasks for each env""" for env_item in envs_list: for test_item in tests_set_list: r_key = 'tests_run.bunch_test_execute_task.{0}.{1}'.format(test_item['test_folder_name'], env_item['env_codename']) bunch_test_execute_task.apply_async(kwargs={'env_item': env_item, 'test_item': [test_item], 'tkn_branch': branch, }, queue='tests_run', routing_key=r_key) variant 2: --> TypeError: 'AsyncResult' object is not subscriptable In this case tasks only add first iteration and then stop. """ This loop create env inst for each task. Works in group Works bad, did not add task in worker queue. """ list_of_groups = [] for test_item in tests_set_list: tasks_group_by_env = [] for env_item in synced_envs: r_key = 'tests_run.bunch_test_execute_env_q_task.{0}.{1}'.format(test_item['test_folder_name'], env_item['env_codename']) task = bunch_test_execute_env_q_task(env_item, [test_item], branch) tasks_group_by_env.append(task) groups = group(tasks_group_by_env) list_of_groups.append(groups) for group_item in list_of_groups: # job = group(*group_item) job = group_item job.apply_async(queue='tests_run') variant 3: --> TypeError: unorderable types: float() >= str() but anyway tasks was added in queue, but execute wi…
has comment: http://stackoverflow.com/comment/81871847
tagged with: celery
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54423093
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/81893928
has title: Python Celery run set of functions on set on envs without overlapping
answer count: 1

http://stackoverflow.com/q/47496474
type: Question
has body: The general structure is Selenium and Jenkins integration. In Jenkins, I have a Windows slave node, and then build the project in the Jenkins master node, let Selenium in the slave node Windows Server running in the background. The results showed that after running the case, there are a lot of error, showing elements are not visible, after the screenshot, I found the window is 1024 * 663, not the expected 1920 * 1080, so do not drag the scroll bar, a lot of elements cannot click. How to modify the window to the maximum? My Chrome version: 62, Python version: 3.6, Selenium: 3. driver.maximize_window () options.add_argument("--start-maximized") Have tried, no luck.
tagged with: jenkins
has title: How to change screen resolution when Selenium WebDriver running as background process?
accepted answer: http://stackoverflow.com/a/47496613
tagged with: python
has answer: http://stackoverflow.com/a/47496613
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
downvote count: 0
tagged with: selenium
favorite count: 0

http://stackoverflow.com/q/47510820
score: 1
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/47510920
tagged with: python-3.x
type: Question
possible better answer: http://stackoverflow.com/a/47510892
tagged with: arrays
tagged with: python
has body: I am currently working on a python's String and List. When I assign string in variable str="string" and try to access it first character by str[0] it works perfectly and give "s". But, when I try to find character str[0][0][0][0][0][0] it again gives "s". But when I give str[0][1] it gives an error: IndexError: string index out of range Its Correct. My Question is Why Simple String Character has So many array Dimensions? and it did not given any error and print 0 character of string when str[0][0][0][0][0][0]. What is Data Structure of String? My Code is str="string" print((str[0][0][0][0][0][0][0][0])) # Working, but my Question is Why Working print((str[1][0][0][0][0])) # Working print((str[2][0][0][0][0])) # Working print((str[3][0][0][0][0])) # Working list=["0","p",0] print(list[0][0][0]) # Working My Output is: s t r i 0
has title: Why Simple String's Character has So many array Dimensions?
has answer: http://stackoverflow.com/a/47510892
accepted answer: http://stackoverflow.com/a/47510866
has answer: http://stackoverflow.com/a/47510866
tagged with: list
type: AnsweredQuestion
answer count: 3
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47535354
type: Answer
has body: array_chunks = [1,2,3] my_string = "987654" result = [] ind = 0 for i in array_chunks: result.append(my_string[ind: ind+i]) ind+=i As per below a list comprehension is also possible. I used a solution with itertools.accumulate from itertools import accumulate [my_string[i: i+j] for i, j in zip(accumulate(range(len(array_chunks))), array_chunks)]
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47535291
downvote count: 0

http://stackoverflow.com/a/47499085
has comment: http://stackoverflow.com/comment/90862905
answers question: http://stackoverflow.com/q/47481909
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Found a solution using event_loop.call_soon_threadsafe(). Here is the code now: def register_signal_handler(loop, handler, signal, sender): def dispatcher_receive(message): loop.call_soon_threadsafe(handler, message) dispatcher.connect(dispatcher_receive, signal=signal, sender=sender, weak=False) class Alice(): def __init__(self): logger.debug('Alice instantiated') self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) register_signal_handler(self.loop, self.alice_receive, signal=BOB_SIGNAL, sender=BOB_SENDER) self.alice() def alice_receive(self, message): logger.debug('Alice has received message: {}'.format(message)) dispatcher.send(message='thank you from Alice', signal=ALICE_SIGNAL, sender=ALICE_SENDER) def alice(self): def procrastinate(): logger.debug('Alice is procrastinating') self.loop.call_later(1, procrastinate) procrastinate() self.loop.run_forever() class Bob(): def __init__(self): logger.debug('Bob instantiated') self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) register_signal_handler(self.loop, self.bob_receive, signal=ALICE_SIGNAL, sender=ALICE_SENDER) self.bob() def bob_receive(self, message): logger.debug('Bob has received message: {}'.format(message)) def bob(self): def poke_alice(): dispatcher.send(message='message from Bob', signal=BOB_SIGNAL, sender=BOB_SENDER) self.loop.call_later(3, poke_alice) self.loop.call_later(3, poke_alice) self.loop.run_forever() So when a message arrives from Bob to Alice, the signal handler does not actually perform the job of handling the message, but only schedules execution of the actual handler that will perform the job. And the actual handler will get called in Alice's thread. In this case: Signal is always initially handled near-instantly and never blocks the sender's thread. Alice's code is always executed in Alice's thread. Bob's code is always executed in Bob's thread. So my goals here are achieved. Do you guys think this is a good solution? Would love to hear a comment o…
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47481909

http://stackoverflow.com/q/47422401
answer count: 1
has comment: http://stackoverflow.com/comment/81800571
has title: How to set airflow DAG runs continuously
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47959095
type: UnansweredQuestion
tagged with: airflow
tagged with: python
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/67053804
has body: I am using airflow to schedule a spark job, I need to got a DAG "run continuously" -- Like I just want a DAG to run, and when it finishes, to start a new DAG instance again. I have two options in my mind: 1. Allow only one DAG instance running at a time and run the DAG more frequently 2. Have another DAG to watch and kick off when it is needed. Have anyone implement it? Suggestions? Thanks!

http://stackoverflow.com/q/47532207
type: Question
has title: How to set the python path for the bluemix CF Python Apps
tagged with: ibm-cloud
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/48326239
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82021751
has body: I deployed a Python Flask app to IBM Cloud (Bluemix). But python files in the inner directories of my app are not found by Bluemix: [ImportError: No module named aciconsts ] unless I modify the path using sys.path. Is it possible to set PYTHONPATH to look for files in Bluemix CF Python App. In other words, are there environment variable like PYTHONPATH that can be set to look for python files in the app?
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/47532050
has comment: http://stackoverflow.com/comment/82020962
upvote count: 2
has comment: http://stackoverflow.com/comment/82021824
has comment: http://stackoverflow.com/comment/82021618
has comment: http://stackoverflow.com/comment/82021955
has comment: http://stackoverflow.com/comment/82021582
score: 2
has body: Create helper Series for get unique consecutive values of column Value, get index of max value byidxmax and last select value by loc: print (df) Timestamp Value 0 11/23/2017 7 1 11/24/2017 3 2 11/25/2017 5 3 11/26/2017 7 4 11/27/2017 7 5 11/28/2017 7 a = df['Value'].ne(df['Value'].shift()).cumsum() b = df.loc[a.idxmax(), 'Timestamp'] print (b) 11/26/2017 Detail: print (a) 0 1 1 2 2 3 3 4 4 4 5 4 Name: Value, dtype: int32 If first column is index solution is simplier, because need index value by max of Series: print (df) Value Timestamp 11/23/2017 7 11/24/2017 3 11/25/2017 5 11/26/2017 7 11/27/2017 7 11/28/2017 7 b = df['Value'].ne(df['Value'].shift()).cumsum().idxmax() print (b) 11/26/2017
downvote count: 0
answers question: http://stackoverflow.com/q/47531990
type: Answer

time
tags question: http://stackoverflow.com/q/47521630
tags question: http://stackoverflow.com/q/47440203
tags question: http://stackoverflow.com/q/47469640
type: Tag
tag name: time
tags question: http://stackoverflow.com/q/47524363
tags question: http://stackoverflow.com/q/47528906
tags question: http://stackoverflow.com/q/47389702

http://stackoverflow.com/a/47486711
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47486683
has body: sorted returns a sorted version of the list you hand over. The list itself is unmodified. You're always printing the unsorted list. Try: sorted_list_1 = sorted(l, key=lambda x: x[0]) sorted_list_2 = sorted(l, key=lambda x: x[2]) print (sorted_list1, sorted_list2)
answers question: http://stackoverflow.com/q/47486683
type: Answer

http://stackoverflow.com/a/47463751
has comment: http://stackoverflow.com/comment/81882853
has body: Use list comprehension with ast.literal_eval: import ast data = ast.literal_eval(open('File.json').read()) asins = [i['asin'] for i in data]
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81882703
answers question: http://stackoverflow.com/q/47463730
has comment: http://stackoverflow.com/comment/81882777

http://stackoverflow.com/comment/81739167
score: 1
has text: Is there a question in there somewhere? :)
type: QuestionComment
comment on: http://stackoverflow.com/q/47391001
type: Comment

http://stackoverflow.com/q/47452663
tagged with: excel
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pandas
upvote count: 7
score: 7
tagged with: xlsxwriter
has title: Xlsxwriter in pandas and outside of pandas lockout
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47452821
has body: I am using xlsxwriter engine to push some dataframes into excel sheet with pandas.to_excel(), but I need a caption above each table. Here is an example of what result I would like to achieve: I did not see any way to use ExcelWriter object of pandas to simply manipulate content of each cell and when I try to do it, I get: Exception: Sheetname 'sample', with case ignored, is already in use. I guess xlsxwriter locks it for itself. Here is an example: xlsx_writer = pd.ExcelWriter( get_target_filepath(xlsx_name), engine='xlsxwriter' ) workbook = xlsx_writer.book worksheet = workbook.add_worksheet(sheet_name) worksheet.write(1, 1, 'ABC') _, sample_table = dataframe_tuples[0] sample_table.to_excel(xlsx_writer, startrow=3, startcol=2, sheet_name=sheet_name) I could save dataframes and go over it again with openpyxl, but I seriously dislike the way they do formatting, which I have to do next, and if I format it in xlsxwriter and then reopen it with openpyxl, it cannot save the formatting back properly, openpyxl ruins it. I can not put excel itself onto server to use VBA macros for styling. Is there any way around this or am I just doing something horribly wrong?
has answer: http://stackoverflow.com/a/47452821
has answer: http://stackoverflow.com/a/47454182
tagged with: python
accepted answer: http://stackoverflow.com/a/47454182

http://stackoverflow.com/a/47462149
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81879355
upvote count: 1
has comment: http://stackoverflow.com/comment/81879293
has comment: http://stackoverflow.com/comment/81879648
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47462122
has comment: http://stackoverflow.com/comment/81879712
answers question: http://stackoverflow.com/q/47462122
type: AcceptedAnswer
has body: Python 3: a = input("What is your age?") # this is a string input a = int(input("What is your age?")) # you need an integer input elif(isinstance(a, int)) # this is how you check if a is integer For your case in Python 2: a = raw_input("What is your age?") # input is interpreted as unicode here try: a = int(a) b = 7 c = ((a-2) * 4) +25 print "Your age in a small dog's years is:", ((a-2) * 4)+28 except: print "You must enter an integer!"

http://stackoverflow.com/comment/81880277
comment on: http://stackoverflow.com/q/47462664
has text: It is possible, but not convenient for more than one element to pick.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47529910
type: Answer
has comment: http://stackoverflow.com/comment/82017147
upvote count: 11
score: 11
has comment: http://stackoverflow.com/comment/82017504
downvote count: 0
answers question: http://stackoverflow.com/q/47529097
has body: Use importlib.import_module and specify your package from __name__ in __init__.py: importlib.import_module(name, package=None) Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. Example: import importlib def call_me(): module = importlib.import_module('.mylib', package=__name__) module.my_func()
has comment: http://stackoverflow.com/comment/82017567
has comment: http://stackoverflow.com/comment/82017449

http://stackoverflow.com/comment/81867044
comment on: http://stackoverflow.com/q/47455850
score: 0
type: Comment
type: QuestionComment
has text: testing your code, the image shows a big white border at the start. So each line contains a lot of 255 values and the ellipsis is used when representing the data because the data is big. I've printed the values and some aren't 255.

http://stackoverflow.com/q/47393631
type: Question
score: 3
tagged with: airflow
tagged with: python
type: AnsweredQuestion
tagged with: google-cloud-platform
has title: Airflow - dags not beeing run
upvote count: 3
accepted answer: http://stackoverflow.com/a/50574061
answer count: 1
downvote count: 0
has body: python: 27 I have just installed airflow on a new vm GCP with a mysql backend. (sudo pip install apache-airflow and sudo pip install apache-airflow[mysql]) I have not created any dags of my own, but trying to run the examples to learn how it works. I have altered the config to use executor = LocalExecutor and done export AIRFLOW_HOME=`pwd`/airflow (in both shells) airflow initdb Webserver is started as "airflow webserver" and in a different shell i have started "airflow scheduler". I have tried going into the web ui to stat task by clicking "DAGs", and then the run button. (where a dialoge opens asking if i want to run now) The ones I've tried starting is "example_bash_operator, example_http_operator, example_python_operator", they now show as running. But the state does not change. I have also clicked so the 3 DAGs shows as "on". When i go to browse -> Task instances and look the first ones that are supposed to start it shows: All dependencies are met but the task instance is not running. In most cases this just means that the task will probably be scheduled soon unless: ....... My servers doesnt give any meaningful output. My scheduler is just outputting [2017-11-20 13:42:37,460] {jobs.py:1407} INFO - Heartbeating the process manager [2017-11-20 13:42:37,460] {jobs.py:1443} INFO - Heartbeating the executor
has answer: http://stackoverflow.com/a/50574061
favorite count: 0

http://stackoverflow.com/comment/106941282
type: Comment
type: AnswerComment
has text: `copy() missing 1 required positional argument: 'Key' `
comment on: http://stackoverflow.com/a/47468284
score: 0

http://stackoverflow.com/a/47445693
answers question: http://stackoverflow.com/q/47445607
has comment: http://stackoverflow.com/comment/81846956
has comment: http://stackoverflow.com/comment/81846908
accepted answer of: http://stackoverflow.com/q/47445607
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: See if this works from functools import reduce import pandas as pd lis = [df1, df2, df3, ... , dfn] inner_align = lambda d1, d2: d1.align(d2, 'inner')[0] outer_align = lambda d1, d2: d1.align(d2, 'outer')[0] inner_indcs = reduce(inner_align, lis) outer_indcs = reduce(outer_aling, lis) innout = lambda d, i, o: d.reindex_like(i).reindex_like(o) output = innout(lis[0], inner_indcs, outer_indcs) Setup lis = [ pd.DataFrame(1, list('abc'), list('xyz')), pd.DataFrame(1, list('acd'), list('wyz')), pd.DataFrame(1, list('bec'), list('ysu')), pd.DataFrame(1, list('cef'), list('xgy')), ] print(*lis, sep='\n'*2) x y z a 1 1 1 b 1 1 1 c 1 1 1 w y z a 1 1 1 c 1 1 1 d 1 1 1 y s u b 1 1 1 e 1 1 1 c 1 1 1 x g y c 1 1 1 e 1 1 1 f 1 1 1 Demonstration from functools import reduce import pandas as pd inner_align = lambda d1, d2: d1.align(d2, 'inner')[0] outer_align = lambda d1, d2: d1.align(d2, 'outer')[0] inner_indcs = reduce(inner_align, lis) outer_indcs = reduce(outer_align, lis) innout = lambda d, i, o: d.reindex_like(i).reindex_like(o) output = innout(lis[0], inner_indcs, outer_indcs) print(output) g s u w x y z a NaN NaN NaN NaN NaN NaN NaN b NaN NaN NaN NaN NaN NaN NaN c NaN NaN NaN NaN NaN 1.0 NaN d NaN NaN NaN NaN NaN NaN NaN e NaN NaN NaN NaN NaN NaN NaN f NaN NaN NaN NaN NaN NaN NaN
type: Answer

http://stackoverflow.com/a/47451359
answers question: http://stackoverflow.com/q/47451334
has body: You want to use max(score); enumerate returns a tuple (index, element); the max of a tuple is evaluated on the first element, which will always be the last (largest index) in this case. winner = max(score) If you also want the indices, you can do as was suggested by @ChrisRand in the comments: winner = max(enumerate(score), key= lambda x: x[1])
has comment: http://stackoverflow.com/comment/81858166
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81858375

http://stackoverflow.com/a/48717713
downvote count: 0
has body: @client.command(description="Some ping command") #here async def ping(*args): await client.say(":ping_pong: Pong!")
type: Answer
answers question: http://stackoverflow.com/q/47441564
score: 3
upvote count: 3

http://stackoverflow.com/comment/83661548
comment on: http://stackoverflow.com/a/48278168
score: 0
type: AnswerComment
has text: On (Ubuntu)Linux you must import MediaInfoDLL on Py2 and *3 on Py3, or you will get an importerror. But it does not work. MediaInfo is installed
type: Comment

http://stackoverflow.com/comment/81859733
comment on: http://stackoverflow.com/q/47434779
score: 0
type: Comment
type: QuestionComment
has text: @ThijmenDam, was my answer useful? If yes -- check a tick near my answer, please.

http://stackoverflow.com/comment/82045012
score: 0
comment on: http://stackoverflow.com/a/47537982
type: Comment
type: AnswerComment
has text: That np.block is about 3 times slower than the hstack+vstack combination is surprising. I never thought it would be that way.

http://stackoverflow.com/a/47448135
accepted answer of: http://stackoverflow.com/q/47442102
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/81886382
has comment: http://stackoverflow.com/comment/81868512
has body: You should provide the data for X/Y next time, or something dummy, it'll be faster and provide you with a specific solution. For now I've created a dummy equation of the form y = X**4 + X**3 + X + 1. There are many ways you can improve on this, but a quick iteration to find the best degree is to simply fit your data on each degree and pick the degree with the best performance (e.g., lowest RMSE). You can also play with how you decide to hold out your train/test/validation data. import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split X = np.arange(100).reshape(100, 1) y = X**4 + X**3 + X + 1 x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3) rmses = [] degrees = np.arange(1, 10) min_rmse, min_deg = 1e10, 0 for deg in degrees: # Train features poly_features = PolynomialFeatures(degree=deg, include_bias=False) x_poly_train = poly_features.fit_transform(x_train) # Linear regression poly_reg = LinearRegression() poly_reg.fit(x_poly_train, y_train) # Compare with test data x_poly_test = poly_features.fit_transform(x_test) poly_predict = poly_reg.predict(x_poly_test) poly_mse = mean_squared_error(y_test, poly_predict) poly_rmse = np.sqrt(poly_mse) rmses.append(poly_rmse) # Cross-validation of degree if min_rmse &gt; poly_rmse: min_rmse = poly_rmse min_deg = deg # Plot and present results print('Best degree {} with RMSE {}'.format(min_deg, min_rmse)) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(degrees, rmses) ax.set_yscale('log') ax.set_xlabel('Degree') ax.set_ylabel('RMSE') This will print: Best degree 4 with RMSE 1.27689038706e-08 Alternatively, you could also build a new class that carries out Polynomial fitting, and pass that to GridSearchCV with a set of parameters.
type: Answer
answers question: http://stackoverflow.com/q/47442102
upvote count: 6
has comment: http://stackoverflow.com/comment/81943140

http://stackoverflow.com/a/47405412
type: Answer
accepted answer of: http://stackoverflow.com/q/47405274
downvote count: 0
answers question: http://stackoverflow.com/q/47405274
score: 1
upvote count: 1
type: AcceptedAnswer
has body: We can groupby and ffill and bfill, then drop_duplicates df.assign(p2=df.groupby('p1')['p2'].apply(lambda x : x.ffill().bfill())).\ drop_duplicates(subset=["p1","p2"], keep='last') Out[645]: p1 p2 0 a 1.0 1 a 2.0 2 a 3.0 3 b NaN 4 c 4.0 6 d 5.0

http://stackoverflow.com/comment/81795914
has text: @BrandonLok you should fix that error rather than use sudo all the time. It will lead to bugs from permissions errors.
score: 0
comment on: http://stackoverflow.com/a/47398214
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47448298
type: Answer
answers question: http://stackoverflow.com/q/47447939
has comment: http://stackoverflow.com/comment/81852225
has body: A simple list comprehension should do the trick since it is not an RDD - url_mod = ["https://hdchjhjedjekdn.com/{}_public.xml".format(x) for x in ids]
score: 0

http://stackoverflow.com/a/47480017
has comment: http://stackoverflow.com/comment/81914885
has comment: http://stackoverflow.com/comment/81914868
type: Answer
accepted answer of: http://stackoverflow.com/q/47479980
has body: We should filter before the groupby auto[auto['name'].str.contains('chevrolet')].groupby('yr')['mpg'].mean() Out[226]: yr 70 17 71 17 Name: mpg, dtype: int64 Your method create another groupby key with [True,False], then , pandas will groupby it and column yr EDIT: You can think this is what your data frame looks like auto['yourkey']=auto['name'].str.contains('chevrolet') auto Out[228]: mpg yr name yourkey 0 18 70 chevroletmalibu True 1 15 70 buickskylark False 2 18 70 fordtorino False 3 16 70 chevroletelcamino True 4 17 71 chevroletchevelle True
answers question: http://stackoverflow.com/q/47479980
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47425788
downvote count: 0
answers question: http://stackoverflow.com/q/47419232
has comment: http://stackoverflow.com/comment/81883387
score: 3
has comment: http://stackoverflow.com/comment/81852544
type: Answer
has body: The solution is as follow: 1. Divide Window into 2 Sections Set the top section to 30% (0.3) of the parent's height by using size_hint_y = 0.3. The bottom section to 70% (0.7) of the parent's height using size_hint_y = 0.7 2. Avoid Top Left Corner Jam Up To spread out the widgets in the top left corner, use size_hint_y = 1 Snippet BoxLayout: orientation: "vertical" size_hint_y: 0.3 BoxLayout: size_hint_y: 1 BoxLayout: orientation: "vertical" Image: dailyview.kv #:kivy 1.10.0 &lt;WeatherWidget&gt;: cols: 1 BoxLayout: orientation: "vertical" size_hint_y: 0.3 BoxLayout: size_hint_y: 1 orientation: "horizontal" BoxLayout: orientation: "vertical" Image: source: 'Weather/partly_cloudy_night@2x.png' keep_ratio: False halign: 'center' Label: text: root.current_temperature()[:3] bold: True font_size: 40 Label: text: root.low_high_temp(0) font_size: 15 color: [1,255,1,1] Label: text: root.get_location() font_size: 15 color: [1,1,1,1] bold: True Label: text: root.sunrise() font_size: 10 color: [1,1,1,1] Label: text: root.sunset() font_size: 10 color: [1,1,1,1] BoxLayout: orientation: 'vertical' Image: source: 'Weather/partly_cloudy_day@2x.png' Label: text: root.forecast_day(1) Label: text: root.low_high_temp(1) font_size: 12 color: [1,255,1,1] Label: text: root.forecast_day(2) Label: text: root.forecast_day(3) Label: text: root.forecast_day(4) Label: text: root.forecast_day(5) BoxLayout: size_hint_y: None BoxLayout: orientation: 'vertical' Button: text: root.TimeHours + ':' + root.TimeMinutes size_hint_x: 1 font_size: 40 size: self.size bold: True halign: 'center' Label: text: root.current_date() size_hint_x: 1 font_size: 15 bold: True halign: 'center' BoxLayout: size_hint_y: 0.8 BoxLayout: size_hint_y: 0.7 BoxLayout: Button: size_hint_y: 1 text: "News Sections" BoxLayout: orientation: "vertical" Button: size_hint_y: 0.5 text: "Stock Quotes" Button: size_hint_y: 0.5 text: "Live Sports Scores" Output
accepted answer of: http://stackoverflow.com/q/47419232
upvote count: 3
has comment: http://stackoverflow.com/comment/81811395
type: AcceptedAnswer

http://stackoverflow.com/comment/81841836
type: AnswerComment
score: 0
has text: This assumes the indexes will be in order
type: Comment
comment on: http://stackoverflow.com/a/47443369

http://stackoverflow.com/a/69000484
answers question: http://stackoverflow.com/q/47540616
has body: To have access to a bigger time span you can do the following ways: download everyday data and add up gradually. you can search on the web to find a dataset The best way is to ask Twitter to give you the data for a specific time span while you have an API developer account. You have asked for a quote using this address: https://www.trackmyhashtag.com/twitter-dataset#request-data-form
type: Answer
score: 0

http://stackoverflow.com/q/47403696
tagged with: python
has body: I'm a bit lost with the use of Feature Hashing in Python Pandas . I have the a DataFrame with multiple columns, with many information in different types. There is one column that represent a class for the data. Example: col1 col2 colType 1 1 2 'A' 2 1 1 'B' 3 2 4 'C' My goal is to apply FeatureHashing for the ColType, in order to be able to apply a Machine Learning Algorithm. I have created a separate DataFrame for the colType, having something like this: colType value 1 'A' 1 2 'B' 2 3 'C' 3 4 'D' 4 Then, applied Feature Hashing for this class Data Frame. But I don't understand how to add the result of Feature Hashing to my DataFrame with the info, in order to use it as an input in a Machine Learning Algorithm. This is how I use FeatureHashing: from sklearn.feature_extraction import FeatureHasher fh = FeatureHasher(n_features=10, input_type='string') result = fh.fit_transform(categoriesDF) How do I insert this FeatureHasher result, to my DataFrame? How bad is my approach? Is there any better way to achieve what I am doing? Thanks!
has answer: http://stackoverflow.com/a/51253711
type: Question
answer count: 2
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: scikit-learn
tagged with: data-science
favorite count: 0
has title: Apply Feature Hashing to specific columns from a DataFrame
score: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47447793

http://stackoverflow.com/comment/82016696
comment on: http://stackoverflow.com/q/47530081
has text: http 403 is "forbidden". Is your service account added to the GA account with user management permissions ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47427918
accepted answer of: http://stackoverflow.com/q/47427837
upvote count: 2
has comment: http://stackoverflow.com/comment/81810511
answers question: http://stackoverflow.com/q/47427837
has comment: http://stackoverflow.com/comment/81810313
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81811076
downvote count: 0
has comment: http://stackoverflow.com/comment/81810479
has comment: http://stackoverflow.com/comment/81810280
score: 2
has body: I think you need merge DataFrames with 2 columns - Close and Date, so select these columns in both DataFrames and then merge: Also there are 2 format of datetimes as strings, so first convert them to datetimes for same type. aur['Date'] = pd.to_datetime(aur['Date']) bal['Date'] = pd.to_datetime(bal['Date']) result = pd.merge(aur'Close', 'Date', bal'Close', 'Date', on='Date') If use: result = pd.merge(aur.Close, bal.Close, on='Date') then try to merge with columns Close (Series) and get error.
type: Answer

http://stackoverflow.com/comment/81957590
score: 0
comment on: http://stackoverflow.com/q/47500289
has text: @juanpa.arrivillaga I added a few more pictures. After starting the System and the idle, the menu of the idle looks weird and my current session is killed after a couple of seconds. The system is brining me back to the login screen. If I am logging in and starting the idle again, no errors appear and i can use it normally.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82027488
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47535299
has text: Unrelated, but all those `g1`, `g2`, `bou1`, etc. are `None` as you assign them the result of `.grid(...)`

http://stackoverflow.com/comment/81932406
comment on: http://stackoverflow.com/a/47486597
score: 0
type: Comment
has text: @sharatpc When I plot figure with the code you suggested, I could get the right coordinates, but the two centroids were not on nodes with coordinates [2, 2] and [6, 6] in the plot. Do you know how to deal with this?
type: AnswerComment

http://stackoverflow.com/q/47433582
has answer: http://stackoverflow.com/a/47468484
score: 1
type: AnsweredQuestion
has title: Spark SQL to Hive table - Datetime Field Hours Bug
answer count: 2
tagged with: pyspark
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47457307
has body: I face this problem: When I enter in a timestamp field in Hive with spark.sql data, the hours are strangely changed to 21:00:00! Let me explain: I have a csv file that I read with spark.sql. I read the file, convert it to dataframe and store it, in a Hive table. One of the fields in this file is date in the format "3/10/2017". The field in Hive that I want to enter it, is in Timestamp format (the reason I use this data type instead of Date is that I want to query table with Impala and Impala has only Timestamp data type, so It is not a solution to simply change the data type to Date) As you can see from documentation the Hive Timestamp data type has "YYYY-MM-DD HH:MM:SS" format so before I enter the dataframe to the Hive Table I convert the date values to the appropriate format. Here is my code in Python: from datetime import datetime from pyspark.sql.functions import udf df = spark.read.csv("hdfs:/user/../MyFile.csv", header=True) #Use a user defined function to convert date format def DateConvert(x): x_augm = str(x)+" 00:00:00" datetime_object = datetime.strptime(x_augm,'%d/%m/%Y %H:%M:%S') return datetime_object.strftime('%Y-%m-%d %H:%M:%S') DateConvert_udf = udf(DateConvert) df= df.withColumn("Trans_Date", DateConvert_udf("Trans_Date")) This properly formats the timestamp. When I run df.select("Trans_Date").show(10, False) I get: +-------------------+ |Trans_Date | +-------------------+ |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| |2017-10-16 00:00:00| +-------------------+ Then I import the data to Hive with Spark SQL like this df.createOrReplaceTempView('tempTable') spark.sql("insert into table db.table select * from tempTable") My problem is that when I go to Hive my Timestamp field has values like: 2017-10-16 21:00:00 which is very peculiar! Thanks in advance for any suggestion
favorite count: 0
tagged with: hive
has answer: http://stackoverflow.com/a/47457307
type: Question
tagged with: apache-spark
possible better answer: http://stackoverflow.com/a/47468484

http://stackoverflow.com/q/47516866
tagged with: testing
upvote count: 2
has body: I'm using graphql (graphene) on a flask application and I want to test that my graphql is working as expected. I looked into apollo but it looks like it only supports node, java and ruby... not python. Does anyone know of any similar tools that I can use to test that the server fires up correctly, renders the graphql interface and returns the correct values when inputting a query?
downvote count: 0
answer count: 1
tagged with: graphql
tagged with: python
has answer: http://stackoverflow.com/a/48427698
has comment: http://stackoverflow.com/comment/82030570
favorite count: 0
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82029349
accepted answer: http://stackoverflow.com/a/48427698
has title: Test Graphql API - python
has comment: http://stackoverflow.com/comment/82062678
type: Question

http://stackoverflow.com/a/49368067
answers question: http://stackoverflow.com/q/47539201
type: Answer
has comment: http://stackoverflow.com/comment/103693338
has comment: http://stackoverflow.com/comment/88120168
score: 0
has body: For Python 3.6, there are actually two path entries. Also, it's best to use the %USERPROFILE% rather than hard coding it. %USERPROFILE%\AppData\Local\Programs\Python\Python36 %USERPROFILE%\AppData\Local\Programs\Python\Python36\Scripts

http://stackoverflow.com/a/47391382
accepted answer of: http://stackoverflow.com/q/47391257
has comment: http://stackoverflow.com/comment/81738811
answers question: http://stackoverflow.com/q/47391257
has body: Have you got a fixed list of cities you want to do this for? Simplest solution is to group by city and can then loop over the groups for city, names in df.groupby("City"): print(city) print(names) Portland City Name 2 Portland John 5 Portland Mary Seattle City Name 0 Seattle Alice 1 Seattle Bob 3 Seattle Mark 4 Seattle Emma Could then assign to a dictionary or some such (df_city[city] = names) if you wanted df_city["Portland"] to work. Depends what you want to do with the groups once split.
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/comment/81915982
score: 0
has text: I was lucky that you were willing to adapt my sketch of an answer to your specific needs
type: Comment
comment on: http://stackoverflow.com/a/47477464
type: AnswerComment

http://stackoverflow.com/comment/81925049
has text: maybe `ballon` should have `balloon.barrier = True/False` so you could use it to control if you can overlap balloon.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47482346
score: 0

http://stackoverflow.com/q/47533697
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82024083
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82024364
has title: How to traverse a website with bs4
type: Question
tagged with: python
favorite count: 0
score: -1
accepted answer: http://stackoverflow.com/a/47541218
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47541218
downvote count: 2
has body: I am trying to write a small script to traverse the quotedb website to get the quote of day , i am using bs4 How do i traverse the content returned to find the quote of the day? The thing is i am finding it pretty hard to traverse or even understand the content of the website. Where do i begin or how do i do so?

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/47448566
tags question: http://stackoverflow.com/q/47443660
tags question: http://stackoverflow.com/q/47426203
tag name: python-packaging
tags question: http://stackoverflow.com/q/47395648

http://stackoverflow.com/q/47451559
type: Question
has body: Just started with Python, so the following code is probably very poor, but it works for now. I have the following issue; I'm using the Pimoroni Unicorn Hat (led hat) for Raspberry Pi, the only way to keep the leds lighted is with a loop. To turn the leds/animations off and on i've created multiple Python files: Control-Led.py (defined the animations for variable a) var.py (writes the argument i use to a .txt file which is variable a) getvar.py (reads the var from the txt file) var.txt (file which contains the variable) The issue i have is that i continuous need to reload(getvar) in order to update the variable from the txt file in the control-led.py, in the first While True i have a time.sleep(2) so that's no issue, but in the second loop i needed to set a time.sleep(0.01) in order to get the animation of the led working. So every 0.01 second the value gets updated now.. it's causing high CPU and i think this is not the correct method. Can you guys help me out please? Control-led.py import varget import time import math import unicornhat as unicorn unicorn.set_layout(unicorn.HAT) unicorn.rotation(90) unicorn.brightness(0.5) width,height=unicorn.get_shape() ''' VARS 0. Turn off 1. Turn on white light 2. Home Axis animation ''' while True: reload(varget) time.sleep(2) if varget.a == 0: unicorn.off() elif varget.a == 1: unicorn.set_all(255,255,255) unicorn.show() elif varget.a == 2: i = 0.0 offset = 30 while varget.a == 2: i = i + 0.3 for y in range(height): for x in range(width): r = 0 g = 0 r = (math.cos((x+i)/2.0) + math.cos((y+i)/2.0)) * 64.0 + 128.0 g = (math.sin((x+i)/1.5) + math.sin((y+i)/2.0)) * 64.0 + 128.0 b = (math.sin((x+i)/2.0) + math.cos((y+i)/1.5)) * 64.0 + 128.0 r = max(0, min(255, r + offset)) g = max(0, min(255, g + offset)) b = max(0, min(255, b + offset)) unicorn.set_pixel(x,y,int(r),int(g),int(b)) unicorn.show() time.sleep(0.01) reload(varget) var.py import sys print sys.argv[1] file = open("./var.txt", "w") file.write(sys.argv[1]) file.close varge…
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81858071
has title: Python reload() to get var in While loop
tagged with: unicorn
has comment: http://stackoverflow.com/comment/81858155
score: 0
tagged with: while-loop
tagged with: python

http://stackoverflow.com/a/47407052
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47399358
score: 4
has body: Another solution is just to put another widget after the first boxlayout which contains the buttons to cover the remaining place &lt;WeatherWidget&gt;: orientation: "vertical" BoxLayout: height: "30dp" size_hint_y: None Button: text: 'New York, NY' size_hint_x: 1 on_press: root.printing_test() Button: text: 'Test' size_hint_x: 0.25 BoxLayout: size_hint_y: .9 #this is a random number that I have chosen
type: Answer

http://stackoverflow.com/comment/81904401
has text: You are most welcome. Good luck with the rest of the project. Please click on the tick - I think it's just below the valuation arrows to show that the answer was useful. I have voted +1 for the question because I learned something while answering it.
type: AnswerComment
comment on: http://stackoverflow.com/a/47474075
score: 0
type: Comment

http://stackoverflow.com/comment/82024286
has text: you cant go faster than O(n) i believe
comment on: http://stackoverflow.com/q/47533820
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/47400036
accepted answer of: http://stackoverflow.com/q/47399875
has comment: http://stackoverflow.com/comment/81754986
answers question: http://stackoverflow.com/q/47399875
type: Answer
has body: This code works by converting the args to a dictionary, then getting the value via key. Also, the code you had on line 13 didn't open the passed in value. This one opens the passed in file. See if this works for you: # !/usr/bin/python3 import argparse import shutil parser = argparse.ArgumentParser(description='Copy multiple Files from a specified data file') parser.add_argument('-c', '--configfile', default="config.dat", help='file to read the config from') def read_config(data): try: dest = '/home/admin/Documents/backup/' # Read in date from config.dat data = open(data) # Interate through list of files '\n' filelist = data.read().split('\n') # Copy through interated list and strip white spaces and empty lines for file in filelist: if file: shutil.copy(file.strip(), dest) except FileNotFoundError: pass args = vars(parser.parse_args()) read = read_config(args['configfile'])
score: 2
upvote count: 3
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/81824907
score: 0
type: Comment
type: QuestionComment
has text: @joaoavf Well, it made post more difficult!
comment on: http://stackoverflow.com/q/47434724

http://stackoverflow.com/comment/82001991
type: Comment
comment on: http://stackoverflow.com/q/47521340
type: QuestionComment
has text: You can't rewrite a line without reading the whole file and overwriting it
score: 0

http://stackoverflow.com/comment/81913547
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47478694
type: AnswerComment
has text: How would I amend this if I've got other columns for example Product Name and Product Code, I've also just noticed the data set has dates like Mon (07/08) and also MON (07/08) meaning I'm getting 2 rows?

http://stackoverflow.com/comment/81893374
type: Comment
has text: thank you so much. what should i do for multiple urls in read_html?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47468201

http://stackoverflow.com/comment/81887890
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47408608
has text: @BoarGules, yes, with no errors

http://stackoverflow.com/q/47444780
favorite count: 0
type: Question
has body: Lets say I have this class: class Test(object): def __init__(self, a): self.a = a def test(self, b): if isinstance(self, Test): return self.a + b else: return self + b This would ideally in my world do this: &gt;&gt;&gt; Test.test(1,2) 3 &gt;&gt;&gt; Test(1).test(2) 3 Now this doesn't work because you get this error: TypeError: unbound method test() must be called with Test instance as first argument (got int instance instead) In python3 this works fine, and I have the sneaking suspicion this is possible with a decorator in python2 but my python foo isn't strong enough to get that to work. Plot Twist: So what happens when I need something on self when it's not called statically.
upvote count: 2
downvote count: 2
tagged with: python
has title: can a function be static and non-static in python 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47444917
score: 0
accepted answer: http://stackoverflow.com/a/47444917
has comment: http://stackoverflow.com/comment/81844858
answer count: 1
tagged with: python-2.x

ggplot2
tags question: http://stackoverflow.com/q/47493007
type: Tag
tags question: http://stackoverflow.com/q/47417107
tag name: ggplot2
tags question: http://stackoverflow.com/q/47484470

http://stackoverflow.com/comment/81740250
type: AnswerComment
comment on: http://stackoverflow.com/a/47393654
has text: it's almost the same as my code, what can make the difference ?
score: 0
type: Comment

http://stackoverflow.com/comment/81759079
comment on: http://stackoverflow.com/q/47402616
type: Comment
score: 0
has text: sorry, the the code should be info+=1. So a total of eighteen 999 are printed. But as I updated info in the for loop, i expected the last 999 to be 1000. Since func prints info.
type: QuestionComment

http://stackoverflow.com/comment/81768243
type: QuestionComment
comment on: http://stackoverflow.com/q/47390305
has text: No segfault while running directly from the terminal. Using shell_exec("path/to/python /path/to/code.py");
score: 0
type: Comment

http://stackoverflow.com/q/47428786
tagged with: c++11
tagged with: c++
type: AnsweredQuestion
has title: Validating Python list indexing syntax with ECMAScript regex
answer count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/81812633
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81812128
accepted answer: http://stackoverflow.com/a/47429983
has body: I am writing a C++ code that takes a string as an input and checks if that string has a valid Python list indexing syntax. For example: a[0], a[:], a[::], a[0:], a[-1::], a[ 2 : 1:2] a[: -1:], a[::- 1], a[1:10:2], and so on. So far I've got the following regular expression: ^[a-zA-Z_][a-zA-Z0-9_]*\[([ ]*-?[ ]*[0-9]+[ ]*)*:?([ ]*-?[ ]*[0-9]+[ ]*)*:?([ ]*-?[ ]*[0-9]+[ ]*)*\]$ However, it looks too long to me and I wonder if there is a better way to do this. Also, the above regular expression will match a[] which is undesirable. I have just started experimenting with regular expressions and my knowledge is limited. So my questions are: Is the a better way to construct a regex for validating Python list indexing? I would like the regex to fail on a[]. How can I do that? I am using C++ 11 regular expressions library which has ECMAScript syntax by default. Thank you.
has answer: http://stackoverflow.com/a/47429983
upvote count: 1
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/81876196
type: QuestionComment
comment on: http://stackoverflow.com/q/47460759
has text: Do you mean in a browser or using node.js? If you mean node, then it's very simple. In a browser, you'd need a lot more work to get access to the filesystem.
type: Comment
score: 0

http://stackoverflow.com/comment/81948669
has text: *dunder methods*, for **d**ouble **under**score.
comment on: http://stackoverflow.com/q/47496704
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81946061
type: QuestionComment
comment on: http://stackoverflow.com/q/47494314
has text: I am wondering whether your question is related to loading pre-trained models from a different working directory or you want to save arguments which initialized the model? To save arguments to initialize the model, you can simply put arguments in a dictionary and save it any file, it shouldn't matter.
score: 0
type: Comment

http://stackoverflow.com/q/47505331
upvote count: 1
favorite count: 0
has body: I am fetching users recently uploaded photos from Picasa. As per documentation sample request url: https://picasaweb.google.com/data/feed/api/user/userID?kind=photo&amp;max-results=10 Response is received but not as per given sample response entry tag is missing while fetching feed in response. Code snippet: credentials = SignedJwtAssertionCredentials( SERVICE_ACCOUNT_EMAIL, file(SERVICE_ACCOUNT_PEM_FILE_PATH, "rb").read(), scope=["https://picasaweb.google.com/data/"], prn=userEmail ) PHOTOS_URL = "https://picasaweb.google.com/data/feed/api/user/%s?kind=photo&amp;max-results=10&amp;alt=json" http = httplib2.Http() http = credentials.authorize(http) response, albumPhotos = http.request(PHOTOS_URL %(userEmail), 'GET') albumPhotos = json.loads(albumPhotos) In the response not getting Entry key which contains feed of recently uploaded photos.
type: Question
has title: Picasa Web Albums API : recently uploaded photos feed not working
tagged with: gdata
tagged with: google-api
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: picasa
score: 1
downvote count: 0

http://stackoverflow.com/a/47504757
answers question: http://stackoverflow.com/q/47504686
score: 1
has body: You can use generator here to read lines from a file in a memory efficient way, you can refer to this Lazy Method for Reading Big File in Python? or you can use f.read(number of lines) to read from line, lets suppose you want to read first 100 lines in a file fname='your file name' with open(fname) as f: lines=100 content = f.read(lines) print content or by using pandas nrows (number of rows) import pandas as pd myfile = pd.read('your file name',nrows=1000)
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47538318
has comment: http://stackoverflow.com/comment/82036149
downvote count: 0
answer count: 1
has body: My project is written in Django. I have one model for academic articles. class Article(models.Model): title = models.CharField(max_length=300) abstract = models.TextField(blank=True) ... I have another model for questions that articles may be responsive to: class Question(models.Model): question = models.CharField(max_length=300) article = models.ManyToManyField(Article) An article can respond to a question in one of three ways: 'yes', 'no', and 'insufficient evidence'. But the same article may respond differently depending on the question. So for example, article1 may respond 'yes' to question1, 'no' to question2 and 'insufficient evidence' to question3. I'm struggling with how to design these responses into my model. I could create a separate model for responses like below: class Response(models.Model): response = models.CharField(max_length=25) then populate that model with my three responses ('yes', 'no', 'insufficient evidence') and then add a field in my Article model for responses like so: response = models.ManyToManyField(Response) But then how would I link an article's response to a question? How do I tell the database that article1's response to question1 is 'yes', its response to question2 is 'no' and its response to question3 is 'insufficient evidence'? Thank you.
has comment: http://stackoverflow.com/comment/82035067
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82035692
linked to: http://stackoverflow.com/q/18676156
has title: Django database model design - linking 3 models
tagged with: django
has answer: http://stackoverflow.com/a/47539614
accepted answer: http://stackoverflow.com/a/47539614
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/82723372
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47861422
has text: Let me know if the github repo above works for you as well.

http://stackoverflow.com/q/47498619
tagged with: performance
has title: Why is pandas.dataframe.groupby faster when assigned to variable first?
tagged with: python
tagged with: optimization
type: AnsweredQuestion
score: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47498659
upvote count: 3
has body: Can anyone please help understand why the following two ways of doing, what i thought was, otherwise the same thing with the pandas.dataframe groupby method, complete in such different times according to iPython's Magic %timeit? %timeit somedf.groupby('someBoolColumn')['someBoolColumn'].count() 484 µs ± 9.52 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit grp = somedf.groupby('someBoolColumn') grp['someBoolColumn'].count() 146 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) somedf has 7200 rows and 24 columns. I cannot find, why the two liner assigning the object to variable grp first is >3 times faster, nor; if this is just specific to the groupby method or something more general to pandas or even python, for example, about variable assigment. Many thanks for any enlightenment as this would really help with many much larger dataframes i'd like to process, repeatedly with many different combinations of parameters.
tagged with: arrays
answer count: 1
has answer: http://stackoverflow.com/a/47498659
downvote count: 0
has comment: http://stackoverflow.com/comment/82232553
favorite count: 0
type: Question

opencv3.0
tags question: http://stackoverflow.com/q/47534108
tags question: http://stackoverflow.com/q/47468222
type: Tag
tags question: http://stackoverflow.com/q/47532858
tags question: http://stackoverflow.com/q/47449400
tag name: opencv3.0
tags question: http://stackoverflow.com/q/47397676
tags question: http://stackoverflow.com/q/47533291
tags question: http://stackoverflow.com/q/47475130

http://stackoverflow.com/comment/81990235
type: Comment
has text: your right, ive further updated question for clarity, thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/47516130
score: 0

http://stackoverflow.com/comment/81783868
type: Comment
type: AnswerComment
has text: yes it would be if vuln.published >= lastmonth: coll.insert(filter_vuln)
score: 0
comment on: http://stackoverflow.com/a/47415143

http://stackoverflow.com/comment/81763918
comment on: http://stackoverflow.com/q/47405143
type: QuestionComment
type: Comment
score: 0
has text: If you use np.genfromtxt, you could specify dtype=None, which will tell genfromtxt to intelligently guess the dtype of each column. Most conveniently, it relieves you of the burder of specifying the number of bytes required for the string column. (Omitting the number of bytes, by specifying e.g. np.str, does not not work.)

http://stackoverflow.com/comment/81837413
type: Comment
type: QuestionComment
has text: Is it in a file or in _Python_ console?
score: 0
comment on: http://stackoverflow.com/q/47441223

http://stackoverflow.com/q/47428746
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
type: Question
tagged with: jquery-ui-autocomplete
has comment: http://stackoverflow.com/comment/81811974
type: UnansweredQuestion
has title: jquery autocomplete issues serializing data properly
linked to: http://stackoverflow.com/q/7102754
has body: I am trying to implement jQuery autocomplete and am unable to pass objects so they have all the information available in my html. I am trying to follow Carl Ekerot's Post, but am unable to serialize this properly. In my template I get no suggestions in the drop down when I type in entries to search. The database is returning several entries properly so the problem must lie somewhere in how it is serializing the data. Here is a link to the jQuery Autocomplete Documentation I am trying to implement. models.py class Serializer(object): def serialize(self): return {c: getattr(self, c) for c in inspect(self).attrs.keys()} @staticmethod def serialize_list(l): return [m.serialize() for m in l] class User(db.Model, Serializer): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), index=True, unique=True, nullable=False) password_hash = db.Column(db.String(128), nullable=False) #active=db.Column(db.Boolean, default=True) admin = db.Column(db.Boolean, default=False) last_seen = db.Column(db.DateTime) roles=db.relationship('Role', backref='user') replies_sent=db.relationship('Message_Reply', backref='from_user') group_admins=db.relationship('Group', secondary='admined', primaryjoin=(admined.c.user_id==id), backref='admins') messages=db.relationship('Message_User', backref='user') groups=db.relationship('Group', secondary='grouped', primaryjoin=(grouped.c.user_id==id), backref='users') permissions = db.relationship('Permission', secondary=permissioned, primaryjoin=(permissioned.c.user_id==id), backref='users') def serialize(self): d = Serializer.serialize(self) del d['password_hash'] del d['admin'] del d['roles'] del d['replies_sent'] del d['group_admins'] del d['messages'] del d['groups'] del d['permissions'] del d['last_seen'] return d views.py @app.route("/search", methods=['GET', 'POST']) def search(): print request.args try: term=request.args['term'] data=User.query.filter(User.username.like('%'+term+'%')).all() ''' q=[] for i in data: q.append(…
tagged with: python
has comment: http://stackoverflow.com/comment/82072815
has comment: http://stackoverflow.com/comment/81832462
score: 0
answer count: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/81947147
type: AnswerComment
has text: to be completely honest you question is misleading. See edit to get what you call the set of supernodes.
comment on: http://stackoverflow.com/a/47486559
score: 0
type: Comment

http://stackoverflow.com/comment/82001095
comment on: http://stackoverflow.com/q/47522299
type: Comment
type: QuestionComment
has text: you have not done a great job of explaining the requirements ... however it sounds like you will probably have to develope your own solution
score: 0

http://stackoverflow.com/a/47487662
downvote count: 0
has body: You just have to inspect the html and identify the tags that hold the data you want to scrape. In this case it's div.centered_image.header_image img for the image and div#read_desc for the description. An example with bs4 css selectors: import requests from bs4 import BeautifulSoup baseurl = "https://www.buycott.com/upc/632930413867" page_html = requests.get(baseurl).content soup = BeautifulSoup(page_html, "html.parser") image = soup.select_one('div.centered_image.header_image img')['src'] description = soup.select_one('div#read_desc').text.strip() print(image) print(description) https://images-na.ssl-images-amazon.com/images/I/416EuOE5kIL.SL160.jpg No description for 632930413867
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47487376
score: 2

dask
tags question: http://stackoverflow.com/q/47513326
type: Tag
tags question: http://stackoverflow.com/q/47392290
tags question: http://stackoverflow.com/q/47436987
tags question: http://stackoverflow.com/q/47518264
tags question: http://stackoverflow.com/q/47440965
tags question: http://stackoverflow.com/q/47440636
tags question: http://stackoverflow.com/q/47499032
tag name: dask
tags question: http://stackoverflow.com/q/47536253
tags question: http://stackoverflow.com/q/47534099
tags question: http://stackoverflow.com/q/47401262

http://stackoverflow.com/comment/82027529
has text: Thank you for that link, those libraries are quite useful. But I do not see how they can be used to access structs in a non-verbose way.
type: Comment
comment on: http://stackoverflow.com/q/47520712
type: QuestionComment
score: 0

http://stackoverflow.com/q/47518379
has comment: http://stackoverflow.com/comment/81993367
answer count: 0
has comment: http://stackoverflow.com/comment/81993016
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/81992958
has comment: http://stackoverflow.com/comment/81993259
type: Question
has comment: http://stackoverflow.com/comment/81992959
score: 0
has comment: http://stackoverflow.com/comment/81993075
has title: Is there a way to run n command lines at the same time
has comment: http://stackoverflow.com/comment/81992913
has body: I have a function which runs a long process and writes to a file. To make things faster, I was opening n python consoles, and executing that function in each. My question: is there is a way to do this in a single instance of the python console. Here's the source I'm working through: def test_random(): while True: kwargs = random_aco_args() args = () num_cities = kwargs.pop("num_cities") tsp_model = get_model(num_cities) print_test(num_cities, kwargs) run_aco(tsp_model, *args, **kwargs) if __name__ == "__main__": test_random() and here is the script I created to call it with Popen: from subprocess import Popen if __name__ == "__main__": f_path = "C:\\Users\\Y\\Desktop\\sketches\\Search_algorithms\\tsp\\testtd.py" for _ in range(0,20): Popen([sys.executable, f_path])
tagged with: python
has comment: http://stackoverflow.com/comment/81993191

http://stackoverflow.com/a/47383609
has body: You should not think of single pixels but of horizontal lines at first. For each y create a list of connected lines. If you find a pixel in searched color and the pixel to the left has same color, add found pixel to the last line. Then go through y to find adjacent lines of same begin and end to build rectangles out of it.
type: Answer
answers question: http://stackoverflow.com/q/47383360
score: 0

http://stackoverflow.com/q/47396126
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: ionic-framework
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: firebase-realtime-database
tagged with: android
has comment: http://stackoverflow.com/comment/115107840
tagged with: python
has title: Unauthorized getting object from firebase database with python
has body: I'm trying to get an object from my production firebase database but I get the following message: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.7/site-packages/firebase_admin/db.py", line 147, in get return self._client.body('get', self._add_suffix()) File "/Library/Python/2.7/site-packages/firebase_admin/_http_client.py", line 93, in body resp = self.request(method, url, **kwargs) File "/Library/Python/2.7/site-packages/firebase_admin/db.py", line 769, in request raise ApiCallError(self._extract_error_message(error), error) firebase_admin.db.ApiCallError: 401 Client Error: Unauthorized for url: https://xxxxx-xxxx.firebaseio.com/xxxxxx/0k4Xx6fnasdlnkas.json Reason: Unauthorized request. I did the same in my development database and it works correctly. I thought that permissions rules from firebase database will be the problem, but I deleted all rules from database and I got the same error. I think that there's something more in firebase that I don't know that makes my following python script crash. import firebase_admin from firebase_admin import credentials from firebase_admin import db cred = credentials.Certificate('deleteUserCredentialsPRO.json') firebase_admin.initialize_app(cred, {'databaseURL': 'https://xxxxxxx-xxxxx.firebaseio.com/'}) toDeleteUrl = db.reference('path-example/0k4Xx6fnasdlnkas') print toDeleteUrl print toDeleteUrl.get() The result from first print (toDeleteUrl) is: &lt;firebase_admin.db.Reference object at 0x1064b42d0&gt; The second print, outputs the error wrote above. Thank you in advanced.
tagged with: firebase-authentication

http://stackoverflow.com/a/47462914
upvote count: 2
type: AcceptedAnswer
has body: Logical xor You should continue the loop if exactly one a and b is equal to 5. It means you need a logical xor. Parens are needed to avoid comparing a to 5 ^ b: while True: a = input("Enter first input: ") b = input("Enter second input: ") try: a = int(a) b = int(b) if (a != 5) ^ (b != 5): print("I'm sorry but it must be a pos int and equal 5") continue break except ValueError: print("That's not an int") It might not be very readable though. Count 5's You could count the number of ints equal to 5: while True: a = input("Enter first input: ") b = input("Enter second input: ") try: a = int(a) b = int(b) count5 = [a, b].count(5) if count5 == 1: break else: print("Exactly one input should be equal to 5.") except ValueError: print("That's not an int") If you want to differentiate between errors: while True: a = input("Enter first input: ") b = input("Enter second input: ") try: a = int(a) b = int(b) count5 = [a, b].count(5) if count5 == 2: print("Inputs cannot both be equal to 5.") elif count5 == 0: print("At least one input should be equal to 5.") else: break except ValueError: print("That's not an int") Here's an example: Enter first input: 3 Enter second input: 1 At least one input should be equal to 5. Enter first input: 5 Enter second input: 5 Inputs cannot both be equal to 5. Enter first input: 3 Enter second input: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47462735
has comment: http://stackoverflow.com/comment/81881183
score: 2
answers question: http://stackoverflow.com/q/47462735
type: Answer
has comment: http://stackoverflow.com/comment/81880959

http://stackoverflow.com/q/47483450
downvote count: 2
has body: As answered in https://stackoverflow.com/a/47478902/9003921 I am using this code to generate a random number. If the number generated is less than 9, I want it to print a name along with it, if the number is 9 or 10, I want the loop to break. import random class Stack: def __init__(self): self.container = [] def isEmpty(self): return self.size() == 0 def push(self, item): self.container.append(item) def peek(self) : if self.size()&gt;0 : return self.container[-1] else : return None def pop(self): return self.container.pop() def size(self): return len(self.container) def printItem(self, run): print(self.container[run]) # Prints last item/name import random while True: rand = random.randint(1, 10) print(rand) if rand &gt; 8: break Names = Stack() Names.push('Mary') Names.push('Peter') Names.push('Bob') Names.push('John') Names.push('Kim') run = -1 while True: rand = random.randint(1, 10) print(rand) if rand &gt; 8: break elif rand: # Calls printItem with run as parameter Names.printItem(run) run-=1 # Subtracts one from run # Sets run to -1 again if all names have been printed if run&lt;(-1*Names.size()): run = -1' When answered in the link above, it still does not print a name with every number less than 9. A sample output it gave was 5 8 10 4 Kim 7 John 1 Bob 2 Peter 7 Mary 2 Kim 10 and another 9 3 Kim 7 John 1 Bob 6 Peter 10 did not exit when it was 9 or 10
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/47478016
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47483805
has comment: http://stackoverflow.com/comment/81922287
has answer: http://stackoverflow.com/a/47483805
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81922067
tagged with: python-3.x
has title: How to connect random number generation to item to print in python
tagged with: random
type: AnsweredQuestion

http://stackoverflow.com/a/72280546
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47493369
score: 3
has body: I see the main difference downstream. const promise = new Promise((resolve, reject) => sendRequest(resolve, reject)); await promise; In JavaScript, the two resolve and reject functions are created by the JS engine and they have to be passed around for you to keep track of them. In the end, you're still using two callback functions most of the time and the Promise won't really do more than setTimeout(() => doMoreStuff()) after doStuff calls resolve. There's no way to retrieve an old result or the status of a Promise once the callbacks were called. The Promise is mostly just the glue code between regular calls and async/await (so you can await the promise somewhere else) and a bit of error callback forwarding for chaining .thens. future = asyncio.Future() sendRequest(future) await future In Python, the Future itself becomes the interface with which a result is returned and it keeps track of the result. Since Andril has given the closest Python equivalent to JavaScript's Promise (which is Task; you give it a callback and wait for it to complete), I'd like to go the other way. class Future { constructor() { this.result = undefined; this.exception = undefined; this.done = false; this.success = () => {}; this.fail = () => {}; } result() { if (!this.done) { throw Error("still pending"); } return this.result(); } exception() { if (!this.done) { throw Error("still pending"); } return this.exception(); } setResult(result) { if (this.done) { throw Error("Already done"); } this.result = result; this.done = true; this.success(this.result); } setException(exception) { if (this.done) { throw Error("Already done"); } this.exception = exception; this.done = true; this.fail(this.exception); } then(success, fail) { this.success = success; this.fail = fail; } } The JS await basically generates two callbacks that are passed to .then, where in a JS Promise the actual logic is supposed to happen. In many examples, this is where you'll find a setTimeout(resolve, 10000) to demonstrate the j…
type: Answer

http://stackoverflow.com/comment/82000428
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47521088
has text: You are calculating `n` x `m` distances?

http://stackoverflow.com/a/47392789
score: -1
upvote count: 0
downvote count: 1
has body: Try this ['url_%s'%x for x in range(500)]
type: Answer
answers question: http://stackoverflow.com/q/47392585

graphviz
tags question: http://stackoverflow.com/q/47440732
tags question: http://stackoverflow.com/q/47404943
tags question: http://stackoverflow.com/q/47426249
tag name: graphviz
type: Tag

http://stackoverflow.com/comment/81911471
comment on: http://stackoverflow.com/q/47477942
score: 0
type: Comment
type: QuestionComment
has text: in the screenshot I can see 2 different matrices. what do you want to know? what clf.coefs_ is ?

http://stackoverflow.com/q/47462903
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81881841
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81882187
tagged with: python
has body: I was writing a program with a start page, and two programs that are called from that start page. Both of the subprograms work by themselves. However, when I put them into my start page, the stopwatch timing label doesn't show up. If you are wondering, I put them into my program by doing: import program program.function() Here is my start page program: from Tkinter import * class start_page: def __init__(self,master): self.master = master self.frame = Frame(self.master) self.countdown = Button(master, text = "Timer", command = self.c).pack() self.stopwatch_butt = Button(master,text="Stopwatch",command=self.g).pack() def g(self): import stopwatch stopwatch.f() def c(self): import timer_prog timer_prog.timer() self.master.after_cancel(timer_prog) def main(): root = Tk() s = start_page(root) root.title("Timer Suite: Brian Ton") root.mainloop() main() If I run this program, the timer program works fine, but the stopwatch doesn't show its label, only its buttons. I tried to clear all Tk after functions, and that didn't work, and I also tried to run the stopwatch program first, to no avail. Here is my stopwatch program: from Tkinter import * import datetime def s(): start.config(state='disabled') stop.config(state="normal") reset.config(state='disabled') Start() def Start(): if reset['state'] == 'disabled' and stop['state'] == 'normal': hidden.set(str(int(hidden.get())+1)) root.update() root.after(1000,Start) curr = hidden.get() g.set(str(datetime.timedelta(seconds=int(curr)))) print g.get() else: return None def Stop(): start.config(state='disabled') stop.config(state='disabled') reset.config(state="normal") def Reset(): start.config(state="normal") stop.config(state="disabled") reset.config(state='disabled') hidden.set('0') g.set(str(datetime.timedelta(seconds=0))) def f(): global root,frame,master,hidden,g,timelabel,start,stop,reset root = Tk() frame = Frame(root) master = root hidden = StringVar() g = StringVar() hidden.set('0') timelabel = Label(master,textvariable=g…
has title: Label Is Not Shown When Called From Other Tkinter Program
type: AnsweredQuestion
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/47464244
score: 1
has answer: http://stackoverflow.com/a/47464244

http://stackoverflow.com/comment/81928880
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47454047
type: QuestionComment
has text: @Thomas, sadly with line by line processing I run into the `Extra data` issue. Since stream analytics JSON files aren't technically valid (no top or bottom delineation of where the file ends). So I need to find a way to make the function read through each line in each file and append to a dict. Will post answer if I figure it out.

http://stackoverflow.com/q/47523708
tagged with: opencv
has title: Synchronizing multiple RTSP streams with OpenCV?
tagged with: python
tagged with: rtsp
favorite count: 0
type: Question
tagged with: c++
has answer: http://stackoverflow.com/a/51733289
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has body: I'm currently using OpenCV to digest an RTSP stream with OpenCV and the Python bindings. However, i'm trying to expand this to capture multiple RTSP streams and then perform operations on each frame and perform additional logic on the aggregate results (in parallel). I need to synch these live streams to within ~1 second accuracy. If all my streams were the same profile, this wouldn't be as challenging. However, some of the streams i am digesting are variable frame rate (VFS) so the FPS can drop from the max FPS to the min FPS depending on the bandwidth, while others may be constant.This could be simplified drastically if there was a way to get an embedded timestamp from the RTSP live stream, which is part of the protocol. But, i don't believe there is a way to get this timestamp using OpenCV.... I'm wondering if this has been done before using OpenCV? I know there are commercial broadcasting tools that can do this, but that seems impractical and over kill for my use case. Someone also recommended http://www.ros.org/about-ros/, but again that may be too much for what i am trying to do...

http://stackoverflow.com/comment/82028803
score: 0
type: AnswerComment
has text: yes, it is a separate db, but not a new db every time. if creation of db is expensive, you could keep it and drop all its collections after the tests.
comment on: http://stackoverflow.com/a/47535806
type: Comment

http://stackoverflow.com/comment/81790592
score: 0
type: Comment
has text: @H.Sodi Thanks for the heads up. I just updated my answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/47418145

http://stackoverflow.com/comment/81765224
type: QuestionComment
has text: Not sure what a nested list is, but I think I recognise that pattern. Had some trouble with it previously so if it's possible to avoid that solution........Ideally the simplier it will be the less hassle I will have with it in the future.
comment on: http://stackoverflow.com/q/47405659
score: 0
type: Comment

http://stackoverflow.com/comment/81835791
type: Comment
score: 0
type: AnswerComment
has text: @Alvaro Yes, that's what I meant by contract.
comment on: http://stackoverflow.com/a/47440027

http://stackoverflow.com/a/47500140
answers question: http://stackoverflow.com/q/47499876
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Focusing only in the error you do get: TypeError: unsupported operand type(s) for +: 'range' and 'list I will give you an explanation. Your current code does work in Python 2: deck = [(value, suit) for value in range(2, 11) + ["J", "Q", "K", "A"] for suit in ["H", "C", "D", "S"]] print deck will print: [(2, 'H'), (2, 'C'), (2, 'D'), (2, 'S'), (3, 'H'), (3, 'C'), (3, 'D'), (3, 'S'), (4, 'H'), (4, 'C'), (4, 'D'), (4, 'S'), (5, 'H'), (5, 'C'), (5, 'D'), (5, 'S'), (6, 'H'), (6, 'C'), (6, 'D'), (6, 'S'), (7, 'H'), (7, 'C'), (7, 'D'), (7, 'S'), (8, 'H'), (8, 'C'), (8, 'D'), (8, 'S'), (9, 'H'), (9, 'C'), (9, 'D'), (9, 'S'), (10, 'H'), (10, 'C'), (10, 'D'), (10, 'S'), ('J', 'H'), ('J', 'C'), ('J', 'D'), ('J', 'S'), ('Q', 'H'), ('Q', 'C'), ('Q', 'D'), ('Q', 'S'), ('K', 'H'), ('K', 'C'), ('K', 'D'), ('K', 'S'), ('A', 'H'), ('A', 'C'), ('A', 'D'), ('A', 'S')] In Python 3 you have to use list(range(2, 11)): deck = [(value, suit) for value in list(range(2, 11)) + ["J", "Q", "K", "A"] for suit in ["H", "C", "D", "S"]] print(deck) will print: [(2, 'H'), (2, 'C'), (2, 'D'), (2, 'S'), (3, 'H'), (3, 'C'), (3, 'D'), (3, 'S'), (4, 'H'), (4, 'C'), (4, 'D'), (4, 'S'), (5, 'H'), (5, 'C'), (5, 'D'), (5, 'S'), (6, 'H'), (6, 'C'), (6, 'D'), (6, 'S'), (7, 'H'), (7, 'C'), (7, 'D'), (7, 'S'), (8, 'H'), (8, 'C'), (8, 'D'), (8, 'S'), (9, 'H'), (9, 'C'), (9, 'D'), (9, 'S'), (10, 'H'), (10, 'C'), (10, 'D'), (10, 'S'), ('J', 'H'), ('J', 'C'), ('J', 'D'), ('J', 'S'), ('Q', 'H'), ('Q', 'C'), ('Q', 'D'), ('Q', 'S'), ('K', 'H'), ('K', 'C'), ('K', 'D'), ('K', 'S'), ('A', 'H'), ('A', 'C'), ('A', 'D'), ('A', 'S')] You have to use list() because range() in Python 3 does create an immutable sequence type, not a list.

http://stackoverflow.com/a/47526066
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82030798
upvote count: 1
has comment: http://stackoverflow.com/comment/82116316
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47526002
has comment: http://stackoverflow.com/comment/82008735
answers question: http://stackoverflow.com/q/47526002
has body: The file is corrupted. The ^@ means the ASCII NUL byte. Simply what has happened is that the file was extended to some larger size; the metadata was flushed to disk, but the actual contents remained in the cache when the computer (accidentally) shut down or the operating system crashed, or the USB drive was removed. I.e. in your case, you probably did lose your latest edit to this file.
has comment: http://stackoverflow.com/comment/82009213

http://stackoverflow.com/q/47530422
possible better answer: http://stackoverflow.com/a/47530618
linked to: http://stackoverflow.com/q/35650793
has body: Trying to make a template tag for my Django blog archive to show the last four months of the year, ie: October 2017 September 2017 August 2017 July 2017 I'm certain that it's so simple it's stupid but I'm just not getting it! Here's what I've got so far: @register.simple_tag def last_four_months(format): today = datetime.today() four_months = today - relativedelta(months=4) for month in four_months: return four_months.strftime(format) This throws a TypeError - 'datetime.datetime' object is not iterable
has answer: http://stackoverflow.com/a/47530618
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47530714
has answer: http://stackoverflow.com/a/47531153
upvote count: 0
answer count: 3
downvote count: 1
accepted answer: http://stackoverflow.com/a/47530714
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82017736
has title: Python function for getting a list of the past X months
tagged with: django
tagged with: python
score: -1

http://stackoverflow.com/comment/81888376
has text: Nope, that would be helpful, but fit just returns a tuple with the fitted numeric values of the parameters, what im trying to to do is associate every value returned by fit , to the parameter name.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47450347
type: Comment

awk
tags question: http://stackoverflow.com/q/47413175
tag name: awk
tags question: http://stackoverflow.com/q/47536497
type: Tag
tags question: http://stackoverflow.com/q/47468423
tags question: http://stackoverflow.com/q/47400218

http://stackoverflow.com/comment/81892658
has text: My guess is `ctypes.byref(ctypes.c_float(1.0))` creates a reference to a float, but that float is a temporary object and is freed after `ctypes.byref()` returns. Hold references to the floats before the function call instead. Without the actual C prototypes of the functions its difficult to tell if you've assigned `.argtypes` and `.restype` correctly for each function.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47466589

http://stackoverflow.com/q/47422148
accepted answer: http://stackoverflow.com/a/47422313
has title: Create a list with certain number of rows and columns in Python
possible better answer: http://stackoverflow.com/a/47422228
has answer: http://stackoverflow.com/a/47422242
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47422228
score: 3
has comment: http://stackoverflow.com/comment/81798827
has comment: http://stackoverflow.com/comment/81798903
tagged with: python
has body: I have a problem I can't seem to get right. I have 2 numbers, A &amp; B. I need to make a list of A rows with B columns, and have them print out 'R0CO', 'R0C1', etc. Code: import sys A= int(sys.argv[1]) B= int(sys.argv[2]) newlist = [] row = A col = B for x in range (0, row): newlist.append(['R0C' + str(x)]) for y in range(0, col): newlist[x].append('R1C' + str(y)) print(newlist) This is not working. The following is the output I get and the expected output: Program Output Program Failed for Input: 2 3 Expected Output: [['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']] Your Program Output: [['R0C0', 'R1C0', 'R1C1', 'R1C2'], ['R0C1', 'R1C0', 'R1C1', 'R1C2']] Your output was incorrect. Try again
has comment: http://stackoverflow.com/comment/81799003
has comment: http://stackoverflow.com/comment/81798938
type: AnsweredQuestion
tagged with: 2d
upvote count: 3
tagged with: list
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47422313

http://stackoverflow.com/q/47528845
tagged with: django
tagged with: python
tagged with: xero-api
score: 0
has title: Issue on Put method for creating a tracking option - Python
has answer: http://stackoverflow.com/a/47540505
answer count: 1
tagged with: python-requests
has body: I want to create a tracking option ((i.e) Add tracking option) under the respective tracking category, using Xero tracking category API for my organisation. But while creating data using 'put' Requests method, it is not creating. I am using the below condition in python: response = requests.put(url=url, auth=oauth, data=xml_string) I want to know, what is the format for the data to be updated in the requests, for both content type xml/text and application/json. xml_string and url, I given is below: xml_string='<Option> S11963 ' url = 'https://api.xero.com/api.xro/2.0/TrackingCategories/{Tracking_Category}/Options' where Tracking_Category='620815a2-a7c6-4b85-8b01-ffb254ab34ad' Error: \r\n 500 \r\n UnknownErrorException \r\n An error occurred in Xero. Check the API Status page http://status.developer.xero.com for current service status. Contact the API support team at api@xero.com for more assistance. \r\n Thanks
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47403134
answer count: 1
has title: How to use mwapi library to get a wikipedia page?
tagged with: python
has comment: http://stackoverflow.com/comment/81761233
has body: I have been trying to figure out the documentation of the mwapi library (MediaWiki API) and I cannot figure out how to simply request a page based on a search query or keyword. I know I should use get() but filling in the parameters with keywords yield errors. Does anyone know how this works to look up something like "Earth Wind and Fire"? Documentation can be found here: http://pythonhosted.org/mwapi and here is the only example they have of get() being used import mwapi session = mwapi.Session('https://en.wikipedia.org') print(session.get(action='query', meta='userinfo')) {'query': {'userinfo': {'anon': '', 'name': '75.72.203.28', 'id': 0}}, 'batchcomplete': ''} print(session.get(action='query', prop='revisions', revids=32423425)) {'query': {'pages': {'1429626': {'ns': 0, 'revisions': [{'user': 'Wknight94', 'parentid': 32276615, 'comment': '/* References */ Removing less-specific cat', 'revid': 32423425, 'timestamp': '2005-12-23T00:07:17Z'}], 'title': 'Grigol Ordzhonikidze', 'pageid': 1429626}}}, 'batchcomplete': ''}
has comment: http://stackoverflow.com/comment/81760425
type: Question
accepted answer: http://stackoverflow.com/a/47403967
score: 0
has comment: http://stackoverflow.com/comment/81761238
tagged with: get
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81761249
tagged with: session
has answer: http://stackoverflow.com/a/47403967

http://stackoverflow.com/a/47430083
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47429981
has body: my_dict = { 'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}], 'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}] } You can use a list comprehension it get the name field from each dictionary contained within the sublists (i.e. within the values of the original dictionary). &gt;&gt;&gt; [d.get('name') for sublists in my_dict.values() for d in sublists] ['john', 'steve', 'jack', 'anna']
accepted answer of: http://stackoverflow.com/q/47429981
type: Answer

http://stackoverflow.com/q/47494774
possible better answer: http://stackoverflow.com/a/47494889
type: Question
has body: There is data that stores datetime and score as follows. data = [ {'datetime': '2016-07-16 01:00:00+00:00', 'score': 100}, {'datetime': '2016-07-16 01:00:00+00:00', 'score': 314}, {'datetime': '2016-07-16 01:00:00+00:00', 'score': 1312}, {'datetime': '2016-07-16 01:30:00+00:00', 'score': 135}, {'datetime': '2016-07-16 01:30:00+00:00', 'score': 594}, {'datetime': '2016-07-16 01:30:00+00:00', 'score': 542}, {'datetime': '2016-07-16 02:00:00+00:00', 'score': 1431}, {'datetime': '2016-07-16 02:00:00+00:00', 'score': 431}, {'datetime': '2016-07-16 02:00:00+00:00', 'score': 89}, {'datetime': '2016-07-16 02:30:00+00:00', 'score': 1340}, {'datetime': '2016-07-16 02:30:00+00:00', 'score': 433}, {'datetime': '2016-07-16 02:30:00+00:00', 'score': 594}, {'datetime': '2016-07-17 01:00:00+00:00', 'score': 100}, {'datetime': '2016-07-17 01:00:00+00:00', 'score': 594}, {'datetime': '2016-07-17 01:00:00+00:00', 'score': 100}, {'datetime': '2016-07-17 01:30:00+00:00', 'score': 594}, {'datetime': '2016-07-17 01:30:00+00:00', 'score': 100}, {'datetime': '2016-07-17 01:30:00+00:00', 'score': 600}, {'datetime': '2016-07-17 02:00:00+00:00', 'score': 500}, {'datetime': '2016-07-17 02:00:00+00:00', 'score': 400}, {'datetime': '2016-07-17 02:00:00+00:00', 'score': 300}, {'datetime': '2016-07-17 02:30:00+00:00', 'score': 400}, {'datetime': '2016-07-17 02:30:00+00:00', 'score': 900}, {'datetime': '2016-07-17 02:30:00+00:00', 'score': 1100}, {'datetime': '2016-07-18 01:00:00+00:00', 'score': 140}, {'datetime': '2016-07-18 01:00:00+00:00', 'score': 150}, {'datetime': '2016-07-18 01:00:00+00:00', 'score': 160}, {'datetime': '2016-07-18 01:30:00+00:00', 'score': 170}, {'datetime': '2016-07-18 01:30:00+00:00', 'score': 180}, {'datetime': '2016-07-18 01:30:00+00:00', 'score': 190}, {'datetime': '2016-07-18 02:00:00+00:00', 'score': 200}, {'datetime': '2016-07-18 02:00:00+00:00', 'score': 120}, {'datetime': '2016-07-18 02:00:00+00:00', 'score': 190}, {'datetime': '2016-07-18 02:30:00+00:00', 'score':…
has title: A method of totaling data every hour from data in which plural datetimes are stored
tagged with: python
has answer: http://stackoverflow.com/a/47494889
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47494883
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47494883

http://stackoverflow.com/a/47421038
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47421003
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47421003
has body: Circular import is happening! Import module as import urls and get urlpatterns like this: def get(self, request, *args, **kwargs): context={"urlnames":[]} for up in urls.urlpatterns: context["urlnames"].append(up.name) return render_to_response('api_list.html', context)

http://stackoverflow.com/q/47540146
has comment: http://stackoverflow.com/comment/87858076
tagged with: python-multiprocessing
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/24894682
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82040571
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82038258
has body: I'm trying to use Python's multiprocessing module to run an analysis on multiple samples in parallel. I'm using pool.map_async to spawn the function (called crispr_analysis) on a tuple of tuples for arguments (zipped_args). Each tuple within zipped_args is not empty, as that can cause multiprocessing to hang. Upon completion of the pool, it hangs and fails to move on to the rest of the script. I know that crispr_analysis finishes as it creates output files (generated with with statements, so they're closing properly); I can browse said files and they are complete. I never see the debug message for sorting the results, and the program never terminates. try: # Use map_async and get with a large timeout # to allow for KeyboardInterrupts to be caught # and handled with the try/except timeout = max((9999, 600 * len(fastq_list))) logging.debug("Setting timeout to %s seconds", timeout) res = pool.map_async(crispr_analysis, zipped_args) # type: multiprocessing.pool.MapResult pool.close() results = res.get(timeout) except (KeyboardInterrupt, ExitPool) as error: # Handle ctrl+c or custom ExitPool pool.terminate() # pool.join() if isinstance(error, KeyboardInterrupt): # ctrl+c sys.exit('\nkilled') elif isinstance(error, ExitPool): # My way of handling SystemExits sys.exit(error.msg) else: # Shouldn't happen, but you know... raise except: pool.terminate(); pool.join() raise else: pool.join() try: logging.debug("Sorting results into alignments and summaries") sort_start = time.time() # type: float alignments, summaries = zip(*results) # type: Tuple[Tuple[alignment.Alignment]], Tuple[Dict[str, Any]] logging.debug("Sorting results took %s seconds", round(time.time() - sort_start, 3)) except ExitPool as error: # Handle ExitPool calls for single-threaded map sys.exit(error.msg) Does anyone have any idea why multiprocessing is hanging and how I can fix it? Extra information: I'm using Python 2.7.8 on CentOS 7.3.1611; platform and Python version are not changeable crispr_analysis retu…
has title: Python multiprocessing hangs indefinitely on completion

http://stackoverflow.com/a/47414016
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81781784
has comment: http://stackoverflow.com/comment/81781878
answers question: http://stackoverflow.com/q/47413270
has body: If you can figure out how to edit a file programmatically, doing it over SSH is not any more complicated, just two steps instead of one. import json newdata = { "kind": "PilotService", "apiVersion": "rbac.newDevops.com/v1", "type": "attribute-based", "metadata": { "name": "apache", "description": "apache service as a process" }, "spec": { "addresses": [ "172.22.0.7/24:80" ] } with open('services.json') as jdata: data = json.load(jdata) data.append(newdata) with open('services.json', 'w') as writable: writable.write(json.dump(data)) If you can save this script on the remote host, all you need is ssh remote python script.py but you might want to look into using Fabric or Paramiko to encapsulate the entire process. If the file is big, you might want to avoid the open file for reading, read into memory, close, open for writing, write pattern, but that's usually the most straightforward way to do it. (You can open for reading and writing, and rewind when you are done reading, but that doesn't really help against race conditions if you might have several processes writing to the same file.)

http://stackoverflow.com/comment/81817595
score: 0
type: Comment
has text: The string come from others, I can not modify it directly. Maybe I should handle it by myself.
type: AnswerComment
comment on: http://stackoverflow.com/a/47430850

http://stackoverflow.com/a/47466473
answers question: http://stackoverflow.com/q/47465219
score: 0
has body: You can load the saved tensorflow model and run the prediction from java. Check here Load the train_graph.pb file and use the feed and fetch function to send and receive data. You can follow the android tutorial
type: Answer

http://stackoverflow.com/a/47417878
answers question: http://stackoverflow.com/q/47417748
type: Answer
has body: You creare new data frame in each step of for element3 in element2 loop. Then you print such created data frame. What you should do instead is to create one (perhaps empty) DataFrame before loop, then for each element3 append row to existing data frame using append method, and finaly print result after leaving loop. BTW take a look at example at the end of mentioned link using pd.concat method. This one should be perfect for your needs.
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81790488

http://stackoverflow.com/q/47493313
has comment: http://stackoverflow.com/comment/81941752
duplicate of: http://stackoverflow.com/q/2123925
tagged with: python
has comment: http://stackoverflow.com/comment/81942024
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has title: difference in id() between list and string type in python
has body: Just for my curiosity, I was trying two different tests a='apple' b='apple' Here id(a) and id(b) returned same. But If i assign a=[1,2,3] b=[1,2,3] id() returns different value for both. Why id() is returning different value for list/dict while its returning same for a string type [ for same data content]?
linked to: http://stackoverflow.com/q/2123925

http://stackoverflow.com/comment/81747293
comment on: http://stackoverflow.com/q/47396866
has text: @Rawing read the first line of the question : "I need to replace the value inside a capture group of a regular expression with some arbitrary value", this is not what your solution is actually doing ...
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/81806906
has text: Try upgrading `pip` by using `pip install --upgrade pip`
comment on: http://stackoverflow.com/q/47425762
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81839310
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47437760
has text: @VipinKumar Did you look at python source? It's just 4 lines and yes, it works. It works even with node when I DON'T use imports.

http://stackoverflow.com/q/47537278
score: 1
tagged with: google-bigquery
has answer: http://stackoverflow.com/a/47537591
has answer: http://stackoverflow.com/a/47537354
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
favorite count: 0
tagged with: python-2.7
type: Question
has title: References from Python Bigquery Client don't work
has body: Im having troubles running the following code: from google.cloud import bigquery client = bigquery.Client.from_service_account_json(BQJSONKEY,project = BQPROJECT) dataset = client.dataset(BQDATASET) assert not dataset.exists() The following error pop up: 'DatasetReference' object has no attribute 'exists' Similarly when i do: table = dataset.table(BQTABLE) i get: 'TableReference' object has no attribute 'exists' However, according to the docs it should work: https://googlecloudplatform.github.io/google-cloud-python/stable/bigquery/usage.html#datasets here is my pip freeze (the part with google-cloud): gapic-google-cloud-datastore-v1==0.15.3 gapic-google-cloud-error-reporting-v1beta1==0.15.3 gapic-google-cloud-logging-v2==0.91.3 gevent==1.2.2 glob2==0.5 gmpy2==2.0.8 google-api-core==0.1.1 google-auth==1.2.1 google-cloud==0.30.0 google-cloud-bigquery==0.28.0 google-cloud-bigtable==0.28.1 google-cloud-core==0.28.0 google-cloud-datastore==1.4.0 google-cloud-dns==0.28.0 google-cloud-error-reporting==0.28.0 google-cloud-firestore==0.28.0 google-cloud-language==1.0.0 google-cloud-logging==1.4.0 google-cloud-monitoring==0.28.0 google-cloud-pubsub==0.29.1 google-cloud-resource-manager==0.28.0 google-cloud-runtimeconfig==0.28.0 google-cloud-spanner==0.29.0 google-cloud-speech==0.30.0 google-cloud-storage==1.6.0 google-cloud-trace==0.16.0 google-cloud-translate==1.3.0 google-cloud-videointelligence==0.28.0 google-cloud-vision==0.28.0 google-gax==0.15.16 google-resumable-media==0.3.1 googleapis-common-protos==1.5.3 I wonder how can i fix it and make it work?
tagged with: service-accounts

http://stackoverflow.com/comment/81795417
comment on: http://stackoverflow.com/a/47418827
score: 0
has text: What do you mean by "binary operation time"? And what is a "fixed variable"? It is possible to reflect the wish to use as few as possible machines in the objective, however not without setting an upper bound for available machines.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82021659
score: 0
comment on: http://stackoverflow.com/q/47532341
type: Comment
type: QuestionComment
has text: array([ 0. , 0.1, 0.2, 0.6, 0.4, 0.9, 0.7, 1. , 0.3, 0.5, 0.8])

http://stackoverflow.com/q/47534576
tagged with: python
type: UnansweredQuestion
has body: Is it possible in flask to seperate GET and POST to 2 functions and access the created wtform in the POST function? @app.route('/foo', methods=['GET']) def foo_get(): ... form = MyForm() # Initialize form ... return render_template('foo.html', form=form) @app.route('/foo', methods=['POST']) def foo_post(): ... # POST function for foo's form # access form here?
score: 0
tagged with: wtforms
upvote count: 1
tagged with: flask
downvote count: 1
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47534755
has title: flask wtform - access object in different function

http://stackoverflow.com/comment/81729197
score: 0
comment on: http://stackoverflow.com/a/47387464
has text: Yeah bro. Do you got any other ways
type: Comment
type: AnswerComment

soap
tags question: http://stackoverflow.com/q/47454744
tags question: http://stackoverflow.com/q/47433921
type: Tag
tags question: http://stackoverflow.com/q/47447506
tags question: http://stackoverflow.com/q/47476811
tag name: soap
tags question: http://stackoverflow.com/q/47540354

http://stackoverflow.com/comment/81939816
comment on: http://stackoverflow.com/a/47492147
type: Comment
has text: Let me set this up again
type: AnswerComment
score: 0

http://stackoverflow.com/q/47448566
accepted answer: http://stackoverflow.com/a/47448787
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81852292
score: 0
tagged with: python-packaging
has body: Ok so i'm trying to install scapy for python3, but ive been having some issues when I enter this command: pip install scapy This is the output: Collecting scapy Using cached scapy-2.3.3.tgz In the tar file C:\Users\MYNAME~1\AppData\Local\Temp\pip-oao3meyq- unpack\scapy-2.3.3.tgz the member scapy-2.3.3/README is invalid: unable to resolve link inside archive Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\MYNAME~1\AppData\Local\Temp\pip-build- qjegdxw6\scapy\setup.py", line 36 os.chmod(fname, 0755) ^ SyntaxError: invalid token ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\MYNAME~1\AppData\Local\Temp\pip-build-qjegdxw6\s capy\ So then I searched around and I tried using this: pip3 install scapy-python3 But it just says that pip3 isnt a command, so im not sure what to do
tagged with: scapy
answer count: 1
has title: Error when installing scapy
linked to: http://stackoverflow.com/q/6587507
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81852286
has answer: http://stackoverflow.com/a/47448787

http://stackoverflow.com/q/47438699
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has body: Just a question regarding some scraping authentication. Using BeautifulSoup: #importing the requests lib import requests from bs4 import BeautifulSoup #specifying the page page = requests.get("http://localhost:8080/login?from=%2F") #parsing through the api soup = BeautifulSoup(page.content, 'html.parser') print(soup.prettify()) From here the output, I think would be important: User: Password: Remember me on this computer This scrapes the website fine, but it requires a login. Here I am using the mechanicalsoup library: import mechanicalsoup browser = mechanicalsoup.StatefulBrowser() browser.open("http://localhost:8080/login?from=%2F") browser.get_url() browser.get_current_page() browser.get_current_page().find_all('form') browser["j_username"] = "admin" browser ["j_password"] = "password" browser.launch_browser() However it still won't let me login. Has anyone used a scraping tool for python 3 that lets them scrape a site that has authentication?
tagged with: python
accepted answer: http://stackoverflow.com/a/47442877
tagged with: mechanicalsoup
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81832222
possible better answer: http://stackoverflow.com/a/47442069
has answer: http://stackoverflow.com/a/47442877
has answer: http://stackoverflow.com/a/47442069
tagged with: web-scraping
has title: Scraping a website with python 3 that requires login
has comment: http://stackoverflow.com/comment/81832044
favorite count: 0

http://stackoverflow.com/comment/81987902
comment on: http://stackoverflow.com/q/47515975
score: 0
type: Comment
type: QuestionComment
has text: And what is your current state? How did you start working on it? On SO no one will implement you a working solution, you will only get some help building your own solution ;)

http://stackoverflow.com/comment/81909032
score: 0
comment on: http://stackoverflow.com/q/47477150
has text: I would have to `return self`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81855170
score: 0
has text: With this it detects rectangular like objects.... everything that can be fitted in a rectangle and that it covers most of the rectangle. The other way is to do line detections with hough transforms.... but for classification problems you should look for a machine learning approach
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47435625

http://stackoverflow.com/q/47387887
accepted answer: http://stackoverflow.com/a/47387898
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/47387898
tagged with: python
has title: Using a list as a value in a pandas dataframe
type: AnsweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has body: I have some data that I want to insert in a dataframe. The data is columns= ['Title', 'Category']. For each Titles I have one or more Categories, and I decided to insert the categories as a list. So my df looks like this: In [39]: title_cat_df Out[39]: Title Category 0 Title1 [Cat1, Cat2] 1 Title3 [Cat5] 2 Title2 [Cat3, Cat4] ... ... ... However I don't know if this is a pythonic/pandaionic(?!) approach, since I have stumbled upon problems such as looking for specific categories using isin: In [41]: test_df['Category'].isin(cat_list) Out[41]: TypeError: unhashable type: 'list' What would be a better way to represent categories in this case, and hopefully be able to look for titles in a specific category or categories?
favorite count: 0
type: Question

http://stackoverflow.com/q/47473442
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: normalization
has answer: http://stackoverflow.com/a/47475170
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47504603
has body: I'm using Tensorflow 1.4.0 &amp; Python 3.6 on Windows 10. I looked at other posts about the ordering of the values, but found nothing that worked so far. Thanks. import tensorflow as tf import numpy as np from sklearn.datasets import fetch_california_housing housing = fetch_california_housing() m, n = housing.data.shape housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data] #normalization scaled_housing_data_plus_bias = tf.nn.l2_normalize(housing_data_plus_bias, 1, epsilon=1e-12,name="Normalized") n_epochs = 1000 learning_rate = 0.01 #error occurs here X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") Traceback (most recent call last): File "C:/Users/tony/PycharmProjects/NNCourse/Hands-On_Book_5.py", line 14, in &lt;module&gt; X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") File "C:\Users\tony\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\constant_op.py", line 208, in constant value, dtype=dtype, shape=shape, verify_shape=verify_shape)) File "C:\Users\tony\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 383, in make_tensor_proto _AssertCompatible(values, dtype) File "C:\Users\tony\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 303, in _AssertCompatible (dtype.name, repr(mismatch), type(mismatch).__name__)) TypeError: Expected float32, got list containing Tensors of type '_Message' instead.
score: 3
answer count: 2
has title: TypeError: Expected float32, got list containing Tensors of type '_Message' instead
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/81935850
type: Comment
comment on: http://stackoverflow.com/q/47490230
has text: Okay. Thanks all, I get it now :)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81967496
comment on: http://stackoverflow.com/q/47505815
type: Comment
score: 0
has text: What problem are you facing? can you give us some information about the problem you are facing?
type: QuestionComment

http://stackoverflow.com/q/47521630
answer count: 2
tagged with: pandas
upvote count: 0
downvote count: 2
duplicate of: http://stackoverflow.com/q/15203623
has comment: http://stackoverflow.com/comment/82000035
favorite count: 0
has title: Need to get date range in Epoch format
has answer: http://stackoverflow.com/a/47521851
linked to: http://stackoverflow.com/q/35630098
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47521692
tagged with: time
has answer: http://stackoverflow.com/a/47521692
score: -2
tagged with: datetime
accepted answer: http://stackoverflow.com/a/47521851
tagged with: python
has body: Need to get range of current month in epoch format (From start and to the end of month, two variables, epoch format with milliseconds). How to do that? Maybe someone already did this and can help?
linked to: http://stackoverflow.com/q/15203623
type: Question

http://stackoverflow.com/comment/81921257
has text: I think you need loop, `for u in ['url1', 'url2']: dfs = pd.read_html(u)`
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47468201

http://stackoverflow.com/a/47461628
has body: I think you have incorrectly splitting instead of stripping. So you should be using: keyAnswer = keyLine.strip() studentAnswer = studentLine.strip()
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47461469
has comment: http://stackoverflow.com/comment/81879243
type: Answer
answers question: http://stackoverflow.com/q/47461469

gimp
tags question: http://stackoverflow.com/q/47463859
tag name: gimp
type: Tag
tags question: http://stackoverflow.com/q/47536186
tags question: http://stackoverflow.com/q/47495484

http://stackoverflow.com/q/47407200
has body: in my Django 'views, I create a pdf file and I want to download it. The file exist (path: /app/data/4.pdf) and i launch this command: def download_line(request): if not request.is_ajax() and not request.method == 'GET': raise Http404 try: fs =FileSystemStorage('/app/data') with fs.open('4.pdf') as pdf: response =HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition']='attachment; filename="4.pdf"' except Exception as e: logger.warning("Download Line | Erreur : " + e.message) return response But the download doesn't start and no error. Have you got a solution? Thanks.
has title: Django How to download existing file?
favorite count: 0
has answer: http://stackoverflow.com/a/53897129
type: Question
has comment: http://stackoverflow.com/comment/81767850
has answer: http://stackoverflow.com/a/47412196
has comment: http://stackoverflow.com/comment/81777122
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54072037
tagged with: python
has comment: http://stackoverflow.com/comment/81775360
answer count: 4
score: 2
tagged with: view
tagged with: download
has comment: http://stackoverflow.com/comment/81768521
upvote count: 2
linked to: http://stackoverflow.com/q/3749231
has answer: http://stackoverflow.com/a/60944587
downvote count: 0
has comment: http://stackoverflow.com/comment/81768957
linked to: http://stackoverflow.com/q/4545311
tagged with: django

http://stackoverflow.com/comment/82015778
type: Comment
type: AnswerComment
has text: Yes, that works as well ! Thanks a lot! Abhi -if img_hd_base['IMAGEZPT'] == UNDEFINED: img_hd_base['IMAGEZPT'] = 22 print(img_hd_base['IMAGEZPT']) - 22
score: 0
comment on: http://stackoverflow.com/a/47527374

http://stackoverflow.com/comment/81849092
comment on: http://stackoverflow.com/q/47446894
type: QuestionComment
has text: What does one divided by python mean in your question? It's the `1 / python` I don't understand.
score: 0
type: Comment

http://stackoverflow.com/comment/82000694
comment on: http://stackoverflow.com/q/47521328
has text: To insert null use the keyword NULL with no quotes.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47535920
type: Question
score: 3
type: UnansweredQuestion
has body: I built an input pipeline for a Convolutional Neural network using tensorflow. In particular, at evaluation time, I need to read an image from the disk and generate several ( it could be 100000) patches from it. This is done using tf.extract_image_patches. Then, I create batches (each of 2000 patches) and I feed them to the network. The problem is that the program allocates the whole tensor of the patches, causing an Out Of Memory issue of my 4GB GPU. I would expect that it just needs to allocate the batch involved in the evaluation at each step. Is there a workaround to avoid this? Error OOM when allocating tensor with shape[104720,50,50,3] [[Node: Cast = Cast[DstT=DT_FLOAT, SrcT=DT_UINT8, _device="/job:localhost/replica:0/task:0/device:GPU:0"](MirrorPad/_63)]] [[Node: Gather/_65 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_22_Gather", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] Minimal Code imagepath = tf.convert_to_tensor(imagepath, dtype=tf.string) image= tf.train.slice_input_producer(imagepath,shuffle=False,num_epochs=1) image = tf.read_file(image) image = tf.image.decode_jpeg(image, channels=3) image=tf.extract_image_patches(image, ksizes=[1,50, 50,1], strides=[1,25,25,1], rates=[1,1,1,1],padding="VALID") image=tf.reshape(image,(-1,50,50,3)) X = tf.train.batch([image], batch_size=2000, capacity=batch_size * 8, num_threads=1, allow_smaller_final_batch=True, enqueue_many=True )
tagged with: python
has comment: http://stackoverflow.com/comment/82028938
has comment: http://stackoverflow.com/comment/82036264
has comment: http://stackoverflow.com/comment/82038924
answer count: 0
upvote count: 3
downvote count: 0
has title: Out of Memoy when tf.extract_image_patches is called
has comment: http://stackoverflow.com/comment/82050399
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/a/47495864
has body: TL;DR In this situation I think I would opt to use the 4th option I present I'm going to present 4 options, some may be more viable than others. If you are worried about code duplication (DRY) for the code represented by execute you can simply define a function that both routes can call: def execute(): # execute, return a value if needed pass @app.route('/') def index(): execute() return render_template('index.html', body=body, block=block) @app.route('/api/') def api(): execute() return 'api' This is probably what you mean and looking for. However, if you want to actually provide two routes to the same function, you can do that also, just remember that they are getting scanned from top to bottom. Obviously you can't return 2 different values with this approach. @app.route('/') @app.route('/api/') def index(): # execute return render_template('index.html', body=body, block=block) A 3rd option, which may seem like an overkill (and/or cumbersome) for what you are looking but I will mention it for the sake of completeness. You can use a single route with an optional value, then decide what you want to return: @app.route('/') @app.route('/&lt;path:address&gt;/') def index(address=None): # execute if address is None: return render_template('index.html', body=body, block=block) elif address == 'api': return 'api' else: return 'invalid value' # or whatever else you deem appropriate A 4th (and last, I promise) option will be to direct the 2 routes to the same function and then use the request object to find what route the client requested: from flask import Flask, request @app.route('/') @app.route('/api') def index(): # execute if request.path == '/api': return 'api' return render_template('index.html', body=body, block=block)
answers question: http://stackoverflow.com/q/47495775
type: Answer
accepted answer of: http://stackoverflow.com/q/47495775
has comment: http://stackoverflow.com/comment/81947312
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81947278
score: 0
has comment: http://stackoverflow.com/comment/81947738

http://stackoverflow.com/a/47422515
has body: without regex: cond1 = any(c.isalpha() for c in password) cond2 = any(c.isnumber() for c in password) cond3 = any(word in password for word in '!$%^&amp;*()-_=+') valid = cond1 and cond2 and cond3
answers question: http://stackoverflow.com/q/47422360
score: 0
type: Answer

http://stackoverflow.com/comment/81986221
type: Comment
has text: Sure is. This seems to be the way the kids are writing code these days! But, hey, that is the requirement of the OP.
type: AnswerComment
comment on: http://stackoverflow.com/a/47515196
score: 0

http://stackoverflow.com/comment/83473595
has text: I am using Python 2.7 I just do "import stripe"
score: 0
comment on: http://stackoverflow.com/q/47468835
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47447400
upvote count: 8
accepted answer of: http://stackoverflow.com/q/47447220
type: Answer
has body: You need to use plt.xticks() as shown here. It controls what ticks and labels to use for your x-axis. In your example, you will have to add another line as shown below: for name in per_data.dtype.names[2:]: plt.plot(per_data['RELEASE'],per_data[name],label=name) plt.legend(loc='upper left',prop = {'size':7},bbox_to_anchor=(1,1)) plt.tight_layout(pad=5) plt.xlabel ('Release') plt.xticks (per_data['RELEASE']) plt.ylabel ('Time/Sec') plt.title ('Ingest Performance Test') plt.grid() plt.show()
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/47447220
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81850070

http://stackoverflow.com/comment/81842569
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47443491
has text: What I would do it figure out what time you want to use. Allow `X` seconds/minutes/hours to be the amount of time you would like the temperature to go from A to B and then model a sin curve after that
score: 0

http://stackoverflow.com/a/47390408
has body: Refer to JSON to pandas DataFrame it is very well described for normalizing JSON. Besides, you can to pass a parsing function for the json columns.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47389138

http://stackoverflow.com/a/47471089
has comment: http://stackoverflow.com/comment/81899682
has comment: http://stackoverflow.com/comment/81896978
answers question: http://stackoverflow.com/q/47470825
type: Answer
has comment: http://stackoverflow.com/comment/81899217
has body: By yielding the value, the caller of the function has access to the intermediate results, making this memory efficient. For example, the following would give you all results up to n as well, but requires that you create a list first to hold those values: def fibonacci(n): results = [] curr = 1 prev = 0 counter = 0 while counter &lt; n: results.append(curr) prev, curr = curr, prev + curr counter += 1 return results If my code then asked for fibonacci(10 ** 9), that would not only take a long time to produce, but would also require a significant amount of memory. The generator option gives the caller access to the results immediately, which means they can use just that one intermediate result in another part of the program.) This makes the generator function far more versatile and flexible. You could sum the fibonacci results, without having to rewrite the generator, for example: sum_of_fibonacci_10 = sum(fibonacci(10)) This is still memory efficient, the summing takes place as the results are produced, at no point do all 10 results have to exist in memory. Just the current intermediate value, and the sum total up to now, are required. If you wanted to just print the values instead, you can do so in a loop: for next_value in fibonacci(10): print(next_value) and the code is still just as efficient, and we still did not have to change the generator function. So generators let you maintain and share intermediate state, saving you memory. This can be done with a class too, but a generator is much more readable. The following would do the same, but is not nearly as easy to follow: class FibonacciGenerator: def __init__(self, n): self.n = n self.curr = 1 self.prev = 0 self.counter = 0 def __iter__(self): return self def __next__(self): if self.counter &gt;= self.n: raise StopIteration self.prev, self.curr = self.curr, self.prev + self.curr self.counter += 1 return self.prev
has comment: http://stackoverflow.com/comment/81896900
has comment: http://stackoverflow.com/comment/81898970
has comment: http://stackoverflow.com/comment/81899011
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47470825

http://stackoverflow.com/comment/81804771
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47424883
has text: Thanks but I forgot to mention that I am trying to use only the graphics file for this. Thanks anyway!

http://stackoverflow.com/comment/82021186
comment on: http://stackoverflow.com/q/47531532
score: 0
type: Comment
type: QuestionComment
has text: Why was [4,2] chosen over [2,4] in the final output?

http://stackoverflow.com/a/47408389
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81770090
has comment: http://stackoverflow.com/comment/81770122
type: Answer
has body: Please don't learn Python with this code. As mentioned by others, this code goes against many Python principles. One example: list is a Python builtin type. Don't overwrite it, especially not with a string instance! The code also mixes class and instance variables and doesn't use super() in subclasses. This code tries to simulate an iterator. So simply use an iterator: give_abcs = iter('ABCDEFG') give_123s = iter('12345') for _ in range(3): print(next(give_abcs)) print(next(give_123s)) # A # 1 # B # 2 # C # 3 If you really want to fix the above code, you could use: class GiveNext : def __init__(self, iterable) : self.i = - 1 self.iterable = iterable def giveNext(self) : self.i += 1 return self.iterable[self.i] giveABCs = GiveNext('ABCDEFG') give123s = GiveNext('12345') for _ in range(3): print(giveABCs.giveNext()) print(give123s.giveNext()) It outputs: A 1 B 2 C 3
upvote count: 1
answers question: http://stackoverflow.com/q/47407887

http://stackoverflow.com/q/47488586
score: 1
has comment: http://stackoverflow.com/comment/81934756
has comment: http://stackoverflow.com/comment/81934560
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/81934791
has comment: http://stackoverflow.com/comment/81933276
favorite count: 0
type: Question
has title: Python: Running subprocess.Popen on batch file in background stops on echo
has body: I'm trying to execute a batch-file in the background using subprocess popen but when there is a echo in the batch-file it stops executing. This is what i'm using in python: subprocess.Popen("test.bat", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) This is an example batch-file that im using for testing as my real batch-file failed so much: @ECHO OFF ECHO %date% %time%: Test 1 &gt;&gt; test.txt ECHO Test 1 ECHO %date% %time%: Test 2 &gt;&gt; test.txt ECHO Test 2 Executing this it almost always stops on "ECHO Test 1" as the text.txt file won't fill with the "Test 2" text. If you remove or comment out "ECHO Test 1" it works. In my real batch-file that is not this simple it also stops after echo so tried with multiple files. It works while executing the batch-file manually as it continues after the echo. I could do a workaround by removing the echo:s but then it doesn't work that well if you want to run the batch-file manually. Am I doing something wrong or is this how it is suppose to work?
tagged with: subprocess
type: UnansweredQuestion
tagged with: python-3.5
answer count: 1
has comment: http://stackoverflow.com/comment/81932206
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81932191
tagged with: batch-file
has comment: http://stackoverflow.com/comment/81933296
has answer: http://stackoverflow.com/a/47489928

http://stackoverflow.com/q/47440481
type: Question
has comment: http://stackoverflow.com/comment/81873885
score: 5
has comment: http://stackoverflow.com/comment/81874644
tagged with: pivot-table
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81873858
upvote count: 6
has body: I have the below pivot table: Fruit | | apple | orange | banana Market | # num bracket | | | :-----------------------------------------------------------: X | 100 | 1.2 | 1.0 | NaN Y | 50 | 2.0 | 3.5 | NaN Y | 100 | NaN | 3.6 | NaN Z | 50 | NaN | NaN | 1.6 Z | 100 | NaN | NaN | 1.3 I want to add in the below row at the bottom Fruit | apple | orange | banana Price | 3.5 | 1.2 | 2 So the new table looks like the below Fruit | x | apple | orange | banana Market | # num bracket | | | :-----------------------------------------------------------: X | 100 | 1.2 | 1.0 | NaN Y | 50 | 2.0 | 3.5 | NaN Y | 100 | NaN | 3.6 | NaN Z | 50 | NaN | NaN | 1.6 Z | 100 | NaN | NaN | 1.3 Price | | 3.5 | 1.2 | 2 Does any one have a quick in easy recommendation on how to do this?
tagged with: python
has title: Adding a row to an existing Pivot table
answer count: 2
tagged with: pandas
downvote count: 1
has answer: http://stackoverflow.com/a/66825041
has answer: http://stackoverflow.com/a/77171537
has comment: http://stackoverflow.com/comment/81873737
favorite count: 0

http://stackoverflow.com/q/47473356
has title: Passing a fixed query term to django-haystack
has body: I'm looking to make a page that displays a fixed set of search results using django-haystack. I already have a page that can be used to make searches using haystack's SearchView, and want to make a second page that by default shows the results from a specific search -- in this example, searching for all documents that contain Fruit. Here's my urls.py: from haystack.views import SearchView from django.conf.urls import url import haystack from .search_Queries import custom_query from .forms import CustomSearchForm urlpatterns = [ url(r'^fruit/', SearchView(form_class=CustomSearchForm, searchqueryset=custom_query)), url(r'^$', SearchView(form_class=haystack.forms.SearchForm, searchqueryset=custom_query), ] And I am trying to make the view display the initial Fruit search term by overriding the get_queryset method in the form -- however, this doesn't seem to be the correct way to go about it forms.py class CustomSearchForm(SearchForm): def get_queryset(self): queryset = super(CustomSearchForm, self).get_queryset() queryset = queryset.auto_query('Fruit') return queryset How can I display a set of search results for a specific term as the default in a view using django-haystack? I want to make a separate view so that my ^fruit/ URL shows the Fruit search results directly, rather than redirecting to /q=Fruit.
tagged with: django-haystack
type: Question
has answer: http://stackoverflow.com/a/47802562
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python
score: 0

http://stackoverflow.com/comment/81903953
type: QuestionComment
has text: HTTP 200 tells you the request was handled okay. What do you mean with 'no data' exactly?
score: 0
comment on: http://stackoverflow.com/q/47474294
type: Comment

http://stackoverflow.com/comment/81841085
type: QuestionComment
comment on: http://stackoverflow.com/q/47442944
has text: As an aside, that seems like an approach prone to errors. You overwriting the value `self.segundo = self._segundo.getCuenta()`, but `self._segundo` was a `Contador` object, now it is an `int`. Smells bad to me.
score: 0
type: Comment

http://stackoverflow.com/comment/81833998
type: Comment
comment on: http://stackoverflow.com/a/47439322
type: AnswerComment
score: 0
has text: @Martijn Yw~ :-)

http://stackoverflow.com/comment/128695306
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47496415
type: Comment
has text: The other duplicate was *clearly* a duplicate of the canonical; the goal was to use existing strings to create variable names procedurally. The goal here is to use a *single* string to *select an already existing* variable. The approach is wrong in the same way in both cases, and the same underlying advice applies, but this is clearly a different question and I've reopened it. https://stackoverflow.com/questions/9437726 is frighteningly bad for something so popular, but it's much more like this question than the variable-variables canonical. If anything, *it* is a duplicate of *this*.

http://stackoverflow.com/comment/81867080
type: Comment
type: AnswerComment
has text: I tried the solution but I still cannot access it from outside.
score: 0
comment on: http://stackoverflow.com/a/47456102

http://stackoverflow.com/a/47415143
has comment: http://stackoverflow.com/comment/81783808
type: Answer
has body: I'm guessing that when you say within the last month you mean the last 30 days, you would need timedelta for this example. from datetime import timedelta, datetime today = datetime.now() lastmonth = today - timedelta(days=30) tests = ['2017-11-21','2017-10-20'] for date in tests: if date &gt;= str(lastmonth): print(date) else: pass The result is : 2017-11-21 That's just an example on how to filter by date
accepted answer of: http://stackoverflow.com/q/47414684
has comment: http://stackoverflow.com/comment/81783868
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81784032
has comment: http://stackoverflow.com/comment/81784422
answers question: http://stackoverflow.com/q/47414684
has comment: http://stackoverflow.com/comment/81783910

http://stackoverflow.com/a/50291275
downvote count: 0
has body: Assuming you have plotted the data calling: fig = corner.corner(samples,show_titles=True,...) These values can be retrieved with the following code: for i in range(2): # must be done once per variable q_16, q_50, q_84 = corner.quantile(samples[:,i], [0.16, 0.5, 0.84]) # your x is q_50 dx_down, dx_up = q_50-q_16, q_84-q_50 # save and/or print them These will be the exact same values shown in the title (if rounded to the 2nd decimal place) because I have checked the corner.py source code for titles
accepted answer of: http://stackoverflow.com/q/47398380
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47398380
type: Answer
has comment: http://stackoverflow.com/comment/98197396
score: 3
upvote count: 3

networkx
tags question: http://stackoverflow.com/q/47501336
tags question: http://stackoverflow.com/q/47506378
tags question: http://stackoverflow.com/q/47466354
tags question: http://stackoverflow.com/q/47476655
tags question: http://stackoverflow.com/q/47415134
tags question: http://stackoverflow.com/q/47474891
tag name: networkx
tags question: http://stackoverflow.com/q/47393222
tags question: http://stackoverflow.com/q/47402177
tags question: http://stackoverflow.com/q/47415317
tags question: http://stackoverflow.com/q/47446817
tags question: http://stackoverflow.com/q/47387090
tags question: http://stackoverflow.com/q/47476419
type: Tag

http://stackoverflow.com/q/47393026
downvote count: 0
has comment: http://stackoverflow.com/comment/81738972
upvote count: 10
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81740021
tagged with: python-3.x
tagged with: syntax-error
has answer: http://stackoverflow.com/a/69461842
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47393831
score: 10
has body: SyntaxError: Non-UTF-8 code starting with '\x90' in file C:\Python36\python.exe on line 1, but no encoding declared I don't understand why it shows me that when I want to open the interpreter. Can someone help me please?
tagged with: python
has comment: http://stackoverflow.com/comment/135486638
has comment: http://stackoverflow.com/comment/81739416
has comment: http://stackoverflow.com/comment/81739917
has comment: http://stackoverflow.com/comment/81739072
has title: SyntaxError: Non-UTF-8 code starting with '\x90' in file C:\Python36\python.exe on line 1, but no encoding declared
has comment: http://stackoverflow.com/comment/81739852
answer count: 2
tagged with: syntax
has comment: http://stackoverflow.com/comment/81739101
has comment: http://stackoverflow.com/comment/81739676
has comment: http://stackoverflow.com/comment/81739459

http://stackoverflow.com/a/47448064
answers question: http://stackoverflow.com/q/47447955
downvote count: 0
upvote count: 1
has body: You can use np.all and np.where: np.where(np.all(a==template, axis=(1,2)))[0][0] # 1
score: 1
type: Answer

http://stackoverflow.com/a/47532099
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47531879
has body: There is always issues with using separated values. For instance, if the data is missing a comma, the second index lookup on data will fail. See simple program below that shows good and bad data. Before referencing data[1], make sure that it is not null. You could do the same for data[0] if there might be a blank line in the data. if data[1] is none room = "" else room = data[1]
downvote count: 0

http://stackoverflow.com/a/47580582
has comment: http://stackoverflow.com/comment/82280361
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: Your logs have the following statement:- ERROR ApplicationMaster: SparkContext did not initialize after waiting for 100000 ms. Please check earlier log output for errors. Failing the application. This arises typically if you are setting .master() in the SparkSession builder.
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47538689
answers question: http://stackoverflow.com/q/47538689

http://stackoverflow.com/comment/81888185
comment on: http://stackoverflow.com/q/47466304
type: QuestionComment
has text: Please add some images and code so that you can get better help
score: 0
type: Comment

http://stackoverflow.com/comment/81882065
comment on: http://stackoverflow.com/q/47463612
has text: I recommend to print each single part; that will help you to understand what is going on.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47511425
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81979985
accepted answer of: http://stackoverflow.com/q/47511255
has body: You can do it in template like : %for row in rows: %for col in row: {{col}} %end %end
score: 3
answers question: http://stackoverflow.com/q/47511255
has comment: http://stackoverflow.com/comment/81979937
type: Answer

http://stackoverflow.com/comment/82023546
score: 0
type: Comment
type: QuestionComment
has text: You haven't shown where the static files are actually located in your project.
comment on: http://stackoverflow.com/q/47533323

http://stackoverflow.com/q/47492343
has title: writing data to columns in excel with openpyxl after
tagged with: python
tagged with: excel
score: 0
has body: Back again... So now, I've been able to get my data pulled into python with openpyxl and have the calculations completed, but now I'm stuck on how to get it printed back out to another sheet. The below only prints the last gross value to the referenced cell, which obviously is not what I would like my outcome to be. I need the row increased and the gross values printed to the excel file. in B2, B3, etc... Referencing the "gross" back with the name of the individual, which is in my dictionaries, and printing that to the third sheet would be even better, so names in A1:Ax and gross B1:Bx. Help getting to either would be greatly appreciated! Thanks wb = openpyxl.load_workbook("Test_book.xlsx") sheet=wb.get_sheet_by_name('Hours') employee_names=[] employee_hours=[] for row in sheet['A']: employee_names.append(row.value) for row in sheet['B']: employee_hours.append(row.value) print(employee_names) print(employee_hours) my_dict=dict(zip(employee_names,employee_hours)) print(my_dict) sheet2=wb.get_sheet_by_name('Rate') employee_names2=[] employee_Rate=[] for row in sheet2['A']: employee_names2.append(row.value) for row in sheet2['B']: employee_Rate.append(row.value) print(employee_names2) print(employee_Rate) my_dict2=dict(zip(employee_names2,employee_Rate)) print(my_dict2) sheet3=wb.get_sheet_by_name('payable') #pulls key from dictionary, multiples it by other number for row in sheet['A']: if row.value in my_dict: gross=(float(my_dict[row.value]*float(my_dict2[row.value]))) print(format(gross,'.2f')) sheet3.cell(row=2,column=2).value=gross wb.save("Test_book.xlsx")
answer count: 1
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47531523
tagged with: openpyxl

http://stackoverflow.com/comment/81953028
type: QuestionComment
has text: @chepner, yes, I would prefer a safer method.
type: Comment
comment on: http://stackoverflow.com/q/47498863
score: 0

http://stackoverflow.com/a/47503818
answers question: http://stackoverflow.com/q/47503531
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47503531
has body: With the instruction self.canvas_widget = MyCanvas(key=unicode(key_name)) you are creating a new widget that does not have a parent so it is not shown, besides it is advisable not to create a new widget since it is a memory expense unnecessary, what you must reuse the widget for it I wrote the setKey method that internally call the compute_initial_figure method that is responsible for redrawing reusing the scatter. from matplotlib.backends.qt_compat import QtCore, QtGui from matplotlib.backends.backend_qt4agg import (FigureCanvasQTAgg as FigureCanvas) from matplotlib.figure import Figure import sys class MyCanvas(FigureCanvas): def __init__(self, parent=None, key="case 1"): self.case_dict = {"case 1": [2, 4, 6, 8, 10], "case 2": [3, 4, 5, 6, 7]} self.key = key self.fig = Figure() self.axes = self.fig.add_subplot(111) FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.updateGeometry(self) self.sc = None self.compute_initial_figure() def setKey(self, key): self.key = key self.compute_initial_figure() def compute_initial_figure(self): x = [1, 2, 3, 4, 5] y = self.case_dict[self.key] self.axes.set_title("%s" % self.key) if self.sc is None: self.sc = self.axes.scatter(x, y) else: import numpy as np data = np.stack((np.asarray(x), np.asarray(y)), axis=1) self.sc.set_offsets(data) self.draw() class MainWindow(QtGui.QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.canvas_widget = MyCanvas() self.combo = QtGui.QComboBox() for key in MyCanvas().case_dict: self.combo.addItem(key) self.combo.setCurrentIndex(-1) self.combo.currentIndexChanged.connect(self.showPlot) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.canvas_widget) layout.addWidget(self.combo) def showPlot(self): key_name = self.combo.currentText() self.canvas_widget.setKey(unicode(key_name))
type: Answer

http://stackoverflow.com/comment/95551761
comment on: http://stackoverflow.com/a/47422997
type: Comment
has text: @Eswar - In some step (I don't know where) between the client and the database table, something was "utf8" when it needed to be "utf8mb4". Note: MySQL's "utf8" is not the same as the outside worlds "UTF-8", which does correspond to "utf8mb4".
type: AnswerComment
score: 0

http://stackoverflow.com/q/47498189
answer count: 2
downvote count: 2
duplicate of: http://stackoverflow.com/q/26506727
tagged with: line
tagged with: skip
has body: file1=open("filex.txt","r") line=file1.readline() for line in file1: print(line,end="") So this prints out all the lines in the file, except the first line for some reason, help me out please!
favorite count: 0
has comment: http://stackoverflow.com/comment/81951595
possible better answer: http://stackoverflow.com/a/47498217
tagged with: list
accepted answer: http://stackoverflow.com/a/47498206
type: Question
has title: Printing skips the first line
has answer: http://stackoverflow.com/a/47498217
has answer: http://stackoverflow.com/a/47498206
tagged with: python
has comment: http://stackoverflow.com/comment/81951593
linked to: http://stackoverflow.com/q/26506727
upvote count: 2
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47407720
tagged with: database
has comment: http://stackoverflow.com/comment/81768609
upvote count: 1
tagged with: python
has title: What is the best way to extract certain strings from a json database with python?
has comment: http://stackoverflow.com/comment/81768721
answer count: 2
downvote count: 3
has body: I have a large data base such as this: {'gifts': [{'id': 603988529, 'created_at': 1511248537, 'item_id': 11, 'item_type': 'Point::Stone', 'quantity': 1, 'description': 'Compensation for the incorrect item names and an incorrect banner description'}, {'id': 603988528, 'created_at': 1511248537, 'item_id': 932, 'item_type': 'SpecialItem', 'quantity': 2, 'description': '"Dokkan Thank-You Celebration" Login Bonus!'}, {'id': 603988527, 'created_at': 1511248537, 'item_id': 931, 'item_type': 'SpecialItem', 'quantity': 2, 'description': '"Dokkan Thank-You Celebration" Login Bonus!'}, {'id': 603988526, 'created_at': 1511248537, 'item_id': 1004, 'item_type': 'TrainingItem', 'quantity': 5, 'description': '"Dokkan Thank-You Celebration" Login Bonus!'}, {'id': 603988525, 'created_at': 1511248537, 'item_id': 1003, 'item_type': 'TrainingItem', 'quantity': 5, 'description': '"Dokkan Thank-You Celebration" Login Bonus!'}, {'id': 603988524, 'created_at': 1511248537, 'item_id': 1002, 'item_type': 'TrainingItem', 'quantity': 5, 'description': '"Dokkan Thank-You Celebration" Login Bonus!'}, {'id': 603988523, 'created_at': 1511248537, 'item_id': 1001, 'item_type': 'TrainingItem', 'quantity': 5, 'description': '"Dokkan Thank-You Celebration" Login Bonus!'}, {'id': 603988522, 'created_at': 1511248537, 'item_id': 1000, 'item_type': 'TrainingItem', 'quantity': 5, 'description': '"Dokkan Thank-You Celebration" Login Bonus!'}]} and I would like to write some code to extract every number after "ID" and put it into a table. so that i can get [603988529, 603988528....] until all the IDs are extracted Thanks
has comment: http://stackoverflow.com/comment/81768612
has answer: http://stackoverflow.com/a/51285195
has answer: http://stackoverflow.com/a/47408096
favorite count: 0
has comment: http://stackoverflow.com/comment/81768629
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: -2

http://stackoverflow.com/comment/81825708
comment on: http://stackoverflow.com/q/47434127
has text: @Rloqvist i added the link if u can do more with it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47420099
has body: a and a.T are two views of the same data. In earlier NumPy versions, when you do a += a.T cell updates that occur earlier in the process may cause later addition operations to use the updated values instead of the original values. For example, as part of a += a.T, NumPy might perform a[0, 99] += a[99, 0] to update a[0, 99], and then later perform a[99, 0] += a[0, 99] to update a[99, 0], using the new value of 2 for a[0, 99] instead of the original value of 1. NumPy 1.13 changes the semantics, guaranteeing that the original values will be used, so you won't see this problem in updated versions of NumPy.
answers question: http://stackoverflow.com/q/47419879
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/47384578
tagged with: pyqt4
downvote count: 0
has comment: http://stackoverflow.com/comment/81722459
tagged with: python
type: AnsweredQuestion
has body: Is there a PyQt QTextEdit method that disables selecting/highlighting of and/or right-clicking on displayed text? Or at least disables clipboard functions such as copy? Thanks. To clarify none-duplicity of this question, I'm talking about this. I want none of that highlight thing when trying to click and drag across part of the displayed text.
answer count: 2
score: 2
tagged with: pyqt
has title: How to make Qtextedit text and non-selectable?
possible better answer: http://stackoverflow.com/a/47385284
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47385284
accepted answer: http://stackoverflow.com/a/47385373
upvote count: 2
has answer: http://stackoverflow.com/a/47385373

http://stackoverflow.com/q/47437879
tagged with: twine
tagged with: nexus
type: UnansweredQuestion
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/57086211
has title: How to upload a PyPI package to Nexus3
tagged with: nexus3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83053614
has body: I am new to Nexus3, I am following the instruction here to upload a PyPI package (python v2.7): https://books.sonatype.com/nexus-book/3.0/reference/pypi.html However, I got the following message prevent me from uploading the the package. HTTPError: 401 Client Error: Unauthorized for url I did the following steps and not sure if I missed anything: 1. Setup blob and repo name in Nexus3 2. Copy the url to .pypirc 3. python setup.py sdist; twine upload -r nexus3 dist/[secure]-0.1.0.tar.gz Please suggest, Thanks!
tagged with: pypi
has comment: http://stackoverflow.com/comment/83112833
favorite count: 0
type: Question
score: 5
has comment: http://stackoverflow.com/comment/88789143

http://stackoverflow.com/comment/81859971
type: AnswerComment
comment on: http://stackoverflow.com/a/47446137
has text: And actually you didn't address the startswith requirement with this.
type: Comment
score: 0

http://stackoverflow.com/comment/81937871
type: AnswerComment
comment on: http://stackoverflow.com/a/47483531
has text: @Vondoe79 Always :)
score: 0
type: Comment

http://stackoverflow.com/a/47465778
has body: You can use regex as shown: import re string="soupnot$23.99dedarikjdf$44.65 notworryfence$98.44coyoteugle$33.94rock$2,300.00" res = re.findall(pattern="[\d.,]+", string=string) output: ['23.99', '44.65', '98.44', '33.94', '2,300.00']
has comment: http://stackoverflow.com/comment/81886237
type: Answer
answers question: http://stackoverflow.com/q/47465748
has comment: http://stackoverflow.com/comment/81886573
accepted answer of: http://stackoverflow.com/q/47465748
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81995720
type: AnswerComment
has text: See my edit. Hopefully you understand what I'm doing.
comment on: http://stackoverflow.com/a/47501764
type: Comment
score: 0

http://stackoverflow.com/a/47534874
downvote count: 0
has body: This is logical. If you write a lexical scope (like if), even after the semicolon, it is still under the if. For example: &gt;&gt;&gt; if False: print('a'); print('b') ... &gt;&gt;&gt; (prints nothing) So: if False: print('a'); print('b') is equivalent to: if False: print('a') print('b') # also under the if Since introducing a new scope makes it terribly hard to understand, the syntax is not allowed in Python. It would create ambugity. So the statement you wrote was incorrect: you would have scoped the if not y under the if not x, which was not what you meant.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47534724
has comment: http://stackoverflow.com/comment/82026587
score: 2

http://stackoverflow.com/a/47539156
answers question: http://stackoverflow.com/q/47538996
has body: So I wrote a type inspector awhile back that has served me well, because as asked we can only guess as to the type of the data when it's output as a string. For all we know it could be an object of type Person or Frombulate who chooses to str() as given. def type_diver(obj, prefix="", index = ""): print "%s'%s': %s%s" % (prefix, obj, type(obj), " - Accessible via " + index if index else "") if not isinstance(obj, str): try: for ind, elem in enumerate(obj): type_diver(elem, " " * len(prefix) + "|---", index + "[%s]" % ind) except TypeError: pass # Don't call recursively on non-iterable objects Which, for a basic python object gives, on your input: '[(451, 165, 76, -77, [98, 42])]': &lt;type 'list'&gt; |---'(451, 165, 76, -77, [98, 42])': &lt;type 'tuple'&gt; - Accessible via [0] |---'451': &lt;type 'int'&gt; - Accessible via [0][0] |---'165': &lt;type 'int'&gt; - Accessible via [0][1] |---'76': &lt;type 'int'&gt; - Accessible via [0][2] |---'-77': &lt;type 'int'&gt; - Accessible via [0][3] |---'[98, 42]': &lt;type 'list'&gt; - Accessible via [0][4] |---'98': &lt;type 'int'&gt; - Accessible via [0][4][0] |---'42': &lt;type 'int'&gt; - Accessible via [0][4][1] But I could write a custom class which str() output looks like that. The only way to know is to ask. If your data is as hpaulj suggested [a numpy array], you might see something like: '[(451, 165, 76, -77, [98, 42])]': &lt;type 'numpy.ndarray'&gt; |---'(451, 165, 76, -77, [98, 42])': &lt;type 'numpy.void'&gt; - Accessible via [0] |---'451': &lt;type 'numpy.int32'&gt; - Accessible via [0][0] |---'165': &lt;type 'numpy.int32'&gt; - Accessible via [0][1] |---'76': &lt;type 'numpy.int32'&gt; - Accessible via [0][2] |---'-77': &lt;type 'numpy.int32'&gt; - Accessible via [0][3] |---'[98 42]': &lt;type 'numpy.ndarray'&gt; - Accessible via [0][4] |---'98': &lt;type 'numpy.int32'&gt; - Accessible via [0][4][0] |---'42': &lt;type 'numpy.int32'&gt; - Accessible via [0][4][1] Given everyone will have a different object they …
has comment: http://stackoverflow.com/comment/82035416
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82035341

http://stackoverflow.com/q/47539025
has comment: http://stackoverflow.com/comment/82035459
upvote count: 0
has answer: http://stackoverflow.com/a/47539245
linked to: http://stackoverflow.com/q/301068
tagged with: python
accepted answer: http://stackoverflow.com/a/47539245
score: -1
has comment: http://stackoverflow.com/comment/82035305
duplicate of: http://stackoverflow.com/q/1436703
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47539148
answer count: 2
has title: python 2.7 -remove backslash from unicode
has comment: http://stackoverflow.com/comment/82035402
has body: I have this unicode xx = u"Merci d'avoir acheté Electricité mobile, votre SPS sera activé prochainement" when i print it it looks ok when i want to compare this xx the unicode appears like this u'Merci d\'avoir acheté Electricité mobile, votre SPS sera activé prochainement' i want to remove this backslash i tried like this but get exception ddd=xx.decode('string_escape') EncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128) any help will be appriciated
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/24085680
has answer: http://stackoverflow.com/a/47539148

http://stackoverflow.com/comment/81837023
type: AnswerComment
has text: eval doesn't work that way - but anyway if you don't know beforehand how many players you have using a dict is the only sane solution. How would you know which variables have been defined else?
comment on: http://stackoverflow.com/a/47439282
score: 0
type: Comment

http://stackoverflow.com/q/47538602
has answer: http://stackoverflow.com/a/47542900
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82037077
has body: I have the following model defined. class Response(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) STATEMENT_CHOICES = ( (-1, "Strongly Disagree"), (-0.5, "Somewhat Disagree"), (0, "Uncertain"), (0.5, "Somewhat Agree"), (1, "Strongly Agree"), ) statement = models.DecimalField( max_digits=2, decimal_places=1, choices = STATEMENT_CHOICES ) def __str__(self): return self.statement when I run the django shell, I create a question q that says you like pizza and response r which is 1 for strongly agree. then when I run the __str__ method on r I get an error saying name 'statement' is not defined. Here is the exact console output... &gt;&gt;&gt; q &lt;Question: You like pizza.&gt; &gt;&gt;&gt; r = Response(question=q, statement=1) &gt;&gt;&gt; r.question &lt;Question: You like pizza.&gt; &gt;&gt;&gt; r.statement 1 &gt;&gt;&gt; r Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/Users/TN/Documents/Programming/Django/Practice/myve /lib/python3.5/site-packages/django/db/models/base.py", line 572, in __repr__ u = six.text_type(self) File "/Users/TN/Documents/Programming/Django/Practice/mysite/personalityQuiz/models.py", line 48, in __str__ return self.statement NameError: name 'statement' is not defined
tagged with: nameerror
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
tagged with: django-models
has comment: http://stackoverflow.com/comment/82034436
has comment: http://stackoverflow.com/comment/82034171
favorite count: 0
type: Question
has title: Django - __str__ method not working, says name is not defined
accepted answer: http://stackoverflow.com/a/47542900

http://stackoverflow.com/q/47515996
favorite count: 0
has answer: http://stackoverflow.com/a/47516130
accepted answer: http://stackoverflow.com/a/47516130
type: Question
has title: Apply function to every column value of each row using pandas
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
has body: For this dataframe : columns = ['A','B', 'C'] data = np.array([[1,2,2] , [4,5,4], [7,8,18]]) df2 = pd.DataFrame(data,columns=columns) df2['C'] If the difference between consecutive rows for column C is &lt;= 2 then the previous and current row should be returned. So I'm attempting to filter out rows where difference for previous row > 2. So expecting these array values to be returned : [1,2,2] [4,5,4] [7,8,18] I'm attempting to implement this functionality using the shift function : df2[(df2.A - df2.shift(1).A &gt;= 2)] The result of which is : A B C 1 4 5 4 2 7 8 18 I think need to apply function to each row in order to achieve this ? Update : Alternative use case : columns = ['A','B', 'C'] data = np.array([[1,2,2] , [2,5,3], [7,8,16]]) df2 = pd.DataFrame(data,columns=columns) df2[df2.A.diff().shift(-1) &gt;= 2] Returned is : A B C 1 2 5 3 but expecting A B C 1 2 5 3 1 7 8 16 so in this case expecting the next and current row to be returned as difference between 2 &amp; 8 in 2 5 3 &amp; 8 8 18 is > 2 Update 2 : Edge case : if the last value being compared is &lt; 2 then the row is ignored columns = ['A','B', 'C'] data = np.array([[2,2,2] , [3,5,3], [5,8,16], [6,8,16]]) df2 = pd.DataFrame(data,columns=columns) df2[df2.A.diff().shift(-1).ffill() &gt;= 2] returns : A B C 1 3 5 3

http://stackoverflow.com/a/47412536
has comment: http://stackoverflow.com/comment/81780748
type: Answer
answers question: http://stackoverflow.com/q/47409228
has comment: http://stackoverflow.com/comment/81780110
has comment: http://stackoverflow.com/comment/81779468
has comment: http://stackoverflow.com/comment/81781120
has comment: http://stackoverflow.com/comment/81780189
has comment: http://stackoverflow.com/comment/81780494
has body: You can get a user's permissions by user.user_permissions.all() and the inverse by Permission.objects.difference(user.user_permissions.all()). But if you have take into account group permissions as well, you have to do something more complicated. An alternative solution, since there was problems with QuerySet.difference() in your setup. current_permissions = Permission.objects.filter(user=user) available_permissions = Permission.objects.exclude(user=user)
score: 0
has comment: http://stackoverflow.com/comment/81780423

http://stackoverflow.com/comment/81854227
comment on: http://stackoverflow.com/a/47432538
type: Comment
score: 0
has text: Hi Varun, you can access them using their index. Say you want to access the "New File" element. It is the first element of the subMenu and the first element also in that element, so you can access it using `subMenu[0][0]`.
type: AnswerComment

http://stackoverflow.com/a/47544958
has comment: http://stackoverflow.com/comment/82105829
type: Answer
accepted answer of: http://stackoverflow.com/q/47483033
has comment: http://stackoverflow.com/comment/82157776
has comment: http://stackoverflow.com/comment/82106259
has comment: http://stackoverflow.com/comment/82157550
has body: What you ask is not easy because it depends on a variety of factors: What is the frequency of the data received? How many clients are expected to connect to this server? Is there a chance two clients try to connect at the same time? How long it takes to handle some received data? What do you need to do with your data? Write to a database? Write to a file? Calculate something? Etc. Depending on your answer you'll have some design decisions to make for your solution. But since you need an answer, here's a hack that represent a way to do things: import socketserver import threading import datetime class SleepyGaryReceptionHandler(socketserver.BaseRequestHandler): log_file_name = "/tmp/sleepygaryserver.log" def handle(self): # self.request is defined in BaseRequestHandler data_received = self.request.recv(1024) # self.client_address is also defined in BaseRequestHandler sender_address = self.client_address[0] # This is where you are supposed to do something with your data # This is an example self.write_to_log('Someone from {} sent us "{}"'.format(sender_address, data_received)) # A way to stop the server from going on forever # But you could do this other ways but it depends what condition # should cause the shutdown if data_received.startswith(b"QUIT"): finishing_thread = threading.Thread(target=self.finish_in_another_thread) finishing_thread.start() # This will be called in another thread to terminate the server # self.server is also defined in BaseRequestHandler def finish_in_another_thread(self): self.write_to_log("Shutting down the server") self.server.shutdown() # Write something (with a timestamp) to a text file so that we # know something is happenning def write_to_log(self, message): timestamp = datetime.datetime.now() timestamp_text = timestamp.isoformat(sep=' ', timespec='seconds') with open(self.log_file_name, mode='a') as log_file: log_file.write("{}: {}\n".format(timestamp_text, message)) service_address = "localhost" port_number = 49101 server = socketse…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47483033
score: 0

http://stackoverflow.com/comment/81909983
has text: _"... linear in time and space, whatever the data."_ Are you sure of that? I'm not an expert but I seem to remember that hash tables have terrible worst case.
score: 0
comment on: http://stackoverflow.com/a/47476910
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47525773
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47528873
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/47526761
has answer: http://stackoverflow.com/a/47526761
favorite count: 0
tagged with: numpy
has body: Is it possible to use np.bincount but get the max instead of sum of weights? Here, bbb at index 3 has two values, 11.1 and 55.5. I want to have 55.5, not 66.6. I doubt I choose use other function but not so sure which one is good for this purpose. bbb = np.array([ 3, 7, 11, 13, 3]) weight = np.array([ 11.1, 22.2, 33.3, 44.4, 55.5]) print np.bincount(bbb, weight, minlength=15) OUT &gt;&gt; [ 0. 0. 0. 66.6 0. 0. 0. 22.2 0. 0. 0. 33.3 0. 44.4 0. ] Note that, in fact, bbb and weight are very large (about 5e6 elements).
type: Question
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47527239
linked to: http://stackoverflow.com/q/47526056
has answer: http://stackoverflow.com/a/47527239
has title: numpy bincount - choose the max weight instead of sum all weights
tagged with: python-2.7

http://stackoverflow.com/comment/82033833
score: 0
type: AnswerComment
has text: Perhaps -- but when I remove the redundant `print` and run this in Python 3, it works fine.
comment on: http://stackoverflow.com/a/47538335
type: Comment

http://stackoverflow.com/comment/81873170
comment on: http://stackoverflow.com/q/47459078
type: Comment
type: QuestionComment
has text: what is input? can u put snippest
score: 0

http://stackoverflow.com/comment/81720877
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47383842
score: 1
has text: @OlafSzmidt PyCharm tells you it *may* be a static method because it isn't mandatory, regardless of it using `self`. It's up to you. One reason to have an instance method without `self` is if you currently aren't using instance information but think that you may want to in the future. Another thing to consider when you have a `staticmethod` is whether it makes sense to move it out of the class.

http://stackoverflow.com/comment/81755942
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the response, although I tried to pickle.dump the final list from the client but ended with EOF error at server receiver end, and because everything is working as expected except storing data in SQLite, I don't want to manipulate client or server-side script. If I could convert received string into a dictionary then it would be easy to process all into SQLite.
comment on: http://stackoverflow.com/a/47400465

http://stackoverflow.com/comment/82039445
type: Comment
type: QuestionComment
has text: Another thing that has not been mentioned yet: if you install opencv with `pip install opencv` or `opencv-contrib` on linux / osx, it is not compiled with video support, because of ffmpeg support. To fix this, you often have to build from source. (See also [the faq on PyPi](https://pypi.python.org/pypi/opencv-python)) I'm not 100% sure `VideoCapture` falls into this category though.
score: 0
comment on: http://stackoverflow.com/q/47533291

http://stackoverflow.com/a/47603453
has comment: http://stackoverflow.com/comment/82190536
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82174243
answers question: http://stackoverflow.com/q/47406062
downvote count: 0
has comment: http://stackoverflow.com/comment/82190478
has body: Approach 1 -- masking + resample for r in ['R1','R2']: df['new'+r] = ((df.Type=='Data')&amp;(df.Retry==1)&amp;(df.Receiver==r)).astype(int) df'newR1','newR2'.resample('s').sum() Approach 2 -- unstacking + resample df=df[df.Type=='Data'].set_index('Receiver',append=True) df['Retry'].unstack().resample('s').sum().fillna(0) Results with either approach are essentially the same, with some minor formatting differences (this is the output from Approach 1): newR1 newR2 Index 1970-01-01 00:00:00 1 0 1970-01-01 00:00:01 0 1 1970-01-01 00:00:02 1 2 1970-01-01 00:00:03 0 1 Quick discussion of different methods: In many cases, both unstack and pivot_table can be used to accomplish similar tasks, as in this case. But pivot_table (as in @Dark's answer) seems clearly superior in this case (but I'll leave my unstack answer here solely for comparison purposes).
type: Answer

http://stackoverflow.com/comment/81828480
has text: @brunodesthuilliers You were right! The XML file was copied from a Windows system and the Python script was running on a Linux system. After careful inspection of the source, a BOM was indeed present. Removing it solves the problem. Many thanks!
type: Comment
comment on: http://stackoverflow.com/q/47434428
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81923542
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47413719
has text: Ok, I post some core code.
score: 0

http://stackoverflow.com/q/47437308
tagged with: python
has comment: http://stackoverflow.com/comment/81990830
tagged with: http://stackoverflow.com/tag/xml
score: 0
answer count: 0
has body: I have a 1GB xml file but it has some invalid characters like '&amp;'. I want to parse it in Python. To do this, I used element tree as below: import xml.etree.cElementTree as cElementTree def main(): context = cElementTree.iterparse('newscor.xml', events=("start", "end")) context = iter(context) event, root = context.__next__() for event, elem in context: if event == "start": if elem.tag == 'group': elem.tail = None print ( elem.text) if elem.tag in ['group']: root.clear() main() But it gave me following error in this line for event, elem in context: xml.etree.ElementTree.ParseError: not well-formed (invalid token) To handle this error, I tried to use lxml with recover=True for parser as described in this link. However, iterparse() does not have a parameter for parser in lxml. Therefore, I also tried to use Sax in this solution but I don't know where to use escape method. What can I use to avoid invalid characters and parse this large file?
has comment: http://stackoverflow.com/comment/81846922
tagged with: sax
tagged with: elementtree
linked to: http://stackoverflow.com/q/13046240
type: Question
has title: Parsing huge xml file with invalid characters
linked to: http://stackoverflow.com/q/42325244
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81829026

http://stackoverflow.com/q/47525536
answer count: 2
has comment: http://stackoverflow.com/comment/82008947
has comment: http://stackoverflow.com/comment/82009361
has comment: http://stackoverflow.com/comment/82008217
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82011266
has body: import csv data=[['p52264'], ['p52265'], ['p52266'], ['p52267'], ['p52268'], ['p52269'], ['p52270'], ['p52271'], ['p52272'], ['p52273'], ['p52274'], ['p52275'], ['p52276'], ['p52277'], ['p52278'], ['p52279'], ['p52280'], ['p52281'], ['p52282'], ['p52283']] print(data=[2:]) i want to remove only two first character from each word. import pandas as pd import csv data=[] ifile = open('skills.csv', "r") read = csv.reader(ifile) for row in read : data.append(row[:1]) print(len(data)) print(data[0]) new_data=[] for i in range(0, len(data)): if i%2!=0: new_data.append(data[i]) print(len(new_data)) with open('newskills.csv', 'w') as f: for i in range(0, len(new_data)): m_data=(new_data[i]) writer=csv.writer(f) w_data=m_data[0][2:] writer.writerows(w_data) I want to write this in csv file but it write only one charcter in one row
type: Question
has comment: http://stackoverflow.com/comment/82009217
has comment: http://stackoverflow.com/comment/82011356
has comment: http://stackoverflow.com/comment/82007609
has answer: http://stackoverflow.com/a/47525563
tagged with: python
has title: Delete some certain character by position in a list using python
has comment: http://stackoverflow.com/comment/82007037
has comment: http://stackoverflow.com/comment/82008926
has answer: http://stackoverflow.com/a/47525642
has comment: http://stackoverflow.com/comment/82009108
tagged with: python-3.5
score: 0

http://stackoverflow.com/a/47440427
answers question: http://stackoverflow.com/q/47440034
type: Answer
has comment: http://stackoverflow.com/comment/81847198
has body: After digging and digging, I finally found the bit of documentation that saved me! Logger.propagate If this evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered. If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers. The constructor sets this attribute to True. Setting log.propagate = False ended my misfortune. It would appear that the 1st use of the default logger through logging.info has initialized the default logger and from that moment the propagation started having an effect.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47440034
score: 1

http://stackoverflow.com/comment/81849350
type: QuestionComment
score: 0
has text: Try monkey patching above your imports, not below.
type: Comment
comment on: http://stackoverflow.com/q/47444541

http://stackoverflow.com/comment/81814987
comment on: http://stackoverflow.com/q/47422493
type: QuestionComment
type: Comment
score: 0
has text: My question was not clear enough. The text I want to start with looks like 'Hello the formula is $\int_{-\infty}^{\infty} f(x)-...$' without any | signs. The | show where I want to split the text into different strings. Best regards

http://stackoverflow.com/q/47403510
has comment: http://stackoverflow.com/comment/81787877
type: Question
has comment: http://stackoverflow.com/comment/81763074
has comment: http://stackoverflow.com/comment/81787790
tagged with: automation
type: UnansweredQuestion
tagged with: dataset
tagged with: python
has comment: http://stackoverflow.com/comment/81795718
has title: How to capture web table to language specific data structure without using external file in python
score: 0
answer count: 0
tagged with: pandas
has body: I am working on Selenium automation. My Web application has a web table and few functions on screen which alters web table data, i.e. merges rows, add two rows, sorting on columns, many more like that. To validate every action, I need snap of web table, before and after action which I will be using to to compare with my expected result. i.e. Table row col1 col2 col3 row1 1 2 3 row2 4 5 5 After clicking ADD button result would be one row and out should be row col1 col2 col3 row1 5 7 8 I want to capture table before and after ADD button, I will do my calculation on before data and prepare output and compare my output with after action table, both should match. Is there any way I can save web table with internal data type, data structure, in python without using an external file like, txt, excel, csv, etc. I don't want to use any external APIs as it will go as production deployment # For loop iterate through each Row for row in get_elements(self.browser, soPg.order_rows): if not get_webelement(row, soPg.order_table_columns).text: break # For each Row, iterate through each column for col in get_webelements(row, soPg.order_table_columns): print col.text, I have currect code which goes through table and prints all the cell values but I want to capture entire web table as object
tagged with: selenium

http://stackoverflow.com/q/47406928
has body: I am having an issue with a LP problem. I'll first try to explain the problem in a simplified way, before explaining the issues. Basic problem Suppose I have three types of machines, all of which can only be operational for two periods of times (T1, T2, T3, or T4), as is indicated by the ones in the below matrix. Machine T1 T2 T3 T4 Amount M1 0 1 1 0 x1 M2 1 1 0 0 x2 M3 0 0 1 1 x3 Each machine can produce any amount of items (x1 to x3; the variables). This is needed to achieve a MIMINUM required production per time period: T1 T2 T3 T4 Required 2 3 1 1 To solve this problem, we need: M2 to produce 2, M3 to produce 1, either M1 or M2 to produce 1, with the effect that one too many is produced at T3 or T1 respectively. which may result in: Machine T1 T2 T3 T4 Amount M1 0 0 0 0 0 M2 3 3 0 0 3 M3 0 0 1 1 1 prod 3 3 1 1 Requ 2 3 1 1 Constraints Production during T1 and T4 is not preferrable and should be punished. In the above example, this would mean that M1 should be used to produce. In simple wording, the problem states to produce at least the required amount, but minimize any excess (especially in T1 and T4). This can be done in two ways: The machines operational during these periods are punished (Punishment by M; M2 and M3). The production per time period is punished (Punished by T; T1 and T4) This would look as follows: Machine T1 T2 T3 T4 Amount Pm M1 0 1 1 0 x1 0 M2 1 1 0 0 x2 0.5 M3 0 0 1 1 x3 0.5 Pt 0.5 0 0 0.5 Issue: I can only get the punishment per machine to work properly. Punishment by time is not infeasible, but gives incorrect output (way too many redundant machines). Attempt and outcome I first programmed the solver with a punishment by m (Pm). The objective function (in Python pulp) here is: amount = LpVariable.dicts("amount_",Machine,0,100000,LpInteger) product_t = LpVariable.dicts("product_",time,0,100000,LpInteger) prob += lpSum([amount[m]*(1+Pm[m]) for m in Machine]) # minimize # constraint for t in time: # production per time period; matrix[m,t] is…
has answer: http://stackoverflow.com/a/47408268
answer count: 2
tagged with: pulp
tagged with: python
tagged with: linear-programming
possible better answer: http://stackoverflow.com/a/47418827
accepted answer: http://stackoverflow.com/a/47408268
has answer: http://stackoverflow.com/a/47418827
type: AnsweredQuestion
has title: Linear programming: Can objective variable have a constraint?
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47479694
has comment: http://stackoverflow.com/comment/115297982
has body: try this: list.index(sorted(list)[1])
type: Answer
has comment: http://stackoverflow.com/comment/115299496
answers question: http://stackoverflow.com/q/47479584
has comment: http://stackoverflow.com/comment/81975549
score: 1
has comment: http://stackoverflow.com/comment/81914566
has comment: http://stackoverflow.com/comment/115305181
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/115298944

http://stackoverflow.com/q/47464067
has comment: http://stackoverflow.com/comment/81885834
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47467238
has title: How to predict labels using cross-validation (Kfold) with sklearn
has answer: http://stackoverflow.com/a/47467238
has comment: http://stackoverflow.com/comment/81897516
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81897750
has body: I would like to compare the predictions of the same classifier. As an example, I picked the Linear Discriminant Analysis classifier. Therefore, I took a look in the documentation of sklearn. I found these two websites: Link 1 Link 2 I would like to link them together: prediction of labels with the help of cross-validation (for example Kfold). However, I cannot manage to make my code work. from sklearn.model_selection import cross_val_predict, KFold from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis X = np.array([[1, 2], [2, 4], [3, 2], [4, 4], [5, 2], [6, 4], [7, 2], [8, 4]]) Y = np.array([1, 2, 3, 4, 5, 6, 7, 8]) Xtrain,Xtest,Ytrain,Ytest = train_test_split(X,Y,train_size=0.5,random_state=1) clf = LinearDiscriminantAnalysis() clf.fit(Xtrain, Ytrain) LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage='auto', solver='lsqr', store_covariance=False, tol=0.001) # without cross-valdidation prediction = clf.predict(Xtest) # with cross-valdidation cv = KFold(n_splits=2) prediction_cv = cross_val_predict(clf, X, Y, cv=cv) Hopefully, someone can help me. EDIT: I think I need to explain more. At the moment, I have 232 datapoints (X). Each point consists of 16 values and is assigned to a specific class. I hope that I can improve the predictions (=less classification mistakes for unseen data points), when I am using cross-validation, like Kfold or Leave One Out. With the line cross_val_predict(clf, X, Y, cv=cv), Python does a Kfold cross-validation. Now, let's say, I get new datapoints (X_new). How can I classify them?
linked to: http://stackoverflow.com/q/41560177
upvote count: 0
downvote count: 2
answer count: 1
tagged with: cross-validation
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
score: -2

http://stackoverflow.com/q/47426546
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74262494
has comment: http://stackoverflow.com/comment/81807945
has comment: http://stackoverflow.com/comment/81807883
has title: NameError: name 'setup' is not defined
tagged with: cython
has comment: http://stackoverflow.com/comment/81807968
possible better answer: http://stackoverflow.com/a/74262494
favorite count: 0
accepted answer: http://stackoverflow.com/a/47426689
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81807955
has answer: http://stackoverflow.com/a/47426689
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81807920
tagged with: python
has comment: http://stackoverflow.com/comment/81807899
has body: Trying to build a simple app integrate with cython. Anyway I keep getting: When I enter in CMD: python setup.py build_ext --inplace Traceback (most recent call last): File "setup.py", line 3, in &lt;module&gt; setup( NameError: name 'setup' is not defined File: from setuptools import Extension from setuptools import Extension Setup( name='main.py', entry_points={ 'console_scripts': [Executable('myapp = myapp.main:main')] }, ext_modules=[ Extension('myapp.cython_module', ['myapp/cython_module.pyx']) ], ) I swear this was working yesterday. As far as I can tell it is named/declared
has comment: http://stackoverflow.com/comment/81807943
score: 2

http://stackoverflow.com/comment/81912144
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47478649
type: Comment
has text: i have got it **thanks man**.

http://stackoverflow.com/q/47477699
accepted answer: http://stackoverflow.com/a/47477898
tagged with: pandas-groupby
possible better answer: http://stackoverflow.com/a/47478368
has title: pandas how to aggregate sum on a column depending on values in other columns
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47477898
tagged with: aggregation
answer count: 2
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47478368
has body: I am trying to sum values in a column by groupby on values in a second column, but meanwhile also considering values on a 3rd column, the df is like, id memo amount 1 pos 1.0 1 pos 2.0 1 neg 3.0 2 pos 4.0 2 pos 5.0 2 neg 6.0 2 neg 7.0 I want to group by id and sum amount, but each group, if memo is pos it is positive and neg for negative, e.g. when groupby 1, the total amount is 0, since -1.0 - 2.0 + 3.0 = 0. If I do df.groupby('id')['amount'].sum(), it only considers id and amount column, I am wondering how to also take memo into account here. so the result will look like, id memo amount total_amount 1 pos 1.0 0.0 1 pos 2.0 0.0 1 neg 3.0 0.0 2 pos 4.0 -4.0 2 pos 5.0 -4.0 2 neg 6.0 -4.0 2 neg 7.0 -4.0
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/a/47456486
has comment: http://stackoverflow.com/comment/81867998
upvote count: 5
type: Answer
has body: &amp; is not a conditional operator. It stands for the bitwise and. Not only it is a different operator but also the operator precedence is different (and is below &gt; while &amp; is above). So first of all an example: &gt;&gt;&gt; 1 and 2 2 &gt;&gt;&gt; 1 &amp; 2 0 Now lets analyze your case: &gt;&gt;&gt; point = 1 &gt;&gt;&gt; score = 2 &gt;&gt;&gt; point == 1 &amp; score &gt; 0 Now the operator precedence kicks in and the last line is equivalent to &gt;&gt;&gt; point == (1 &amp; score) &gt; 0 Note that == and &gt; have equivalent precedence. So lets evaluate that: &gt;&gt;&gt; 1 &amp; score 0 &gt;&gt;&gt; point == 0 &gt; 0 The last line is equivalent to (point == 0) &gt; 0 (when operators have equal precedence then you simply go from left to right). Lets evaulate that: &gt;&gt;&gt; point == 0 False &gt;&gt;&gt; False &gt; 0 False All in all &gt;&gt;&gt; point == 1 &amp; score &gt; 0 False Can you break down the evaluation for your second statement now?
answers question: http://stackoverflow.com/q/47456405
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/81867755

http://stackoverflow.com/comment/81891116
has text: The `commands` module is long since deprecated. None of this is hard to do natively in Python itself.
comment on: http://stackoverflow.com/q/47468423
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81785855
type: Comment
comment on: http://stackoverflow.com/a/47412418
score: 0
type: AnswerComment
has text: I updated the answer. Sorry, misunterstood you there. The code will generate and append columns with all possible distances. Please be aware that this might result in a large table. You should better just extract the values and not append it to your table.

http://stackoverflow.com/a/47518332
has comment: http://stackoverflow.com/comment/82051791
type: Answer
answers question: http://stackoverflow.com/q/47509013
has body: You can overcome this error by adding the following lines before calling r.xpath(): import docx docx.oxml.ns.nsmap['a:14'] = "http://schemas.microsoft.com/office/drawing/2010/main" Then this code will allow you to set the a14:sharpenSoften attribute: xpath_str = ( './/w:drawing/wp:inline/a:graphic/a:graphicData/pic:pic/pic:blipFill' '/a:blip/a:extLst/a:ext/a14:imgProps/a14:imgLayer/a14:imgEffect/a14:' 'sharpenSoften' ) sharpenSoftens = r.xpath(xpath_str) if not sharpenSoftens: # then that element is not found return sharpenSoften = sharpenSoftens[0] sharpenSoften.set('amount', '-50000')
has comment: http://stackoverflow.com/comment/82051524
score: 0
has comment: http://stackoverflow.com/comment/82050789
has comment: http://stackoverflow.com/comment/82076710
has comment: http://stackoverflow.com/comment/82093851
has comment: http://stackoverflow.com/comment/82092872

http://stackoverflow.com/a/47404217
has body: What is currently happening is the first thing being called is sum_all(number). The value in number will be passed into sum_all as the parameter n. However, number isn't defined outside the function sum_all so the code will throw an error similar to the following: NameError: name 'number' is not defined Now, the question becomes what are you actually trying to do? Do you want to keep getting user inputs and adding those inputs together? If this is the case, then you don't need recursion for this. You can use a simple loop. If you want to get the input once and then get the sum of that input, then you need recursion. But if you need the input only once - then you should only be calling it once - not every time you go through the function. Let's illustrate this with a a call to sum_all(5): sum_all(5): | sum_all(4): | | sum_all(3): | | | sum_all(2): | | | | sum_all(1): | | | | | return 1 | | | | return 2 + 1 | | | return 3 + 3 | | return 4 + 6 | return 5 + 10 This means with an input of 5, sum_all returns 15. If this is what you intend to do, then you should only be getting input once, outside of the function sum_all, and be passing the value input by the user into sum_all.
answers question: http://stackoverflow.com/q/47404153
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47413640
has title: Convert a string not a csv to an array in Python
downvote count: 2
has comment: http://stackoverflow.com/comment/81780765
has body: I have a difficult task to achieve which is to Binary compare 2 files (.bin) and somehow list an array of the differences of the 2 files. Like list the addresses that the offsets occur or list the offsets themselves. For now I have manage to read the files and extract their content in a string with import binascii file1contents = binascii.hexlify(file1.read) And that should give me the hex values contained in the file WHICH ARE HOWEVER stored in the file1contents = "" as a string. That makes it difficult to compare so I want to convert that string into an array. Then convert contents of file2 into an Array and compare the 2 for differences. That should be a start. Can you please help me on converting that string into an array?? I have tried storing them in file1contents = [] but then I can't print(file1contents) to see what is contained.
answer count: 1
has comment: http://stackoverflow.com/comment/81819297
has comment: http://stackoverflow.com/comment/81828110
has comment: http://stackoverflow.com/comment/81787421
has answer: http://stackoverflow.com/a/47437021
favorite count: 0
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/81787376
has comment: http://stackoverflow.com/comment/81786932
type: UnansweredQuestion
score: -2
tagged with: arrays
has comment: http://stackoverflow.com/comment/81783928
has comment: http://stackoverflow.com/comment/81785182
tagged with: python
upvote count: 0

http://stackoverflow.com/comment/81877038
type: QuestionComment
comment on: http://stackoverflow.com/q/47460570
has text: This may help you https://stackoverflow.com/questions/8249042/uploading-large-files-with-python-django
score: 0
type: Comment

http://stackoverflow.com/comment/82016180
comment on: http://stackoverflow.com/q/47529828
type: Comment
type: QuestionComment
has text: You can use dask instead, check it here http://dask.pydata.org/en/latest/dataframe.html
score: 1

restore
tag name: restore
tags question: http://stackoverflow.com/q/47518987
type: Tag

http://stackoverflow.com/q/47504695
tagged with: python
has title: Superset : Where to force an autologin
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47516068
upvote count: 3
score: 3
tagged with: python-2.7
downvote count: 0
tagged with: apache-superset
answer count: 1
has body: I am using superset 0.20.4 If I want to add a token to my URL to autologin to a specific user superset/dashboard/3?standalone=true&amp;token=123456789 Where in the codes should I add a check on the token to login and force a user login action? something like : if request.args.get('token') == '123456789': login user xxx How can I autologin ? I see lots of g.user being called but I don't see where the actual login process is being made. Where did the username/password/csrf_token get used to authenticate the user?

http://stackoverflow.com/comment/82128358
type: Comment
comment on: http://stackoverflow.com/a/47460544
score: 0
type: AnswerComment
has text: The critical point is that no matter how you use `import A.B.C...`. You first get the access to top scope `A`. So you will have access to every submodules if they have been imported somewhere.

http://stackoverflow.com/comment/82018289
has text: don't know why I am getting below error when I install TextBlob: No module named _sqlite3
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47505569

http://stackoverflow.com/a/47406309
has body: Here's one using stride_tricks for efficient retrieval of slices: import numpy as np from numpy.lib.stride_tricks import as_strided # create mock data data = np.random.randint(0, 9, (3, 1000, 100)) fstmone = np.random.randint(30, 101, (3, 1000)) data[np.arange(100) &gt;= fstmone[..., None]] = -1 # count -1s (ok, this is a bit wasteful compared to @Divakar's) aux = np.where(data[..., 30:] == -1, 1, -100) nmones = np.maximum(np.max(np.cumsum(aux[..., ::-1], axis=-1), axis=-1), 0) # slice (but this I'd expect to be faster) sliceable = as_strided(data, data.shape[:2] + (71, 30), data.strides + data.strides[2:]) result = sliceable[np.arange(3)[:, None], np.arange(1000)[None, :], 70-nmones, :] Benchmarks, best solution is a hybrid of @Divakar's and mine, @Florian Rhiem's is also quite fast: import numpy as np from numpy.lib.stride_tricks import as_strided # create mock data data = np.random.randint(0, 9, (3, 1000, 100)) fstmone = np.random.randint(30, 101, (3, 1000)) data[np.arange(100) &gt;= fstmone[..., None]] = -1 def pp(data, N): # count -1s aux = np.where(data[..., N:] == -1, 1, -data.shape[-1]) nmones = np.maximum(np.max(np.cumsum(aux[..., ::-1], axis=-1), axis=-1), 0) # slice sliceable = as_strided(data, data.shape[:2] + (data.shape[-1]-N+1, N), data.strides + data.strides[2:]) return sliceable[np.arange(data.shape[0])[:, None], np.arange(data.shape[1])[None, :], data.shape[-1]-N-nmones, :] def Divakar(data, N): # mask of value (minus 1 here) to be found mask = data==-1 # Get the first index with the value along the last axis. # In case its not found, choose the last index idx = np.where(mask.any(-1), mask.argmax(-1), mask.shape[-1]) # Get N ranged indices along the last axis ind = idx[...,None] + np.arange(-N,0) # Finally advanced-index and get the ranged indexed elements as the o/p m,n,r = data.shape return data[np.arange(m)[:,None,None], np.arange(n)[:,None], ind] def combined(data, N): # mix best of Divakar's and mine mask = data==-1 idx = np.where(mask.any(-1)…
has comment: http://stackoverflow.com/comment/81766608
score: 5
answers question: http://stackoverflow.com/q/47405541
downvote count: 0
upvote count: 5
type: Answer

http://stackoverflow.com/comment/81893957
type: AnswerComment
has text: Keep in mind, however, that comparing versions isn't so straightforward. 10.0 is greater than 2.0 but your approach isn't going to pick up on that.
comment on: http://stackoverflow.com/a/47469789
type: Comment
score: 0

http://stackoverflow.com/q/47388642
has comment: http://stackoverflow.com/comment/81730748
has comment: http://stackoverflow.com/comment/81732462
has comment: http://stackoverflow.com/comment/81857583
has comment: http://stackoverflow.com/comment/81825110
score: 0
has comment: http://stackoverflow.com/comment/81731316
has comment: http://stackoverflow.com/comment/81848105
answer count: 0
has comment: http://stackoverflow.com/comment/81731027
type: UnansweredQuestion
has body: I'm using newest version of 64 bit Python officially released by Python.org on Windows 10. &gt;&gt;&gt; sys.version '2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)]' There are two data vectors sp1 and sp2 and are normalized to the highest value with highest value being 100. I want to bar in the same figure for comparison using matplotlib. However, the saved figure is white (or blank), as shown below. The codes I used for baring are: import matplotlib.pyplot as plt from math import floor, ceil sp1 = [[110.0709, 45.0], [113.105, 89.0], [114.1093, 236.0], [115.1071, 70.0], [116.1098, 332.036], [117.1118, 135.0], [118.1093, 276.0], [119.1148, 88.0], [120.0791, 49.0], [121.1197, 437.0], [136.0767, 34.1259], [139.0833, 36.0004], [141.0944, 58.036], [143.0981, 83.7717], [145.1055, 53.0], [147.1081, 42.0], [149.1147, 45.0], [158.0878, 49.0], [161.1083, 29.0], [175.1172, 188.5742]] sp2 = [[101.0693, 51.0], [102.055, 35.0], [110.0711, 43.0], [112.0854, 47.0], [113.1062, 186.0], [114.1097, 501.0], [115.1083, 168.0], [116.1096, 829.0], [117.1132, 258.0], [118.1094, 614.0], [119.1123, 190.0], [120.1185, 36.0], [121.1199, 1049.0], [136.0735, 292.0], [139.0847, 107.0], [141.0918, 128.0], [143.1005, 232.0], [145.1077, 123.0], [147.1073, 112.0], [149.1159, 86.0]] # x and y values of vector sp1 mz1, int1 = [x[0] for x in sp1], [x[1] for x in sp1] # normalize the vector to the highest value with highest value being 100. int1 = [x/max(int1)*100. for x in int1] # x and y values of vector sp2 mz2, int2 = [x[0] for x in sp2], [x[1] for x in sp2] # normalize the vector to the highest value with highest value being 100. int2 = [x/max(int2)*-100. for x in int2] # bar vectors fig, ax = plt.subplots() specbar1 = ax.bar(mz1, int1, width = 0.001) specbar2 = ax.bar(mz2, int2, width = 0.001, color = 'r', edgecolor = 'r') # plot baseline at y=0 xlim = ax.get_xlim() xl = [x/10. for x in xrange(int(floor(xlim[0]))*10, int(ceil(xlim[1]))*10)] yl = [0]*len(xl) ax.plot(xl,…
has comment: http://stackoverflow.com/comment/81730303
type: Question
has comment: http://stackoverflow.com/comment/81731976
has title: matplotlib 64 bit bar blank
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/comment/81963564
type: Comment
comment on: http://stackoverflow.com/a/47472563
score: 0
type: AnswerComment
has text: I was under the assumption that I will get the device handle after calling device function. Thanks for clarifying that device handle exists in `device` variable as soon as `uiautomator` is imported. Thank you @nkborba

http://stackoverflow.com/a/49197093
upvote count: 1
answers question: http://stackoverflow.com/q/47481250
type: Answer
has body: I hope the two functions below will help you :) First function # replace multiple occurrences of a string by an incremental number # e.g. &lt;rn&gt;, &lt;rn&gt;, &lt;rn&gt; ... # becomes # &lt;rn1&gt;, &lt;rn2&gt;, &lt;rn3&gt; ... # # **m.group(1)** same like regex argument **\1** # **global counter** means: use (global) variable **counter** outside def in def # more about global and local variables: https://www.python-course.eu/global_vs_local_variables.php import re counter = 0 def get_counter(m): global counter counter = counter + 1 return m.group(1) + str(counter) + '&gt;' editor.rereplace('(&lt;rn)&gt;', get_counter, re.IGNORECASE) Second function # replace X followed by numbers by an incremental number # e.g. X56 X39 X999 # becomes # Y57 Y40 Y1000 def add_1(m): return 'Y' + str(int(m.group(1)) + 1) editor.rereplace('X([0-9]+)', add_1)
score: 1
downvote count: 0

http://stackoverflow.com/q/47533641
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Matching similar strings with common significant words
tagged with: fuzzywuzzy
score: 0
has body: I want to match similar strings with same significant word. Problem: I have two files one master and one input file. I have to iterate through the input file and find similar record from master. Currently I have indexed the master file in ElasticSearch and try to get similar records from ElasticSearch but since the Master contains of many similar records it return many records and finding the appropriate one from them is the problem. Sample Input record: 1. H1 Bulbs Included Sample Output From ElasticSearch: 1. Included H1 [Correct One] 2. H7 Bulbs Included 3. H8 Bulbs Provided 4. H1 not Included[Should not match this] I have tried using POS tagger to get the important terms but it does not work well. POS Tagger Output: 1. H1/NNP Included/NNP 2. H8/NNP Bulbs/NNP Provided/NNP How to proceed with this? Edit: In the above example H1 is the significant term Sample Input Record: 1. H1 Bulbs included Sample Output from ElasticSearch: 1. H2 Bulbs Included 2. H3 Bulbs Included 3. H1 [Correct One] Initially I need to identify the Significant word. There is currently no pattern in the significant word. i.e.) 1.H1 bulbs [H1] 2.9600 added [9600] 3.It has H8 [H8] 4.1/2 wire for 4500 bulb [4500]
has answer: http://stackoverflow.com/a/47544037
tagged with: elasticsearch
tagged with: nlp

http://stackoverflow.com/comment/139046494
comment on: http://stackoverflow.com/a/78830180
type: Comment
score: 0
type: AnswerComment
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).

http://stackoverflow.com/a/47430846
has comment: http://stackoverflow.com/comment/81816284
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47430507
has comment: http://stackoverflow.com/comment/81816474
upvote count: 2
has comment: http://stackoverflow.com/comment/81816393
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47430507
has comment: http://stackoverflow.com/comment/81816616
score: 2
has comment: http://stackoverflow.com/comment/81816274
has body: What I changed: I added a prompt for the user (it helped me when testing and I'm sure it will help you too). I added a check to make sure the user enters a valid, numeric string (before we convert it using int. Addressing your specific concern: Make sure you are entering your data by using 1{enter}2{enter}3{enter}. Because you have it shown as 123 and 1 2 3. If you want to be able to enter data like 123, I can help you with that; just comment. Code num_array = [] num = input("Please enter number of elements: ") print('') for i in range(int(num)): n = input(f"Element[i]: ") if not n.isnumeric(): print("Please enter an integer") raise "You failed to enter an integer" num_array.append(int(n)) print(num_array[::-1]) If you want to use spaces num_array = ''.join(input("Please enter your data: ").split())[::-1] print(num_array) Program running: Input&lt;&lt; Please enter your data: 5 2 1 3 Output&gt;&gt; 3125 If you want to use no spaces num_array = input(f"Please enter your data: ")[::-1] print(num_array) Program running: Input&lt;&lt; Please enter your data: 5123 Output&gt;&gt; 3215 Noob Editor's explanation (Included so I take up 90% of the total page space used). Existing issue as per terminal dump : In [6]: %cpaste Pasting code; enter '--' alone on the line to stop or use Ctrl-D. :def abc(): num_array = [] num = input() print() for i in range(int(num)): n = input() num_array.append(int(n)) print(num_array[::-1]) :-- In [7]: abc() 2 12 // this is where enter is pressed --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-7-79c8afb7007d&gt; in &lt;module&gt;() ----&gt; 1 abc() &lt;ipython-input-6-f0dc94278ce8&gt; in abc() 5 for i in range(int(num)): 6 n = input() ----&gt; 7 num_array.append(int(n)) 8 print(num_arra) ValueError: invalid literal for int() with base 10: '' In [8]: ---- correct implementaion --- In [9]: def abc(): ...: num_array = [] ...: num = input() ...: print() ...: f…
has comment: http://stackoverflow.com/comment/81816398

http://stackoverflow.com/q/47524976
score: 1
has comment: http://stackoverflow.com/comment/82009852
downvote count: 1
has comment: http://stackoverflow.com/comment/82006473
favorite count: 0
possible better answer: http://stackoverflow.com/a/47527865
type: Question
has answer: http://stackoverflow.com/a/47527865
tagged with: python
tagged with: module
accepted answer: http://stackoverflow.com/a/47525224
has answer: http://stackoverflow.com/a/47525334
linked to: http://stackoverflow.com/q/13857
has answer: http://stackoverflow.com/a/47526817
has body: Is it possible to achieve this in python? Basically, shared_fun() is a very frequently used utility function, used in multiple modules (user_module1 and user_module2). However, each user wants a slightly different parameter SHARE_GLOBAL_VAR. Some motivation why I would want it this way: A. Imagine there are a lot of shared_fun(), shared_fun1(), shared_fun2() ...... and all of them rely on the same SHARE_GLOBAL_VAR but do different things with it. Therefore I really don't want to make SHARE_GLOBAL_VAR an argument for every one of those shared_fun(SHARE_GLOBAL_VAR) B. I want to make the maintenance of shared_fun() easy so that I don't want to copy the code into each user_module.py file individually. I think the task boils down to make a copy of share module namespace inside each user_module namespace, which I'm not sure if it's legal in python. #share.py: SHARE_GLOBAL_VAR = 0 def shared_fun(): return SHARE_GLOBAL_VAR #user_module1.py: import share share.SHARE_GLOBAL_VAR = 1 def user1_fun(): return share.shared_fun() #user_module2.py: import share share.SHARE_GLOBAL_VAR = 2 def user2_fun(): return share.shared_fun() #main.py: import user_module1 import user_module2 # expecting a result of 1 print(user_module1.user1_fun()) # expecting a result of 2 print(user_module2.user2_fun())
answer count: 4
has answer: http://stackoverflow.com/a/47525224
tagged with: python-import
has title: Python reuse the same module by multiple other modules
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/comment/82010020
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47526001
score: 0
has text: No, it would create 40 batches of 32 samples each.

http://stackoverflow.com/comment/82008090
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159962/discussion-between-david-and-frank-ak).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47525872

http://stackoverflow.com/comment/81871392
comment on: http://stackoverflow.com/q/47458172
type: Comment
type: QuestionComment
has text: Have you restarted your shell after adding it to bashrc?
score: 0

http://stackoverflow.com/comment/96056296
comment on: http://stackoverflow.com/a/47540675
type: Comment
has text: *On the other hand, if you SELECT, the last operation doesn't really affect rows, it is a result set. In that case, 0 would be syntactically incorrect, so the interface returns -1 instead.* This is not correct, sorry. Many database implementations will set the rowcount to the *number of rows selected*. It is only set to -1 if that number can't be determined up-front; e.g. the SQLite engine won't be able to tell you how many rows are selected until it has returned all rows. The pyodbc documenation [explicitly covers this case](https://github.com/mkleehammer/pyodbc/wiki/Cursor).
type: AnswerComment
score: 2

http://stackoverflow.com/q/47457768
has comment: http://stackoverflow.com/comment/81870304
has comment: http://stackoverflow.com/comment/81871005
type: Question
has comment: http://stackoverflow.com/comment/81870480
has comment: http://stackoverflow.com/comment/81870890
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81870322
upvote count: 0
type: UnansweredQuestion
answer count: 1
has title: calling variables into different functions within the same class in tkinter
has comment: http://stackoverflow.com/comment/81870213
has answer: http://stackoverflow.com/a/47458354
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81870149
has comment: http://stackoverflow.com/comment/81870421
has comment: http://stackoverflow.com/comment/81870475
has comment: http://stackoverflow.com/comment/81870645
has body: I am trying to make a password generator and checker program in python. At the moment I have finished the gui but I am having trouble making the tkinter label update and display the textvariable as it just comes up with a blank space instead of 'error', 'weak' etc. someone else helped me with the generator but what they did wouldn't work in this case unfortunately. class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label1 = tk.Label(self, text="Check your password", font=controller.title_font) label1.pack(side="top", fill="x", pady=10) entry = tk.Entry(self, bd =6) button1 = tk.Button(self, text="Enter", command=checkPassword(entry.get())) self.update button2 = tk.Button(self, text="Back", command=lambda: controller.show_frame("StartPage")) label2 = tk.Label(self, text="Strength:", font=controller.title_font) label3 = tk.Label(self, textvariable=passwordStrength, font=controller.title_font) entry.pack() button1.pack() button2.pack() label2.pack() label3.pack() def checkPassword(password): passwordStrength = tk.StringVar() strength = ['Password can not be Blank', 'Very Weak', 'Weak', 'Medium', 'Strong', 'Very Strong', 'Password must be less than 24 characters'] score = 1 print (password), len(password) if len(password) == 0: passwordStrength.set(strength[0]) return if len(password) &gt; 24: passwordStrength.set(strength[6]) return if len(password) &lt; 4: passwordStrength.set(strength[1]) return if len(password) &gt;= 8: score += 1 if re.search("[0-9]", password): score += 1 if re.search("[a-z]", password) and re.search("[A-Z]", password): score += 1 if re.search(".", password): score += 1 passwordStrength.set(strength[score]) If you require more info on what my project is, or the rest of the code, just ask. All help is much appreciated, thanks in advance:)
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81870107

http://stackoverflow.com/a/71330420
score: 0
answers question: http://stackoverflow.com/q/47458888
has body: Building on Ajax1234's top voted answer with a bit more information for less advanced programmers. A python string is an array. Unlike other languages it is not an array of char type values as Python does not have a char data type. A single letter is simply a string of length 1. So we can access any 'character' in the string the same as we would any array my_string = "Hello, World!" print(my_string[0] print(my_string[1] print(my_string[2] Will print H e l We can also iterate over it as we would any array for s in my_string: print(s) So what you want to do here is my_dict = {} # create your dict my_string = "HELLO" # iterate over your string and add to the count in your dict/map for s in my_string: # account for duplicate values! if s in my_dict: my_dict[s] += 1 else: my_dict[s] = 1 print(my_dict) So if you enter hello as input this will give {'h': 1, 'e': 1, 'l': 2, 'o': 1} Since you are counting letters rather than unique characters you may also want to add an if case and use the lower() inbuilt method.
type: Answer

http://stackoverflow.com/comment/81810671
type: QuestionComment
has text: 01012017 here it is!
type: Comment
comment on: http://stackoverflow.com/q/47428132
score: 0

http://stackoverflow.com/comment/82030060
comment on: http://stackoverflow.com/q/47535861
type: Comment
type: QuestionComment
score: 1
has text: import json then print json.dumps(event)

http://stackoverflow.com/q/47497474
has answer: http://stackoverflow.com/a/47501118
answer count: 2
has answer: http://stackoverflow.com/a/47501125
type: UnansweredQuestion
has title: error evaluating network in tensorflow
tagged with: python
score: 0
has body: I'm trying to load a saved model by saver and evaluate the output of the network over the test data, restoring a saved model and using the network as a function: def model(x, x_size): with tf.variable_scope("my_net", reuse=tf.AUTO_REUSE): W1 = tf.get_variable('w1', [x_size, x_size], initializer=tf.random_normal_initializer()) b1 = tf.get_variable('b1', [x_size], initializer=tf.random_normal_initializer()) y1 = tf.nn.relu(tf.matmul(x, W1) + b1,'y1') return y1 eval_x = tf.placeholder(tf.float32, name='eval_x', shape=[None, x_size]) eval_probs = model(eval_x, x_size) with tf.Session() as sess: new_saver = tf.train.import_meta_graph('save_model/model.ckpt.meta') new_saver.restore(sess, "save_model/model.ckpt") probs = sess.run(eval_probs, feed_dict={eval_x: test_x}) The error I get is: FailedPreconditionError (see above for traceback): Attempting to use uninitialized value my_net/w1 [[Node: my_net/w1/read = IdentityT=DT_FLOAT, _class=["loc:@my_net/w1"], _device="/job:localhost/replica:0/task:0/device:CPU:0"]] Can anybody help?
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/47506812
has body: In my basic web application, when click to "calculate" button there can be two options. First, there is only one result so I directly show them to the users. Secondly, there can be more than one result so I need to use table to show my results. For the first option, I can show my result like below: Result {{result}} But I cannot figure out if my "result" parameter is array and how can I show all values of array in the table in my html file. Any help is appreciated.
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/47506960
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47506960
has title: Adding table with flask
possible better answer: http://stackoverflow.com/a/47507322
upvote count: 1
has answer: http://stackoverflow.com/a/47507322
tagged with: flask
tagged with: jinja2
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47512304
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47401030
has body: Bill is correct. Understand the flowchart on the link he posted (http://docs.developer.amazonservices.com/en_US/reports/Reports_Overview.html) and then make the appropriate MWS calls. Basically, request it, poll it to see if it's completed, then retrieve it and do what you need to do with it. You can use their client libraries, which do most of the work, right here: https://developer.amazonservices.com/gp/mws/api.html/139-2745849-3030362?ie=UTF8&amp;group=bde&amp;section=reports&amp;version=latest
score: 1

http://stackoverflow.com/q/47400056
score: 1
tagged with: python
tagged with: pygame
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47400975
upvote count: 1
has body: I am new to python and pygame and I'm trying to move a image over drawed rectangles with changing colors. Whenever I run this code the image moves but it creates a track of the image. I know that I need to blit the background of the image in the game loop but how can I blit the background if the background is not an image? Or do I need to draw my rectangles in a different way? Full code: import pygame pygame.init() screen = pygame.display.set_mode((600,200)) pygame.draw.rect(screen, (175,171,171), [0, 0, 600, 200]) pygame.draw.rect(screen, (255,192,0), [200, 0, 200, 200]) clock = pygame.time.Clock() # load your own image here (preferably not wider than 30px) truck = pygame.image.load('your_image.png').convert_alpha() class Truck: def __init__(self, image, x, y, speed): self.speed = speed self.image = image self.pos = image.get_rect().move(x, y) def move(self): self.pos = self.pos.move(self.speed, 0) def game_loop(): newTruck = Truck(truck, 0, 50, 1) gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True newTruck.move() screen.blit(newTruck.image, newTruck.pos) clock.tick(60) pygame.display.update() game_loop()
possible better answer: http://stackoverflow.com/a/47408007
favorite count: 0
has answer: http://stackoverflow.com/a/47408007
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47400975
has title: Pygame moving image over rectangle with different colors

http://stackoverflow.com/comment/81984920
has text: @Harvey You don't even want a user's name? In that case, you should use this scope - `https://www.googleapis.com/auth/plus.login`. It will only get a user's language and their age-range (if the user is 18+ or 21+, etc).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47512029
type: Comment

http://stackoverflow.com/a/47433432
answers question: http://stackoverflow.com/q/47432480
type: Answer
accepted answer of: http://stackoverflow.com/q/47432480
has comment: http://stackoverflow.com/comment/81821281
score: 0
has body: The error with connection to Postgresql. Flask app can not connect to your database with following connection string postgresql://fish:postgres@localhost:5433/exam_app. Try to connect to db with this credentional by hand, may be with PgAdmin, you will see that db does not available by this adress.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81821957

http://stackoverflow.com/comment/81922067
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47483450
has text: You have only 5 entries, why would you expect it to work for values of `run` greater than 4? Also: `if rand > 8: break; elif rand < 9: ...` is redundant.
score: 0

http://stackoverflow.com/q/47443332
has answer: http://stackoverflow.com/a/47443650
has title: Combine lists having a specific merge order in a pythonic way?
has answer: http://stackoverflow.com/a/47443369
linked to: http://stackoverflow.com/q/27073596
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/47780201
has comment: http://stackoverflow.com/comment/81841955
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81843576
accepted answer: http://stackoverflow.com/a/47443528
downvote count: 3
score: 24
has answer: http://stackoverflow.com/a/47444625
has answer: http://stackoverflow.com/a/47443528
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49090232
upvote count: 27
has comment: http://stackoverflow.com/comment/81842273
has body: I would like to construct list x from two lists y and z. I want all elements from y be placed where ypos elements point. For example: y = [11, 13, 15] z = [12, 14] ypos = [1, 3, 5] So, x must be [11, 12, 13, 14, 15] Another example: y = [77] z = [35, 58, 74] ypos = [3] So, x must be [35, 58, 77, 74] I've written function that does what I want but it looks ugly: def func(y, z, ypos): x = [0] * (len(y) + len(z)) zpos = list(range(len(y) + len(z))) for i, j in zip(y, ypos): x[j-1] = i zpos.remove(j-1) for i, j in zip(z, zpos): x[j] = i return x How to write it in pythonic way?
has comment: http://stackoverflow.com/comment/81841691
possible better answer: http://stackoverflow.com/a/47443369

http://stackoverflow.com/a/47393777
type: AcceptedAnswer
has body: For me it working nice, small improvement is use parameter fill_value=0 in reindex: new_index = pd.MultiIndex.from_product([all_dates, station_index], names=('date', 'station')) df_trans = df_trans.reindex(new_index, fill_value=0) print (df_trans.head(10)) count date station 2014-01-09 00:00:00 A 0 B 0 2014-01-09 01:00:00 A 0 B 0 2014-01-09 02:00:00 A 0 B 0 2014-01-09 03:00:00 A 0 B 0 2014-01-09 04:00:00 A 0 B 0 print (df_trans[df_trans['count'] != 0]) count date station 2015-01-01 13:00:00 A 4 2015-01-01 14:00:00 B 2 2015-01-02 15:00:00 A 7 print (df_trans.index.levels) [[2014-01-09 00:00:00, 2014-01-09 01:00:00, 2014-01-09 02:00:00, 2014-01-09 03:00:00, 2014-01-09 04:00:00, 2014-01-09 05:00:00, 2014-01-09 06:00:00, 2014-01-09 07:00:00, 2014-01-09 08:00:00, 2014-01-09 09:00:00, 2014-01-09 10:00:00, 2014-01-09 11:00:00, 2014-01-09 12:00:00, 2014-01-09 13:00:00, 2014-01-09 14:00:00, 2014-01-09 15:00:00, 2014-01-09 16:00:00, 2014-01-09 17:00:00, 2014-01-09 18:00:00, 2014-01-09 19:00:00, 2014-01-09 20:00:00, 2014-01-09 21:00:00, 2014-01-09 22:00:00, 2014-01-09 23:00:00, 2014-01-10 00:00:00, 2014-01-10 01:00:00, 2014-01-10 02:00:00, 2014-01-10 03:00:00, 2014-01-10 04:00:00, 2014-01-10 05:00:00, 2014-01-10 06:00:00, 2014-01-10 07:00:00, 2014-01-10 08:00:00, 2014-01-10 09:00:00, 2014-01-10 10:00:00, 2014-01-10 11:00:00, 2014-01-10 12:00:00, 2014-01-10 13:00:00, 2014-01-10 14:00:00, 2014-01-10 15:00:00, 2014-01-10 16:00:00, 2014-01-10 17:00:00, 2014-01-10 18:00:00, 2014-01-10 19:00:00, 2014-01-10 20:00:00, 2014-01-10 21:00:00, 2014-01-10 22:00:00, 2014-01-10 23:00:00, 2014-01-11 00:00:00, 2014-01-11 01:00:00, 2014-01-11 02:00:00, 2014-01-11 03:00:00, 2014-01-11 04:00:00, 2014-01-11 05:00:00, 2014-01-11 06:00:00, 2014-01-11 07:00:00, 2014-01-11 08:00:00, 2014-01-11 09:00:00, 2014-01-11 10:00:00, 2014-01-11 11:00:00, 2014-01-11 12:00:00, 2014-01-11 13:00:00, 2014-01-11 14:00:00, 2014-01-11 15:00:00, 2014-01-11 16:00:00, 2014-01-11 17:00:00, 2014-01-11 18:00:00, 2014-01-11 19…
has comment: http://stackoverflow.com/comment/81740724
has comment: http://stackoverflow.com/comment/81740900
answers question: http://stackoverflow.com/q/47393658
has comment: http://stackoverflow.com/comment/81740978
has comment: http://stackoverflow.com/comment/81741020
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81740815
has comment: http://stackoverflow.com/comment/81741191
accepted answer of: http://stackoverflow.com/q/47393658
has comment: http://stackoverflow.com/comment/81741067
has comment: http://stackoverflow.com/comment/81741292
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81841301
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47439924
has text: @wim So what you are saying, is that a decorator can do anything it likes, and sometimes it will work and sometimes it won't. While technically correct, you are also not being very helpful in a practical sense.

http://stackoverflow.com/q/47485692
type: UnansweredQuestion
tagged with: arrays
tagged with: python
tagged with: audio
score: 3
answer count: 3
has answer: http://stackoverflow.com/a/62852574
upvote count: 3
has answer: http://stackoverflow.com/a/47489641
downvote count: 0
has comment: http://stackoverflow.com/comment/81934292
has body: I would like to record a tone with sounddevice i created numpy and write it into a wav file. here is the code: import numpy import sounddevice as sd import soundfile as sf import sys duration = 3 amplitude = 0.3 sampling_frequency = 44100 time = numpy.arange(int(numpy.ceil(duration * sampling_frequency))) / sampling_frequency frequency1 = 500 tone1 = amplitude * numpy.sin(2* numpy.pi * frequency1 * time) frequency2 = 700 tone2 = amplitude * numpy.sin(2* numpy.pi * frequency1 * time) frequency3 = 1500 tone3 = amplitude * numpy.sin(3* numpy.pi * frequency1 * time) frequency4 = 400 tone4 = amplitude * numpy.sin(4* numpy.pi * frequency1 * time) result = tone1 result2 = tone2 result3 = tone3 result4 = tone4 sd.play(result + result2 + result3 + result4, sampling_frequency) filename = 'output.wav' mydata = sd.rec(int(result + result2 + result3 + result4),sampling_frequency,channels=2, blocking=True) sf.write(filename, mydata, sampling_frequency) I get this error: only length-1 arrays can be converted to Python scalars What's wrong with the code? I'm a newbie with python
has title: Writing a wav file using sounddevice and numpy in python3
favorite count: 0
has answer: http://stackoverflow.com/a/73900960
type: Question
tagged with: numpy

http://stackoverflow.com/q/47511376
type: Question
has comment: http://stackoverflow.com/comment/81978926
has body: I am trying to create a supervised machine learning model to predict probability of a given URL that belongs to benign or malicious class, based on both numerical features and text features. Numerical Featurs - Length of URL Length of primary domain Number of dots Contains IP etc. Text Features - Name of registrar Name of registrant Country List of words in URL etc. I have dataframe with required features, but I don't know what to do with text data. Can someone guide me in this? Below is an sample dataframe that i have- url_length length_domain is_ip registrar registrants tokens_in_url 0 50 18 0 a1 z1 [abc, def, ghi, jkl] 1 98 23 0 a2 z2 [mno, pqr, stu] 2 146 8 0 a3 z3 [vwx, yz] Thanks in Advance.
type: UnansweredQuestion
tagged with: feature-extraction
has answer: http://stackoverflow.com/a/56846321
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/81978690
tagged with: artificial-intelligence
answer count: 2
has answer: http://stackoverflow.com/a/47511709
downvote count: 0
upvote count: 1
score: 1
has title: How to Combine text and numerical features in training sets for machine learning?
favorite count: 0

http://stackoverflow.com/comment/81876938
score: 0
type: Comment
type: QuestionComment
has text: Dude, is `screenGab()` a function or a class you are calling/initializing? your function signature doesn't match at all.
comment on: http://stackoverflow.com/q/47460524

http://stackoverflow.com/comment/81945646
type: Comment
comment on: http://stackoverflow.com/a/47495261
has text: First of all thanks for the answer. I am getting an error on: w.writerow((ngram, freq)) UnsupportedOperation: not writable. Am I missing something?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81784208
type: Comment
has text: How do you intend the partition to work ? It seems not to depend on gap_minutes since all elements with the same value in this column do not end up in the same part
type: QuestionComment
comment on: http://stackoverflow.com/q/47415306
score: 0

http://stackoverflow.com/comment/81796252
comment on: http://stackoverflow.com/q/47407887
type: Comment
score: 0
type: QuestionComment
has text: Do these things involve the code doing a lot of introspection to decide what is going on? I always have the sneaky suspicion that Django code is examining itself, and then doing things based on that - rather than doing things directly.

http://stackoverflow.com/q/47525074
has comment: http://stackoverflow.com/comment/82009253
possible better answer: http://stackoverflow.com/a/47525926
tagged with: python
has answer: http://stackoverflow.com/a/47525719
has body: I have a numpy array a: a = np.array([[0,4,3,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,4,3,5,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,8,3,9,2,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,9,2,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,4,2,9,2,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,2,2,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,2,6,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,2,6,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,2,6,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,2,6,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,2,6,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,9,2,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,2,2,2,6,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,4,2,2,6,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,4,4,3,4,4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], [4,4,4,3,4,4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]]) I'm looking for the index of the smallest neighbours of cell(s) where value= 2 (numpy.where(a==value)) but bigger than value. I also need the index of the corresponding cell(s) = value for which we found the smallest neighbour. Result in this case (value = 2) should be: index of neighbouring cells: [0,2] and [4,3] The corresponding and index of corresponding cell(s): [1,2] and [3,3] Please apologies if the question is not very clear. This is what I have so far: import numpy as np value = 2 neighbors = np.zeros(4, dtype = np.float) fdx = np.flatnonzero(a== value) locations = fdx // a.shape[1], fdx % a.shape[1] maximums = [] for item in zip(*locations): i, j = item[0], item[1] neighbors[0], neighbors[1], neighbors[2],neighbors[3] = [a[i-1,j], a[i+1,j], a[i,j-1], a[i,j+1]] maximums.append(min(neighbors[neighbors&gt; value])) print np.where(a==min(m…
has comment: http://stackoverflow.com/comment/82010877
type: AnsweredQuestion
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/82014192
score: 1
has answer: http://stackoverflow.com/a/47526351
linked to: http://stackoverflow.com/q/45960192
has answer: http://stackoverflow.com/a/47525926
accepted answer: http://stackoverflow.com/a/47525719
has title: Index of smallest neighbouring cell greater than a value in 2D array
has comment: http://stackoverflow.com/comment/82008876
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/82008654
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82009049
tagged with: numpy

http://stackoverflow.com/q/47437299
score: 0
tagged with: pandas
has body: I have a Pandas Dataframe read in from a CSV file. I want to create a larger Dataframe what includes some of the columns in the CSV file - however the header names are different so translation is needed. The larger Dataframe values not included in the CSV file should be settable to some default value. My best idea so far is to start with the dataframe from the CSV and use a dictionary to translate the column names. Then I can add the remaining columns to the resulting structure. This feels a bit clunky tho - any suggestions on how to best approach this? An illustrative example Initial CSV file: Name,Age,Address,PhoneNumber Dataframe output: Given the above we have - Age=Age, FullName=Name, HomeAddress=Address. The defaults for example could be - Nationality="USA", WorkAddress="Google", StarSign="Leo". PhoneNumber is ignored completely in the output. Age,Nationality,FullName,HomeAddress,WorkAddress,StarSign
answer count: 1
has answer: http://stackoverflow.com/a/47437498
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47437498
tagged with: python
has title: Translate Pandas Dataframe

http://stackoverflow.com/q/47436987
has title: Dask: How to efficiently distribute a genetic search algorithm?
type: AnsweredQuestion
has body: I've implemented a genetic search algorithm and tried to parallelise it, but getting terrible performance (worse than single threaded). I suspect this is due to communication overhead. I have provided pseudo-code below, but in essence the genetic algorithm creates a large pool of "Chromosome" objects, then runs many iterations of: Score each individual chromosome based on how it performs in a 'world.' The world remains static across iterations. Randomly selects a new population based on their scores calculated in the previous step Go to step 1 for n iterations The scoring algorithm (step 1) is the major bottleneck, hence it seemed natural to distribute out the processing of this code. I have run into a couple of issues I hoped I could get help with: How can I link the calculated score with the object that was passed to the scoring function by map(), i.e. link each Future holding a score back to a Chromosome? I've done this in a very clunky way by having the calculate_scores() method return the object, but in reality all I need is to send a float back if there is a better way to maintain the link. The parallel processing of the scoring function is working okay, though takes a long time for map() to iterate through all the objects. However, the subsequent calls to draw_chromosome_from_pool() run very slowly compared to the single-threaded version to the point that I've not yet seen it complete. I have no idea what is causing this as the method always completes quickly in the single-threaded version. Is there some IPC going on to pull the chromosomes back to the local process, even after all the futures have completed? Is the local process de-prioritised in some way? I am worried that the overall iterative nature of building/rebuilding the pool each cycle is going to cause an enormous amount of data transmission to the workers. The question at the root of this concern: what and when does Dask actually send data back and forth to the worker pool. i.e. when does Environm…
score: 1
favorite count: 0
tagged with: multiprocessing
type: Question
accepted answer: http://stackoverflow.com/a/47438154
tagged with: dask
has answer: http://stackoverflow.com/a/47438154
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/86267072
type: AnswerComment
has text: Sorry but I don't know what causes this problem at the beginning. My only guess is that VS Code couldn't fetch pylint location to use it. So adding pylint path manually would override the default behavior and solve the issue
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47486549

http://stackoverflow.com/a/47446352
has body: There are two methods of solving this. The method 1 is using ObjectProperty, and the method 2 is using StringProperty. Method 1 - Using ObjectProperty In this example, an ObjectProperty is used to hook up to the button because an id is a weakref to the widget. Using ObjectProperty creates a direct reference, provides faster access and is more explicit. main.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.lang import Builder from kivy.clock import Clock import random root = Builder.load_string(''' &lt;Demo&gt;: btn: btn orientation: 'vertical' Button: id: btn text: 'rand_val_here' size_hint: .2, .2 pos_hint: {'x':0, 'center_y': .1} ''') class Demo(BoxLayout): btn = ObjectProperty(None) def __init__(self, **kwargs): super(Demo, self).__init__(**kwargs) Clock.schedule_interval(self.randgen, 0.01) def randgen(self, dt): self.btn.text = str(random.randint(0, 10)) class MainApp(App): title = "Updating Button's Text - Using ObjectProperty" def build(self): return Demo() if __name__ == '__main__': MainApp().run() Output Method 2 - Using StringProperty Without changing much of your original app, the solution is as follow: Since your root widget class, Demo is a BoxLayout, therefore the attribute cols: 1 which is only applicable to GridLayout is not required in the kv file Declare rand_val of type StringProperty Populate the button's text using app.rand_val Note: Your app has nested BoxLayout. main.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty from kivy.lang import Builder from kivy.clock import Clock import random root = Builder.load_string(''' &lt;Demo&gt;: BoxLayout: orientation: 'vertical' Button: text: app.rand_val size_hint: .2, .2 pos_hint: {'x':0, 'center_y': .1} ''') class Demo(BoxLayout): pass class MainApp(App): rand_val = StringProperty("") def build(self): Clock.schedule_interval(self.randgen, 0.01) return Demo() def randgen(…
has comment: http://stackoverflow.com/comment/81858218
type: Answer
answers question: http://stackoverflow.com/q/47440568
upvote count: 2
score: 1
downvote count: 1

http://stackoverflow.com/a/47534117
has comment: http://stackoverflow.com/comment/82053476
answers question: http://stackoverflow.com/q/47534099
has comment: http://stackoverflow.com/comment/82024906
has comment: http://stackoverflow.com/comment/82025439
has comment: http://stackoverflow.com/comment/82025180
upvote count: 2
has comment: http://stackoverflow.com/comment/82025223
has comment: http://stackoverflow.com/comment/82026995
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82025482
has comment: http://stackoverflow.com/comment/82025505
downvote count: 1
has body: I think you need convert index to Series by to_series, keep='first' should be omit, because default parameter in duplicated: df = df[~df.index.to_series().duplicated()]
has comment: http://stackoverflow.com/comment/82054186
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47534099
has comment: http://stackoverflow.com/comment/82024966

http://stackoverflow.com/a/47432411
accepted answer of: http://stackoverflow.com/q/47432192
type: Answer
has body: TL:DR; No. PATH is used to search for the (executable) file you're trying to run. If a file is not executable (e.g., text files), windows will try to look up which program is registered to handle the file's extension (in your case notepad) an open that one, passing the file's path as argument to it. Once the correct program has been found, all the following arguments are first checked for eventual %ENVIRONMENT_VARIABLE% placeholders to replace with the actual values, then treated as a list of space-separated strings and passed to the program starting. It's the program's task, then, to figure out what to do with them. PATH has no play in the arguments resolution. Why is it so? Arguments to a program can be anything. Imagine you're passing the filename of a file you want to create in the current folder. How can the OS know that the filename you're passing in is not actually an existing file to be searched for in PATH, but a file that will be created by the program? That's why the responsibility to handle arguments is entirely on the program that is being started.
has comment: http://stackoverflow.com/comment/81819123
score: 0
answers question: http://stackoverflow.com/q/47432192
type: AcceptedAnswer

http://stackoverflow.com/q/47528724
has body: I am using django-custom-user to make login with e-mail. I have 2 models CustomUser and ClientData: models.py class CustomUser(AbstractEmailUser): first_name = models.CharField(max_length=200, blank=True, null=True, default=None) last_name = models.CharField(max_length=200, blank=True, null=True, default=None) phone = models.CharField(max_length=20, blank=True, null=True, default=None) class ClientData(models.Model): user = models.OneToOneField(CustomUser) company = models.CharField(max_length=200, blank=True, null=True, default=None) bank_account = models.CharField(max_length=25, blank=True, null=True, default=None) I am trying to make a register form with both models and i have managed to do that, i have also made a clean password function, everything works, but when i purposely give 2 different password i get: 'ValidationError' object has no attribute 'get' forms.py class UserRegistrationForm(forms.ModelForm): email = forms.EmailField(required=True, max_length=150) first_name = forms.CharField(required=True, max_length=100) last_name = forms.CharField(required=True, max_length=100) password1 = forms.CharField(required=True, label='Password', max_length=100, widget=forms.PasswordInput()) password2 = forms.CharField(required=True, label='Confirm Password', max_length=100, widget=forms.PasswordInput()) phone = forms.CharField(required=True, max_length=20) class Meta: model = CustomUser fields = ['email', 'first_name', 'last_name', 'password1', 'password2', 'phone'] def clean(self): cleaned_data = super(UserRegistrationForm, self).clean() password1 = cleaned_data.get('password1') password2 = cleaned_data.get('password2') if password1 != password2: return forms.ValidationError('Password did not match.') return cleaned_data class UserDataRegistrationForm(forms.ModelForm): class Meta: model = ClientData fields = ['company', 'bank_account'] and this is the view i've made: views.py def register(request): data = dict() if request.method == 'POST': user_form = UserRegistrat…
type: AnsweredQuestion
score: 1
has title: Django clean password 'ValidationError' object has no attribute 'get'
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47528823
answer count: 1
has answer: http://stackoverflow.com/a/47528823
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47390473
has body: I am using tensorflow dataset api for my training data, the input_fn and generator for tf.data.Dataset.from_generator api def generator(): ...... yield { "x" : features }, label def input_fn(): ds = tf.data.Dataset.from_generator(generator, ......) ...... feature, label = ds.make_one_shot_iterator().get_next() return feature, label then I created a custom model_fn for my Estimator with some code like : def model_fn(features, labels, mode, params): print(features) ...... layer = network.create_full_connect(input_tensor=features["x"], (or layer = tf.layers.dense(features["x"], 200, ......) ...... when training : estimator.train(input_fn=input_fn) however, the code doesn't work since the features parameter for function model_fn is something : Tensor("IteratorGetNext:0", dtype=float32, device=/device:CPU:0) code "features["x"]" will fail and tell me : ......"site-packages\tensorflow\python\ops\array_ops.py", line 504, in _SliceHelper end.append(s + 1) TypeError: must be str, not int if I changes input_fn to : input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array([[1,2,3,4,5,6]])}, y=np.array([1]), the code goes on because features now is a dict. I have searched code for estimator and found it use some function such as features, labels = self._get_features_and_labels_from_input_fn( input_fn, model_fn_lib.ModeKeys.TRAIN) to retrieve features and label from input_fn, but I have no idea about why it passes me(model_fn) two different data type of features by using different dataset implements, if I want to use my generator mode, then how to use that type (IteratorGetNext) of features ? thanks for any help! [UPDATED] I had made some change to code, def generator(): ...... yield features, label def input_fn(): ds = tf.data.Dataset.from_generator(generator, ......) ...... feature, label = ds.make_one_shot_iterator().get_next() return {"x": feature}, label however, still failed at tf.layers.dense, now it said "Input 0 of layer dense_1 is incompatible with the layer: it…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47390639
answer count: 1
downvote count: 0
has title: is there a simple way to use features from tf.data.Dataset.from_generator with a custom model_fn(Estimator) in tensorflow
has answer: http://stackoverflow.com/a/47390639
tagged with: tensorflow
favorite count: 0
type: Question
score: 9
upvote count: 9
tagged with: python

http://stackoverflow.com/a/47516549
has comment: http://stackoverflow.com/comment/82126235
accepted answer of: http://stackoverflow.com/q/47515586
has comment: http://stackoverflow.com/comment/82040217
has comment: http://stackoverflow.com/comment/82124797
type: Answer
has comment: http://stackoverflow.com/comment/82125486
has comment: http://stackoverflow.com/comment/81996132
score: 2
has comment: http://stackoverflow.com/comment/82041698
has comment: http://stackoverflow.com/comment/82039967
has comment: http://stackoverflow.com/comment/82039893
has comment: http://stackoverflow.com/comment/82031401
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82125455
downvote count: 0
has comment: http://stackoverflow.com/comment/82040507
has body: Turning your input data into a csv file, I did the following, and it works well. import pandas as pd DF = pd.read_csv("CombinerData.csv") print DF print def combine_Columns_Into_New_Column(DF, columns_To_Combine, new_Column_Name): DF[new_Column_Name] = '' for Col in columns_To_Combine: DF[new_Column_Name] += DF[Col].map(str) + ' ' DF = DF.drop(columns_To_Combine, axis=1) DF = DF.groupby(by=['Identifier']).sum() return DF DF = combine_Columns_Into_New_Column(DF, ['Op1','Op2','Op3'],'Ops') print DF OUTPUT: Ops Identifier A str_1 str_2 str_3 B str_4 str_5 str_6 str_7 str_8 str_9 str_10 str... C str_13 str_14 str_15 str_16 str_17 str_18 INPUT FILE: Identifier,Op1,Op2,Op3 A,str_1,str_2,str_3 B,str_4,str_5,str_6 B,str_7,str_8,str_9 B,str_10,str_11,str_12 C,str_13,str_14,str_15 C,str_16,str_17,str_18
answers question: http://stackoverflow.com/q/47515586

http://stackoverflow.com/comment/81736176
type: QuestionComment
has text: @Ken: Still not working. Returns the same error.
score: 0
comment on: http://stackoverflow.com/q/47391242
type: Comment

http://stackoverflow.com/comment/81738185
type: Comment
score: 0
type: AnswerComment
has text: I cant provide anything minimal more than this, it is working fine, till the end. The output is just wrong.
comment on: http://stackoverflow.com/a/47392070

http://stackoverflow.com/q/47537644
score: 5
has body: I want to store a few different Wikipedia links but I don't want to store two different links to the same page twice. For example the following links are different but they point to the same Wikipedia page: https://en.wikipedia.org/w/index.php?title=(1S)-1-Methyl-2,3,4,9-tetrahydro-1H-pyrido-3,4-b-indole&amp;redirect=no https://en.wikipedia.org/w/index.php?title=(1S)-1-methyl-2,3,4,9-tetrahydro-1H-pyrido-3,4-b-indole&amp;redirect=no __________________________________________________|___________________________________________________________ The only difference is that one uppercase character. Or the following links: https://en.wikipedia.org/wiki/(0,1)-matrix https://en.wikipedia.org/wiki/(0,1)_matrix ___________________________________|______ That are only different because one has '-' and the other has '_'(' '). So what I want is storing only one of them or the following links: https://en.wikipedia.org/wiki/Tetrahydroharman https://en.wikipedia.org/wiki/Logical_matrix I have already tried the answer to this SO question. But it didn't work for me. (The result is the initial URL for me, not the one wiki redirects me to in the browser) So how can I achieve what I'm looking for!?
has answer: http://stackoverflow.com/a/48090694
possible better answer: http://stackoverflow.com/a/48090694
upvote count: 5
tagged with: http-redirect
tagged with: python
has title: Python - How to get the page Wikipedia will redirect me to?
has comment: http://stackoverflow.com/comment/82032387
has comment: http://stackoverflow.com/comment/82032419
linked to: http://stackoverflow.com/q/36070821
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47537837
downvote count: 0
has answer: http://stackoverflow.com/a/53668520
has answer: http://stackoverflow.com/a/76545029
tagged with: python-requests
tagged with: http
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47537837

http://stackoverflow.com/comment/81768430
type: AnswerComment
has text: This looks like the best solution here. `raw_input` could mention the fact that the number should be long enough.
score: 0
comment on: http://stackoverflow.com/a/47407105
type: Comment

http://stackoverflow.com/q/47493042
favorite count: 0
has comment: http://stackoverflow.com/comment/83299380
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83279791
upvote count: 1
tagged with: imshow
has body: I'm trying to insert a plot into another one by using: ... im = plt.imread(get_sample_data('Inset.eps', asfileobj=True),format='eps') newax = f.add_axes([0.14, 0.30, 0.45, 0.40]) newax.imshow(im,interpolation='none') newax.axis('off') plt.savefig('FinalPlot.eps',format='eps',dpi=1000,bbox_inches='tight') The problem is that everything in FinalPlot.eps has good resolution but the inset, it has a really poor quality. Do you know how to improve the quality of the inset? Image example
has comment: http://stackoverflow.com/comment/83307973
tagged with: resolution
tagged with: imread
score: 1
has title: Losing resolution inset plot Python
tagged with: python
tagged with: insets

http://stackoverflow.com/comment/81830962
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47424522
type: AnswerComment
has text: I tried that and it still doesn't work? still getting the same copy a slice error

http://stackoverflow.com/comment/134407878
comment on: http://stackoverflow.com/a/47490220
score: 0
has text: Thanks, is there a way to horizontally center the button with respect to the existing axis?
type: Comment
type: AnswerComment

refactoring
tags question: http://stackoverflow.com/q/47398441
type: Tag
tag name: refactoring

http://stackoverflow.com/a/47642587
type: Answer
answers question: http://stackoverflow.com/q/47519836
has body: When dealing with the ctypes module, everything is going to be byte aligned (8 bits). To account for the possibility of fields with non-byte aligned bit lengths, ctypes automatically allocates the space with the size of the field selected and then places the sub-fields into the newly byte aligned allocated space. For example, given the following ctypes Structure: from ctypes import * class simple_pkt(Structure): _fields_ = ( ('A', c_int8, 4), ('B', c_int8, 4), ('C', c_int8) ) The end packet produced in memory will be: +---------------------------------------------------------------+ | bit locations | +-------------------------------+-------------------------------+ | Byte 0 | Byte 1 | +===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | A | A | A | A | B | B | B | B | C | C | C | C | C | C | C | C | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ This is nice and lined up as expected. Now, let's look at , if you have two sub-fields whose bit lengths added up aren't byte aligned: class simple_pkt(Structure): _fields_ = ( ('A', c_int8, 2), ('B', c_int8, 4), ('C', c_int8) ) You'll get empty or spare bits: +---------------------------------------------------------------+ | bit locations | +-------------------------------+-------------------------------+ | Byte 0 | Byte 1 | +===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | A | A | B | B | B | B | | | C | C | C | C | C | C | C | C | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ Notice that there is a gap between B and C. This is the case for all of the c_&lt;int&gt; data types within the ctypes module. As far as I know, there is no way around this.
score: 0

http://stackoverflow.com/comment/82025320
type: Comment
comment on: http://stackoverflow.com/q/47533601
type: QuestionComment
has text: The problem here might be that your flask server is the one which has socket connection with the client and not your celery process. you might refer to this answer https://stackoverflow.com/a/33763838/4662041 You can also refer to this section of the documentation of Flask-SocketIO: https://flask-socketio.readthedocs.io/en/latest/#emitting-from-an-external-process
score: 0

http://stackoverflow.com/a/47416302
type: Answer
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47416270
has comment: http://stackoverflow.com/comment/81786681
has comment: http://stackoverflow.com/comment/81786662
has body: The method din't work because df.filter(regex='dt_') is a modified copy. For assigning data for multiple columns you need to select the columns from the actual dataframe with index based selection or assign it inplace using assign. So after filtering get the columns and do a boolean indexing before assigning it i.e df[df.filter(regex = 'dt_').columns] = df.filter(regex = 'dt_').apply(lambda x: pd.to_datetime(x)) dt_one dt_two other_col 0 2015-01-01 2015-01-01 1 1 2016-02-02 2016-02-02 2

http://stackoverflow.com/comment/81969920
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47506934
type: Comment
has text: This data from Database table or which format it is ?

http://stackoverflow.com/comment/81763703
comment on: http://stackoverflow.com/q/47391001
type: Comment
score: 0
has text: @JoshuaDrake I decompiled all the pyc files so I guess I answered my own question. I'm trying to decompile source code but I could not find it despite decompiling every single pyc file visible.
type: QuestionComment

http://stackoverflow.com/q/47449241
has title: bitwise and operator discrepancy in javascript
tagged with: javascript
has comment: http://stackoverflow.com/comment/81853880
has comment: http://stackoverflow.com/comment/81854126
score: 0
has comment: http://stackoverflow.com/comment/81853496
has comment: http://stackoverflow.com/comment/81853950
tagged with: python
tagged with: bitwise-and
tagged with: node.js
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81864163
has body: bitwise operator is resulting in incorrect response in javascript, compared with the same in python. Following is the code snippet, can someone help me with this regard? # Python =========================== $ cat bitwise_example.py x = 2650800128 y = 2684354559 m = x while (x &lt; y): m = m &amp; x x += 1 print m ============ $ python bitwise_example.py 2650800128 =========================== # JavaScript =========================== $ cat bitwise_example.js let x = 2650800128; let y = 2684354559; let m = x; while (x &lt; y) { m = m &amp; x; x += 1; } console.log(m); ============ $ node bitwise_example.js -1644167168 ========================
type: UnansweredQuestion

http://stackoverflow.com/a/47415406
upvote count: 1
type: Answer
has body: Try {% for article in articles %} {{ article.values }} {% endfor %} But a debugger is really what you want for this kind of stuff. Or even just printing to the console. Printing Objects in Django
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47415234

http://stackoverflow.com/comment/82019259
comment on: http://stackoverflow.com/q/47531444
score: 0
type: Comment
type: QuestionComment
has text: It would be good if you post a minimum working or the sample code to reproduce?

http://stackoverflow.com/comment/81900776
score: 1
comment on: http://stackoverflow.com/a/47470563
type: AnswerComment
type: Comment
has text: AJAX is used to make calls with different methods like GET and POST and make changes in parts of your html document on the events of success or failure. Now, even for a GET method you will have to manually create the URL by appending your parameters. AJAX won't do that for you.

http://stackoverflow.com/comment/81900845
type: Comment
type: QuestionComment
has text: In script for conversion is bad value of divisor. Right value is 255.0
comment on: http://stackoverflow.com/q/47470040
score: 0

http://stackoverflow.com/comment/94651087
has text: @DanielMöller, i have similar problem, i want to binarize(quantize) gradients at each backpropagation.. is there anyway i could achieve that in keras..in tensorflow it is possible i beleive
type: Comment
comment on: http://stackoverflow.com/a/47417083
score: 0
type: AnswerComment

http://stackoverflow.com/a/47544645
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: I figured it out - pretty simple. The first and second prefetch statements are just fine. However the way I was accessing them was not. Should have accessed like so: player.team.all_team_players forgot to access the team first thru player, then the attribute is accessible. Doh
accepted answer of: http://stackoverflow.com/q/47536903
type: Answer
answers question: http://stackoverflow.com/q/47536903

http://stackoverflow.com/a/57731434
has body: You should verify if the predicted probabilities are higher than the default threshold. If it is the case, you will find always 1 as the class predicted. To verify the values of the probabilities, you may run the following code, since your test features are idenfied in your code as: flat. clf = svm.SVC(gamma=0.001, C=100) # This line of code is from your post x,y = digits.data[:-1], digits.target[:-1] # This line of code is from your post clf.fit(x,y) # This line of code is from your post y_pred=svc.predict_proba(flat) # Here, I predict the probabilities, using the test data you have named flat. # The predicted probabilities are printed bellow print(y_pred) Sure, you have taken a glance at the values of the predicted probabilities, y_pred, printed with the code above. If all these probabilities are higher than 0.5, which is the default threshold for binary classification, you should used the code below, and change the threshold to a value higher than the minimum value of the probabilities predicted above. For example, suppose that the minimum value of the probabilities is 0.55, the threshold should be higher than 0.55. I choose 0.6. However, if 0.6 is higher than the maximum value of the probability, threshold=0.6 ypred=(y_pred[:,1]&gt;threshold).astype('int') print(ypred) You can try several value for the threshold and test which one produce the best metric (accuracy score, recall, precision etc.) you are interested.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47425872

http://stackoverflow.com/q/47538080
has comment: http://stackoverflow.com/comment/82033421
answer count: 4
has title: Python subprocess command answering prompt
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82066207
has answer: http://stackoverflow.com/a/61014137
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82033523
downvote count: 0
tagged with: process
tagged with: python
has comment: http://stackoverflow.com/comment/82033600
has comment: http://stackoverflow.com/comment/82033903
has answer: http://stackoverflow.com/a/63500883
score: 2
has body: I am trying to call a command ionic cordova prepare which prompts for a "Y/N" response. I always want this to be yes. When i tried using os.system it would hang at the last part and not move onto the rest of the script. Does anyone know the right way of writing this. This is what i tried foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE) yes_proc = Popen(['yes', 'y'], stdout=foo_proc.stdin) foo_proc.communicate()[0] yes_proc.wait() But it just hangs on the command and doesn't seem to execute
tagged with: subprocess
has comment: http://stackoverflow.com/comment/82033514
has answer: http://stackoverflow.com/a/47553846
tagged with: scripting
tagged with: shell
has answer: http://stackoverflow.com/a/60228351
has comment: http://stackoverflow.com/comment/82033224

http://stackoverflow.com/q/47490851
has body: My goal is to have a "sizegrip widget" that enables the user to resize a text widget. Picture to illustrate: (I apologize for the bad gridding) Is it possible to make the sizegrip widget resize a text widget instead of the root window? Any alternative widget that fits my needs?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81937341
has comment: http://stackoverflow.com/comment/81937789
score: 1
has comment: http://stackoverflow.com/comment/81937622
tagged with: python
has answer: http://stackoverflow.com/a/47492547
has title: tkinter - resize text widget (sizegrip for text widget)
has comment: http://stackoverflow.com/comment/81937855
has comment: http://stackoverflow.com/comment/81937257
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81937565
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81939111
upvote count: 1

http://stackoverflow.com/comment/81910424
has text: Oh wow! it worked. I didn't add event=None in the method defenition. That was the problem.
type: Comment
comment on: http://stackoverflow.com/a/47476389
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81884209
has text: It should work to me. I suspect that you have another definition of `MagicCardSet` "somewhere", which does not possess the method `get_uncommon_colors`. Where "somewhere" means between the definition you show us, and the instantiation/call.
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47464697
type: QuestionComment

http://stackoverflow.com/q/47463480
has body: I have to replace every element in the list by sum of all other elements in the list. [1, 2, 3] =&gt; [5, 4, 3] [1] =&gt; [0] [2, 7, 9] =&gt; [16, 11, 9] I have done so far: for i in range(len(numbers)): numbers[i] = sum[numbers[:i]] + sum[numbers[i+1:]] return numbers But I'm keep getting TypeError
has comment: http://stackoverflow.com/comment/81881807
answer count: 1
accepted answer: http://stackoverflow.com/a/47463505
downvote count: 1
has title: Replace every element by sum of all other elements
favorite count: 0
has answer: http://stackoverflow.com/a/47463505
type: Question
tagged with: python-3.5
upvote count: 0
tagged with: python
score: -1
tagged with: list-comprehension
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/81806059
score: 0
comment on: http://stackoverflow.com/q/47425528
type: Comment
type: QuestionComment
has text: You must point pip at the archive for `master` branch, not at the git repository itself.

http://stackoverflow.com/comment/81960302
type: Comment
type: QuestionComment
has text: how do you expect me to confirm that without the data? You need to make a MCWE that demonstrates this problem. https://stackoverflow.com/help/mcve
comment on: http://stackoverflow.com/q/47502181
score: 1

http://stackoverflow.com/comment/81933634
type: QuestionComment
comment on: http://stackoverflow.com/q/47489301
score: 0
type: Comment
has text: Did you google? There are many questions to your question, what are `common things` do you mean similar colors? similar found objects?

http://stackoverflow.com/comment/81942431
has text: Note that the quoted post was made by Python core developer, Raymond Hettinger, a principal author of the C code for both [`list`](https://github.com/python/cpython/blob/3.6/Objects/listobject.c) and [`deque`](https://github.com/python/cpython/blob/3.6/Modules/_collectionsmodule.c#L10), so he knows what he's talking about!
score: 5
comment on: http://stackoverflow.com/a/47493474
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81834907
type: AnswerComment
has text: Is there no way of turning a string into a "soon to be variable?" I tried using eval(player) = Character() why didn't it work?
type: Comment
comment on: http://stackoverflow.com/a/47439282
score: 0

http://stackoverflow.com/comment/134954722
type: Comment
comment on: http://stackoverflow.com/a/47496649
has text: I work with a COTS product that allows us to script in Python. Our script will be passed, in a predictably named variable, the name of a variable that holds a value we may want to work with. @timgeb's "accepted" answer doesn't work at all in this case, as I have no control over how the COTS product passes data to my script. On the other hand, this `locals()[var_with_varname]` approach from @KarlKnechtel works great!
score: 0
type: AnswerComment

http://stackoverflow.com/a/47436190
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47431777
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47431777
has body: Feedable iterators should help, but they're tough to work with. You need to create a placeholder and string handles: dataset_trn = tf.data.Dataset.range(10) dataset_tst = tf.data.Dataset.range(10).map(lambda i: i + 1000) holder = tf.placeholder(tf.string, shape=[]) iterator = tf.data.Iterator.from_string_handle( holder, dataset_trn.output_types, dataset_trn.output_shapes) batch = iterator.get_next() trn_iter = dataset_trn.make_one_shot_iterator() trn_handle = trn_iter.string_handle() tst_iter = dataset_tst.make_one_shot_iterator() tst_handle = tst_iter.string_handle() with tf.Session() as sess: for _ in range(2): trn_string = sess.run(trn_handle) tst_string = sess.run(tst_handle) for _ in range(5): print(sess.run(batch, feed_dict={holder: trn_string})) print(sess.run(batch, feed_dict={holder: tst_string}))
downvote count: 0

http://stackoverflow.com/a/47435789
has comment: http://stackoverflow.com/comment/81826481
answers question: http://stackoverflow.com/q/47435446
has comment: http://stackoverflow.com/comment/81827343
has body: It seems that factory boy have a feature to provided additional parameters without having to add theses fields to the exclude attribute: http://factoryboy.readthedocs.io/en/latest/reference.html#simple-parameters: class UserFactory(factory.DjangoModelFactory): class Params: has_purchase = False Used in conjunction with the http://factoryboy.readthedocs.io/en/latest/reference.html#lazyattribute maybe ?
type: Answer
has comment: http://stackoverflow.com/comment/81826608
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/81827415

http://stackoverflow.com/a/47429612
accepted answer of: http://stackoverflow.com/q/47429113
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81815476
answers question: http://stackoverflow.com/q/47429113
score: 1
has body: When you use depends the field must have a compute attribute : some_feild = fiels.SomeType(......., compute='method_name') @api.depends('some_field_2', ...) def method_name(self): # and here the function will be computed. If your field are 100% computed field, best thing in odoo that you can listen for changing in the parent class to compute the child field: class bsi_print_order(models.Model): _name = 'bsi.print.order' .... class bsi_print_order_lines(models.Model): _name = 'bsi.print.order.lines' is_book_block = fields.Boolean(string="Is Book Block Done", compute="compute_book_block") @api.depends('print_order.book_block') def compute_book_block(self): # in depends it's always a good this to loop # or use api.one with depends for rec in self: if rec.print_order: self.is_book_block = self.print_order.book_block But this is Ok only if this field is always a compute field, i mean the user will never change it's value from the UI. If your field is not computed and the user can change the value if he want than you need to use onchange in the parent class. class bsi_print_order(models.Model): _name = 'bsi.print.order' .... @api.onchange('book_block '): def onchange_book_block(self): # in onchange no need for loop # because self should always have only one recod for line in self.order_picking: line.is_book_block = self.book_block
type: Answer

flask-admin
tags question: http://stackoverflow.com/q/47454315
type: Tag
tag name: flask-admin

http://stackoverflow.com/q/47465922
has comment: http://stackoverflow.com/comment/81886491
has answer: http://stackoverflow.com/a/47466174
downvote count: 0
has answer: http://stackoverflow.com/a/47465999
possible better answer: http://stackoverflow.com/a/47465992
has title: Python 2.7: Format a list within a list using for loops
has answer: http://stackoverflow.com/a/47465992
type: AnsweredQuestion
has body: Input: data = [['A', 'B', 'C'], ['001', 'ddd', 'eee', '10'], ['002', 'fff', 'ggg', '20']] Expected output: data = ['A', 'B', 'C'], [1, 'ddd', 'eee', 10], [2, 'fff', 'ggg', 20]] Convert columns with numerical values from strings to integers (with quotes around the numbers removed I have attempted with the below code but I am getting this error: ValueError: could not convert string to float: A Could anyone point out my mistake? formatted = [] for row in data: new_row = [] for i, col in enumerate(row): if i != [1,2]: new_row.append(col) new_row.append(float(col)) formatted.append(new_row) print formatted
score: 3
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/47465999
upvote count: 3
has comment: http://stackoverflow.com/comment/81886477
tagged with: python
has answer: http://stackoverflow.com/a/47466005
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81886496
has comment: http://stackoverflow.com/comment/81886474
has answer: http://stackoverflow.com/a/47466086
answer count: 5

http://stackoverflow.com/comment/81979566
type: AnswerComment
has text: This is just an Enigma - i will find it out tomorrow with our developers because i really tried any possible solution. thanks anyway.
type: Comment
comment on: http://stackoverflow.com/a/47508494
score: 0

http://stackoverflow.com/comment/81800931
type: Comment
has text: I don't know what you tried but yes, the label "t5" is obviously not a float.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47422781

http://stackoverflow.com/a/47536532
score: 0
answers question: http://stackoverflow.com/q/47536287
has body: You have included your implementation inside a function read(). You need to call the function somewhere. def read(): file1=open("file.txt","r") dict={} for line in file1: line=line.split() if not line:continue dict[line[0]]=line[1:] print(dict) read() Try this.
type: Answer

http://stackoverflow.com/a/47521796
downvote count: 0
has comment: http://stackoverflow.com/comment/82098940
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47521452
has body: Not sure what you mean here, but maybe your can use groupby() and then traverse the groups? Here's a simple example (using pyplot) import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline dicts = [] dicts.append({'item':'book','year':2000,'price':2, 'quantity':50}) dicts.append({'item':'table','year':2000,'price':33, 'quantity':44}) dicts.append({'item':'chair','year':2000,'price':21, 'quantity':31}) dicts.append({'item':'book','year':2001,'price':3, 'quantity':50}) dicts.append({'item':'table','year':2001,'price':20, 'quantity':44}) dicts.append({'item':'chair','year':2001,'price':2, 'quantity':31}) dicts.append({'item':'book','year':2002,'price':36, 'quantity':7}) dicts.append({'item':'table','year':2002,'price':200, 'quantity':50}) dicts.append({'item':'chair','year':2002,'price':44, 'quantity':5}) df = pd.DataFrame.from_records(dicts) grouped = df.groupby('item') fig, axes = plt.subplots(1,3,sharey=True) fig.set_size_inches(15,4) for i,group_key in enumerate(list(grouped.groups.keys())): grouped.get_group(group_key).set_index('year').plot(kind='bar',ax = axes[i]) axes[i].set_title(group_key,fontsize=15)
accepted answer of: http://stackoverflow.com/q/47521452
type: Answer
has comment: http://stackoverflow.com/comment/82042647
has comment: http://stackoverflow.com/comment/82011673

http://stackoverflow.com/a/47384608
score: 2
has body: You can divide each value in your list comprehension by n: x = [b ** i for i in range(n)] x_over_n = [a/n for a in x] edit: def x_to_the_i_over_n(x, i, n): return x**i / n n = 4 x = 123 results = [] for i in range(n): results.append(x_to_the_i_over_n(x, i, n)) edit 2: import numpy b = numpy.array(range(10)) b**2 #--&gt; array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) b**2 / 4 #--&gt; array([ 0. , 0.25, 1. , 2.25, 4. , 6.25, 9. , 12.25, 16. , 20.25])
has comment: http://stackoverflow.com/comment/81722098
has comment: http://stackoverflow.com/comment/81722918
accepted answer of: http://stackoverflow.com/q/47384581
upvote count: 2
has comment: http://stackoverflow.com/comment/81722402
has comment: http://stackoverflow.com/comment/81722409
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81722558
downvote count: 0
has comment: http://stackoverflow.com/comment/81722072
has comment: http://stackoverflow.com/comment/81723498
has comment: http://stackoverflow.com/comment/81722436
has comment: http://stackoverflow.com/comment/81722685
has comment: http://stackoverflow.com/comment/81722755
has comment: http://stackoverflow.com/comment/81722476
type: Answer
has comment: http://stackoverflow.com/comment/81722653
answers question: http://stackoverflow.com/q/47384581
has comment: http://stackoverflow.com/comment/81722045
has comment: http://stackoverflow.com/comment/81723124
has comment: http://stackoverflow.com/comment/81723464
has comment: http://stackoverflow.com/comment/81722637

http://stackoverflow.com/tag/zip
tags question: http://stackoverflow.com/q/47499824
tags question: http://stackoverflow.com/q/47526165
tags question: http://stackoverflow.com/q/47518041
type: Tag
tags question: http://stackoverflow.com/q/47425802
tags question: http://stackoverflow.com/q/47439536
tag name: zip
tags question: http://stackoverflow.com/q/47452016
tags question: http://stackoverflow.com/q/47473084
tags question: http://stackoverflow.com/q/47438424
tags question: http://stackoverflow.com/q/47419655
tags question: http://stackoverflow.com/q/47401016
tags question: http://stackoverflow.com/q/47489711

http://stackoverflow.com/comment/81879376
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47449694
has text: Yes. Your both versions are good. I've done already very similar approach. I wonder if it's optimal in terms of speed. It works quite slow. Maybe it's the case Python is overall slow on my computer (apart from R for example)
type: Comment

http://stackoverflow.com/a/63447691
downvote count: 0
score: 15
has comment: http://stackoverflow.com/comment/131839616
has body: The recommended buildpack doesn't work anymore. Here's a quick, direct way to do the same: Set config variables: heroku config:set GOOGLE_APPLICATION_CREDENTIALS=gcp_key.json heroku config:set GOOGLE_CREDENTIALS=&lt;CONTENTS OF YOU GCP KEY&gt; The GOOGLE_CREDENTIALS is easier to set in the Heroku dashboard. Create a .profile file in your repo with a line to write the json file: echo ${GOOGLE_CREDENTIALS} &gt; /gcp_key.json .profile is run every time the container starts. Obviously, commit the changes to .profile and push to Heroku, which will trigger a rebuild and thus create that gcp_key.json file.
answers question: http://stackoverflow.com/q/47446480
has comment: http://stackoverflow.com/comment/121477169
has comment: http://stackoverflow.com/comment/124780059
type: Answer
has comment: http://stackoverflow.com/comment/124623890
upvote count: 15
has comment: http://stackoverflow.com/comment/132547976

http://stackoverflow.com/comment/81838584
has text: A good SO question shows what works or doesn't work - errors, tracebacks, right and wrong results. We don't like setting up our own test cases even if the functions are clear.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47440161
type: Comment

http://stackoverflow.com/comment/81839766
type: QuestionComment
comment on: http://stackoverflow.com/q/47442153
has text: What does `go env GOPATH` show from within your python process? `go build ./src/folder` looks odd too, what exactly are you doing?
score: 0
type: Comment

http://stackoverflow.com/comment/81977570
type: Comment
type: QuestionComment
has text: OP, I've come up with a more efficient version of my previous answer. Take a look and see if it works for you. Thanks!
comment on: http://stackoverflow.com/q/47508789
score: 0

http://stackoverflow.com/q/47502652
accepted answer: http://stackoverflow.com/a/47502703
upvote count: 0
has comment: http://stackoverflow.com/comment/81961149
has answer: http://stackoverflow.com/a/47502703
has comment: http://stackoverflow.com/comment/81961146
has title: Inexplicable, simple, 'list index out of range' -- Python
tagged with: django
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/81961186
has comment: http://stackoverflow.com/comment/81961126
has comment: http://stackoverflow.com/comment/81961111
has comment: http://stackoverflow.com/comment/81963145
tagged with: python
score: -1
has body: I keep trying to use this for loop. Actually a variety of for loops. I keep getting the error, 'list index out of range'. No idea. for q in range(0, len(list(package_ids))-1): if (q==0): query = 'Zero' + package_ids[q] else: query = 'More' + package_ids[q]
possible better answer: http://stackoverflow.com/a/47502710
has comment: http://stackoverflow.com/comment/81961178
favorite count: 0
has comment: http://stackoverflow.com/comment/81961134
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47502710
answer count: 2

http://stackoverflow.com/a/47424355
score: 0
has body: I would have implemented this in three steps: The first step would build a complete list of item URLs with corresponding categories and subcategories in which they were found. I would then implement some logic on this list to make sure that only the most specific (i.e deepest) category were used. The cleaned list of URLs would then be fed to the second step scraper that would scrape the actual item data. More strategy than coding, but hope it helps. In summary: crawl -> clean -> scrape
answers question: http://stackoverflow.com/q/47417326
type: Answer

http://stackoverflow.com/a/47495222
has comment: http://stackoverflow.com/comment/81945672
has body: You said you are tried for single face. Have you succeed in that? What is the error you are getting after executing the given code?
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47495048

http://stackoverflow.com/q/47520356
tagged with: python
has answer: http://stackoverflow.com/a/47520980
tagged with: dictionary
answer count: 2
has answer: http://stackoverflow.com/a/47520564
type: UnansweredQuestion
has body: I have a big nested, then nested then nested json file saved as .txt format. I need to access some specific key pairs and crate a data frame or another transformed json object for further use. Here is a small sample with 2 key pairs. [ { "ko_id": [819752], "concepts": [ { "id": ["11A71731B880:http://ontology.intranet.com/Taxonomy/116@en"], "uri": ["http://ontology.intranet.com/Taxonomy/116"], "language": ["en"], "prefLabel": ["Client coverage &amp; relationship management"] } ] }, { "ko_id": [819753], "concepts": [ { "id": ["11A71731B880:http://ontology.intranet.com/Taxonomy/116@en"], "uri": ["http://ontology.intranet.com/Taxonomy/116"], "language": ["en"], "prefLabel": ["Client coverage &amp; relationship management"] } ] } ] The following code load the data as list but I need to access to the data probably as a dictionary and I need the "ko_id", "uri" and "prefLabel" from each key pair and put it to a pandas data frame or a dictionary for further analysis. with open('sample_data.txt') as data_file: json_sample = js.load(data_file) The following code gives me the exact value of the first element. But donot actually know how to put it together and build the ultimate algorithm to create the dataframe. print(sample_dict["ko_id"][0]) print(sample_dict["concepts"][0]["prefLabel"][0]) print(sample_dict["concepts"][0]["uri"][0])
has title: Create a data frame from a complex nested dictionary?
type: Question
score: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/47534021
score: 0
has body: 1 - Open a terminal and pip install cmake: pip install cmake 2 - Download opencv repository from https://github.com/opencv/opencv 3 - On your terminal cd to the folder where you downloaded the opencv repository and compile it with cmake typing the following commands: mkdir release cd release cmake -D CMAKE_BULD_TYPE=RELEASE -D BUILD_PYTHON_SUPPORT=ON USE_V4L=ON WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON USE_GStreamer=ON .. make make install Opencv is now correctly installed on your machine and you should be able to successfully import it in Python with no error. Let me know if this solves the problem
answers question: http://stackoverflow.com/q/47532858
type: Answer

http://stackoverflow.com/a/47463599
has comment: http://stackoverflow.com/comment/81882321
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81882548
has comment: http://stackoverflow.com/comment/81882263
has comment: http://stackoverflow.com/comment/81883729
answers question: http://stackoverflow.com/q/47462255
type: Answer
has body: Nothing will ever happen with your matrix because your first if-check will always perform an early return: def traceback(i, j, matrix1): if j - i &gt; 0: return ... traceback(0, n-1, matrix1) To go beyond the first return, j should be less than i, right? Now observe your inputs: (n - 1) - 0 &lt;= 0 =&gt; n - 1 &lt;= 0 =&gt; n &lt;= 1 So in the current state, your traceback function will execute the matrix element checks if and only if n == 0 or n == 1, both being the trivial cases of an empty submatrix or a scalar submatrix. I suppose the first block should restrict the traversal to the upper triangle, above the main diagonal? Then simply flip the sign: if j - i &lt; 0: return

http://stackoverflow.com/q/47401517
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81756710
downvote count: 5
score: -4
has body: I am using Python 3 and want to turn something into a while loop but I am new so I am having some trouble with this. username_chosen = input("Enter the username of the user for their details :") with open("data.txt") as f: for line in f: if username_chosen in line: print(line) The loop I want is where the program keeps checking if there is a username as the one entered by the user and if there is not then it tells them error and prompts them to input again until the program can find the username.
has answer: http://stackoverflow.com/a/47401783
has title: Iterating through a file using a While loop instead of For
favorite count: 0
has answer: http://stackoverflow.com/a/47404950
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81756926
type: UnansweredQuestion

http://stackoverflow.com/comment/81760263
score: 0
comment on: http://stackoverflow.com/q/47402445
type: Comment
type: QuestionComment
has text: Great, I've added it as an answer.

http://stackoverflow.com/comment/81951593
type: Comment
type: QuestionComment
has text: `line = file1.readline()` ?
comment on: http://stackoverflow.com/q/47498189
score: 1

http://stackoverflow.com/comment/81799225
type: Comment
type: QuestionComment
has text: Also, notebook example here: https://gist.github.com/mikofski/5851633
comment on: http://stackoverflow.com/q/47422147
score: 0

http://stackoverflow.com/q/47484680
favorite count: 0
has answer: http://stackoverflow.com/a/47484738
tagged with: strip
has comment: http://stackoverflow.com/comment/81924294
has body: I have the following data in a huge string: data="in West upto 19:17 &amp;nbsp; &amp;nbsp; &amp;nbsp; in North from 19:17 " I am trying to remove "'&amp;nbsp ;'" from this huge string but it does not work with strip like this: data= data.strip('&amp;nbsp;') Same output as before no change in text of data: print(data) in West upto 19:17 &amp;nbsp; &amp;nbsp; &amp;nbsp; in North from 19:17 Why is there no change no stripping is happening all the &amp;nbsp are present there and then? Help Please!
type: Question
possible better answer: http://stackoverflow.com/a/47484729
has answer: http://stackoverflow.com/a/47484729
tagged with: python
score: -3
downvote count: 4
has comment: http://stackoverflow.com/comment/81924320
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81924284
answer count: 2
has comment: http://stackoverflow.com/comment/81924279
has title: Why strip not working?
accepted answer: http://stackoverflow.com/a/47484738
upvote count: 1

http://stackoverflow.com/q/47490505
has answer: http://stackoverflow.com/a/70739935
has answer: http://stackoverflow.com/a/47490612
score: 10
upvote count: 10
type: Question
has body: For simplicity sake, lets say I have this dataframe. Date Open Close 2016-01-01 100 129 2016-01-02 198 193 2016-01-03 103 102 2016-01-04 102 109 I can't state all the column names because there are too many. So how can I shift all the columns except for two of them (Date &amp; Close)? I want to shift all the columns except (Date &amp; Close) back one row. Date Open Close 2016-01-01 198 129 2016-01-02 103 193 2016-01-03 102 102 2016-01-04 NaN 109
answer count: 2
has title: How do I shift multiple columns? Pandas, Python
type: UnansweredQuestion
downvote count: 0
tagged with: python
favorite count: 0
tagged with: pandas

http://stackoverflow.com/a/47391298
downvote count: 0
upvote count: 1
has body: I guess what you want is to show different data on all 4 plots, hence use a single loop. Make sure to use the axes plotting method, not plt.plot as the latter would always plot in the last subplot. import matplotlib.pyplot as plt import numpy as np def load_file(filename): return np.loadtxt(filename, delimiter=',', usecols=(0, 1), unpack=True, skiprows=1) fig, ax_list = plt.subplots(2,2) for i,(filename,ax) in enumerate(zip(file_list, ax_list.flatten())): x,y = load_file(filename) ax.plot(x,y, linewidth=0.5,ls='-' ) plt.show()
type: Answer
answers question: http://stackoverflow.com/q/47391136
score: 1

http://stackoverflow.com/q/47487029
has comment: http://stackoverflow.com/comment/81930489
tagged with: python
has body: I'm learning how to use Selenium with Python by trying to scrap Matrix ITA software (in case you don't know that, it helps to find good flight fares). I'm filling the whole form with Selenium exactly in the same way as manually (same airports, same dates, multicity: AAA-BBB,BBB-AAA,CCC-DDD). When running the script I get completely different results. Manually the flight CCC-DDD is operated by airline X, when running Selenium - it is operated by airline Y. It dramatically changes the overall price of whole booking. Why? I set up the same user agent as well as incognito mode. Is there any trick?
has title: Different results when using Selenium + Python
score: 0
has comment: http://stackoverflow.com/comment/81928963
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81929668
tagged with: selenium
tagged with: web-scraping
type: Question

http://stackoverflow.com/comment/81786363
comment on: http://stackoverflow.com/q/47404792
score: 0
has text: Have you tried running on bigger machines?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47431616
tagged with: django
has answer: http://stackoverflow.com/a/47433866
type: Question
tagged with: cassandra
score: 0
has answer: http://stackoverflow.com/a/47433083
has answer: http://stackoverflow.com/a/47431946
tagged with: python
has body: I am learning RestAPI and When I try to post data to update my database columns the modified_on column should automatically populated to current date and time but it is not updating. I am currently using django cassandra engine ORM where there is no functionality like auto_add_now() or auto_now(). Can any one give a suggestion where am I going wrong? Model Class: class Mydb(DjangoCassandraModel): id = columns.UUID(primary_key=True, default=uuid.uuid4()) user_name = columns.Text() user_email = columns.Text(default=None) user_password = columns.Text() description = columns.Text() creation_date = columns.DateTime(default=datetime.datetime.today(), static=True) modified_on = columns.DateTime(default=datetime.datetime.today()) My Serialization class: class TaskSerializer(serializers.Serializer): # id = serializers.UUIDField(default=uuid.uuid4) USER_ID = serializers.UUIDField(default= uuid.uuid4(),source='id') # user_name = serializers.CharField(max_length=50) USER_NAME_FIELD = serializers.CharField(max_length=50, source='user_name') USER_EMAIL = serializers.CharField(source='user_email') USER_PASSWORD = serializers.CharField(max_length=20, source='user_password') EXPLANATION = serializers.CharField(max_length=100, source='description') MODIFIED_AT = serializers.DateTimeField(default=datetime.datetime.today(), source='modified_on') CREATED_ON = serializers.DateTimeField(default=datetime.datetime.today(), source='creation_date') def create(self, validated_data): return Mydb.objects.create(**validated_data) def update(self, instance, validated_data): # instance.id = validated_data.get('id', instance.id) instance.user_name = validated_data.get('user_name', instance.user_name) instance.user_email = validated_data.get('user_email', instance.user_email) instance.user_password = validated_data.get('user_password', instance.user_password) instance.description = validated_data.get('description',instance.description) instance.modified_on = validated_data.get('modified_on', instance…
accepted answer: http://stackoverflow.com/a/47431946
has title: Django ORM Issue
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47431832
possible better answer: http://stackoverflow.com/a/47431832

http://stackoverflow.com/comment/82027112
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47531444
type: Comment
has text: `value = np.fmax(value, np.var.universe.min())` is the error shown

http://stackoverflow.com/comment/81915626
has text: can you show your view post method ? the method that you use to handle the post request
type: QuestionComment
comment on: http://stackoverflow.com/q/47480302
score: 0
type: Comment

http://stackoverflow.com/comment/82033484
type: Comment
type: QuestionComment
has text: Show us your view if you want to send data with post
score: 0
comment on: http://stackoverflow.com/q/47538130

http://stackoverflow.com/a/47421361
has body: Thank you FredMan. I did not know about this API. It seems we need to give only the article id and we can the comments from the article. This was the solution I was looking for.
answers question: http://stackoverflow.com/q/47402798
type: Answer
score: 0

http://stackoverflow.com/comment/127255388
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47422176
has text: I have the same problem. when the application makes multiple requests. but when it's only one it works.

http://stackoverflow.com/comment/81870645
has text: @j.walker You should rather update your question to its current version and include the error message as well.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47457768

http://stackoverflow.com/comment/81900715
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47472574
has text: @Grzegorz Oledzki, I checked the question that you think is a duplicate with my question. However, I think my question is a bit different from that question. What I don't understand is, if the value of z has changed, why not that of y?
type: Comment

http://stackoverflow.com/a/47408562
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81806139
answers question: http://stackoverflow.com/q/47407438
has comment: http://stackoverflow.com/comment/81886255
score: 1
has body: I adapted the code from pyimagesearch to work in python 3.5 and opencv 3.3 import os import cv2 import imutils import numpy as np import pytesseract from PIL import Image def order_points(pts): # initialzie a list of coordinates that will be ordered # such that the first entry in the list is the top-left, # the second entry is the top-right, the third is the # bottom-right, and the fourth is the bottom-left rect = np.zeros((4, 2), dtype="float32") # the top-left point will have the smallest sum, whereas # the bottom-right point will have the largest sum s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] # now, compute the difference between the points, the # top-right point will have the smallest difference, # whereas the bottom-left will have the largest difference diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] # return the ordered coordinates return rect def four_point_transform(image, pts): # obtain a consistent order of the points and unpack them # individually rect = order_points(pts) (tl, tr, br, bl) = rect # compute the width of the new image, which will be the # maximum distance between bottom-right and bottom-left # x-coordiates or the top-right and top-left x-coordinates widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) maxWidth = max(int(widthA), int(widthB)) # compute the height of the new image, which will be the # maximum distance between the top-right and bottom-right # y-coordinates or the top-left and bottom-left y-coordinates heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) maxHeight = max(int(heightA), int(heightB)) # now that we have the dimensions of the new image, construct # the set of destination points to obtain a "birds eye view", # (i.e. top-down view) of the image, again specifying points # in the top-left, …
upvote count: 1
has comment: http://stackoverflow.com/comment/81877704
has comment: http://stackoverflow.com/comment/81771283

http://stackoverflow.com/comment/81941109
comment on: http://stackoverflow.com/q/47491750
score: 0
has text: never use sudo pip install, install every library in virtualenvironment
type: Comment
type: QuestionComment

cgi
tags question: http://stackoverflow.com/q/47482939
type: Tag
tag name: cgi

http://stackoverflow.com/a/47522470
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47521665
has comment: http://stackoverflow.com/comment/82023344
has body: In the question that you linked, I mentioned that it was added that the support to decorate classes with cherrypy.expose was added in CherryPy version 6. You're are using 3.8. Upgrade CherryPy to any version after 6.0, or just don't use the expose decorated and set a property of exposed = True. class StringGeneratorWebService(object): # this is the attribute that configured the expose decorator exposed = True @cherrypy.tools.accept(media='text/plain') def GET(self): return cherrypy.session['mystring'] def POST(self, length=8): some_string = ''.join(random.sample(string.hexdigits, int(length))) cherrypy.session['mystring'] = some_string return some_string def PUT(self, another_string): cherrypy.session['mystring'] = another_string def DELETE(self): cherrypy.session.pop('mystring', None)
accepted answer of: http://stackoverflow.com/q/47521665
score: 1

http://stackoverflow.com/a/57524869
answers question: http://stackoverflow.com/q/47460722
type: Answer
has body: E.g. you can remove a sub-string from a string and check if you succeeded, using the tf.regex_replace() operator like this: import tensorflow as tf str = tf.constant("your string") sub_str = tf.constant("string") def not_contains(str1, str2): cut1 = tf.regex_replace(str1, str2, "") split1 = tf.string_split([cut1], "") split2 = tf.string_split([str1], "") size1 = tf.size(split1) size2 = tf.size(split2) return tf.equal(size1, size2) is_not_in = not_contains(str, sub_str) sess = tf.Session() sess.run(is_not_in) # False
score: 0

http://stackoverflow.com/comment/81787973
comment on: http://stackoverflow.com/q/47416917
has text: I expect no more than 20 groups. And one element can only belong to 1 group.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47454950
has comment: http://stackoverflow.com/comment/81864858
has comment: http://stackoverflow.com/comment/81865203
has comment: http://stackoverflow.com/comment/81864591
downvote count: 0
has comment: http://stackoverflow.com/comment/81866600
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81864426
has comment: http://stackoverflow.com/comment/81868603
has comment: http://stackoverflow.com/comment/81866054
answers question: http://stackoverflow.com/q/47454330
has comment: http://stackoverflow.com/comment/81865067
has body: You could save the image to a file and then load the file into an array using PIL: from PIL import Image import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.text(0.0,0.0,"Test", fontsize=45) ax.axis('off') ax.imshow(np.random.random((3,3))) filename = '/tmp/out.png' fig.savefig(filename) img = Image.open(filename).convert('RGB') arr = np.asarray(img) img.show() If you wish to avoid disk I/O, you could save the image to a BytesIO object instead: import io from PIL import Image import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.text(0.0,0.0,"Test", fontsize=45) ax.axis('off') ax.imshow(np.random.random((3,3))) with io.BytesIO() as memf: fig.savefig(memf, format='PNG') memf.seek(0) img = Image.open(memf) arr = np.asarray(img) img.show()
type: Answer
has comment: http://stackoverflow.com/comment/81864946
has comment: http://stackoverflow.com/comment/81864919

http://stackoverflow.com/a/47431426
upvote count: 1
has body: Since we are talking about json.loads() means that you are reading files. you can do so with bash and the amazing sed sed -i 's/"{/{/g' filename.json &amp;&amp; sed -i 's/}"/}/g' filename.json and if you wanna be very cool you can even use a fabric script!
has comment: http://stackoverflow.com/comment/81818671
has comment: http://stackoverflow.com/comment/81817893
has comment: http://stackoverflow.com/comment/81821009
type: Answer
has comment: http://stackoverflow.com/comment/81830066
has comment: http://stackoverflow.com/comment/81820126
score: 1
answers question: http://stackoverflow.com/q/47430767
downvote count: 0

google-sheets-api
tags question: http://stackoverflow.com/q/47448731
tags question: http://stackoverflow.com/q/47494011
type: Tag
tag name: google-sheets-api

http://stackoverflow.com/comment/82026393
has text: Sorry maybe I wasn't that clear, I don't want all "C" element texts, only the specific one with absolute path /A/B/C. I've edited the question to emphasis that more.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47533456

http://stackoverflow.com/a/47540567
upvote count: 2
answers question: http://stackoverflow.com/q/47539882
downvote count: 0
has body: There is other threads on this but basically this is the rules I use: You should definately remote migrations files using Git. Never run makemigrations on production environment always in developpment. Now, let's say you made a change on one of your models (in developpment I hope), you will run a normal makemigrations. Then, run migrate (still in dev) in order to test everything. When you're ready, you will commit and push the created files and pull in prod to then run migrate to update database schema. This will assure good versionning of your migrations files. Also, it will greatly help you in the long run, because running makemigrations in produciton and in dev simultaneously will just cause more conflicts on migrations files which can be a pain.
type: Answer
score: 2

http://stackoverflow.com/a/68607949
score: 1
answers question: http://stackoverflow.com/q/47494720
has body: Chris Moffitt has created a library named sidetable to ease this process which can be used with the groupby object with an accessor making it very easy. That said, the accepted answer and comments are a gold mine, which I feel it's worth checking it out first.
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/a/47392334
accepted answer of: http://stackoverflow.com/q/47390996
type: Answer
answers question: http://stackoverflow.com/q/47390996
has body: Try this: from functools import reduce from operator import mul from scipy import stats and generate a Test Array like this: X = stats.randint(-10,10).rvs(100) Then you can calculate the Subsequence with the maximal product like this: &gt; max([(reduce(mul, X[i:j], 1), i,j) for i in range(X.size) for j in range(i,X.size)]) (2140585984, 32, 66) This means, that the Subsequence X[32:66] has the maximum product. (But beware of overflow: The numpy-Datatypes have restricted memory space).
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/47466982
linked to: http://stackoverflow.com/q/2998215
tagged with: git
has answer: http://stackoverflow.com/a/47467023
answer count: 3
has answer: http://stackoverflow.com/a/47467268
tagged with: python
has body: i've been working with the python project before and never submitted a pyc file. Not sure as to why. I am using intellij, maybe it automatically ignores those files and doesn't display them? maybe I am not using CPython? python --version spits out to me Python 3.6.1 :: Continuum Analytics, Inc.
has comment: http://stackoverflow.com/comment/81888648
type: Question
has answer: http://stackoverflow.com/a/47467099
type: UnansweredQuestion
score: 0
has title: pyc got checked into my git project by coworker, how comes?
tagged with: intellij-idea

http://stackoverflow.com/q/47427418
answer count: 0
type: UnansweredQuestion
has title: How to create popup window from json schema?
tagged with: python
has comment: http://stackoverflow.com/comment/81809309
tagged with: jsonschema
score: 0
tagged with: popupwindow
upvote count: 1
has comment: http://stackoverflow.com/comment/81809406
downvote count: 1
has body: Actually am stuck in my project. I need to generate a popup window from JSON schema and according to the schema only I need to take input from the user. this is my schema: { "type":"object", "properties":{ "APPLICATION":{"type":"string","enum":["MUL"]}, "CAR_TYPE":{"type":"string"}, "VER":{"type":"number"} } } and I need output like: In the popup window, if the user enters "APPLICATION field other than "MUL" then it won't allow the user to proceed further.
favorite count: 0
type: Question

http://stackoverflow.com/comment/82016830
type: QuestionComment
has text: @Kendas stick that in an answer and claim the prize
comment on: http://stackoverflow.com/q/47530093
score: 0
type: Comment

http://stackoverflow.com/q/47396732
answer count: 2
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47396773
accepted answer: http://stackoverflow.com/a/47396773
type: Question
has title: Python transforming value to tuple
has body: In python, I receive JSON data. The data looks like the following stub: { "id": 1, "naam": "4.13", "ruimte_temperatuur_sensor": {...}, // etc } I map this json to an object (note the sensor is mapped already): ruimte = Ruimte(id=id, naam=naam, ruimte_temperatuur_sensor=temperatuur_sensor, ruimte_humiditeit_sensor=humiditeit_sensor, ruimte_beweging_sensor=beweging_sensor, airco_temperatuur_sensor=airco_sensor, radiator_temperatuur_sensor=radiator_sensor) The strangest thing happens: The id field in JSON is an integer, but Python maps it to a tuple. In my debugger, you can clearly see that the id=id maps to an integer, but then all of a sudden my object contains a tuple: The object's constructor should not cause that: class Ruimte: def __init__(self, id: int, naam: str, ruimte_temperatuur_sensor: Sensor, ruimte_humiditeit_sensor: Sensor, ruimte_beweging_sensor: Sensor, airco_temperatuur_sensor: Sensor, radiator_temperatuur_sensor: Sensor): self.id = id, self.naam = naam, self.ruimte_temperatuur_sensor = ruimte_temperatuur_sensor self.ruimte_humiditeit_sensor = ruimte_humiditeit_sensor self.ruimte_beweging_sensor = ruimte_beweging_sensor self.airco_temperatuur_sensor = airco_temperatuur_sensor self.radiator_temperatuur_sensor = radiator_temperatuur_sensor In the sub-objects the id is not parsed to a tuple, for exampe ruimte.airco_temperatuur_sensor.id is an integer: but that JSON is parsed the same way: def _parse_json_to_sensor(self, json: dict) -&gt; Sensor: id = json["id"] type = SensorType(json["type"]) meet_interval_sec = json["sensorInstelling"]["meetIntervalSec"] opslaan_interval_sec = json["sensorInstelling"]["opslaanIntervalSec"] sensor = Sensor(id=id, type=type, meet_interval_sec=meet_interval_sec, opslaan_interval_sec=opslaan_interval_sec) I'm totally lost on this. What could cause this?
tagged with: python
possible better answer: http://stackoverflow.com/a/47396890
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47396890
score: 0

http://stackoverflow.com/comment/136094181
score: 2
type: AnswerComment
has text: Just FYI when you do this you may have to "sudo dmesg", I mention this because it would be possible to misinterpret the "Operation not permitted" as the cause of your original problem, rather than telling you that you may not use dmesg without "sudo".
comment on: http://stackoverflow.com/a/47409304
type: Comment

http://stackoverflow.com/comment/81832598
type: Comment
comment on: http://stackoverflow.com/q/47437752
type: QuestionComment
has text: Just added the form class and the model field.
score: 0

http://stackoverflow.com/q/47508003
has comment: http://stackoverflow.com/comment/81971800
answer count: 0
has title: Python: How to parse Timex3 into datetime or equivalent
tagged with: stanford-nlp
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: timex
favorite count: 0
type: Question
tagged with: sutime
has comment: http://stackoverflow.com/comment/81971980
tagged with: python
has body: In my Python3 project, I use SUTime together with Stanford CoreNLP to retrieve normalized time expression in the Timex3 standard. I access CoreNLP using pycorenlp. How can I parse the resulting time expression in Timex3 (part of the TimeML standard) into a datetime or another temporal instance? I guess that datetime is probably not sufficient since it cannot represent dateranges For instance, Timex3 expressions are: 2017-11 referring to the whole month November 2017-10-07 referring to the whole seventh day in November I've already tried parsing them with the Python library parsedatetime, which is able to read almost any input containing a temporal expression, but the library is obviously not suited for the Timex3 format, i.e., it converts 2017-11 to a datetime of the current day (assuming it's November 2017): &gt;&gt;&gt; dateparser.parse('2017-11') datetime.datetime(2017, 11, 27, 0, 0) Isn't there a Python library for converting Timex3 expressions into datetime or something equivalent? Someone commented that 2017-11 cannot be converted into a datetime (as each only reflects a single points in time). But there's for example the pandaslibrary, which contains date ranges as well.

http://stackoverflow.com/comment/82036154
has text: Check edit. If it's satysfying mark as done, please.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47535119
type: AnswerComment

http://stackoverflow.com/a/47537240
has comment: http://stackoverflow.com/comment/82033030
answers question: http://stackoverflow.com/q/47536982
has comment: http://stackoverflow.com/comment/82067209
has body: I want to select all rows where A or B contain any value from C You can use .isin() here. Here is a small example: df1 = pd.DataFrame([[1,4,1], [2,5,4], [3,6,7]], columns=['a','b','c']) df1.loc[df1['a'].isin(df1['c'])] #output: a b c 0 1 4 1 The reason why this returns the row is does is because the value 1 is in column c.
upvote count: 1
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82033545
has comment: http://stackoverflow.com/comment/82070418
score: 0

http://stackoverflow.com/comment/81846466
type: Comment
has text: Looks good to me (assuming the over-indentation is a SO formatting issue, and not how your code actually looks). Can you please share the exact text of the error you're getting?
type: QuestionComment
comment on: http://stackoverflow.com/q/47445534
score: 0

http://stackoverflow.com/q/47426126
tagged with: python
type: AnsweredQuestion
score: 0
has body: Following function is not working: def myround(sfloat, dec): print("{0:."+str(dec)+"f}") # only to show the string formed. return ("{0:."+str(dec)+"f}".format(sfloat)) myround(2.35698, 2) The error is: {:.2f} Traceback (most recent call last): File "mytest.py", line 8, in &lt;module&gt; myround(2.35698, 2) File "mytest.py", line 6, in myround return ("{0:."+str(dec)+"f}".format(sfloat)) ValueError: Single '}' encountered in format string The first print function shows proper string: {:.2f}. I tried {0:.2f} but that also does not work. \{ and \} also do not work. Where is the problem and how can it be solved?
has title: Round a float in a function
answer count: 1
accepted answer: http://stackoverflow.com/a/47426153
type: Question
has answer: http://stackoverflow.com/a/47426153
tagged with: format

http://stackoverflow.com/a/47514415
downvote count: 0
answers question: http://stackoverflow.com/q/47513273
upvote count: 1
score: 1
type: Answer
has body: I think the most pythonic way is to put it in a try ... except block and catch the ValueError: n = input("Eine Zahl eingeben: ") try: print(int(n, 2)) except ValueError: print("Nicht möglich")

http://stackoverflow.com/a/47457276
type: Answer
has comment: http://stackoverflow.com/comment/81871089
answers question: http://stackoverflow.com/q/47454689
has comment: http://stackoverflow.com/comment/81869415
has comment: http://stackoverflow.com/comment/81870241
score: 1
has comment: http://stackoverflow.com/comment/81871221
has comment: http://stackoverflow.com/comment/81869464
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81906038
has comment: http://stackoverflow.com/comment/81870970
downvote count: 0
has comment: http://stackoverflow.com/comment/81870593
upvote count: 1
has body: How about using positive lookahead and lookbehind: (?&lt;=\"fileAssetId\":\")[a-fA-F0-9-]+?(?=\") captures the fileAssetId and (?&lt;=\"filename\":\").+?(?=\") matches the filename. For a detailed explanation of the regex have a look at the Regex101-Example. (Note: I combined both in the example with an OR-Operator | to show both matches at once) To get a list of all matches use re.findall or re.finditer instead of re.match. re.findall(pattern, string) returns a list of matching strings. re.finditer(pattern, string) returns an iterator with the objects.
has comment: http://stackoverflow.com/comment/81870264
has comment: http://stackoverflow.com/comment/81869976
has comment: http://stackoverflow.com/comment/81869921
has comment: http://stackoverflow.com/comment/81883502
accepted answer of: http://stackoverflow.com/q/47454689
has comment: http://stackoverflow.com/comment/81871243

http://stackoverflow.com/comment/81851637
type: AnswerComment
comment on: http://stackoverflow.com/a/47448123
score: 1
type: Comment
has text: WOW, It is amazing to think of using b! Thank you very much.

opencv
tags question: http://stackoverflow.com/q/47494350
tags question: http://stackoverflow.com/q/47414371
tags question: http://stackoverflow.com/q/47523708
tags question: http://stackoverflow.com/q/47503987
type: Tag
tags question: http://stackoverflow.com/q/47483951
tags question: http://stackoverflow.com/q/47417718
tags question: http://stackoverflow.com/q/47533291
tags question: http://stackoverflow.com/q/47395299
tags question: http://stackoverflow.com/q/47401651
tags question: http://stackoverflow.com/q/47466583
tags question: http://stackoverflow.com/q/47525860
tags question: http://stackoverflow.com/q/47446952
tags question: http://stackoverflow.com/q/47485011
tags question: http://stackoverflow.com/q/47483411
tags question: http://stackoverflow.com/q/47496287
tags question: http://stackoverflow.com/q/47407438
tags question: http://stackoverflow.com/q/47451166
tags question: http://stackoverflow.com/q/47520532
tags question: http://stackoverflow.com/q/47461826
tags question: http://stackoverflow.com/q/47530508
tags question: http://stackoverflow.com/q/47482493
tags question: http://stackoverflow.com/q/47424360
tags question: http://stackoverflow.com/q/47486692
tags question: http://stackoverflow.com/q/47413719
tags question: http://stackoverflow.com/q/47394535
tags question: http://stackoverflow.com/q/47444783
tags question: http://stackoverflow.com/q/47384294
tags question: http://stackoverflow.com/q/47492640
tags question: http://stackoverflow.com/q/47396372
tags question: http://stackoverflow.com/q/47514485
tags question: http://stackoverflow.com/q/47534338
tags question: http://stackoverflow.com/q/47406906
tags question: http://stackoverflow.com/q/47505117
tags question: http://stackoverflow.com/q/47460860
tags question: http://stackoverflow.com/q/47462522
tags question: http://stackoverflow.com/q/47517351
tags question: http://stackoverflow.com/q/47429206
tags question: http://stackoverflow.com/q/47491861
tags question: http://stackoverflow.com/q/47424061
tags question: http://stackoverflow.com/q/47474155
tags question: http://stackoverflow.com/q/47517667
tags question: http://stackoverflow.com/q/47392589
tags question: http://stackoverflow.com/q/47473861
tags question: http://stackoverflow.com/q/47405684
tags question: http://stackoverflow.com/q/47520487
tags question: http://stackoverflow.com/q/47503177
tags question: http://stackoverflow.com/q/47416523
tags question: http://stackoverflow.com/q/47475206
tags question: http://stackoverflow.com/q/47402445
tags question: http://stackoverflow.com/q/47449512
tags question: http://stackoverflow.com/q/47403302
tags question: http://stackoverflow.com/q/47501953
tags question: http://stackoverflow.com/q/47522403
tags question: http://stackoverflow.com/q/47475976
tags question: http://stackoverflow.com/q/47429580
tags question: http://stackoverflow.com/q/47477338
tags question: http://stackoverflow.com/q/47498061
tags question: http://stackoverflow.com/q/47482055
tags question: http://stackoverflow.com/q/47420130
tags question: http://stackoverflow.com/q/47489301
tags question: http://stackoverflow.com/q/47409879
tags question: http://stackoverflow.com/q/47496425
tags question: http://stackoverflow.com/q/47397247
tags question: http://stackoverflow.com/q/47436176
tags question: http://stackoverflow.com/q/47495048
tags question: http://stackoverflow.com/q/47466304
tags question: http://stackoverflow.com/q/47532858
tags question: http://stackoverflow.com/q/47390787
tags question: http://stackoverflow.com/q/47479480
tags question: http://stackoverflow.com/q/47519099
tag name: opencv
tags question: http://stackoverflow.com/q/47505134
tags question: http://stackoverflow.com/q/47454317
tags question: http://stackoverflow.com/q/47427767
tags question: http://stackoverflow.com/q/47384902
tags question: http://stackoverflow.com/q/47468222
tags question: http://stackoverflow.com/q/47450179

http://stackoverflow.com/comment/81996465
comment on: http://stackoverflow.com/a/47519660
type: Comment
score: 0
type: AnswerComment
has text: I can open up but did you understand what i am trying to do

http://stackoverflow.com/q/47518631
has comment: http://stackoverflow.com/comment/81995598
type: Question
has title: end point connected to start point graph
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81995425
has comment: http://stackoverflow.com/comment/81995457
has comment: http://stackoverflow.com/comment/81995542
score: 0
has comment: http://stackoverflow.com/comment/81995473
answer count: 0
has body: I am graphing data from different MATLAB files with Python. P0[filenumber] and CF[filenumber] are arrays that have a lot of numbers from each file. I am only getting one point from each of these arrays within the files. So I made an array with just those points by appending them to a new array. When I graph my results, I get my endpoint connected to the first point, even though I broke the graph into two: How can I graph, without the last point looping to the first point? I know my data is out of order, but is there a way I can plot a nice graph without having to rearrange all of my data? Max=[] F=[] #length is the number of files I'm reading for s in range(0,length): Max.append(P0[s][30]) F.append(CF[s][0]) plt.plot(F[length:],Max[length:]) plt.plot(F[0:length],Max[0:length]) plt.show()
tagged with: loops
tagged with: plot
tagged with: matlab

http://stackoverflow.com/q/47431927
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
answer count: 2
tagged with: django-views
has answer: http://stackoverflow.com/a/47432997
has body: I am using the requests library with python 3. My goal is a two-step process: Send post request from python program to my Django app. Process that post request by creating a new database entry with the information sent in said Django app. I think the first part has been set-up properly, the development server registers the POST requests. However, I am having some trouble with step two. I created a special url and html template just to see if anything gets picked up after I have made a POST request. The view is handled in this manner: def new_instance(request): instance = 'Nothing picked up!' if request.method == 'POST': post = request.POST['ID'] instance = IDInstance(id=post) instance.save() return render( request, 'viewpage.html', context = {'instance':instance}) However, neither the instance variable nor my database get updated. The request that is being made looks like this: Info = {'ID':'23234234'} r = requests.post(domain,data=Info)
has title: Django - Obtaining information from Requests POST Method
upvote count: 1
has answer: http://stackoverflow.com/a/47432709
tagged with: python-requests
tagged with: django-rest-framework
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47464086
favorite count: 0
has answer: http://stackoverflow.com/a/47464198
type: Question
tagged with: python-3.x
upvote count: 3
has answer: http://stackoverflow.com/a/47464199
possible better answer: http://stackoverflow.com/a/47464200
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/81883150
has answer: http://stackoverflow.com/a/47464200
has title: Finding the first index where sum of elements before it is bigger than the element itself
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81883088
accepted answer: http://stackoverflow.com/a/47464198
has answer: http://stackoverflow.com/a/47464348
has body: I have to find the first index where sum of elements up to that index (itself not included) is bigger than the element itself. If there is no such element just return -1. My code: def bigger_sum(numbers): tmp_var = 0 for i in range(len(numbers)): tmp_var += numbers[i] if tmp_var &gt; numbers[i]: return i return -1 [1, 2, 3, 4] =&gt; 3 [1, 2, 3] =&gt; -1 [1, 2] =&gt; -1 I got correct output only on last two lists -1, but if i try first list the output is empty. What is wrong with the code?
answer count: 4

http://stackoverflow.com/comment/81866887
type: QuestionComment
has text: You did not ask matplotlib to use a marker.
score: 0
comment on: http://stackoverflow.com/q/47455969
type: Comment

http://stackoverflow.com/q/47400505
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47400597
answer count: 1
tagged with: authentication
tagged with: django
type: Question
has title: form_invalid() missing 1 required positional argument: 'form'
accepted answer: http://stackoverflow.com/a/47400597
has body: Hi how are I having a problem with my django user authentication since I am using AbstractBaseUser Model from Apps.grupo.models import Grupo from Apps.empresa_area.models import Empresa_area from Apps.archivos.models import Archivos from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, Group, ) class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("Usuuario tiene email") if not password: raise ValueError("usuario debe tener contraseña") user_obj = self.model( email =self.normalize_email(email) ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True, ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=200, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) celular = models.CharField(max_length=20) saludo = models.CharField(max_length=10) grupo = models.ForeignKey(Grupo, null=True, blank=True, on_delete=models.CASCADE) archivo = models.ForeignKey(Archivos, null=True, blank=True, on_delete=models.CASCADE) fec_creacion = models.DateTimeField(auto_now=False, auto_now_add=False) empresa_area_id = models.ForeignKey(Empresa_area, null=True, blank=True, on_delete=models.CASCADE) cargo = models.ManyToManyField(Group) USERNAME_FIELD = 'email' REQUIRED_FILES = [] objects = UserManager() class Meta: verbose_name = ('user') verbose_name_plural = ('users') def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return s…
tagged with: python
has comment: http://stackoverflow.com/comment/81754755

http://stackoverflow.com/q/47446489
answer count: 1
tagged with: python
tagged with: webdriver
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47464463
has title: click on element multiple times selenium
has body: I'm trying to give clicks on some elements that have the same id and name, after clicking on of those elements , the element disappears and then I want to click the next one. What I want to create is a loop to click on the elements and if there's no more elements with same id or name it should pass and continue the test, this is the element: mark_complete = self.driver.find_element_by_xpath('//button[contains(.,"Mark complete")]') thanks in advance
has answer: http://stackoverflow.com/a/47464463
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/81961762
has text: `winfo_height` and `winfo_width` will always return the number of pixels. If you think it is not, please provide a [mcve].
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/47495285

http://stackoverflow.com/a/47521829
answers question: http://stackoverflow.com/q/47520105
score: 16
upvote count: 16
has body: The underlying problem turned out to be the nginx proxy in front of the interface server. The proxy was set to proxy_read_timeout 20s;. If there were keepalive pings generated from the server, these were not getting counted toward the upstream read timeout. Increasing this timeout to a larger value allows the Websocket to stay open longer. I kept proxy_connect_timeout and proxy_send_timeout at 20s.
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47520105
type: AcceptedAnswer

http://stackoverflow.com/comment/81884924
has text: Thanks, glob does seem to do the trick. However, I can't believe this operation cannot be done with os, does a simple procedure like this really require importing another module? There's much more to my script and this would be the only place glob is used.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47464938

http://stackoverflow.com/q/47436176
has title: Error when using scipy.misc.imread inside the loop
has comment: http://stackoverflow.com/comment/81826612
linked to: http://stackoverflow.com/q/40690442
upvote count: 2
score: 2
answer count: 0
downvote count: 0
has body: I have a case similar to this question. Faced it when training deep learning model and reading images inside the loop. scipy.misc.imread(rawImagePath).astype(numpy.float32) The code above is working perfectly the vast majority of the time, but sometimes I get the error: batch 90, loading batch data... x path: /path_to_dataset/train/9.png 2017-10-31 20:23:34.531221: W tensorflow/core/kernels/queue_base.cc:294] _0_input_producer: Skipping cancelled enqueue attempt with queue not closed Traceback (most recent call last): File "train.py", line 452, in &lt;module&gt; batch_X = load_data(batch_X_paths) File "/path_to_my_script/utilities.py", line 85, in load_data x = misc.imread(batch_X_paths[i]).astype(np.float32) TypeError: float() argument must be a string or a number The difference is: I have a fixed set of files and I do not write new ones to the directory. I made a little research and figured out that error comes not from numpy.astype() but from PIL.Image.open() scipy.misc uses PIL under the hood. Also, I managed to reproduce this bug in Jupyter Notebook. I made a loop with reading/astype code inside. After few seconds (the size of my test .png is about 10MB) I interrupt cell's execution and voila! error reproduced in Jupyter Notebook Inside scipy.misc sources there is a code like this: def imread(name, flatten=False, mode=None): im = Image.open(name) return fromimage(im, flatten=flatten, mode=mode) Image here is a PIL object. And Image.open() gives us 0-dimension list when interrupting cell. I have tried Evert's advice and made a loop with try/except, but sometimes it fails even after 5 attempts. Also I tried OpenCV imread() method instead of scipy.misc and sometimes it fails too. Error text: libpng error: incorrect data check So... I ran out of ideas.
has comment: http://stackoverflow.com/comment/81830688
has comment: http://stackoverflow.com/comment/81826743
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81830882
tagged with: opencv
has comment: http://stackoverflow.com/comment/82113648
has comment: http://stackoverflow.com/comment/81826878
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81841617
tagged with: imread
has comment: http://stackoverflow.com/comment/81827405
tagged with: scikit-image
tagged with: python

http://stackoverflow.com/comment/81930426
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47487308
has text: @aaron it first wanted me to install 'Cython' so I did. Then it gave this error in cmd: 'failed with error code 1' with a lot of other stuff.
score: 0

http://stackoverflow.com/q/47497001
has answer: http://stackoverflow.com/a/47503039
tagged with: python
has title: Python unit test coverage for multiple modules
upvote count: 22
score: 22
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47503039
answer count: 1
downvote count: 0
tagged with: python-unittest
has comment: http://stackoverflow.com/comment/81949323
favorite count: 0
tagged with: unit-testing
type: Question
tagged with: coverage.py
has body: I searched for a long time and surprisingly found no satisfactory answer. I have multiple modules/files in my Python project that I wrote unit tests for using unittest. The structure is such that I have production-modules module_A.py and module_B.py in one directory (say myproject/production) and corresponding test-files test_module_A.py and test_module_B.py in a sibling directory (say myproject/tests). Now I have coverage.py installed and want to run all the tests associated with the project (i.e. all .py-files with the prefix test_ from the tests directory) and receive a coverage report showing the coverage for all the production-modules (module_A.py and module_B.py). I figured out that I can do this by running the following commands from the myproject/tests directory: coverage erase coverage run -a --source myproject.production test_module_A.py coverage run -a --source myproject.production test_module_B.py coverage report This gives me that nice table with all my production modules listed and their coverage results. So far so good. But can I do this with just one command? Assuming I have not 2 but 20 or 200 tests that I want to include in one report, doing this "by hand" seems ridiculous. There must be a way to automate this, but I can't seem to find it. Sure a shell-script might do it, but that is rather clumsy. I am thinking of something akin to unittest discover, but for coverage.py this doesn't seem to work. Or could I accomplish this using the coverage-API somehow? So far I had no luck trying. . SOLUTION: (credit to Mr. Ned Batchelder) From myproject/tests directory run: coverage run --source myproject.production -m unittest discover &amp;&amp; coverage report One line, doing exactly what was needed.
tagged with: code-coverage

http://stackoverflow.com/q/47396442
has comment: http://stackoverflow.com/comment/81746550
accepted answer: http://stackoverflow.com/a/47396828
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: How I can create an interval column in pandas?
tagged with: python
has answer: http://stackoverflow.com/a/47396828
has body: I hav a data frame like : name1 name2 mounth A B 01 B C 02 A B 02 A B 04 B C 03 I want to creat a column that shows interval for each pair of names: name1 name2 interval A B [1,2];[4,4] B C [2,3] Is it possible to create interval like above column in pandas ?
has comment: http://stackoverflow.com/comment/81746919
type: Question

http://stackoverflow.com/comment/81951491
score: 1
comment on: http://stackoverflow.com/q/47498061
has text: check this out : https://stackoverflow.com/questions/39908406/unable-to-locate-finder-for-pip-vendor-distlib-error-when-using-pip-instal
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82034217
has text: I can't believe I hadn't noticed this, thanks - life saver!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47538647

http://stackoverflow.com/comment/81924594
type: AnswerComment
score: 1
type: Comment
has text: A code to show and a snippet to explain whats happening is always an awesome answer. Thank You
comment on: http://stackoverflow.com/a/47484806

http://stackoverflow.com/comment/81942399
score: 0
type: Comment
has text: Do all the arrays have the same shape and data type? You say *"... however this does not work if i try and write the arrays as binary"*, but you didn't explain how you attempted to do this, and what went wrong. Please give more details about what you tried.
type: QuestionComment
comment on: http://stackoverflow.com/q/47493409

http://stackoverflow.com/a/47537734
score: 0
has body: This code will work ok. def save(self, force_insert=False, force_update=False, *args, **kwargs): similars = Reaction.objects.filter(user=self.user, content_type=self.content_type, object_id=self.object_id) if similars.exists(): similars.delete() similars.update(user=self.user, react_type=self.react_type) else : similars.update(user=self.user, react_type=self.react_type) super(Reaction, self).save(*args, **kwargs)
type: Answer
answers question: http://stackoverflow.com/q/47526387

http://stackoverflow.com/comment/104374057
has text: you can use like this ,, cannot_come = guest_list.pop() print(cannot_come)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47390905
type: Comment

http://stackoverflow.com/comment/82036443
has text: You are trying to send the tuple `("0", data)` with the `.sendall()` method. This method requires a `bytes`-like object instead. What are you trying to accomplish with the `"0"` prefix?
score: 0
comment on: http://stackoverflow.com/q/47539645
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81931395
comment on: http://stackoverflow.com/a/47488255
type: AnswerComment
score: 0
has text: @Bharath ah, :-)
type: Comment

http://stackoverflow.com/q/47537775
has title: Output only certain portions of row in pandas
has answer: http://stackoverflow.com/a/47537909
tagged with: dataframe
tagged with: python
answer count: 2
tagged with: file-io
has body: I have this dataframe X Y Z A 0 1 2 0 4 1 0 2 3 0 2 1 0 3 4 3 1 0 0 4 4 1 0 0 0 I want to save it as a text file with this format (all rows are output but any columns with 0 are excluded) 1,2,4 2,3 1,3,4 1,4 1 This can be outputted with a for loop but it is very inefficient with a large dataframe. Is there any faster way to do this?
tagged with: pandas
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47537888
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/118892275
comment on: http://stackoverflow.com/a/67201621
has text: Although beware of negative performance impact. For me it took 0.3 seconds, which make is almost unusable, except of some very specific use case...
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47492293
has body: I'm willing to bet that the reason your program doesn't work well for large strings is because it has a complexity greater than Θ(n). This function will cut a string how you want it to be cut in that time: def cut_string(string, cutters, cutspots): split_list = [''] cut_next = False for char in string: if cut_next: split_list.append(char) cut_next = (char in cutters) and (cutspots[cutters.index(char)]) else: if char in cutters: if cutspots[cutters.index(char)]: cut_next = True split_list[-1] += char else: split_list.append(char) else: split_list[-1] += char return [string for string in split_list if string] Then, we can simply check if any any word in the wordlist is a split portion of the string (I'm assuming you meant wordlist to be 'WORD', 'ANOTHERK': def list_cut(letterlist, wordlist, cutters, cutspots): out_list = [] for sub_list, string in zip(wordlist, letterlist): cut_list = cut_string(string, cutters, cutspots) out_list.append([word in cut_list for word in sub_list]) return out_list wordfinder = list_cut(letterlist, wordlist, cutters, cutspots) print(wordfinder) #True, False
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47492104
accepted answer of: http://stackoverflow.com/q/47492104
type: AcceptedAnswer

http://stackoverflow.com/comment/128017564
type: AnswerComment
has text: How are you deleting df2 before using it on the merge? How are you getting the df2 data to merge with df1?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47387088

http://stackoverflow.com/comment/81725077
score: 0
comment on: http://stackoverflow.com/q/47385830
has text: `[re.sub(r'\s+\|\s+', '|', s) for s in input]` for any number of whitespace and only around `'|'`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81829192
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47437384
has text: istead of `return` you should be having `yield` to keep it working as a generator.

http://stackoverflow.com/q/47467343
score: 0
answer count: 1
tagged with: inputstream
type: Question
tagged with: buffer
has answer: http://stackoverflow.com/a/47468116
type: UnansweredQuestion
has body: i have one application nodejs which request send to python using python-shell npm package. and python script read data and parse string. nodejs file : teststr.js let buf = ` Reply ` var PythonShell = require('python-shell') var options = { mode: 'binary', args: ['html'], scriptPath: __dirname + '/', pythonPath: '/usr/bin/python3' } var pyshell = new PythonShell('test.py', options) pyshell.stdout.on('data', function (message) { console.log(message) }) pyshell.send(buf) pyshell.end(function (err) { if (err) { console.log('End Script' + err) } }) Python File : test.py import sys import base64 import struct import io type = sys.argv[1] html = "" htmlBuffer = "" for line in sys.stdin.buffer: htmlBuffer = io.BufferedReader(line) #htmlBuffer = to_str(htmlBuffer) #htmlBuffer.decode('utf-8', errors='ignore').strip() print("%s" % (htmlBuffer)) given Output is as below : <Buffer 62 27 3c 68 74 6d 6c 3e 3c 62 6f 64 79 3e 3c 70 3e 52 65 70 6c 79 3c 2f 70 3e 3c 2f 62 6f 64 79 3e 3c 2f 68 74 6d 6c 3e 27 0a> expect result : Reply
has title: Nodejs InputStream Buffer convert to string using python
tagged with: python
tagged with: node.js

http://stackoverflow.com/a/47520564
downvote count: 0
upvote count: 2
type: Answer
has body: for record in sample_dict: df = pd.DataFrame(record['concepts']) df['ko_id'] = record['ko_id'] final_df = final_df.append(df)
score: 2
answers question: http://stackoverflow.com/q/47520356

http://stackoverflow.com/comment/81730787
has text: @JonClements - Yes I agree, was trying not to change too many things at once in this code :) (also noted for the OP to add error handling)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47388911

http://stackoverflow.com/comment/81777242
comment on: http://stackoverflow.com/q/47411872
type: Comment
has text: @Divakar in my case I won't have any windows which extend past the image by construction. But let's say I'd like to just discard any windows that don't fit within the constraints of `im`, so they wouldn't show up in the resulting patches array.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81743914
type: Comment
comment on: http://stackoverflow.com/q/47395353
score: 1
has text: yes, use `lag` (window-functions)
type: QuestionComment

http://stackoverflow.com/comment/81954520
has text: "expecting <INVALID>" usually means that you're using a token rule that's impossible to match (possibly because it conflicts with another token rule). Beyond that, we can't help you without seeing the grammar. So I second Mike's suggestion, except that if the grammar is too long to post here, you should post an [MCVE](https://stackoverflow.com/help/mcve), not a link to the whole grammar.
type: QuestionComment
comment on: http://stackoverflow.com/q/47498553
score: 0
type: Comment

http://stackoverflow.com/a/49332968
answers question: http://stackoverflow.com/q/47470441
type: Answer
has body: I know I'm late, but hopefully this will still be helpful and/or point others in the right direction. This problem results from a hidden import in pandas/a missing hook in pyinstaller. It's solved by adding this hook file in drive_c/Python*/Lib/site-packages/PyInstaller/hooks. It's discussed in this github issue and resolved by the link above. I was able to find the answers here and here in other Stack Overflow questions. Once I got this resolved, I started getting an error related to numpy (I don't remember exactly what it was, I think it involved dates and it was in the importing of numpy or pandas because I was using a test .py that did essentially only that) which resolved by uninstalling and reinstalling pandas with pip (using, in my case, "wine python.exe ./Scripts/pip.exe uninstall pandas" while in /path/to/drive_c/Python27). Lastly, I found this site helpful for understanding how to work in the wine environment (e.g. how to use pip in wine).
score: 0

http://stackoverflow.com/comment/81768896
has text: Ok, I have added another condition to check if . exists. That should handle it.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47405587

http://stackoverflow.com/comment/81812036
comment on: http://stackoverflow.com/a/47428467
type: Comment
score: 0
type: AnswerComment
has text: Well, are you sure `dict(list)` will work, I thought we need to `zip` the list because this does not work in console.

http://stackoverflow.com/a/47536983
has body: Since you don't need it to be trainable, a lambda function will also do. Or you can keep the custom layer as you have it, and set trainable to False. The weights will never be updated for this layer, and whatever you do here will forward propagate to the next layer in the model and as mentioned in the comments, backprop will impact the other layers with weights. So, definitely your model will learn something. I personally recommend using a custom layer, if you decide later to add some learning to this layer and check your results. You cannot do this in a Lambda function. If you add one (kernel), you will have to use in the 'call' method. Your model will throw an error during training otherwise.
has comment: http://stackoverflow.com/comment/82031915
has comment: http://stackoverflow.com/comment/82032123
accepted answer of: http://stackoverflow.com/q/47536066
score: 0
has comment: http://stackoverflow.com/comment/82032121
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82044311
has comment: http://stackoverflow.com/comment/82032041
has comment: http://stackoverflow.com/comment/82030949
has comment: http://stackoverflow.com/comment/82033166
has comment: http://stackoverflow.com/comment/82035582
answers question: http://stackoverflow.com/q/47536066
has comment: http://stackoverflow.com/comment/82031878
type: Answer

http://stackoverflow.com/comment/81796536
type: Comment
comment on: http://stackoverflow.com/q/47420328
type: QuestionComment
score: 0
has text: @glibdud, it worked for me, thanks for bringing in the security consideration. I am reading the username myself and generating the path separately to keep the shell=False. Is it the right way to do it ?

http://stackoverflow.com/a/47497495
type: Answer
has body: Create new Series with numpy.random.choice and then replace NaNs by fillna or combine_first: df['A'] = df['A'].fillna(pd.Series(np.random.choice(fill_list, size=len(df.index)))) #alternative #df['A'] = df['A'].combine_first(pd.Series(np.random.choice(fill_list, size=len(df.index)))) print (df) A 0 1.0 1 2.0 2 84.0 3 5.0 4 53.0 5 56.0 Or: #get mask of NaNs m = df['A'].isnull() #count rows with NaNs l = m.sum() #create array with size l s = np.random.choice(fill_list, size=l) #set NaNs values df.loc[m, 'A'] = s print (df) A 0 1.0 1 2.0 2 56.0 3 5.0 4 53.0 5 56.0
accepted answer of: http://stackoverflow.com/q/47497466
answers question: http://stackoverflow.com/q/47497466
type: AcceptedAnswer
downvote count: 0
score: 9
upvote count: 9

http://stackoverflow.com/comment/81808027
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47417295
has text: @smokes2345 wiringpi allows me only to toggle. i am using the data from some pins and passing it to some conditions then if the condition is true some other gpio will turn on or off according to the condition.

http://stackoverflow.com/comment/81816012
has text: @omri_saadon that's weird because I'm only entering numbers
comment on: http://stackoverflow.com/a/47430612
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82077541
has text: I had to read through and implement the other answer first before I could understand this simplified answer. This is clean and helps a lot. Thank you! Even though LP doesn't generally handle inequalities I'm guessing this can be correct with some small constant value c? For example: x1 + c<= x2 + delta M; x1 + c<= x3 + delta M; x1 >= c + x2 - (1-delta)M; x1 >= c + x3 - (1-delta)M; delta in {0,1}
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47493093
score: 1

http://stackoverflow.com/q/47485810
accepted answer: http://stackoverflow.com/a/47486141
possible better answer: http://stackoverflow.com/a/47485972
has title: How to conditionally do a vlookup in Pandas dataframe
answer count: 2
has answer: http://stackoverflow.com/a/47486141
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
has body: I am trying to figure out how to do a vlookup to pick out the latest price to fill up a second table. An example below. For item #1, the latest price is at Month 6 (=$6) while item #2 is at Month 5 (=$4). What's the best way to fill up Table B? Note: There might be occasion that item_id cannot be found in Table A if the item is new. Any guidance? Many Thanks. Table A (Reference) | Item_ID | Month | Price | |---------|-------|-------| | 1 | 4 | 10 | | 1 | 5 | 8 | | 1 | 6 | 6 | | 2 | 5 | 4 | Table B (To Fill) | Shop_ID | Item_ID | Price | |---------|---------|-------| | 1 | 1 | 6 | | 1 | 2 | 4 |
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47485972
tagged with: python

http://stackoverflow.com/q/47400775
accepted answer: http://stackoverflow.com/a/47400821
has title: Panel data: create new variable with a condition
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47400962
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47401552
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81755224
has answer: http://stackoverflow.com/a/47400821
favorite count: 0
type: Question
has body: I am trying to create a new variable from the following df. I want to create a new binary (0 or 1) variable which placed 1 in every quarter of the year if in any of their quarters the variable entr is equal to one, and by id. Example from this data frame transform to: id year quarter fecha entr 1 2007 1 220 0 1 2007 2 221 0 1 2007 3 222 0 1 2007 4 223 0 1 2008 1 224 0 1 2008 2 225 0 1 2008 3 226 1 1 2008 4 227 0 1 2009 1 228 0 1 2009 2 229 0 1 2009 3 230 0 1 2009 4 231 0 2 2007 1 220 0 2 2007 2 221 0 2 2007 3 222 0 2 2007 4 223 0 2 2008 1 224 0 2 2008 2 225 0 2 2008 3 226 0 2 2008 4 227 0 2 2009 1 228 0 2 2009 2 229 1 2 2009 3 230 0 2 2009 4 231 0 result should be look like: id year quarter fecha entr new variable 1 2007 1 220 0 0 1 2007 2 221 0 0 1 2007 3 222 0 0 1 2007 4 223 0 0 1 2008 1 224 0 1 1 2008 2 225 0 1 1 2008 3 226 1 1 1 2008 4 227 0 1 1 2009 1 228 0 0 1 2009 2 229 0 0 1 2009 3 230 0 0 1 2009 4 231 0 0 2 2007 1 220 0 0 2 2007 2 221 0 0 2 2007 3 222 0 0 2 2007 4 223 0 0 2 2008 1 224 0 0 2 2008 2 225 0 0 2 2008 3 226 0 0 2 2008 4 227 0 0 2 2009 1 228 0 1 2 2009 2 229 1 1 2 2009 3 230 0 1 2 2009 4 231 0 1 thank you very much and sorry for my english.
has answer: http://stackoverflow.com/a/47400962

http://stackoverflow.com/q/47451123
has comment: http://stackoverflow.com/comment/81857367
has comment: http://stackoverflow.com/comment/81857372
has comment: http://stackoverflow.com/comment/81857760
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81857208
has comment: http://stackoverflow.com/comment/81857824
tagged with: python-module
tagged with: python
has body: I am currently running evaluations with multiple parameter configurations in a medium sized project. I set certain parameters and change some code parts and run the main file with python. Since the execution will take several hours, after starting it I make changes to some files (comment out some lines and change parameter) and start it again in a new tmux session. While doing this, I observed behaviour, where the first execution will use configuration options of the second execution, so it seems like python was not done parsing the code files or maybe lazy loads them. Therefore I wonder how python loads modules / code files and if changing them after I started the execution will have an impact on the execution?
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has title: When does python parse code files?

http://stackoverflow.com/q/47500836
has comment: http://stackoverflow.com/comment/81961353
tagged with: anaconda
has title: What do the last characters of a conda package's name mean?
score: 1
tagged with: python
has body: I'm fairly new to python and got myself familiar with how to set up project in python (via virtual environments) and how to reference other project with pip or Anaconda. Looking into the Anaconda repository, I realized that packages/libraries contains of the name, version and an odd looking number in the end. So my question is, what does this set of characters of an arbitrary length indicate? Is it like a specific build from that version? If so, why are there difference between the same version? Shouldn't it be a new version?
has comment: http://stackoverflow.com/comment/81958121
type: Question
linked to: http://stackoverflow.com/q/45874816
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81957991
upvote count: 1
duplicate of: http://stackoverflow.com/q/45874816
has comment: http://stackoverflow.com/comment/81957512
favorite count: 0

http://stackoverflow.com/q/47488668
type: UnansweredQuestion
tagged with: python
tagged with: optimization
has body: It's my first post. Sorry if it looks like a wall of text. Hoping someone can understand my question and provide an example module that can do this, or some code to try. I am working with timeseries csv data, example rows below, the columns are (datetime,O,H,L,C) 1999-10-26 21:00:00 68.81 68.83 68.07 68.19 1999-10-27 21:00:00 68.19 68.2 66.83 67.43 1999-10-28 21:00:00 67.43 68.06 66.91 68.06 1999-10-29 21:00:00 68.06 68.11 66.31 66.66 1999-01-11 22:00:00 66.66 67.15 66.09 66.63 1999-02-11 22:00:00 66.63 67.38 66.42 66.58 1999-03-11 22:00:00 66.58 67.73 66.42 67.48 1999-04-11 22:00:00 67.48 67.81 66.54 66.76 1999-05-11 22:00:00 66.76 68.2 66.54 67.87 Which is what is known as a candlestick in financial price data and can be represented visually like so: Now, what I am trying to achieve is to automatically plot a line that would cross as many wicks (vertical lines on candlesticks) as possible, while not crossing more than a specified tolerance number of candle bodies (green or red color areas) Hope this makes sense. Example. The line to cross as many wicks (in this case below the candles) would start on position 4, around 66.4 and have an up slope until position 9 around 66.55... What I imagine the line to look like based on the picture above Is there a module that can do this if I provide a starting position? Basically, something like a line of best fit, but actually crossing all the points (a point is a vertical line, so a range on the x axis), while avoiding to cross red/green areas so essentially a trendline (not curved) If this is too complicated because the line is diagonal, you may as well provide an example for a horizontal line to do the same (just one value from x axis). For example, a value of 66.54 will work too (it will cross all wicks, and touch last two ones) as seen in the data L (4th column) of last two records See yellow line crossing or touching all low wicks in this case value (x axis) of the starting position candle does not matter and was adjuste…
downvote count: 0
score: 1
upvote count: 1
has title: Python optimisation algorithm to adjust line to cross as many points as possible
answer count: 1
has answer: http://stackoverflow.com/a/47490239
tagged with: pyqtgraph
tagged with: plot
favorite count: 0
type: Question
tagged with: algorithm

http://stackoverflow.com/a/47503436
type: Answer
accepted answer of: http://stackoverflow.com/q/47500832
answers question: http://stackoverflow.com/q/47500832
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: If you want a very simple approximation to the best strategy you can use a greedy strategy of trying to clear as many lines as possible in the current round. You can also write a simple evaluation function to favor things like tight packing of blocks, leaving holes that future block shapes might fit nicely, etc. However, I suspect this will be far from optimal because you may clear a line but leave a huge mess behind which will be hard to clear in future rounds. If you want to find the optimal placement of the three blocks you will have to solve the entire game tree, since the block placements decides not only your score for the current round, but also how well you will do in future rounds. Since the game tree is far to large to solve completely, you will have to find a good approximate solution. For a number of reasons, I think this problem is a good candidate for Monte Carlo Tree Search, for example: The game tree is large with a high branching factor The game has a clear forward directionality Playing random moves will tend to score better starting from better board positions. MCTS does not require writing an evaluation function for non-terminal positions The game tree will have two kinds of nodes: player nodes and chance nodes. Each player node represents one block placements on the board, and each chance node represents the three blocks you draw at random at the beginning of the round which the player has no control over. The pseudocode for the MCTS algorithm for this game will be: def MCTS(root, board, n_sims): for 1...n_sims: b = board.copy() cur_node = root while cur_node.vists &gt;= expand_threshold: if cur_node is expanded: if cur_node is chance node: cur_node = sample child uniformly at random else: cur_node = child that maximizes UCT score b.update(cur_node) # update the board position with the block placement or the new three block draw else if b.game_over(): break else: expand(cur_node, b) # add all child nodes to tree score = b.roll_out() # play rando…
score: 1

http://stackoverflow.com/a/47460926
has body: The API Doc tells me that you can also use a String notation for filtering: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.filter import pyspark.sql.functions as F df = df.withColumn("unix_timestamp", df.unix_timestamp.cast("timestamp")) .filter("unix_timestamp &gt; %s" % hours_36) Maybe its not so effienc though
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47460650

http://stackoverflow.com/comment/81986641
has text: The keys of a dictionary are not per se ordered, so `[s.keys()[0]]` can lead to non-determinstic behavior.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47515312

http://stackoverflow.com/a/47531560
has body: Django have some paginator classes that can help you build it on your own. If you want to build a pagination you could do it like this: from django.core.paginator import Paginator def viewPage(request, page): paginator = Paginator(data, 10) # 10 being how many objects per page you want, data being an array of tracks try: tracks = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. tracks = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. tracks = paginator.page(paginator.num_pages) return render(request, 'view_page.html', { 'tracks': tracks, }) The data you need to give the Paginator() is the entire collection of tracks as an iterable.
downvote count: 1
answers question: http://stackoverflow.com/q/47531504
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/comment/81870182
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47457813
has text: It should be `a` not `key` for lower()

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/47410232
tags question: http://stackoverflow.com/q/47404203
tags question: http://stackoverflow.com/q/47450881
tags question: http://stackoverflow.com/q/47462114
tags question: http://stackoverflow.com/q/47449557
tags question: http://stackoverflow.com/q/47525680
tags question: http://stackoverflow.com/q/47519807
tags question: http://stackoverflow.com/q/47436008
tags question: http://stackoverflow.com/q/47420268
tags question: http://stackoverflow.com/q/47512770
type: Tag
tags question: http://stackoverflow.com/q/47526269
tags question: http://stackoverflow.com/q/47399830

http://stackoverflow.com/comment/81967986
type: Comment
score: 0
type: QuestionComment
has text: Yes, how to modify my code?Can you give me some suggestions
comment on: http://stackoverflow.com/q/47503177

http://stackoverflow.com/comment/82028753
score: 0
type: AnswerComment
has text: Thank you so much! Very helpful.
comment on: http://stackoverflow.com/a/47524126
type: Comment

http://stackoverflow.com/a/47480307
has body: This seems appropriate: def find_2nd_smallest(iterable): try: st = set(iterable) st.discard(min(st)) return iterable.index(min(st)) except: return None my_list = [7,3,6,4,6] print (find_2nd_smallest(my_list)) prints the index of the first occurrence of the 2nd smallest: 3 And if you want a function where you can input the number smallest (the 2 means 2nd smallest): def find_nth_smallest(iterable,n): try: st = set(iterable) for i in range(n-1): st.discard(min(st)) return iterable.index(min(st)) except: return None my_list = [7,3,6,4,6] print (find_nth_smallest(my_list,2)) Please note these functions may not be the most efficient solutions.
type: Answer
answers question: http://stackoverflow.com/q/47479584
score: 0

http://stackoverflow.com/comment/81787041
comment on: http://stackoverflow.com/q/47415796
score: 0
has text: Your app sending nothing [Check this](https://stackoverflow.com/questions/12607516/python-udp-broadcast-not-sending)
type: Comment
type: QuestionComment

aes
tag name: aes
tags question: http://stackoverflow.com/q/47383825
tags question: http://stackoverflow.com/q/47473479
tags question: http://stackoverflow.com/q/47495326
type: Tag

http://stackoverflow.com/comment/81787498
type: QuestionComment
has text: You'll need to drop an excessive arg you're passing: `predict_results = self.model.predict(self.params, exog, *args, **kwargs)` --> `predict_results = self.model.predict(self.params, exog, **kwargs)`. Prediction function the way you defined it takes X and kwargs but you tried to pass more stuff at the call site
comment on: http://stackoverflow.com/q/47416721
score: 0
type: Comment

http://stackoverflow.com/comment/81724246
comment on: http://stackoverflow.com/q/47385617
score: 0
type: QuestionComment
has text: Sounds like you're passing an `int` to `max`/`min` instead of a list of them.
type: Comment

http://stackoverflow.com/q/47402759
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47403250
has answer: http://stackoverflow.com/a/47403169
has comment: http://stackoverflow.com/comment/81759801
score: 1
has comment: http://stackoverflow.com/comment/81759885
upvote count: 1
tagged with: key
has body: I'm writing code for a project and it searches a text file for occurrences of a word on each line. When I use a example text file and search for a word it always prints out "No results for: " even if the word I searched for is in it. Did I setup the dictionary wrong or something? # -*- coding: utf-8 -*- """ Created on Tue Nov 14 11:31:17 2017 @author: Ben Roux """ import re from collections import Counter stringinput = raw_input("Please enter a filename to open: ") dictionary = {} def openFile(stringinput): try: filevariable = open(stringinput, 'r') return filevariable except IOError: print("Cannot Find File!") def readData(stringinput): filevariable = open(stringinput, 'r') rawline = filevariable.readline() line = 1 while (rawline !=""): pl1 = rawline.replace(",","") pl2 = pl1.replace("'","") pl3 = pl2.replace("!","") pl4 = pl3.replace("-"," ") pl5 = pl4.replace(".","") pl6 = re.sub('(\\b[A-Za-z] \\b|\\b [A-Za-z]\\b)', '', pl5) pl7 = pl6.lower() checkdictionary = sorted(Counter(pl7.split()).items()) for i in range(len(checkdictionary)): if checkdictionary[i] in dictionary: firstvalue = dictionary.get(checkdictionary[i]) newvalue = str(firstvalue) + ", " + str(line) d1 = {checkdictionary[i]: newvalue} dictionary.update(d1) else: d2 = {checkdictionary[i]: line} dictionary.update(d2) rawline = filevariable.readline() line+=1 def processText(dictionary, searchkey): if searchkey in dictionary: print(str(searchkey) + " Appears On Lines: " + (str(dictionary[searchkey]))) else: print("No results for: " + str(searchkey)) while (True): try: openFile(stringinput) readData(stringinput) searchkey = raw_input("Enter a keyword to search for: ") processText(dictionary, searchkey) break except IOError: break
has title: Python dictionary search not finding result given a string
possible better answer: http://stackoverflow.com/a/47403250
favorite count: 0
has comment: http://stackoverflow.com/comment/81759957
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81759939
has comment: http://stackoverflow.com/comment/81759299
has comment: http://stackoverflow.com/comment/81759818
downvote count: 0
tagged with: python
tagged with: dictionary
tagged with: regex
accepted answer: http://stackoverflow.com/a/47403169
tagged with: search

pyspark
tags question: http://stackoverflow.com/q/47494439
tags question: http://stackoverflow.com/q/47461969
tags question: http://stackoverflow.com/q/47458805
tags question: http://stackoverflow.com/q/47507159
tags question: http://stackoverflow.com/q/47394035
tags question: http://stackoverflow.com/q/47481814
tags question: http://stackoverflow.com/q/47386168
tags question: http://stackoverflow.com/q/47382768
tags question: http://stackoverflow.com/q/47509249
tags question: http://stackoverflow.com/q/47466002
tags question: http://stackoverflow.com/q/47402179
tags question: http://stackoverflow.com/q/47426943
tags question: http://stackoverflow.com/q/47463990
tags question: http://stackoverflow.com/q/47460650
tags question: http://stackoverflow.com/q/47467883
tags question: http://stackoverflow.com/q/47433582
tags question: http://stackoverflow.com/q/47512037
type: Tag
tags question: http://stackoverflow.com/q/47535578
tags question: http://stackoverflow.com/q/47517262
tags question: http://stackoverflow.com/q/47526055
tags question: http://stackoverflow.com/q/47458595
tags question: http://stackoverflow.com/q/47525063
tags question: http://stackoverflow.com/q/47483901
tags question: http://stackoverflow.com/q/47505106
tag name: pyspark
tags question: http://stackoverflow.com/q/47452209
tags question: http://stackoverflow.com/q/47470772
tags question: http://stackoverflow.com/q/47395353
tags question: http://stackoverflow.com/q/47506763
tags question: http://stackoverflow.com/q/47493442

http://stackoverflow.com/q/47437134
downvote count: 2
tagged with: plot
favorite count: 0
type: AnsweredQuestion
has title: PrettyTable format title
score: 1
tagged with: prettytable
answer count: 1
tagged with: python
has body: I want to format a title for prettytable with values but I can't. from prettytable import PrettyTable name = "table 1" table = PrettyTable() owntitle = "table name is {}".format(str(name)) table.title = owntitle table.field_names = ['Experiment', 'Value'] table.add_row(['bla', 3.14]) table.add_row(['baz', 42.0]) print(table) any suggestions?
accepted answer: http://stackoverflow.com/a/47437182
type: Question
has answer: http://stackoverflow.com/a/47437182
upvote count: 3

http://stackoverflow.com/q/47468045
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
tagged with: linux
tagged with: python
has comment: http://stackoverflow.com/comment/81890534
has title: TimeoutError when two computers communicated
type: Question
accepted answer: http://stackoverflow.com/a/47468428
has body: I am using Python3 to learn distributed programming there are two python file，one's name is main.py, it distributes information, the other one manipulation data, and the name is worker.py. everything goes well when I run this two file in one computer[set server address = 127.0.0.1, port = 5000] but when i run these two files in seperate computers, they cannot connect to each other, and TimeoutError was encoutered. I don't know why. one computer is Win10 at my home, the other is a linux cloud server which I baught. the code works in one computer. but when I ran main.py in linux, and ran worker.py{change server to linux's ip address} in win10, then the worker.py encounter a TimeoutError I know nothing about the linux, is there some security settings I need to open or close? """main.py""" import queue from multiprocessing.managers import BaseManager import datetime import time TASK_QUEUE = queue.Queue() RESULT_QUEUE = queue.Queue() def get_task_queue(): """set TASK_QUEUE as a function""" global TASK_QUEUE return TASK_QUEUE def receive_result_queue(): """set RESULT_QUEUE as a function""" global RESULT_QUEUE return RESULT_QUEUE class QueueManager(BaseManager): """inherit BaseManager from multiprocessing.managers""" pass if __name__ == '__main__': QueueManager.register('distribute_task_queue', callable=get_task_queue) QueueManager.register('receive_result_queue', callable=receive_result_queue) # bind port 5000, set verification code = 'abc' MANAGER = QueueManager(address=('127.0.0.1', 5000), authkey=b'abc') # start manager MANAGER.start() TASK = MANAGER.distribute_task_queue() RESULT = MANAGER.receive_result_queue() # put each line into manager`enter code here` with open("C:/Users/dayia/Desktop/log.20170817") as f: for line in f: TASK.put(line) # try receive result while 1: try: r = RESULT.get(timeout=1) if r[0] == r[1] and r[0] == "done": break else: print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),"line %s\'s length is %s" % (r[0], r[1])) except queue.Empty: …
has answer: http://stackoverflow.com/a/47468428

http://stackoverflow.com/comment/81866609
type: QuestionComment
score: 2
has text: I'm assuming since you're happy to use the same function for all cases, that it checks whether a or b are None to do it's logic. If so, pass them in as `eatAB(a if a else None, b if b else None)` and get rid of all the conditions.
comment on: http://stackoverflow.com/q/47456079
type: Comment

proxy-authentication
tags question: http://stackoverflow.com/q/47499986
type: Tag
tag name: proxy-authentication

http://stackoverflow.com/a/47431780
has body: You're trying to cascade from the back. So I reverse the order of the columns with iloc. I follow that up with pd.DataFrame.notnull() to identify which cells are not null. When I subsequently run pd.DataFrame.idxmax, I find all the column names for the first non null value in each row, starting from the back. Finally, I use pd.DataFrame.lookup to find the values associated with the found columns. df.assign( category_id=df.iloc[:, ::-1].notnull().idxmax(1).pipe( lambda d: df.lookup(d.index, d.values) ) ) category_id1 category_id2 category_id3 category_id4 category_id5 category_id6 category_id7 category_id 0 32991 22 33058 NaN NaN NaN NaN 33058 1 32991 22 51 NaN NaN NaN NaN 51 2 32991 22 121 NaN NaN NaN NaN 121 3 32991 22 120 NaN NaN NaN NaN 120 4 32991 22 32438 NaN NaN NaN NaN 32438
type: Answer
accepted answer of: http://stackoverflow.com/q/47431356
answers question: http://stackoverflow.com/q/47431356
type: AcceptedAnswer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81825650
downvote count: 0

http://stackoverflow.com/q/47532529
tagged with: https
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47532947
upvote count: 0
type: UnansweredQuestion
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/82021477
has comment: http://stackoverflow.com/comment/82021839
has title: unable to connect HTTPS url in python
score: -5
has comment: http://stackoverflow.com/comment/82021726
has comment: http://stackoverflow.com/comment/82021957
has body: #!/usr/bin/python import requests from requests.auth import HTTPBasicAuth requests.get('url', auth=HTTPBasicAuth('XXXX','XXXX')) I am getting Below error (Caused by ProxyError('Cannot connect to proxy.', error(111, 'Connection refused') requests.exceptions.ConnectionError: HTTPSConnectionPool(host='XXXX', port=443): Max retries exceeded with url
answer count: 1

http://stackoverflow.com/q/47394035
tagged with: http://stackoverflow.com/tag/csv
tagged with: pyspark
tagged with: python
type: UnansweredQuestion
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/81741902
score: 0
has title: Pyspark - reading a malformed CSV
answer count: 0
has body: I have a CSV file which I want to read into DataFrame Here is an example of my file (last column may contains string with spaces): C1 C2 C3 1 2 ab cd 11 12 xx yz 5 6 mm nn pl I tried to read this file using: spark.read.csv("myFile",header=True, mode="DROPMALFORMED",sep=' ') But It fails (all rows are malformed) In order to succeed on reading this file, I need to update it first (remove spaces, add underscores,etc..): C1 C2 C3 1 2 ab_cd 11 12 xx_yz 5 6 mm_nn_pl Is there a way to read the file into CSV without changing it? I also tried to use the attributes ignoreLeadingWhiteSpace and ignoreTrailingWhiteSpace without success. spark.read.csv("myFile",header=True, mode="DROPMALFORMED",sep=' ', ignoreLeadingWhiteSpace=True, ignoreTrailingWhiteSpace=True) Thanks for the help
has comment: http://stackoverflow.com/comment/81745656
linked to: http://stackoverflow.com/q/29936156
type: Question

http://stackoverflow.com/comment/82037813
type: QuestionComment
comment on: http://stackoverflow.com/q/47540344
score: 0
has text: I have fixed for them
type: Comment

http://stackoverflow.com/q/47403435
tagged with: flask
tagged with: password-protection
score: 1
has title: Twilio and Ngrok with password?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I'm using Flask, Twilio, and Ngrok to run a program on a Raspberry Pi. The username/password authentication in ngrok is working fine when I access the ngrok URL on a browser, but I want to be able to pass the username/pw in a text message to authenticate and then carry on with the code. Is it even possible? app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def camera_toggle(): from_number = request.values.get('From', None) from_message = request.values.get('Body', None) resp = MessagingResponse() resp.message("Please enter your username:password") if ":" not in from_message: #Split the username/password, then somehow login?? return str(resp) else: from_number = request.values.get('From', None) from_message = request.values.get('Body', None) if callers[from_number] == "John Doe": if from_message == "CameraON": subprocess.call(["bash", "camera.sh"]) return str("Please enter the keyword to turn on the camera") Is this even possible?
tagged with: twilio
has answer: http://stackoverflow.com/a/47403575
type: UnansweredQuestion
tagged with: ngrok
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47452016
answer count: 1
tagged with: django-rest-framework
type: Question
has title: Django REST zip file download return empty zip
tagged with: http://stackoverflow.com/tag/zip
tagged with: download
has body: I'm writing a script to download a zip file. I read a lot around on how to do this, but i still got some troubles. As you can see in the code, I first create a tempfile, write data on it, then zip it and download. The problem is the result: a zip archive with an empty file inside. This is the code: f = tempfile.NamedTemporaryFile() f.write(html.encode('utf-8')) print(f.read) #the "writing of tmp file" seem to work, the expected output is right fzip = ZipFile("test.zip","w") fzip.write(f.name,'exercise.html') #this file remains empty response = HttpResponse(fzip, content_type="application/zip") response['Content-Disposition'] = 'attachment; "filename=test.zip"' return response I already tried to set NamedTemporaryFile(delete=False) or to seek(0) and stuff like that. I think the problem is the fzip.write, but actually I can't figure other solutions, can anyone help? thanks :)
has answer: http://stackoverflow.com/a/47452183
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0

http://stackoverflow.com/comment/81815107
type: AnswerComment
comment on: http://stackoverflow.com/a/47429322
type: Comment
has text: No, I need to get /tmp/a/conf_web_16.2/c/* as I posted before. I give an example in my post, can you give me another suggestion?
score: 0

http://stackoverflow.com/q/47427136
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47427324
has body: In my serializer I override the create method: class CloudServerPayOrderSerializer(ModelSerializer): class Meta: model = TradeRecord exclude = ( 'id', 'name', 'traderecord_num', 'money', 'balance', 'desc', # 自己生成 ) def create(self, validated_data): # 先支付 TODO # 再生成交易记录 user = getUserFormSerializer(self) # --- 数据 name = "购买云服务器" traderecord_num = generateTradeRecordNum(userid=user.id) #order_id = validated_data.pop("order") #order = Order.objects.get(id=order_id) order = validated_data.pop("order") order.order_status = "已支付，未完成" order.save() paytype = validated_data.pop("paytype") money = order.cost account = Account.objects.get(user=user) balance = account.balance desc = "购买云服务器" traderecord_data = { "traderecord_num": traderecord_num, "name":name, "order": order, "money": money, "balance": balance, "paytype":paytype, "desc":desc, } traderecord = TradeRecord.objects.create(**traderecord_data) return traderecord But when I execute the traderecord = TradeRecord.objects.create(**traderecord_data) line, I get TypeError: TypeError at /api/userfront_product/cloudserver/order/pay/ init() got an unexpected keyword argument 'paytype' I use debug to test it, when debug the traderecord = TradeRecord.objects.create(**traderecord_data) step: enter image description here And I also copy the data out: {'paytype': '支付宝', 'order': &lt;Order: 用户名： vcpus：1核 ram：1G 系统盘：SSD40GB 数据盘：SSD0GB 1M &gt;, 'money': Decimal('220.00'), 'name': '购买云服务器', 'traderecord_num': 'TRN15113262838882', 'desc': '购买云服务器', 'balance': Decimal('0.00')} My TradeRecord model is bellow: class TradeRecord(models.Model): traderecord_num = models.CharField(unique=True, max_length=32, help_text="交易记录编号") name = models.CharField(max_length=64, help_text="交易记录名称") order = models.OneToOneField(to=Order, null=True , related_name="traderecord", help_text="对应的订单") money = models.DecimalField( decimal_places=2, default=0.0, max_digits=8, help_text="交易记录金额" ) # 正：代表账户入款 负：出款 balance = models.DecimalField( decimal_places=2, def…
has answer: http://stackoverflow.com/a/47427324
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1
has title: When I excute TradeRecord.objects.create(**traderecord_data) there raise TypeError
tagged with: django-rest-framework
favorite count: 0
type: Question
score: 1

http://stackoverflow.com/comment/81880401
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47462608
has text: i thought of (-1,2,n,r) too, but it doesn't work for odd numbers. For eg: 9x2x2 would refuse to split into (-1, 2, 2, 2). If I try (-1,1,n,r) I'm reshaping the last dim ://
type: AnswerComment

http://stackoverflow.com/comment/81757732
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47401961
has text: Use `str.extract` and `merge`.

http://stackoverflow.com/q/47481398
has comment: http://stackoverflow.com/comment/81918448
has comment: http://stackoverflow.com/comment/81918357
has comment: http://stackoverflow.com/comment/81918848
linked to: http://stackoverflow.com/q/3167154
type: AnsweredQuestion
has body: For every input file processed (see code below) I am trying to use "os.path.basename" to write to a new output file - I know I am missing something obvious...? import os import glob import gzip dbpath = '/home/university/Desktop/test' for infile in glob.glob( os.path.join(dbpath, 'G[D|E]/????/*.gz') ): print("current file is: " + infile) ** outfile=os.path.basename('/home/university/Desktop/test/G[D|E] /????/??????.xaa.fastq.gz').rsplit('.xaa.fastq.gz')[0] file=open(outfile, 'w+') ** gzsuppl = Chem.ForwardSDMolSupplier(gzip.open(infile)) for m in gzsuppl: if m is None: continue ...etc file.close() print(count) It is not clear to me how to capture the variable [0] (i.e. everything upstream of .xaa.fastq.gz) and use as the basename for the new output file? Unfortunately it simply writes the new output file as "??????" rather than the actual sequence of 6 letters. Thanks for any help given.
has answer: http://stackoverflow.com/a/47482133
has comment: http://stackoverflow.com/comment/81918413
has comment: http://stackoverflow.com/comment/81918427
answer count: 2
upvote count: 2
tagged with: os.path
has comment: http://stackoverflow.com/comment/81918591
has comment: http://stackoverflow.com/comment/81918335
downvote count: 3
has comment: http://stackoverflow.com/comment/81918890
possible better answer: http://stackoverflow.com/a/47482312
has title: os.path.basename to outfile
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47482133
has comment: http://stackoverflow.com/comment/81918650
has comment: http://stackoverflow.com/comment/81918529
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47482312

http://stackoverflow.com/comment/81719506
comment on: http://stackoverflow.com/q/47383380
has text: Use the `list.sort` method described in the [documentation](https://docs.python.org/3/library/stdtypes.html#list.sort). You can also use the `sorted()` function which is documented [here](https://docs.python.org/3/library/functions.html#sorted).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82051843
score: 0
type: Comment
type: QuestionComment
has text: Hey ahed87, just thought I would update you since I solved the problem. The solution was to use the draw method of the FigureCanvasQTAgg class, rather than the show method of the matplotlib.pyplot class. It was also necessary to maintain a persistent reference to ani so that it doesn't garbled up by the garbage collector. Thanks for all your help.
comment on: http://stackoverflow.com/q/47494757

http://stackoverflow.com/comment/81749858
comment on: http://stackoverflow.com/q/47398264
score: 0
type: Comment
type: QuestionComment
has text: Can you show exactly the code you are using and provide the `numpy` version?

http://stackoverflow.com/a/51717621
has body: You can use tf.fake_quant_with_min_max_vars, which accepts tensors as min/max arguments: return tf.fake_quant_with_min_max_vars(tensor, min=mean-3*std, max=mean+3*std)
type: Answer
answers question: http://stackoverflow.com/q/47537821
score: 0

http://stackoverflow.com/comment/81922367
type: Comment
type: QuestionComment
has text: The latter, yes; otherwise I'd just be changing the brightness of the color by a random amount, rather than making it a visibly different color.
comment on: http://stackoverflow.com/q/47483590
score: 0

http://stackoverflow.com/q/47496327
accepted answer: http://stackoverflow.com/a/47500277
answer count: 1
has title: scipy: scale the probability plot
tagged with: scipy
favorite count: 0
type: Question
has body: I have 38400 measurement values which are normal distributed. The mean is -4.10e-11 and sigma is 0.0229. Not surprisingly, the probability plot has a slope of 0.0229. For plotting and the detection of outliers I would like to plot it with a slope of 1. The range of theoretical quantiles should then be approximately the same as for the observations, i.e. between -0.09 and +0.09. How can I do this? (For the code example I am using random numbers instead of real measurements). import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats mean = -4.10e-11 sigma = 0.0229 np.random.seed(7654321) e_array = np.random.normal(mean, sigma, 38400) minvalue = np.min(e_array) maxvalue = np.max(e_array) qq = stats.probplot(e_array, dist="norm", plot=plt) qq_slope, qq_intercept, qq_r = qq[1] print('Minimum value: ', minvalue) print('Maximum value: ', maxvalue) print('QQ slope:', qq_slope) print('QQ intercept:', qq_intercept) print('QQ r:', qq_r) plt.show()
tagged with: python
tagged with: statistics
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47500277

http://stackoverflow.com/comment/81806660
has text: It's a `print` feature not `codecs` issue.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47425858

http://stackoverflow.com/comment/81993317
comment on: http://stackoverflow.com/q/47518518
has text: You need a While loop or a some similar construct. I'm not a Python programmer, but that gives you something to Google.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47531558
type: AcceptedAnswer
has body: You have to access to the content of the defined variables, done with the dollar sign. python sortout.py "${var1}" "${var2}"
has comment: http://stackoverflow.com/comment/82107423
has comment: http://stackoverflow.com/comment/82023367
accepted answer of: http://stackoverflow.com/q/47531502
type: Answer
answers question: http://stackoverflow.com/q/47531502
has comment: http://stackoverflow.com/comment/82023175
score: 0

http://stackoverflow.com/comment/81864227
type: AnswerComment
has text: thanks, now I just have to get the check function working (I have it working in a separate file but integration is difficult). You are a life saver
comment on: http://stackoverflow.com/a/47454733
type: Comment
score: 0

http://stackoverflow.com/a/47502341
answers question: http://stackoverflow.com/q/47501469
upvote count: 4
has body: If you want Route details it is best to query the Route model directly: routedetails = Route.objects.filter(driver__user=request.user) You can then iterate through the Route objects in your template: {% for route in routedetails %} &lt;p&gt;{{ route.leave_from }}&lt;/p&gt; &lt;p&gt;{{ route.destination }}&lt;/p&gt; ... {% endfor %}
downvote count: 0
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/47501469
type: AcceptedAnswer

http://stackoverflow.com/comment/81965933
has text: You ran out of memory.
comment on: http://stackoverflow.com/q/47505050
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81831258
score: 0
type: Comment
has text: Cannot return function to call. I changed it to "return EMA" and it works
type: AnswerComment
comment on: http://stackoverflow.com/a/47436889

http://stackoverflow.com/a/47483522
has comment: http://stackoverflow.com/comment/81922191
has body: Here you go: for i in index: list[i] = letter
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47483496
downvote count: 0
has comment: http://stackoverflow.com/comment/81921810
has comment: http://stackoverflow.com/comment/81922047

http://stackoverflow.com/a/47431137
has body: UPDATE: I've just re-read the question, which still doesn't make a lot of sense, but I've concluded that I'm not answering the question being asked here, but I shall leave this here for the time being in case it helps the OP in some small way. So I think I figured out what you were looking for. And I've made a working sample by changing your data slightly. So where you have post_no values that look like this: 110001~111000 I've modified in my sample to be: 1000, as you've not provided an explanation to why these values show like this and how we can use them. This sample gives you the basic operation to get your desired amount values based on whether or not the value is divisible by 1000. Reference: % (Modulus) (Transact-SQL) Returns the remainder of one number divided by another. Sample CREATE TABLE #temp ( post_no INT, id INT, region NVARCHAR(1)); INSERT INTO #temp ( post_no, id, region) VALUES (1000, 1, 'A'), (2000, 2, 'A'), (3000, 3, 'A'), (3222, 4, 'A'), (1000, 5, 'B'), (2000, 6, 'B'), (3000, 7, 'B'), (4000, 8, 'B'), (4174, 9, 'B'); SELECT t.post_no, t.id, t.region, CASE WHEN t.post_no % 1000 = 0 THEN post_no / ROW_NUMBER() OVER (PARTITION BY t.region ORDER BY id) ELSE t.post_no % 1000 END AS amount FROM #temp AS t; DROP TABLE #temp; Result: post_no id region amount ----------- ----------- ------ -------------------- 1000 1 A 1000 2000 2 A 1000 3000 3 A 1000 3222 4 A 222 1000 5 B 1000 2000 6 B 1000 3000 7 B 1000 4000 8 B 1000 4174 9 B 174 Note: This could be further simplified to simply return 1000 where the number is divisible by 1000, but I'll leave the above in there to be safe. Alternate code would look like this: SELECT t.post_no, t.id, t.region, CASE WHEN t.post_no % 1000 = 0 THEN 1000 -- just return 1000 if it's divisible by 1000 ELSE t.post_no % 1000 END AS amount FROM #temp AS t;
score: 2
answers question: http://stackoverflow.com/q/47430496
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47430496

jupyter-notebook
tags question: http://stackoverflow.com/q/47489272
tags question: http://stackoverflow.com/q/47499676
tags question: http://stackoverflow.com/q/47468627
tags question: http://stackoverflow.com/q/47447589
tags question: http://stackoverflow.com/q/47491733
tags question: http://stackoverflow.com/q/47463990
tags question: http://stackoverflow.com/q/47447033
tags question: http://stackoverflow.com/q/47507830
tags question: http://stackoverflow.com/q/47437396
tags question: http://stackoverflow.com/q/47413302
tags question: http://stackoverflow.com/q/47434544
tags question: http://stackoverflow.com/q/47411316
tags question: http://stackoverflow.com/q/47493806
tags question: http://stackoverflow.com/q/47446817
tags question: http://stackoverflow.com/q/47534298
tags question: http://stackoverflow.com/q/47385446
tags question: http://stackoverflow.com/q/47400353
tags question: http://stackoverflow.com/q/47522316
tags question: http://stackoverflow.com/q/47536735
tags question: http://stackoverflow.com/q/47438572
tags question: http://stackoverflow.com/q/47508168
tags question: http://stackoverflow.com/q/47492150
tags question: http://stackoverflow.com/q/47474072
tags question: http://stackoverflow.com/q/47516276
tags question: http://stackoverflow.com/q/47518874
tags question: http://stackoverflow.com/q/47397717
tags question: http://stackoverflow.com/q/47440694
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/47436322
type: Tag
tags question: http://stackoverflow.com/q/47437381
tags question: http://stackoverflow.com/q/47419823
tags question: http://stackoverflow.com/q/47431306
tags question: http://stackoverflow.com/q/47398264
tags question: http://stackoverflow.com/q/47382679
tags question: http://stackoverflow.com/q/47510845
tags question: http://stackoverflow.com/q/47418760
tags question: http://stackoverflow.com/q/47417933
tags question: http://stackoverflow.com/q/47521214
tags question: http://stackoverflow.com/q/47481544
tags question: http://stackoverflow.com/q/47488215
tags question: http://stackoverflow.com/q/47526002

http://stackoverflow.com/q/47505428
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/47505450
type: Question
has comment: http://stackoverflow.com/comment/81966934
accepted answer: http://stackoverflow.com/a/47506086
has title: How to change an array max in Python
has answer: http://stackoverflow.com/a/47507097
has comment: http://stackoverflow.com/comment/81966910
downvote count: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/47505450
has body: I want to change the max value of a list as below: a = [2, 2, 4, 5] max(a) = 10 print(a) but consistently get: SyntaxError: can't assign to function call Does anybody know how to change the max value? Thank everyone for the help! I want to replace the maximum of an array with another number, which will be my new maximum.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47506086
score: 0
has answer: http://stackoverflow.com/a/47505533
has comment: http://stackoverflow.com/comment/81966803
tagged with: python

http://stackoverflow.com/a/47416110
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/81786061
has comment: http://stackoverflow.com/comment/81786290
score: 0
answers question: http://stackoverflow.com/q/47415878
has body: You can try this: import itertools vector_input= [(3, 3, 3, 3, 3), (0, 0, 1), (3, 4, 3, 3, 4, 4), (1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 3, 3, 3, 1, 1, 3), (0, 0), (4, 4, 4, 4, 4), (1, 1), (3, 3), (1, 4, 3, 2), (3, 3, 4, 4, 4), (4, 4, 4, 4, 4), (3,), (2, 2), (2, 2, 2, 2, 2, 2), (0, 0, 0, 0, 1, 0), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (0, 0, 0, 0, 0, 0, 1, 0, 0, 1)] full_listing = list(set(itertools.chain(*vector_input))) final_data = [tuple(list(b).count(c) for c in range(min(full_listing), max(full_listing)+1)) for b in vector_input] Output: [(0, 0, 0, 5, 0), (2, 1, 0, 0, 0), (0, 0, 0, 3, 3), (0, 4, 0, 0, 0), (0, 16, 0, 0, 0), (0, 3, 0, 4, 0), (2, 0, 0, 0, 0), (0, 0, 0, 0, 5), (0, 2, 0, 0, 0), (0, 0, 0, 2, 0), (0, 1, 1, 1, 1), (0, 0, 0, 2, 3), (0, 0, 0, 0, 5), (0, 0, 0, 1, 0), (0, 0, 2, 0, 0), (0, 0, 6, 0, 0), (5, 1, 0, 0, 0), (0, 5, 0, 0, 0), (0, 5, 0, 0, 0), (8, 2, 0, 0, 0)]
has comment: http://stackoverflow.com/comment/81786008
type: Answer
accepted answer of: http://stackoverflow.com/q/47415878
upvote count: 1

http://stackoverflow.com/a/57878626
answers question: http://stackoverflow.com/q/47394060
has body: def move_to_player(self, Player): if Player.rect.x &gt; enemy.rect.x: enemy.changespeed(1,0) elif Player.rect.x &lt; enemy.rect.x: enemy.changespeed(-1,0) elif Player.rect.y &gt; enemy.rect.y: enemy.changespeed(0,1) elif Player.rect.y &lt; enemy.rect.y: enemy.changespeed(0,-1) The code above is a logic, not an AI you have coded a set of conditions for it to follow in a particular way. If you want an AI you would probably want to look at A-star pathfinding. This is what is used in most games nowadays. Furthermore, about the red block going mental. It maybe because you haven't set the frames per second correctly so the updates the screen is getting is too much changing the movement of the enemy by a lot.
score: 0
type: Answer

http://stackoverflow.com/q/47516326
tagged with: pandas
has title: Pandas DataFrame Issue. Don't know how to clean and manage a sort of block matrix
answer count: 1
tagged with: dataframe
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47516466
tagged with: python-3.x
upvote count: 2
has body: here is my first question: I have a pandas DataFrame that looks like the following: Pandas Dataframe The DataFrame shown in the picture is simplified (its original shape is [1195674 x 11]) but it doesn't matter. I am trying to set the left hand side (columns A, B, C, D) as index and the right hand side (columns E, F, G) as corresponding values (look at the colors). Do you have any hint? P.S. another way could be to replicate the left hand side (rows) in order to have something like the following (the red rows should be cancelled out): Second Solution Can you propose any other way to accomplish this task? Many thanks in advance! Franco
downvote count: 0
tagged with: data-cleaning
has comment: http://stackoverflow.com/comment/81988743
tagged with: python
accepted answer: http://stackoverflow.com/a/47516466
has comment: http://stackoverflow.com/comment/81988823
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81989070
score: 2
has comment: http://stackoverflow.com/comment/81988904

maya
tags question: http://stackoverflow.com/q/47398318
tags question: http://stackoverflow.com/q/47497669
type: Tag
tag name: maya
tags question: http://stackoverflow.com/q/47436562
tags question: http://stackoverflow.com/q/47496477

http://stackoverflow.com/comment/81814764
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47387082
type: Comment
has text: BTW, it is generally better to show the code directly in your question, in a code block, rather than a screenshot of a jupyter session. (Then people can try your code, and you are more likely to get a useful answer.)

http://stackoverflow.com/comment/81853383
has text: Oops, closed by accident.
type: Comment
comment on: http://stackoverflow.com/q/47449222
score: 0
type: QuestionComment

http://stackoverflow.com/q/47512118
tagged with: regex
has title: Python Regex: remove underscores and dashes except if they are in a dict of string substitutions
answer count: 4
has body: I'm pre-processing a string. I have a dictionary of 10k string substitutions (e. g. "John Lennon": "john_lennon"). I want to replace all other punctuation with a space. The problem is some of these string substitutions contain underscores or hyphens, so I want to replace punctuation (except full stops) with spaces unless the word is contained in the keys of this dict. I also want to do it in one Regex expression since the text corpus is quite large and this could be a bottleneck. So far, I have: import re input_str = "John Lennon: a musician, artist and activist." multi_words = dict((re.escape(k), v) for k, v in multi_words.items()) pattern = re.compile("|".join(multi_words.keys())) output_str = pattern.sub(lambda m: multi_words[re.escape(m.group(0))], input_str) This replaces all strings using the keys in a dict. Now I just need to also remove punctuation in the same pass. This should return "john_lennon a musician artist and activist."
accepted answer: http://stackoverflow.com/a/47512552
type: Question
has answer: http://stackoverflow.com/a/47512520
has answer: http://stackoverflow.com/a/47512552
possible better answer: http://stackoverflow.com/a/47512503
tagged with: python
tagged with: string
tagged with: dictionary
has answer: http://stackoverflow.com/a/47512503
has comment: http://stackoverflow.com/comment/81981422
has comment: http://stackoverflow.com/comment/81980759
has comment: http://stackoverflow.com/comment/81980631
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47512567
score: 0

http://stackoverflow.com/comment/81766183
type: AnswerComment
comment on: http://stackoverflow.com/a/47406269
type: Comment
has text: @jezrael 0.21 on python3.4 (Ipython5), MacOS. My machine is a bit old so timings would vary.
score: 0

http://stackoverflow.com/q/47427238
downvote count: 0
tagged with: covariance
has answer: http://stackoverflow.com/a/47427304
has title: Diagonal element for covariance matrix not 1 pandas/numpy
has answer: http://stackoverflow.com/a/47428113
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47427265
tagged with: dataframe
tagged with: python
score: 4
has body: I have the following dataframe: A B 0 1 5 1 2 6 2 3 7 3 4 8 I wish to calculate the covariance a = df.iloc[:,0].values b = df.iloc[:,1].values Using numpy for cov as : numpy.cov(a,b) I get: array([[ 1.66666667, 1.66666667], [ 1.66666667, 1.66666667]]) Shouldn't the diagonal elements be 1? How do I get the diagonal elements to 1?
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47427265
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47428113

http://stackoverflow.com/comment/81812243
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47428737
has text: Thank you very much for the help! I also got another answer but I will see which works better out of the two.

http://stackoverflow.com/q/47454706
tagged with: pandas
favorite count: 0
type: Question
upvote count: 2
has body: I am trying to create cumulative table from dataframe, I get sum and then I get cumsum with following code. g=df.groupby(['Category'])['VALUE'].agg(['sum']).sort_values(by="sum", ascending=False) index = g.index.values cum_sum = g['sum'].cumsum() data = g['sum'] g['cum_sum'] = g['sum'].cumsum() cum_max = g['cum_sum'].max() But I want to create new dataframe like this: |Category|Sum|CumSum|Percentage|CumPercentage| A 5 5 1 1 B 4 9 2 3 I have tried to get cumsum with aggregate too, but didn't success: g=df.groupby(['Category'])['VALUE'].agg(['sum'i 'cumsum']).sort_values(by="sum", ascending=False) Above code didn't work for me. Category VALUE ST_CITY ST_STATE ST_POSTAL ST_COUNTRY Category1 72 CHARLESTON SC 29403 USA Category1 36 BROOKLYN NY 11235 USA Category2 9 FAIRFIELD CT 6824 USA Category2 9 FAIRFIELD CT 6824 USA Category3 12 CHARLESTON SC 29412 USA Category1 30 WALLINGFORD PA 19086 USA Category2 9 GRAND RAPIDS MI 49506 USA Category3 12 ALAMEDA CA 94502 USA Category2 9 DANVILLE CA 94526 USA Category2 9 LONGWOOD FL 32779 USA Category3 12 NEW YORK NY 10022 USA Category1 36 ALAMOGORDO NM 88310 USA Category3 12 BRECKSVILLE OH 44141 USA Category3 12 CHICAGO IL 60657 USA Category2 9 BIRMINGHAM AL 35242 USA Category2 9 BIRMINGHAM AL 35242 USA Category2 9 GREENWOOD VILLAGE CO 80121 USA Category1 36 GREENWOOD VILLAGE CO 80121 USA Category1 36 CHICAGO IL 60615 USA Category2 9 MANASSAS VA 20112 USA Category2 9 OTIS ORCHARDS WA 99027 USA Category2 9 ARNOLD MD 21012 USA Category2 9 MOUNTAIN VIEW CA 94043 USA Category1 36 DEL MAR CA 92014 USA Category1 36 NEW YORK NY 10023 USA Category1 36 NEW YORK NY 10128 USA Category3 12 OJAI CA 93023 USA Category2 9 BROOKLYN NY 11201 USA Category2 9 ST. CHARLES MO 63301 USA
downvote count: 0
has title: Sum, Cumsum, Percetage, Cum Percentage from Pandas Dataframe
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47455023
accepted answer: http://stackoverflow.com/a/47455023
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/47503117
has comment: http://stackoverflow.com/comment/81962449
answers question: http://stackoverflow.com/q/47502849
type: AcceptedAnswer
has body: I did the following: all = (soup.findAll("span",{"class":"title"})) for a in all: print(a.text) break When I looked in the soup, I could see the playlist has class=title for each song in the list. The output is: Ed Sheeran - Thinking Out Loud [Official Video]
accepted answer of: http://stackoverflow.com/q/47502849
score: 0
type: Answer

http://stackoverflow.com/comment/81910610
score: 0
comment on: http://stackoverflow.com/a/47462753
has text: @Ben Yes you are entirely write, there was confusion on my part. I have updated the answer now, and it is actually a shorter expression now!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/116567106
has text: A "volume label" is not at all "the name of a partition." The name of a partition is a user-assigned 'label' that has nothing to do with a "volume label." Volume labels are either `msdos` or `gpt`. I know this is an old question but this is not good information on SO.
type: Comment
comment on: http://stackoverflow.com/a/47464669
type: AnswerComment
score: 0

http://stackoverflow.com/a/51801290
answers question: http://stackoverflow.com/q/47539201
type: Answer
has body: I too was struggling with this issue, and everything was configured correctly. I installed and setup my system path variables as one would. And everything was fine. Then upon reboot windows would not recognize 'python' as a command as if it were unaware of the path variable. Double checked to confirm everything was still setup correctly (it was). It only started to work again after I manually browsed to the directory in which python.exe existed, and ran 'python'. After that windows seemed to recognize my path variable and I could call 'python' from where ever need be. Very odd. Figured I'd share in case someone else runs into this.
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82506816
comment on: http://stackoverflow.com/q/47431458
type: Comment
type: QuestionComment
score: 0
has text: You just edited an answer into your question. Please undo the edit and post that as an answer and you can accept it.

http://stackoverflow.com/q/47421908
upvote count: 1
tagged with: python
has title: How to handle pins in A64-OLinuXino-1G4GW board using Python?
score: 1
downvote count: 0
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
has body: I am working on a project where we would like to use A64-OLinuXino-1G4GW board. There is a problem with pin handling of the board, as the programs I want to run are written in Python language and I have not found any library to control pins. I would greatly appreciate it if you could quote some library or some examples of python code for pin handling. PS: The project started with raspberry pi board so it would be great if I could use same py files but with the appropriate library for A64-OLinuXino-1G4GW board.

http://stackoverflow.com/comment/81799266
comment on: http://stackoverflow.com/a/47422344
score: 0
type: Comment
type: AnswerComment
has text: That's probably the best answer. I wonder how the performance compares to mine.

http://stackoverflow.com/q/47441239
has body: I'm trying to upload a user photo and show it in homepage. problem 1 : When i upload an image from admin section it gets saved in database but it doesn't show up in 'homepage.html'. Problem 2 : When i try to upload an image using 'profile.html' template the image is not even saved in database. I've tried several solution from stackoverflow but failed to solve my problem. My code is given below: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') first_name= models.CharField(max_length=100, default='', blank=True) last_name = models.CharField(max_length=100, default='', blank=True) email = models.CharField(max_length=100, default='', blank=True) pro_pic = models.ImageField(upload_to='profilepic',blank=True) phone = models.CharField(max_length=20, blank=True, default='') city = models.CharField(max_length=100, default='', blank=True) country = models.CharField(max_length=100, default='', blank=True) job = models.CharField(max_length=20, blank=True, default='') organization = models.CharField(max_length=100, default='', blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py from django.contrib.auth.models import User from django import forms from .models import UserProfile class UserForm(forms.ModelForm): class Meta: model = UserProfile fields = ['first_name', 'last_name', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['pro_pic','phone', 'city', 'country', 'job', 'organization'] settings.py MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(B…
upvote count: 0
has answer: http://stackoverflow.com/a/47442126
has comment: http://stackoverflow.com/comment/81838186
tagged with: django
tagged with: django-models
tagged with: python
score: -1
tagged with: django-database
has comment: http://stackoverflow.com/comment/81837599
has title: Django Image is not saving in database
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47441718
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47441718
downvote count: 1
has comment: http://stackoverflow.com/comment/81837505
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81837663
accepted answer: http://stackoverflow.com/a/47442126

http://stackoverflow.com/a/47499055
has body: If you have t='12904\n', make sure to put t=t.strip() to remove whitespace on the edges. Also if you expect non-integer inputs, use float instead of int.
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81953321
upvote count: 0
answers question: http://stackoverflow.com/q/47498974

http://stackoverflow.com/a/76951352
has body: You are almost there. The full pathlib version would be something like: folder = "path/to/folder" file_base = "file_name_base" file_extension = ".extension" p_folder = pathlib.Path(folder) p_file_base = p_folder / file_base p_file = p_file_base.with_suffix(file_extension) p_file.parent.mkdir(parents=True, exist_ok=True) # or `p_folder` p_file.write_text("Your text here", encoding ="utf-8") I decomposed all steps to make it as transparent as possible, you can shorten this code. For example: p_file = pathlib.Path("path/to/folder/file_base") p_file.parent.mkdir(parents=True, exist_ok=True) p_file.with_suffix(".extension").write_text("Your text here", encoding ="utf-8")
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47518669
type: Answer

http://stackoverflow.com/comment/82029129
comment on: http://stackoverflow.com/a/47531396
type: AnswerComment
score: 0
has text: I think I'll end up going with Row Level Security on PostgreSQL: https://www.postgresql.org/docs/9.5/static/ddl-rowsecurity.html. This article helped me a lot to bridge the application level users with postgres policies: https://blog.2ndquadrant.com/application-users-vs-row-level-security/
type: Comment

url
tags question: http://stackoverflow.com/q/47526788
tag name: url
tags question: http://stackoverflow.com/q/47424245
tags question: http://stackoverflow.com/q/47443434
tags question: http://stackoverflow.com/q/47514188
tags question: http://stackoverflow.com/q/47388870
tags question: http://stackoverflow.com/q/47418812
type: Tag

http://stackoverflow.com/comment/82002702
comment on: http://stackoverflow.com/q/47523071
score: 0
type: Comment
type: QuestionComment
has text: connection can be defined in the 4 or 8 neighbouring cells.

http://stackoverflow.com/a/47521266
type: Answer
has body: You can do something like this: import json nl=[] for di in json.loads(js): min_,sep,max_=map(lambda s: s.strip(), di['min_max'].partition('/')) if sep=='/': del di['min_max'] di['min']=min_ di['max']=max_ nl.append(di) print json.dumps(nl) This keeps the "min_max" values that cannot be separated into two values unchanged.
score: 0
answers question: http://stackoverflow.com/q/47516976

http://stackoverflow.com/comment/82023328
has text: after first login attempt, redirect user to that screen where user have to input the OTP ( he get by either email or phone )
score: 0
comment on: http://stackoverflow.com/a/47531347
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47435446
has title: Django + Factory Boy: How to use a named parameter to control behavior of factory.Maybe + factory.RelatedFactory
has body: Is there a way to define a named parameter (that is not a model attribute) to control the behavior of factory.Maybe? For example: I want to create a named parameter that controls the creation of a RelatedFactory through a Maybe condition, I tried to do this: # factories.py class Purchase(factory.DjangoModelFactory): user = factory.SubFactory('project.factories.UserFactory') total = uniform(10, 100) class Meta: model = Purchase class UserFactory(factory.DjangoModelFactory): first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') has_purchase = False purchases = factory.Maybe( 'has_purchase', yes_declaration=factory.RelatedFactory(Purchase, 'purchase'), no_declaration=None ) class Meta: exclude = ['has_purchase', 'purchases'] model = User # tests.py user_without_purchase = UserFactory.create() user_with_purchase = UserFactory.create(has_purchase=True) It seems that I can't change the value of has_purchase through the named parameter, it's always set as False. I don't know if it's because both fields are declared in exclude Meta attribute. And I have to put them in exclude or else DjangoModelFactory tries to use these fields when saving it to the database, which causes an Integrity error. Is there a way to do that?
type: Question
has answer: http://stackoverflow.com/a/53616592
answer count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47435789
tagged with: django
tagged with: python
favorite count: 0
score: 3
upvote count: 3
tagged with: factory-boy

http://stackoverflow.com/q/47493559
has body: I recently started to follow along with Siraj Raval's Deep Learning tutorials on YouTube, but I an error came up when I tried to run my code. The code is from the second episode of his series, How To Make A Neural Network. When I ran the code I got the error: Traceback (most recent call last): File "C:\Users\dpopp\Documents\Machine Learning\first_neural_net.py", line 66, in &lt;module&gt; neural_network.train(training_set_inputs, training_set_outputs, 10000) File "C:\Users\dpopp\Documents\Machine Learning\first_neural_net.py", line 44, in train self.synaptic_weights += adjustment ValueError: non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,4) I checked multiple times with his code and couldn't find any differences, and even tried copying and pasting his code from the GitHub link. This is the code I have now: from numpy import exp, array, random, dot class NeuralNetwork(): def __init__(self): # Seed the random number generator, so it generates the same numbers # every time the program runs. random.seed(1) # We model a single neuron, with 3 input connections and 1 output connection. # We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1 # and mean 0. self.synaptic_weights = 2 * random.random((3, 1)) - 1 # The Sigmoid function, which describes an S shaped curve. # We pass the weighted sum of the inputs through this function to # normalise them between 0 and 1. def __sigmoid(self, x): return 1 / (1 + exp(-x)) # The derivative of the Sigmoid function. # This is the gradient of the Sigmoid curve. # It indicates how confident we are about the existing weight. def __sigmoid_derivative(self, x): return x * (1 - x) # We train the neural network through a process of trial and error. # Adjusting the synaptic weights each time. def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations): for iteration in range(number_of_training_iterations): # Pass the training set through our neural netw…
possible better answer: http://stackoverflow.com/a/54029292
score: 17
tagged with: artificial-intelligence
upvote count: 18
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/77991159
has answer: http://stackoverflow.com/a/47493938
tagged with: neural-network
tagged with: python
has answer: http://stackoverflow.com/a/54029292
has comment: http://stackoverflow.com/comment/81942817
accepted answer: http://stackoverflow.com/a/47493938
has title: ValueError: non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,4)
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/47410628
has answer: http://stackoverflow.com/a/47412990
tagged with: python
linked to: http://stackoverflow.com/q/3232904
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47412990
answer count: 1
tagged with: scrapy
downvote count: 1
has title: ERROR for site owner: Invalid domain for site key
favorite count: 0
type: Question
upvote count: 2
has body: Im trying to scrape some images with the help of Scrapy, after i have fetched the site,and type in the command view response, A window opens in my browser like it should,but instead of the photos and details being shown, i get the captcha errorERROR for site owner: Invalid domain for site key. What am i supposed to do get around this!,any suggestions would be helpful. Thanks in advance. The link of the website. The screenshot of the error is also posted below:

http://stackoverflow.com/q/47388258
type: AnsweredQuestion
tagged with: statsmodels
tagged with: pandas
has answer: http://stackoverflow.com/a/72659306
tagged with: linear-regression
has title: How to extract the regression coefficient from statsmodels.api?
upvote count: 51
linked to: http://stackoverflow.com/q/51734180
linked to: http://stackoverflow.com/q/29165601
has answer: http://stackoverflow.com/a/72644324
has comment: http://stackoverflow.com/comment/94125514
possible better answer: http://stackoverflow.com/a/58319425
favorite count: 0
type: Question
score: 51
accepted answer: http://stackoverflow.com/a/47388554
answer count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/47388554
tagged with: python
has body: result = sm.OLS(gold_lookback, silver_lookback ).fit() After I get the result, how can I get the coefficient and the constant? In other words, if y = ax + c how to get the values a and c?
has answer: http://stackoverflow.com/a/58319425
has answer: http://stackoverflow.com/a/60637504

http://stackoverflow.com/comment/81888521
type: QuestionComment
comment on: http://stackoverflow.com/q/47466397
score: 0
type: Comment
has text: One way is to use virtual environments. Now that python 2 is already there all you need is create a virtual Environment in python 2 and install python 3 inside that. Other way is to use like you said in the question call python 3 as "python3" and "python" or "python2" for python 2.

http://stackoverflow.com/comment/81803296
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47424173
type: Comment
has text: @Elisha512 Sorry, there was a typo in my answer which I fixed. Check both our solutions and see which one is faster on your data.

http://stackoverflow.com/a/47493146
downvote count: 0
has body: The general idea is to use the GCS client library's .open() function instead of the regular filesystem open(). Maybe you can expand (by using a csv.reader instead of the csv.writer) from Write a CSV to store in Google Cloud Storage. Maybe something along these lines? (not tested): gcs_file = gcs.open(os.path.join(bucket, filename), 'r') csv_reader = csv.reader(gcs_file) # add whatever options you need # CSV processing gcs_file.close()
answers question: http://stackoverflow.com/q/47492839
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/82055912
has text: That's beautiful! Thank you very much, Tanaike! :) It worked like a charm.
type: Comment
comment on: http://stackoverflow.com/a/47524181
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81844194
comment on: http://stackoverflow.com/a/47443343
score: 0
has text: Makes sense. BTW, my real problem is a nonlinear least squares minimization subject to interval and inequality constraints. I assume that both the square root version of SLSQP as well as cvxpy should handle this, right? (Verifying this for SLSQP now).
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/103133505
type: Comment
score: 0
type: AnswerComment
has text: Last but not least, rather than use `hex = str(hex)`, consider using `if isinstance(hex, uuid.UUID): hex, int = None, hex.int`, as a faster alternative that doesn't require formatting the `.int` attribute as hex then splitting it out into a larger string, only to then be parsed out into an integer again..
comment on: http://stackoverflow.com/a/50823527

http://stackoverflow.com/comment/81863818
score: 0
comment on: http://stackoverflow.com/q/47453372
type: Comment
type: QuestionComment
has text: I think that what i need is a 4 or 5-level-loop to catch all values with a check if old-tag is empty or not.

http://stackoverflow.com/comment/81830610
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47437398
has text: You are doing tri-gram, that's why. You should be amazed it works within 30 minutes.

http://stackoverflow.com/a/47409330
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47406832
type: Answer
answers question: http://stackoverflow.com/q/47406832
has body: My advice would be to store all the emails from testmail.txt in a set, compile the regex, and then iterate over the lines of maillog.txt and search in the mail is in the set. That way, only the shorter of the files has to reside in memory, the regex pattern in only compiled once, and researches are done in a set which is optimized for this kind of access: import re pattern=r'(?P&lt;month&gt;[A-Za-z]{3})\s{1,3}(?P&lt;day&gt;\d{1,2})\s{1,2}(?P&lt;ts&gt;\d+:\d+:\d+).*to=&lt;(?P&lt;email&gt;([\w\.-]+)@([\w\.-]+))' # load the testmail file into a set mails = set() with open('testmail.txt') as fd: for line in fd: mails.add(line.strip()) #compile the regex once rx = re.compile(pattern) #process the maillog file: with open('maillog.txt') as fd: for line in fd: m = rx.match(line) if m is not None and m.groupdict()['email'] in mails: print(m.groupdict()) The output with your example data is as expected: {'month': 'Nov', 'day': '3', 'ts': '10:08:43', 'email': 'adamson@example.com'}
score: 1

password-protection
tags question: http://stackoverflow.com/q/47403435
tag name: password-protection
type: Tag

http://stackoverflow.com/comment/81886494
score: 0
has text: Just for clarification, are you refering to the `imageUrl` key? Like these, [here](https://imgur.com/a/irD2V)?
type: QuestionComment
comment on: http://stackoverflow.com/q/47465930
type: Comment

http://stackoverflow.com/q/47401451
has comment: http://stackoverflow.com/comment/81762575
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81758263
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81761844
tagged with: whoosh
tagged with: nltk
has body: So, I am working on a search engine. We have two indexed corpora and some relevant queries based on the corpora. After running the query , we are getting top 10 results. Now I am trying to rank/score the results according to their relevance. I was looking up the BM25F algorithm and I can't figure out how to use the algorithm in Whoosh. with ix.searcher(weighting = whoosh.scoring.BM25F()) as searcher: query_text = QueryParser("stem_text", ix.schema, termclass=query.Variations, group= qparser.OrGroup).parse( "what is something pretty astonishing?") results = searcher.search(query_text, sortedby= scores, limit = 10) for hit in results: print(hit["stem_text"]) I would like to apply the BM25F algorithm on the results.
has comment: http://stackoverflow.com/comment/81756754
has comment: http://stackoverflow.com/comment/81761821
tagged with: python
has title: How to implement the BM25F with a set of corpus and queries in Python using Whoosh indexing tool?
tagged with: nlp

http://stackoverflow.com/comment/81895143
has text: You seem to have pandas. So you could just sample and then split. The index lets you know where the sampled data came from. Ping me if you're interested in an answer.
score: 0
comment on: http://stackoverflow.com/q/47469786
type: QuestionComment
type: Comment

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/47436398

http://stackoverflow.com/q/47477771
tagged with: hosting
tagged with: heroku
score: 0
has body: After 30mins of not being used Heroju resets my django site, however when the site is reset the database/models controlled and changed in the admin page are reset back to when the site was first uploaded. How do i stop this and make changes made in admin mode permanently to the site? thank you.
has title: Heroku and Django, database resets when heroku restarts the site
answer count: 1
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47478237
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/82004307
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47459254
type: Comment
has text: Did you create a setup.cfg file and added it to the same directory as the setup.py file?

http://stackoverflow.com/a/47413576
accepted answer of: http://stackoverflow.com/q/47413345
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47413345
has body: For me working set only by MutliIndex Series in 0.21.0 : mux = pd.MultiIndex.from_product([['aaa'], ['x', 'y']]) ser.loc['A'] = pd.Series([100, 202], index=mux) print (ser) u v A x 100 y 202 B x 2 y 3 dtype: int64 Also working solution from comment of Michał Politowski: ser['A'] = pd.Series([100, 202], index=['x', 'y'])

http://stackoverflow.com/q/47442902
tagged with: sqlite
accepted answer: http://stackoverflow.com/a/47444061
answer count: 1
has answer: http://stackoverflow.com/a/47444061
type: Question
has comment: http://stackoverflow.com/comment/81841951
has comment: http://stackoverflow.com/comment/81840920
has comment: http://stackoverflow.com/comment/81841929
tagged with: python
has title: How do I delete from a SQLite database in python using a tkinter entry instead of stating a string or value?
has body: I am trying to delete a row in my SQLite database using the following lines: conn = sqlite3.connect('test.db') c = conn.cursor() memID = str(idBox.get()) #c.execute('DELETE FROM Test WHERE memberID = idBox.get()') so i am trying to delete from the table using a tkinter entry (idBox) but get the following error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\Python36\lib\tkinter__init__.py", line 1699, in call return self.func(*args) File "I:/Onedrive/PycharmProjects/TKinter/MainProgram/main.py", line 36, in delete_data_entry c.execute('DELETE FROM Test WHERE memberID = idBox.get()') sqlite3.OperationalError: near "(": syntax error I have been stuck with this for quite some time and would appreciate some help more code (memberid variable being created): memberid = str(uuid.uuid4()) print(memberid[0:8]) c.execute("INSERT INTO Test(memberID, fullname, username, password) VALUES (?, ?, ?, ?)", (memberid[0:8], fullnameBox.get(), usernameBox.get(), passwordBox.get())) conn.commit()
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81840819

http://stackoverflow.com/comment/81939598
score: 1
comment on: http://stackoverflow.com/q/47475627
type: Comment
has text: You should not need to prepare 10 templates but you probably may use QPixmap/QImage/QPicture/QIcon/QBitmap to create the blue circle with the number and then add it as an icon overlay using QPainter.
type: QuestionComment

http://stackoverflow.com/comment/81849035
score: 0
comment on: http://stackoverflow.com/q/47444756
type: Comment
type: QuestionComment
has text: best I can tell its version 0.13.0 if this seems correct. I did a 'conda list' command and thats what I got.

cross-platform
tags question: http://stackoverflow.com/q/47395189
tag name: cross-platform
type: Tag

http://stackoverflow.com/a/47511107
upvote count: 2
has comment: http://stackoverflow.com/comment/81977859
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82003928
answers question: http://stackoverflow.com/q/47511055
has comment: http://stackoverflow.com/comment/82003445
type: Answer
has comment: http://stackoverflow.com/comment/81977849
has body: Maybe you need np.where i.e df['count'] = np.where(df['Name']!='NaN',df['Name'].str.count(',')+1,'') Name count 0 Raj 1.0 1 NaN 2 Ravi,kumar 2.0

http://stackoverflow.com/comment/82006838
type: QuestionComment
score: 0
has text: i know the mpl built in function but i didn't know how to use it with my dataset
comment on: http://stackoverflow.com/q/47518937
type: Comment

http://stackoverflow.com/comment/81769106
type: AnswerComment
comment on: http://stackoverflow.com/a/47407390
type: Comment
has text: Reading your question carefully again my answer makes no sense :/
score: 0

http://stackoverflow.com/a/47468325
score: 1
has body: You can do this. This will return data for every div. from bs4 import BeautifulSoup soup = BeautifulSoup(b) // b is html rows =soup.find_all('div', {'class': 'DataNew'}) for tag in rows: for tag in li: for i in tag.find_all("div", {"class": "name"}): print i.getText() break for i in tag.find_all("div", {"class": "details"}): print i.getText() break for i in tag.find_all("div", {"class": "header"}): print i.getText() break for i in tag.find_all("div", {"class": "ideas"}): print i.getText() break for i in tag.find_all("div", {"class": "profile"}): print i.getText() break for i in tag.find_all("div", {"class": "Data Right"}): print i.getText() break
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47468194

http://stackoverflow.com/q/47478837
has title: Get filtered values from SQL Alchemy ORM Query
has body: I have a Query object which I've done some filtering on. Now I pass that query around and then later I'd like to see what I've filtered on, using some kind of inspection. I've got as far as: &gt;&gt;&gt; q = session.query(Activity).filter(Activity.label == "Foo") &gt;&gt;&gt; print(q.whereclause) table.activity.label = :label_1 I can't find a way to get anything else out of that sqlalchemy.sql.elements.BinaryExpression other than the column name (not the filtered value which I want, in this case "Foo").
tagged with: sqlalchemy
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47479760
type: Question
has answer: http://stackoverflow.com/a/47479760
tagged with: python

http://stackoverflow.com/q/47439189
favorite count: 0
has comment: http://stackoverflow.com/comment/81833227
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47439824
has comment: http://stackoverflow.com/comment/81833896
has comment: http://stackoverflow.com/comment/81834061
linked to: http://stackoverflow.com/q/9010222
tagged with: python
has title: Python Object as Dict Key using __hash__ for access
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47439824
downvote count: 3
score: 1
has comment: http://stackoverflow.com/comment/81833926
has body: Take this super simple class: class Foo(): def __init__(self, iden): self.iden = iden def __hash__(self): return hash(self.iden) def __repr__(self): return str(self.iden) The goal is to create instances of the class to use as dict keys. If __repr__ is omitted, the keys are the standard object address. With __repr__ a printable representation might be: f = Foo(1) g = Foo(2) d = {f:'a', g:'b'} print(d) &gt;&gt;&gt; {1:'a', 2:'b'} When attempting to access the dict by key though, it does not appear to be immediately obvious how to utilize the __repr__ (or __str__ for that matter) representation as the key. print(d[1]) &gt;&gt;&gt; KeyError
answer count: 1
upvote count: 4

http://stackoverflow.com/q/47446494
downvote count: 0
accepted answer: http://stackoverflow.com/a/47446822
has body: I am new to webscraping and regular expressions and facing a problem here. One of my code gives me an output in HTML but I need to extract a certain part out of the paragraph and not the complete paragraph. I Need help with this. Below is my code. import mechanize from bs4 import BeautifulSoup import urllib2 br = mechanize.Browser() response = br.open("http://www.consultadni.info/index.php") br.select_form(name="form1") br['APE_PAT']='PATRICIO' br['APE_MAT']='GAMARRA' br['NOMBRES']='MARCELINA' req=br.submit().read() soup = BeautifulSoup(req, "lxml") for link in soup.findAll("a"): sub=link.get("href") soup1 = BeautifulSoup(sub, "lxml") print soup1.find_all('p') Output on screen: [&lt;p&gt;/&lt;/p&gt;] [&lt;p&gt;datospersonales.php?nc=PATRICIO GAMARRA MARCELINA&amp;amp;dni1=40772568&amp;amp;dni2=12405868&amp;amp;id1=12a40a58a68&amp;amp;id2=30/06/1980&amp;amp;dni3=40631880&lt;/p&gt;] [&lt;p&gt;datospersonales.php?nc=PATRICIO GAMARRA MARCELINA&amp;amp;dni1=40772568&amp;amp;dni2=12405868&amp;amp;id1=12a40a58a68&amp;amp;id2=30/06/1980&amp;amp;dni3=40631880&lt;/p&gt;] [&lt;p&gt;http://www.infocorpperuconsultatusdeudas.blogspot.com/2015/05/infocorp-consulta-gratis-tu-reporte-de.html?ref=dnionline&lt;/p&gt;] What I need: 30/06/1980 &amp; 40631880
tagged with: web-scraping
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47446575
has comment: http://stackoverflow.com/comment/81848747
has title: How to extract certain parts of an HTML paragraph
tagged with: mechanize
has comment: http://stackoverflow.com/comment/81848434
tagged with: python
has answer: http://stackoverflow.com/a/47446822
has comment: http://stackoverflow.com/comment/81848751
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47446575
score: 1
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/47501400
answers question: http://stackoverflow.com/q/47501343
type: Answer
score: 0
has body: scipy.integrate.quad() expects a function as its first argument (docs). Here you can either use function or lambda expression: lower_bound = 0 upper_bound = 5 def s1(x): return 5*x**2 - 4*x + 2 quad(s1, lower_bound, upper_bound) quad(lambda x: 5*x**2 - 4*x + 2, lower_bound, upper_bound) If you wanted to parse from the symbolic expression in a string, as a quick hack you can use eval(): s1 = "5*x**2 - 4*x + 2" quad(lambda x: eval(s1), lower_bound, upper_bound) If you are doing a lot of symbolic maths, I would suggest you to use SymPy.

http://stackoverflow.com/comment/81956179
score: 0
type: AnswerComment
has text: Sorry, forgot to mention that Rendition model defines fk to Image model this way: image = models.ForeignKey(Image, related_name='renditions', on_delete=models.CASCADE)
type: Comment
comment on: http://stackoverflow.com/a/47492179

computer-vision
tags question: http://stackoverflow.com/q/47514485
tags question: http://stackoverflow.com/q/47405684
tags question: http://stackoverflow.com/q/47483951
tags question: http://stackoverflow.com/q/47494896
tags question: http://stackoverflow.com/q/47496425
tags question: http://stackoverflow.com/q/47390787
tags question: http://stackoverflow.com/q/47462522
tags question: http://stackoverflow.com/q/47426002
tags question: http://stackoverflow.com/q/47517667
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/47417718
tags question: http://stackoverflow.com/q/47402445
tags question: http://stackoverflow.com/q/47429580

http://stackoverflow.com/q/47515233
has comment: http://stackoverflow.com/comment/81994510
tagged with: backpropagation
has comment: http://stackoverflow.com/comment/81989547
tagged with: tensorflow
favorite count: 0
type: Question
has title: Custom gradients for vector binarization in tensorflow
linked to: http://stackoverflow.com/q/43839431
answer count: 0
upvote count: 2
tagged with: gradient-descent
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I am trying to implement the "feed-forward convolutional/deconvolutional residual encoder" as described in this paper: https://arxiv.org/abs/1511.06085 In the network architecture they use a binarization layer, where they first use a standard fully-connected layer with tanh-activation to produce a vector with components in the continuous interval [-1,1]. Then they probabilistically map each component to either -1 or 1. The problem now is that backpropagation is not trivially applied for this second step. After some reasoning they say that they pass the gradients through this stage unchanged. Now my question is, how can I implement this in tensorflow? Is there a simply way to define custom gradients for an operation? A simple example would be very appreciated. EDIT: Would the following code do what I want? def binarization(x): g = tf.get_default_graph() with ops.name_scope("Binarization") as name: with g.gradient_override_map({"Ceil": "Identity", "Sub": "CustomGrad", "Div": "CustomGrad", "Add": "CustomGrad", "Mul": "CustomGrad"}): scaled_x = (x + 1) / 2 binary_x = tf.ceil(scaled_x - tf.random_uniform(tf.shape(x)), name=name) return (binary_x * 2) - 1 @ops.RegisterGradient("CustomGrad") def customGrad(op, grad): return [grad, tf.zeros(tf.shape(op.inputs[1]))]
score: 2

http://stackoverflow.com/comment/81799151
type: QuestionComment
comment on: http://stackoverflow.com/q/47404943
has text: Possible duplicate of [Graphviz bold font attribute](https://stackoverflow.com/questions/30194104/graphviz-bold-font-attribute)
score: 1
type: Comment

http://stackoverflow.com/q/47521213
has body: I am having trouble reading TFRecord format image data using the "new" (TensorFlow v1.4) Dataset API. I believe the problem is that I am somehow consuming the whole dataset instead of a single batch when trying to read. I have a working example of doing this using the batch/file-queue API here: https://github.com/gnperdue/TFExperiments/tree/master/conv (well, in the example I am running a classifier, but the code to read the TFRecord images is in the DataReaders.py class). The problem functions are, I believe, these: def parse_mnist_tfrec(tfrecord, features_shape): tfrecord_features = tf.parse_single_example( tfrecord, features={ 'features': tf.FixedLenFeature([], tf.string), 'targets': tf.FixedLenFeature([], tf.string) } ) features = tf.decode_raw(tfrecord_features['features'], tf.uint8) features = tf.reshape(features, features_shape) features = tf.cast(features, tf.float32) targets = tf.decode_raw(tfrecord_features['targets'], tf.uint8) targets = tf.one_hot(indices=targets, depth=10, on_value=1, off_value=0) targets = tf.cast(targets, tf.float32) return features, targets class MNISTDataReaderDset: def __init__(self, data_reader_dict): # doesn't matter here def batch_generator(self, num_epochs=1): def parse_fn(tfrecord): return parse_mnist_tfrec( tfrecord, self.name, self.features_shape ) dataset = tf.data.TFRecordDataset( self.filenames_list, compression_type=self.compression_type ) dataset = dataset.map(parse_fn) dataset = dataset.repeat(num_epochs) dataset = dataset.batch(self.batch_size) iterator = dataset.make_one_shot_iterator() batch_features, batch_labels = iterator.get_next() return batch_features, batch_labels Then, in use: batch_features, batch_labels = \ data_reader.batch_generator(num_epochs=1) sess.run(tf.local_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) try: # look at 3 batches only for _ in range(3): labels, feats = sess.run([ batch_labels, batch_features ]) This generates an error like…
accepted answer: http://stackoverflow.com/a/47614539
has answer: http://stackoverflow.com/a/47614539
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: dataset
tagged with: tensorflow
favorite count: 0
has title: Read TFRecord image data with new TensorFlow Dataset API
type: Question

http://stackoverflow.com/q/47526002
answer count: 1
tagged with: jupyter-notebook
type: Question
has body: About a year ago I noticed that when I tried opening my python notebooks I had saved on a university server I got a “Notebook does not appear to be JSON” error. At first I was shocked and dismayed that all my hard work was gone forever, but when I inspected the file in emacs I saw that it was all there except that the end of the life contained a long list of ^@ symbols, which confused the JSON interpreter (example below). Simply deleting these ^@ symbols restored the file. Since then every time I get this JSON error (which is fairly often) I just open emacs and delete the symbols, but it’s getting annoying. Can anyone explain to me why this happens and can it be prevented? As far as I can tell, this only happens when I work on ipynb files from a server that my personal laptop (MacBook Pro OS X 10.12.6) is connected to via smb. It never happens when the ipynb files are stored locally. I just prefer working from the server because everything is automatically backed up and sometimes I use different computers, so I always have access to my files.
tagged with: python
has title: Why does jupyter notebook append long list of ^@ symbols to end of ipynb file?
has answer: http://stackoverflow.com/a/47526066
accepted answer: http://stackoverflow.com/a/47526066
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/81816451
comment on: http://stackoverflow.com/q/47430030
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga Well, I thought I would avoid this for now;) thanks for the tips, i will use :)
score: 0

http://stackoverflow.com/comment/81892588
comment on: http://stackoverflow.com/a/47468942
has text: The `flat_list` processing is still kind of ugly and inefficient. If you simply do `flat_list.extend(target2.split())` there is no need to separately flatten the result (let alone do it over and over inside the innermost loop, or keep the `aux` variables).
type: AnswerComment
score: 2
type: Comment

http://stackoverflow.com/a/47532103
has comment: http://stackoverflow.com/comment/82021182
has comment: http://stackoverflow.com/comment/82021043
has comment: http://stackoverflow.com/comment/82049040
has body: What you are seeing are unicode characters when you see \xe9 \xe7. These are unicode characters. You may have some luck with this module Unidecode I have used it before with success, but those characters are fine I think your console just isn't set to render them. Web pages or source data doesn't always tell the truth about its encoding. Often data is a jumble of encodings. Unidecode will do its best to represent the character in ASCII. from unidecode import unidecode unidecode(u"\u5317\u4EB0") # Note the u before the string on this line stands for unicode
has comment: http://stackoverflow.com/comment/82020794
has comment: http://stackoverflow.com/comment/82028682
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82022029
answers question: http://stackoverflow.com/q/47524492
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47524492
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82028761

http://stackoverflow.com/q/47425694
upvote count: 4
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47425745
answer count: 1
downvote count: 1
has body: I am using Python 3.6.1 | Anaconda 4.4.0 I am novice in ML and practicing while learning. I picked up a kagle dataset to practice LDA for dimensionality reduction. Two confusion arised: I started getting warning error "Variables are collinear." Even though i am using n-components as 2, still the output vector x_train is showing only 1 feature. code: import numpy as np import matplotlib.pyplot as plt import pandas as pd datasets = pd.read_csv('mushrooms.csv') X_df = datasets.iloc[:, 1:] # Independent variables y_df = datasets.iloc[:, 0] # Dependent variables from sklearn.preprocessing import LabelEncoder, OneHotEncoder X_df = X_df.apply(LabelEncoder().fit_transform) x = OneHotEncoder(sparse=False).fit_transform(X_df.values) y = LabelEncoder().fit_transform(y_df.values) # Splitting dataset in to training set and test set. from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0) # Feature scaling from sklearn.preprocessing import StandardScaler sc_x = StandardScaler() x_train = sc_x.fit_transform(x_train) x_test = sc_x.transform(x_test) #--------------------------------------------- # Applying LDA (Linear Discriminant Analysis) #--------------------------------------------- from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA lda = LDA(n_components = 2) x_train = lda.fit_transform(x_train, y_train) x_test = lda.transform(x_test)
has comment: http://stackoverflow.com/comment/81806336
score: 3
tagged with: python
has title: LDA processing failing with "Variables are collinear." error in python
favorite count: 0
type: Question

http://stackoverflow.com/q/47508349
score: 0
has comment: http://stackoverflow.com/comment/81973009
upvote count: 1
tagged with: floating-point
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81972505
has body: So I have a tkinter program and it has 4 variable labels. To get one of the labels i need to divide a different variable by 100, but when I run the program, it is equal to 0. This is the part of the code: eggzps = chookz / 100, And here is the whole code: import tkinter as tk from PIL import Image, ImageTk # --- functions --- def moar_eggz(): global eggzps, chookz chookz += 1 def update_labels(): try: label1.config(text="Eggs: " + str(eggz)) label2.config(text="Eggs Per Second: " + str(eggzps)) label3.config(text="Egg Value: " + str(eggvalue)) label4.config(text=" Chickens: " + str(chookz)) except Exception as e: print(e) # display exception to see problem # repeat it after 20ms root.after(20, update_labels) def main_loop(): global eggz, eggzps eggzps = chookz / 100 try: eggz += eggzps except Exception as e: print(e) # display exception to see problem # repeat it after 1000ms root.after(1000, main_loop) # --- main --- root = tk.Tk() root.title("Chicken Clicker") eggz = 0 eggvalue = 0.2 chookz = 0 eggzps = 0 printeggzps = 0 # empty labels - `update_labels` will add text label4 = tk.Label(root) label3 = tk.Label(root) label2 = tk.Label(root) label1 = tk.Label(root) label4.pack() label3.pack() label2.pack() label1.pack() imagecnv = Image.open("img\\1.png") photo = ImageTk.PhotoImage(imagecnv) openbutton = tk.Button(root, image=photo, width=500, height=500, command=moar_eggz) openbutton.pack() # run it first time at once main_loop() update_labels() root.mainloop() I have tried many things, most of them causing errors that I have had to post on here, but when the error is fixed, The problem is not solved. I have spent a whole day trying to get this to work, so I have resorted to just asking. Any suggestions or answers will be highly appreciated. Thanks in advance!
type: Question
accepted answer: http://stackoverflow.com/a/47508388
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/47508388
has title: How to a divide into a float instead of an integer? (python)
tagged with: int
has comment: http://stackoverflow.com/comment/81972859
has comment: http://stackoverflow.com/comment/81973087
tagged with: tkinter
type: AnsweredQuestion

http://stackoverflow.com/a/47475711
score: 2
answers question: http://stackoverflow.com/q/47475611
downvote count: 0
upvote count: 2
type: Answer
has body: Approach #1 One approach would be using np.in1d - m_a = np.in1d(a,b) I = np.flatnonzero(m_a) J = np.flatnonzero(np.in1d(b, a[m_a])) Sample input, output - In [367]: a Out[367]: array([1, 2, 3, 4]) In [368]: b Out[368]: array([3, 5, 6, 4]) In [370]: I Out[370]: array([2, 3]) In [371]: J Out[371]: array([0, 3]) Approach #2 Another straight-forward but memory heavy way would be with broadcasting - I,J = np.nonzero(a[:,None] == b) Approach #3 For the case where we have no duplicates within the input arrays, we could use np.searchsorted. There are two variants here - One for sorted a, and another for a generic a. Variant #1 : For sorted a - idx = np.searchsorted(a, b) idx[idx==a.size] = 0 mask = a[idx] == b I = np.searchsorted(a,b[mask]) J = np.flatnonzero(mask) Variant #2 : For this generic variant case, we need to use argsort indices of a - sidx = a.argsort() a_sort = a[sidx] idx = np.searchsorted(a_sort, b) idx[idx==a.size] = 0 mask = a_sort[idx] == b I = sidx[np.searchsorted(a_sort,b[mask])] J = np.flatnonzero(mask)

http://stackoverflow.com/comment/81960365
has text: @KomalMadamwar - Because you're probably doing exactly what the error is telling you. You're trying to call a module object. Make sure you do this as your import: `from validate_email import validate_email`
comment on: http://stackoverflow.com/a/47432395
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82061406
has text: That won't be too difficult (If you have GPUs), assuming flags will have a rectangular geometry, use OpenCV to detect rectangular contours in a frame then analyze them one by one by a trained model!
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47493017
type: QuestionComment

http://stackoverflow.com/comment/81720108
type: AnswerComment
comment on: http://stackoverflow.com/a/47383569
has text: @cᴏʟᴅsᴘᴇᴇᴅ, trying to learn the difference between resample and asfreq, any ideas?
type: Comment
score: 0

http://stackoverflow.com/comment/81845066
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47444841
has text: `line not in ("0","5", ...)` checks if the whole line neither equals "0" or "5" or ...
score: 1

http://stackoverflow.com/comment/81930915
type: QuestionComment
comment on: http://stackoverflow.com/q/47488012
has text: Possible duplicate of [Strip HTML from strings in Python](https://stackoverflow.com/questions/753052/strip-html-from-strings-in-python)
score: 0
type: Comment

http://stackoverflow.com/comment/81985197
type: Comment
type: AnswerComment
score: 1
has text: Interestingly `df['Buyer'], df['Seller'] = zip(*np.where(df.amount < 0,(df['cparty'],df['party']),(df['party'],df['cparty'])).T)` is about 20% faster for 100000 iterations using timeit. It's functionally identical.
comment on: http://stackoverflow.com/a/47512735

http://stackoverflow.com/q/47397469
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/81748018
has body: I have 2 numpy arrays: arr_a = array(['1m_nd', '2m_nd', '1m_4wk'], dtype='&lt;U15') arr_b = array([0, 1, 1]) I want to select elements from arr_a based on arr_b. I am doing this: arr_a[arr_b], but I get this as result: array(['1m_nd', '2m_nd', '2m_nd'], dtype='&lt;U15') instead of: array(['2m_nd', '1m_4wk'], dtype='&lt;U15') How do i fix this?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47397617
downvote count: 0
tagged with: python
score: 4
answer count: 2
has answer: http://stackoverflow.com/a/47397606
has title: Subset numpy array based on another array

http://stackoverflow.com/a/47528889
score: 1
type: AcceptedAnswer
has body: This should work: vm_name = 'my_vm-84' pattern = r'vm\.cpu\.num_cores{.+name="%s".+} (\d+)' %vm_name res = re.search(pattern, metric_data) RegEx Demo Note that your sample data has double quotes around your variable value "my_vm-84"
answers question: http://stackoverflow.com/q/47528678
accepted answer of: http://stackoverflow.com/q/47528678
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81972534
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47450879
type: Comment
has text: Sorry wasn't very clear meant more the dictionary `[ { "Unit": "mill Sm3" }, {"Value": 80 } ]` to `[{"Unit":"mill Sm3","Value":"80"}` kinda so the 'value' in the same dictionary as the 'unit'? My description probs aint technically correct. Guess it happens around the `applymap(lambda x: {'Value': x}).apply(f)` area

http://stackoverflow.com/a/47442411
score: 1
type: Answer
has body: According to the Python 2 documentation: On a typical machine running Python, there are 53 bits of precision available for a Python float, so the value stored internally when you enter the decimal number 0.1 is the binary fraction 0.00011001100110011001100110011001100110011001100110011010 which is close to, but not exactly equal to, 1/10.
answers question: http://stackoverflow.com/q/47442088
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81743040
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47394969
type: QuestionComment
has text: How do you mean provide?

http://stackoverflow.com/comment/81763053
score: 0
type: QuestionComment
type: Comment
has text: I'm happy to use pygame for music! I'm just not using it for the game itself.
comment on: http://stackoverflow.com/q/47383483

http://stackoverflow.com/a/47503899
accepted answer of: http://stackoverflow.com/q/47503739
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47503739
score: 0
has body: To set the text of a label in Tkinter you can use StringVar and set it's value accordingly. Please see if the below code helps: labelText1 = Stringvar() label1 = Label(self, textvariable=labelText1) The variable can be assigned using set function whenever there is update in the database: labelText1.set(labelTextValue)
type: Answer

http://stackoverflow.com/comment/81882390
type: QuestionComment
comment on: http://stackoverflow.com/q/47462524
has text: I still have the same error ;-(
score: 0
type: Comment

http://stackoverflow.com/a/47487805
downvote count: 0
answers question: http://stackoverflow.com/q/47487749
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81930625
score: 1
has body: Calling os.system("second.py") or using subprocess.Popen from you first script should work for you.

http://stackoverflow.com/q/47489567
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47490919
has title: how do i continously keep on updating my label in kivy?
accepted answer: http://stackoverflow.com/a/47489726
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/47489726
favorite count: 0
type: Question
tagged with: kivy-language
tagged with: raspberry-pi
tagged with: user-interface
upvote count: 1
possible better answer: http://stackoverflow.com/a/47489720
downvote count: 1
has body: I've been stuck on this one for hours now. I'm making a homemade smarthome terminal, and have been tinkering with kivy for about 2 weeks and it's been great so far. I'm at the point where I want to show the temperature inside a label inside a screen. I've made an actionbar with 4 buttons that slides through screens when clicked. In the first screen called "Thermostaat", I want to display a label with a temperature read from another external script I've written. I can't seem to get the temperature inside a label, even with a dummy value' Here's my main.py: #!/usr/bin/env python3 from kivy.app import App from kivy.uix.screenmanager import ScreenManager,Screen from kivy.properties import ObjectProperty, StringProperty from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivy.uix.label import Label from kivy.lang import Builder class Menu(BoxLayout): manager = ObjectProperty(None) def __init__(self,**kwargs): super(Menu, self).__init__(**kwargs) Clock.schedule_interval(self.getTemp, 1) def getTemp(self,dt): thetemp = 55 #will be changed to temp.read() self.ids.TempLabel.text = str(thetemp) print(thetemp) class ScreenThermo(Screen): pass class ScreenLight(Screen): pass class ScreenEnergy(Screen): pass class ScreenWeather(Screen): pass class Manager(ScreenManager): screen_thermo = ObjectProperty(None) screen_light = ObjectProperty(None) screen_energy = ObjectProperty(None) screen_weather = ObjectProperty(None) class MenuApp(App): def thermostaat(self): print("Thermostaat") def verlichting(self): print("Verlichting") def energie(self): print("Energie") def weer(self): print("Het Weer") def build(self): Builder.load_file("test.kv") return Menu() if __name__ == '__main__': MenuApp().run() And here's my .kv file: #:kivy 1.10.0 &lt;Menu&gt;: manager: screen_manager orientation: "vertical" ActionBar: size_hint_y: 0.05 ActionView: ActionPrevious: ActionButton: text: "Thermostaat" on_press: root.manager.current= 'thermo' on_release: app.thermostaat() ActionB…
has answer: http://stackoverflow.com/a/47489720
type: AnsweredQuestion

http://stackoverflow.com/q/47489850
tagged with: progress-bar
has comment: http://stackoverflow.com/comment/81934979
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81934918
type: Question
has answer: http://stackoverflow.com/a/47489940
has body: import time for i in range(100): print('*',end='') time.sleep(0.1) why this code is not working for showing progress? Expected output was to be showing a progress '****************'.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81934956
answer count: 1
has title: Progress bar not working?
has comment: http://stackoverflow.com/comment/81934994

http://stackoverflow.com/comment/81874534
comment on: http://stackoverflow.com/q/47459950
score: 0
type: Comment
has text: *"I tried adding import parse.py but it would give an error.*" - what was the error? Are you saying you have two scripts called `parse.py`?
type: QuestionComment

http://stackoverflow.com/a/47526895
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47526773
answers question: http://stackoverflow.com/q/47526773
type: Answer
has comment: http://stackoverflow.com/comment/82010173
has comment: http://stackoverflow.com/comment/82009774
has body: Here is the one liner using list comprehension : &gt;&gt;&gt; staffing_title = ['14', '28', '14', '20'] &gt;&gt;&gt; staff_text=['31','32'] &gt;&gt;&gt; res = [staff_text.pop(0) if item == str(14) else item for item in staffing_title ] &gt;&gt;&gt; print(res) ['31', '28', '32', '20']

http://stackoverflow.com/comment/81877111
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47460947
type: AnswerComment
has text: Of course it would be that easy, knew I'd missed something easy. No more issues, thanks for all the help

http://stackoverflow.com/comment/81746578
type: Comment
has text: `Counter` already exhibits that behaviour. Try `Counter('')['a']`. I suspect the problem is that `merge_with` is checking something like `key in d` and so is never trying `Counter(myList)['e']` to get that zero value. Try to write a different function to replace `tuple` that will fill in mizzing values. Or you might be able to write a `Counter` subclass that overwrite `__contains__` to return `True` for everything
comment on: http://stackoverflow.com/q/47396350
score: 1
type: QuestionComment

http://stackoverflow.com/q/47398744
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81754682
has answer: http://stackoverflow.com/a/47399424
has body: I'm coding this program but running it and typing "2" when I type a subject it doesn't print the result once but nine times. Where is the problem? 9 is the number of subjects in the list named mat so it's strictly connected. Now to check some files .txt as placeholder but I'd like also using the module json. import os def spat(): a=len(list(os.listdir('C:/Users/SUINO/Desktop/python/prob/cache/'+y))) print(a) b=100/(25-a) print(b) mat=["latino","greco","storia","latino","scienze","matematica","grammatica", "promessi sposi,","eneide"] #mat means subject c=input("Do you want to add a placeholder or calculate probabilties? 1|2: ") if c == "1": c=input("Insert a subject: ") c=c.lower if c in mat: name=input("Insert the name of the student: ") open('C:/Users/SUINO/Desktop/python/prob/cache/'+c+'/'+name+".txt") else: print("Materia non esistente!") if c == "2": y=input("Materia: ") y=y.lower() x={"latino":spat(),"greco":spat(),"eneide":spat(),"promessi sposi":spat(), "mate":spat(),"grammatica":spat(),"storia":spat(),"scienze":spat(), "inglese":spat(),} The objective of the program is to calculate the probabilities of being interrogated using the files .txt that have as name the name of the student interrogated yet.
has title: Dictionary - printing result multiple times?
tagged with: python
score: -1
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/47399424
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81750705
has comment: http://stackoverflow.com/comment/81755081
has comment: http://stackoverflow.com/comment/81754449
has comment: http://stackoverflow.com/comment/81750637
answer count: 2
has comment: http://stackoverflow.com/comment/81751295
accepted answer: http://stackoverflow.com/a/47399129
upvote count: 0
has comment: http://stackoverflow.com/comment/81750621
has comment: http://stackoverflow.com/comment/81750605
has comment: http://stackoverflow.com/comment/81750718
has answer: http://stackoverflow.com/a/47399129
has comment: http://stackoverflow.com/comment/81750758
downvote count: 1

http://stackoverflow.com/a/47464837
accepted answer of: http://stackoverflow.com/q/47461625
type: AcceptedAnswer
type: Answer
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81976852
answers question: http://stackoverflow.com/q/47461625
has body: It just tells the index of the max element in your original tensor along the queried dimension. E.g. 0.9477 1.0090 0.8348 -1.3513 -0.4861 1.2581 0.3972 1.5751 -1.2277 -0.6201 -1.0553 0.6069 0.1688 0.1373 0.6544 -0.7784 [torch.FloatTensor of size 4x4] # torch.max(a, 1) ( 1.0090 1.5751 0.6069 0.6544 [torch.FloatTensor of size 4] , 1 3 3 2 [torch.LongTensor of size 4] ) In the above example in torch.LongTensor, 1 is the index of 1.0090 in your original tensor (torch.FloatTensor) 3 is the index of 1.5751 in your original tensor (torch.FloatTensor) 3 is the index of 0.6069 in your original tensor (torch.FloatTensor) 2 is the index of 0.6544 in your original tensor (torch.FloatTensor) along dimension 1. Instead, if you'd have requested torch.max(a, 0), the entries in torch.LongTensor would correspond to the indices of max elements in your original tensor along dimension 0.

http://stackoverflow.com/comment/81920290
type: QuestionComment
comment on: http://stackoverflow.com/q/47482708
score: 0
has text: try using pip install -e "Path where you downloaded locally"
type: Comment

http://stackoverflow.com/a/47543334
has comment: http://stackoverflow.com/comment/82067876
answers question: http://stackoverflow.com/q/47457956
type: Answer
score: 0
has body: Another approach would be to run, say, DBSCAN separately for all subsets of colours, obtaining a large set of putative neighbourhoods, and then to take the minimal elements of this set, with respect to set inclusion. In the above example: green gives you the south-west, blue, red, and blue+red give you the north and the south-east, green+red/blue/both give you the north and the south (a merge of two correct neighbourhoods) and then you filter out the south by taking the minimal elements.

http://stackoverflow.com/q/47482620
answer count: 0
has comment: http://stackoverflow.com/comment/81920125
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81920121
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81921311
tagged with: selenium
has comment: http://stackoverflow.com/comment/81920076
has body: I have been doing some work recently with Python's Selenium package and came across this weird HTML format that I have never seen before (posted below). From this HTML page source, I would like to extract the value '-26.507', but it does not have a clear identifier. What is the best way to approach this issue? I have thought about using xpath but I am unsure how to implement it correctly. GEOID COMPUTATIONS Output from GEOID12B latitude longitude N error (95% confidence interval) Station Name ddd mm ss.sssss ddd mm ss.sssss meters meters USER LOCATION 28 0 0.00000 95 0 0.00000 -26.507 0.096
type: Question
tagged with: xpath
has title: Python Selenium Extraction of Buried Variable
tagged with: extract

http://stackoverflow.com/q/47390874
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: flask-wtforms
answer count: 1
downvote count: 0
tagged with: flask
accepted answer: http://stackoverflow.com/a/47393865
favorite count: 0
type: Question
has title: How to use Flask-Babel gettext in Flask-WTForms render_kw?
has body: I'm starting using Babel with WTForms and Flask. Below I try to gettext the placeholder keywords for my Username and Password fields : #!/usr/bin/env python # -*- coding: utf-8 -*- from flask_babel import gettext from flask_wtf import FlaskForm from wtforms import PasswordField, StringField from wtforms.validators import DataRequired class LoginForm(FlaskForm): username = StringField(label='username', validators=[DataRequired()], render_kw={"placeholder": gettext('Username')}) password = PasswordField(label='password', validators=[DataRequired()], render_kw={"placeholder": gettext('Password')}) Here is my French .po file (which has of course been compiled) : # French (France) translations for PROJECT. # Copyright (C) 2017 ORGANIZATION # This file is distributed under the same license as the PROJECT project. # FIRST AUTHOR &lt;EMAIL@ADDRESS&gt;, 2017. # msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2017-11-20 12:08+0100\n" "PO-Revision-Date: 2017-11-20 12:10+0100\n" "Language: fr_FR\n" "Language-Team: fr_FR &lt;LL@li.org&gt;\n" "Plural-Forms: nplurals=2; plural=(n &gt; 1);\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.5.1\n" "Last-Translator: \n" "X-Generator: Poedit 2.0.4\n" #: app/forms.py:13 msgid "Username" msgstr "Nom d’utilisateur" #: app/forms.py:16 msgid "Password" msgstr "Mot de passe" #: app/templates/login.html:34 msgid "Login" msgstr "Se connecter" Unfortunately, even when I force the locale in French those two fields stay in English. I made it work for the Login translation in my Jinja2 template. Did I write something wrong ?
has answer: http://stackoverflow.com/a/47393865
tagged with: flask-babel
tagged with: python
tagged with: python-babel

http://stackoverflow.com/q/47483010
favorite count: 0
tagged with: python-3.x
type: Question
has body: I have looked through multiple related articles on here to do with labels/buttons/configuration and have so far not identified any explaining this exact issue. I have written basic label configuration programs with success previously (using 'functions' and the use of 'command=' as well as 'lambda' etc) but they only involved configuration code in the function using a set string (text="String"). What I am intending to do in this program is change the label text to that of the same text in a 'button', so when the user clicks the button, the label displays the text with an accompanying string ("Contact info for: " + button clicked) I am sure the issue is with my 'function code' itself (the formatting of the latter part of the line in particular), either that or the 'button creation' line in the 'for loop' below may need editing (or maybe both). I'm guessing there would be more than 'one route' to approach this, considering all the 'button texts' are also contained within a dictionary as key(name), so any suggestions of any kind, either way would be greatly appreciated, I'm new to Python so I'm sure this will actually be a simple easy problem for experienced coders # The purpose of this program is to produce a GUI that acts as a 'contacts #info retriever', when a 'contact' 'button' is clicked it displays the contact #information of that person # Make a 'dictionary' containing contact info contacts = { 1: {"Name" : "Max", "Address" : "18 Fake Street, Hollywood", "Mobile" : "07542564872"}, 2: {"Name" : "Brian", "Address" : "17 Fake Boulevard, Hollywood", "Mobile" : "07895465231"}, 3: {"Name" : "Sally", "Address" : "19 Hill Valley, Hollywood", "Mobile" : "07956423145"}, 4: {"Name" : "Steve", "Address" : "22 Fake House, Hollywood", "Mobile" : "07456213895"}, 5: {"Name" : "Sara", "Address" : "46 Fake Drive, Hollywood", "Mobile" : "07652348192"}, 6: {"Name" : "Kevin", "Address" : "18 Labyrinth Avenue, Hollywood", "Mobile" : "07563245196"}, 7: {"Name" : "Paula", "Address" : "3…
tagged with: python
accepted answer: http://stackoverflow.com/a/47483058
has answer: http://stackoverflow.com/a/47483058
tagged with: tkinter
type: AnsweredQuestion
has title: python/GUI creation: how to reconfigure the text of a label to 'match the text of the button clicked'
downvote count: 0
upvote count: 1
score: 1
answer count: 1

http://stackoverflow.com/comment/82012407
type: QuestionComment
comment on: http://stackoverflow.com/q/47527222
has text: And... what is the rule (even in plain English) to identify a topic and the associated postname?
score: 0
type: Comment

http://stackoverflow.com/comment/81727690
has text: Thank you, now added to satisfy the order, can you please review and remove the downvote?
type: AnswerComment
comment on: http://stackoverflow.com/a/47387042
score: 0
type: Comment

http://stackoverflow.com/q/47524066
score: 1
upvote count: 1
answer count: 1
has title: Use the generate_files_directory method to change the FielField upload_to param do not work
favorite count: 0
tagged with: filefield
has comment: http://stackoverflow.com/comment/82004792
type: Question
accepted answer: http://stackoverflow.com/a/47524373
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47524373
has body: I write a generate_files_directory method to generate the upload path: def generate_files_directory(self,filepath): url = "images/%s" % (filepath) return url The model is bellow: class Upload(models.Model): filepath = models.CharField(max_length=64, default="imgs/test/") pic = models.FileField(upload_to=generate_files_directory) upload_date=models.DateTimeField(auto_now_add =True) The form code is bellow: class UploadForm(ModelForm): class Meta: model = Upload fields = ('pic', 'filepath') my views.py: def home(request): if request.method=="POST": img = UploadForm(request.POST, request.FILES) if img.is_valid(): img.save() return HttpResponseRedirect(reverse('imageupload')) else: img=UploadForm() images=Upload.objects.all() return render(request,'home.html',{'form':img,'images':images}) and I write a home.html to upload the files: picture {% csrf_token %} {{form}} {% for img in images %} {{forloop.counter}}.{{ img.pic.name }} ({{img.upload_date}}) {% endfor %} But seem it did not upload to the generated path, it still upload to the /images/ directory: all in there:
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/81877877
type: Comment
type: QuestionComment
score: 0
has text: What do you mean "does not continue"?
comment on: http://stackoverflow.com/q/47461571

http://stackoverflow.com/comment/81803407
comment on: http://stackoverflow.com/a/47423751
type: Comment
has text: Was trying to accept it as answer, But couldn't find that button. Might be it will appear after sometime. Will check back after sometime.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82008409
comment on: http://stackoverflow.com/q/47525920
score: 0
type: Comment
has text: You didn't explain what went wrong. `tree` should contain the parse tree.
type: QuestionComment

http://stackoverflow.com/comment/81903874
type: AnswerComment
has text: You can also add paths to PYTHONPATH from RIDE>Tools>Preferences.
score: 0
comment on: http://stackoverflow.com/a/47430459
type: Comment

http://stackoverflow.com/comment/86478108
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47679185
type: AnswerComment
has text: Do you have .pem certificate. .pem Defined in RFC's 1421 through 1424, this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. Confusingly, it may also encode a CSR (e.g. as used here) as the PKCS10 format can be translated into PEM. The name is from Privacy Enhanced Mail (PEM), a failed method for secure email but the container format it used lives on, and is a base64 translation of the x509 ASN.1 keys.

http://stackoverflow.com/q/47521917
has answer: http://stackoverflow.com/a/47536590
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82013284
score: -3
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82003840
has body: I'm trying to turn my player paddle into an actual image. However, I'm not sure how to do this. I'm currently performing the image assigning options in my PlayerPaddle Class's init class Paddle(object): def __init__(self, screen_size, XCenter, YCenter, height, width, color): self.screen_size = screen_size self.XCenter = XCenter self.YCenter = YCenter self.height = height self.width = width self.color = color #Create the paddle surface on the sides of the screen self.rect = pygame.Rect(0, self.YCenter - self.height//2, self.width, self.height) def draw(self, screen): pygame.draw.rect(screen, self.color, self.rect, 0) pygame.draw.rect(screen, BLACK, self.rect, 1) class PlayerPaddle(Paddle): def __init__(self, screen_size, XCenter, YCenter, height, width, color): super().__init__(screen_size, XCenter, YCenter, height, width, color) self.speed = 5 self.direction = 0 self.score = 0 self.image = pygame.image.load("naruto.png") self.imagerect = self.image.get_rect() def draw(self, screen): super().draw(screen) screen.blit(self.image, self.imagerect) Right now, I"m just drawing the photo in the top right corner. How should I fix this?
downvote count: 3
tagged with: pygame
has title: Make my player paddle into an image

http://stackoverflow.com/comment/81951436
comment on: http://stackoverflow.com/q/47498071
score: 0
has text: hopefully this solves the issue : https://stackoverflow.com/questions/6454564/target-wsgi-script-cannot-be-loaded-as-python-module
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47460722
downvote count: 0
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/57524869
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51452124
favorite count: 0
type: Question
answer count: 2
tagged with: tensor
type: UnansweredQuestion
tagged with: python
has title: How to perform regex operations on a string tensor on TensorFlow?
tagged with: regex
has comment: http://stackoverflow.com/comment/81877561
has body: How can I perform regex operations on a string tensor? Normally, I would just use a python string but when using Tensorflow Serving, I need my input to be a string tensor. So I created a string placeholder and am just injecting another layer into the graph where I take the placeholder and make it ready for the passing it to the model. I have looked at using py_funcbut I still cannot perform pattern operations on a bytes-like object. Is there any way of performing these operations on a tensor? I cannot do an eval() on the placeholder because the data is only fed in when the savedModel is loaded and run. Code I have been using for testing: def remove_urls(vTEXT): vTEXT = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&amp;|\%)*\b', 'url', vTEXT, flags=re.MULTILINE) return(vTEXT) input_string_ph = tf.constant("This is string https:www.someurl.com") input_string_lower = tf.py_func(lambda x: x.lower(), [input_string_ph], tf.string, stateful=False) # input_string_no_url = tf.py_func(lambda x: remove_urls(x), [input_string_lower], tf.string, stateful=False) sess = tf.InteractiveSession() print (input_string_no_url.eval())
has comment: http://stackoverflow.com/comment/81876171
score: 1

http://stackoverflow.com/comment/81955901
has text: `print node.find('domain').text` should do it. By the way, your xml string in the example is not parsable. Had to remove some things before making it work. You might want to look into that if you are getting a `ParseError`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47500129

http://stackoverflow.com/q/47439545
has title: .loc in pandas looking up a name in one column and seeing if it exists in another column
tagged with: python
possible better answer: http://stackoverflow.com/a/47439727
tagged with: lookup
score: 0
answer count: 2
tagged with: pandas
has body: In Pandas, I'm trying to look up a string value of names in Column A and if it is the same value in Column B, I would like to put a 1 in Column C and 0 if it doesn't. So, If I look up "Kyrie Irving" in Column A and it also in Column B, I would like to put a 1 in Column C and 0 in Column C if he doesn't exist.
accepted answer: http://stackoverflow.com/a/47439648
type: Question
has answer: http://stackoverflow.com/a/47439727
has answer: http://stackoverflow.com/a/47439648
type: AnsweredQuestion

http://stackoverflow.com/q/47442937
has comment: http://stackoverflow.com/comment/81842523
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81841406
has title: Boolean annotation resulting in duplicates?
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/81842558
downvote count: 0
has body: I am trying to implement a basic 'favourites' system based on a foreign key table. Let's say I have the following simple models: class Item(models.Model) id = models.IntegerField() class User(models.Model) id = models.IntegerField() class UserFavourites(models.Model) user = models.ForeignKey(User, related_name='user_for_fav_rel') item = models.ForeignKey(Item, related_name='item_for_fav_rel') Now I generate the following queryset for items to see if they have been marked as a favourite by the user: queryset = Item.objects.all() USER_ID = request.user.id queryset = queryset.annotate( favourite=Case( When( item_for_fav_rel__user__id=USER_ID, then=Value('True') ), default=Value('False'), output_field=BooleanField() ) ) All of this works great, but in the response, if the item has indeed been favourited, I receive a duplicate of that particular item in the queryset. Any idea how to avoid this? Resultant SQL Query (edited down to the minimal example I think...) SELECT "core_item"."id", CASE WHEN "core_userfavourites"."user_id" = 1 THEN True ELSE False END AS "favourite" FROM "core_item" LEFT OUTER JOIN "core_userfavourites" ON ("core_item"."id" = "core_userfavourites"."item_id")
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81841788
has answer: http://stackoverflow.com/a/47444037
accepted answer: http://stackoverflow.com/a/47444037
tagged with: django
tagged with: django-1.11
tagged with: python

http://stackoverflow.com/q/47523544
has comment: http://stackoverflow.com/comment/82005162
has comment: http://stackoverflow.com/comment/82025167
tagged with: python
has comment: http://stackoverflow.com/comment/82008706
linked to: http://stackoverflow.com/q/54948548
score: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82004866
has answer: http://stackoverflow.com/a/47534612
type: Question
has comment: http://stackoverflow.com/comment/82003502
has title: Argparse optional arguments with default values
tagged with: argparse
has body: I'm working on something where I need to use argparse. Here's the code I got a problem with: parser = argparse.ArgumentParser() parser.add_argument('--create n file', dest='create', nargs=2, default=(1, 'world1.json'), help='Create a party of n player with mission parameters in file') I'm trying to find a way to either set both n and file to another value, or set only one of them. n is an int and file a str. Here's what I would like to get, using the following command: Command Expected result python mission.py --create 2 create = [2, 'world1.json'] python mission.py --create world2.json create = [1, 'world2.json'] python mission.py --create 3 world2.json create = [3, 'world2.json'] When --create is used (with or without specifying n/file), I'll need to start a function using the list as arguments. I've tried multiple things and read argparse documentation more than once but can't find a way to do it.

http://stackoverflow.com/a/47417483
has body: I could imagine you want to fix the boundaries of colors shown on the plot and in the colorbar to the values of numpy.linspace(0,.5,11). import numpy as np import matplotlib.pyplot as plt import matplotlib.colors cmap = plt.get_cmap("jet",11) data = np.random.rand(10,10)/2. norm=matplotlib.colors.BoundaryNorm(np.linspace(0,0.5,11),11) plt.pcolor(data, norm=norm, cmap=cmap) cb = plt.colorbar(extend='both', ticks=np.linspace(0,0.5,11)) cb.set_label('CPRESS', fontsize=7, labelpad=-10, y=1.05, rotation=0) plt.show()
score: 0
accepted answer of: http://stackoverflow.com/q/47413437
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47413437

http://stackoverflow.com/q/47517925
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I need to validate if a QTableWidget has lost focus, so I can validate the entry text and change its text if it's not valid for my program.
has comment: http://stackoverflow.com/comment/81992014
tagged with: python
tagged with: qtablewidgetitem
has comment: http://stackoverflow.com/comment/81992147
has title: Validate text in QTableWidget
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47518156
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/47518156
answer count: 1
tagged with: pyqt5
upvote count: 1

http://stackoverflow.com/a/47528896
answers question: http://stackoverflow.com/q/47528678
score: 1
type: Answer
has body: The first column of the input text is json, and you should really parse it as json; that said, you are missing the double quotes in your regex: pattern = r"(vm\.cpu\.num_cores{.+name=)\"my_vm-84\"(.+}) (\d+)"
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81973920
score: 0
has text: You can still do template matching when the crops aren't exact. With template matching you can find the best match, it doesn't have to be exactly equal.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47505867

http://stackoverflow.com/a/47417274
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: If you want it to be really fast, you should reverse your data structure to have a dictionary of sets where the key would be a town and the set would contain all towns in same group. That way you can make sure that in_same_group will only need: one single dictionary research on single set containment research As those accesses are optimized for dictionaries and sets, the research should be as fast as it can be Code could be: import collections h = collections.defaultdict(set) lists = [list1, list2, list3, list4] for l in lists: for town in l: for other in l: if town != other: h[town].add(other) The function is now as simple as: def in_same_group(t1, t2): return t2 in h[t1]
answers question: http://stackoverflow.com/q/47416917

linux
tags question: http://stackoverflow.com/q/47424885
tags question: http://stackoverflow.com/q/47503021
tags question: http://stackoverflow.com/q/47444178
tags question: http://stackoverflow.com/q/47483033
tags question: http://stackoverflow.com/q/47468423
tags question: http://stackoverflow.com/q/47447836
tags question: http://stackoverflow.com/q/47426699
tag name: linux
tags question: http://stackoverflow.com/q/47412633
tags question: http://stackoverflow.com/q/47436949
tags question: http://stackoverflow.com/q/47460580
tags question: http://stackoverflow.com/q/47519055
tags question: http://stackoverflow.com/q/47398489
tags question: http://stackoverflow.com/q/47417279
tags question: http://stackoverflow.com/q/47407680
tags question: http://stackoverflow.com/q/47508964
tags question: http://stackoverflow.com/q/47523196
tags question: http://stackoverflow.com/q/47408993
tags question: http://stackoverflow.com/q/47442348
tags question: http://stackoverflow.com/q/47517323
tags question: http://stackoverflow.com/q/47500289
tags question: http://stackoverflow.com/q/47516543
tags question: http://stackoverflow.com/q/47444042
tags question: http://stackoverflow.com/q/47423878
tags question: http://stackoverflow.com/q/47390305
tags question: http://stackoverflow.com/q/47435672
tags question: http://stackoverflow.com/q/47514185
tags question: http://stackoverflow.com/q/47511298
tags question: http://stackoverflow.com/q/47440539
tags question: http://stackoverflow.com/q/47536497
tags question: http://stackoverflow.com/q/47425329
tags question: http://stackoverflow.com/q/47448430
tags question: http://stackoverflow.com/q/47405813
tags question: http://stackoverflow.com/q/47527621
type: Tag
tags question: http://stackoverflow.com/q/47522743
tags question: http://stackoverflow.com/q/47450744
tags question: http://stackoverflow.com/q/47413839
tags question: http://stackoverflow.com/q/47426914
tags question: http://stackoverflow.com/q/47464706
tags question: http://stackoverflow.com/q/47468045
tags question: http://stackoverflow.com/q/47412460
tags question: http://stackoverflow.com/q/47449512
tags question: http://stackoverflow.com/q/47426938
tags question: http://stackoverflow.com/q/47465292
tags question: http://stackoverflow.com/q/47413099
tags question: http://stackoverflow.com/q/47470557
tags question: http://stackoverflow.com/q/47393518
tags question: http://stackoverflow.com/q/47526914

http://stackoverflow.com/comment/82086077
type: Comment
type: QuestionComment
score: 0
has text: You're welcome! Glad it worked.
comment on: http://stackoverflow.com/q/47497809

http://stackoverflow.com/a/47525555
answers question: http://stackoverflow.com/q/47525351
has comment: http://stackoverflow.com/comment/82007397
type: Answer
score: 2
upvote count: 2
has body: One way for ensuring this would be by generating a session id from server. You would need to generate a unique session id every time a user logs in and store it in some database against that user. Apart from this you would need to authenticate user every time an endpoint call, which requires user to be logged in, is made. And of course discard the session id on logout. This way whenever a user logs in the old session id is discarded and the previous session no more remains valid.
has comment: http://stackoverflow.com/comment/82008856
downvote count: 0

http://stackoverflow.com/q/47460623
has answer: http://stackoverflow.com/a/47460805
accepted answer: http://stackoverflow.com/a/47460710
type: AnsweredQuestion
tagged with: for-loop
has answer: http://stackoverflow.com/a/47501732
answer count: 3
has answer: http://stackoverflow.com/a/47460710
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81881672
favorite count: 0
type: Question
score: 0
has body: for line in infileStudents: line = line.rstrip() parts = line.split(':') studentID = int(parts[0]) studentName = parts[1] if studentID == ID: break else: print("No record") I am trying to search for an ID number in a file and print a message if the ID doesn't exist in the file. The above code reads each line and prints a message for each line. How do I print only one message after I read all the IDs in the file?
tagged with: python
has comment: http://stackoverflow.com/comment/81875884
possible better answer: http://stackoverflow.com/a/47460805
has title: Print once after for loop

http://stackoverflow.com/q/47506763
has comment: http://stackoverflow.com/comment/81979662
favorite count: 0
type: Question
has body: I have a dictionary and a dataframe like these: dict = {'a': 1, 'b': 2, ...} # Dataframe's column-names and type dataframe[letters: Str, ...] What I want to do is to get the rows of the dataframe of which 'letters' column-values coincide with the keys of the dictionary. How can I do it?
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: pyspark
has comment: http://stackoverflow.com/comment/81969198
upvote count: 1
tagged with: python
tagged with: dictionary
has title: How to get ocurrences of a dictionary in a dataframe in Pyspark?
tagged with: join
score: 1
tagged with: dataframe

http://stackoverflow.com/a/47527692
has comment: http://stackoverflow.com/comment/82012766
has comment: http://stackoverflow.com/comment/82012929
has comment: http://stackoverflow.com/comment/82011677
answers question: http://stackoverflow.com/q/47527238
upvote count: 1
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/82012592
has body: EDITED ANSWER: user Popen instead of run() and then: x = subprocess.Popen(...,stdout=subprocess.STDOUT) while True: line = x.stdout.readline() do whatever you want and decide if to print this line or not
has comment: http://stackoverflow.com/comment/82013783
type: Answer

http://stackoverflow.com/q/47411166
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47411223
duplicate of: http://stackoverflow.com/q/2970608
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/81775595
type: AnsweredQuestion
tagged with: namedtuple
score: 2
has comment: http://stackoverflow.com/comment/81775575
has body: Attempting to run this code in Python3 Jupyter notebook : t = namedtuple('a', 'b') a = [1,0,1] b = [1,1,1] Out, In = np.asanyarray(a), np.asanyarray(b) t(Out.shape[0], *In.shape) returns error : --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-151-7955ff03a60d&gt; in &lt;module&gt;() 3 b = [1,1,1] 4 Out, In = np.asanyarray(a), np.asanyarray(b) ----&gt; 5 t(Out.shape[0], *In.shape) TypeError: __new__() takes 2 positional arguments but 3 were given Is possible to create namedtuple with two arguments ? Update : Why does this not cause similar issue : t = namedtuple('ps', 'Out In S') a = np.asanyarray([[1]]) b = np.asanyarray([[1]]) d = t(a.shape[0], *b.shape) d computes : ps(Out=1, In=1, S=1) Update 2 : Think i understand now namedtuple('ps', 'Out In S') translates to namedtuple('name_of_tuple', 'tuple_values_seperated_by_spaces')
downvote count: 2
accepted answer: http://stackoverflow.com/a/47411223
duplicate of: http://stackoverflow.com/q/18707277
answer count: 1
linked to: http://stackoverflow.com/q/2970608
has title: namedtuple takes 3 arguments?
favorite count: 0

http://stackoverflow.com/comment/81982498
type: Comment
has text: Note that `type(n)` is always `str` when reading from `input()`
comment on: http://stackoverflow.com/q/47513273
score: 1
type: QuestionComment

timex
tags question: http://stackoverflow.com/q/47508003
type: Tag
tag name: timex

http://stackoverflow.com/comment/81874508
score: 0
type: Comment
has text: length = number of words or number of characters?
type: QuestionComment
comment on: http://stackoverflow.com/q/47459824

http://stackoverflow.com/a/53050405
has comment: http://stackoverflow.com/comment/118040697
downvote count: 0
answers question: http://stackoverflow.com/q/47533875
upvote count: 23
has body: I would suggest you to extract the table using tabula. Pass your pdf as an argument to the tabula api and it will return you the table in the form of dataframe. Each table in your pdf is returned as one dataframe. The table will be returned in a list of dataframea, for working with dataframe you need pandas. This is my code for extracting pdf. import pandas as pd import tabula file = "filename.pdf" path = 'enter your directory path here' + file df = tabula.read_pdf(path, pages = '1', multiple_tables = True) print(df) Please refer to this repo of mine for more details.
type: Answer
score: 23
has comment: http://stackoverflow.com/comment/118041184

http://stackoverflow.com/a/60465596
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47419943
has body: Change the character set and collation properties of the databases, tables, and columns to use utf8mb4 instead of utf8. docs # For each database: ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; # For each table: ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; # For each column: ALTER TABLE table_name CHANGE column_name column_name VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; # (Don’t blindly copy-paste this! The exact statement depends on the column type, maximum length, and other properties. The above line is just an example for a `VARCHAR` column.)
has comment: http://stackoverflow.com/comment/128655912
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47445607
accepted answer: http://stackoverflow.com/a/47445693
has comment: http://stackoverflow.com/comment/81846986
type: Question
tagged with: python
has title: How to find an intersection of a list of dataframes with exactly same columns and indexes but different values in pandas python?
type: AnsweredQuestion
score: 0
has body: I have a list of pandas dataframes as: lis = [df1, df2, df3, ... , dfn] I want to find an intersection of these dataframes such that my final df called intersection_df have only values that are common to all. All columns and rows should still be there but filled with na if no intersection is found. My dataframes are all multidimensional with same number of rows and columns which look like this like this: 1 2 3 4 5 cat cat 1 0 0 1 1 dog 1 0 0 1 1 fox 0 0 0 0 0 jumps 0 0 1 1 1 over 1 0 0 1 1 the 1 0 0 1 1 dog cat 1 0 0 1 0 dog 1 0 0 1 0 fox 0 0 0 0 0 jumps 1 0 0 1 0 over 1 0 0 1 0 the 1 1 0 1 0 I have tried different solutions found on stackoverflow but no luck, any ideas?
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/81847001
tagged with: dataframe
has answer: http://stackoverflow.com/a/47445693

http://stackoverflow.com/q/47475627
favorite count: 0
type: Question
has title: PySide2 - How can I show the "count of unread" on label?
has answer: http://stackoverflow.com/a/47501137
accepted answer: http://stackoverflow.com/a/47501137
answer count: 2
tagged with: pyside2
has comment: http://stackoverflow.com/comment/81907793
downvote count: 0
has comment: http://stackoverflow.com/comment/81905970
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81906112
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81908876
has comment: http://stackoverflow.com/comment/81939598
score: 1
has body: I know that when I trigger an edit event, I add the one to the counter, but how to display it on the label ? Or, is this actually two labels displayed in the same block ?
has comment: http://stackoverflow.com/comment/81940351
has answer: http://stackoverflow.com/a/47492412
possible better answer: http://stackoverflow.com/a/47492412

http://stackoverflow.com/q/47441934
tagged with: python
has comment: http://stackoverflow.com/comment/98302001
tagged with: constraints
tagged with: list
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/53240056
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python PuLP Beginner Constraint lists
type: UnansweredQuestion
has body: I am a beginner in Python. I am using PuLP to solve a minimization problem for a Renewable Energy System (PV + Wind + Battery). My system uses timesteps (24h, per hour). My question is how can I create a list in the constraints that collects the state of charge of the battery, as well as the inlet and outlet of it (variables that change value each timestep). In mathlab I have seen people use "eye", but here in PuLP I am not sure how can be done. Any help would be very well appreciated. Here is part of the code I have (which I know, is not correct). import numpy as np import pandas as pd from pulp import * #cfPV Values 'Renewable Ninja values' idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] d = { 'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx), 'hour':pd.Series(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'], index=idx), 'output':pd.Series([0,0,0,0.087,0.309,0.552,0.682,0.757,0.783,0.771,0.715,0.616,0.466,0.255,0.022,0,0,0,0,0,0,0,0,0], index=idx)} cfPV = pd.DataFrame(d) #cfWT Values 'Renewable Ninja values' idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] d1 = { 'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx), 'hour':pd.Series(['00:00:00', '01:00:00', '02:00…
downvote count: 0
tagged with: pulp

http://stackoverflow.com/a/47493427
upvote count: 2
answers question: http://stackoverflow.com/q/47491354
has comment: http://stackoverflow.com/comment/81996740
score: 2
downvote count: 0
has body: The issue you're encountering is that your selector is finding 2 elements that match. The first element that matches is hidden. The hidden element is displayed when the page is viewed by a mobile browser. I did some investigating, and found that the following CSS selector will find the element you are looking for. bank_type = find_element_by_css_selector('.show-for-large select#SelectAccount.banking-target')
type: Answer

http://stackoverflow.com/q/47512079
has title: python threads - run with timeout
has comment: http://stackoverflow.com/comment/81980208
tagged with: multithreading
answer count: 0
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
tagged with: synchronization
has body: We have created a pool of workers to crawl web pages in background with the similar to the one below import requests from multiprocessing.dummy import Pool as ThreadPool urls = [ ... ] # Make the Pool of workers pool = ThreadPool(4) results = pool.map(requests.get, urls) pool.close() pool.join() Question: The system hangs sometimes. Observed for some cases the get method is not returning and hence the whole system hangs. What I am looking for? Is there a way to set timeout for thread execution and close the thread to return empty?
type: Question
has comment: http://stackoverflow.com/comment/81980938
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81979942

http://stackoverflow.com/comment/81721795
has text: Yes, thank you. In my original file 'hi' was the name of the list I was using but I changed it to list as an example. I will update my description. However, I am still getting the same error. I cant find a reason for the value of h to be larger than the length of the list 'list'.
score: 0
comment on: http://stackoverflow.com/a/47384173
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81953160
type: QuestionComment
comment on: http://stackoverflow.com/q/47498974
has text: You can't be getting this error as there are even no calls to `int`...
score: 1
type: Comment

http://stackoverflow.com/comment/81856830
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47402765
type: QuestionComment
has text: and what does: `library(rPython)` `python.exec(c("import sys", "\n", "print(sys.version)"))` return? I suspect that rPython is using another Python version, not 3.5.2

http://stackoverflow.com/comment/81884523
score: 1
has text: Functions and types are first class objects; simply referencing one doesn't call it.
type: Comment
comment on: http://stackoverflow.com/a/47464833
type: AnswerComment

http://stackoverflow.com/q/47495285
has comment: http://stackoverflow.com/comment/81961762
has answer: http://stackoverflow.com/a/47622396
tagged with: size
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/103869289
possible better answer: http://stackoverflow.com/a/47622396
tagged with: pixel
has title: Get tkinter widget size in pixels
has comment: http://stackoverflow.com/comment/81947708
score: 1
has body: If I define for example tkinter.Button widget with parameters (width=10, height=1)(in characters) and then I want to retrieve it's size in pixels, how do I do it? EDIT: I tried widget.winfo_height() and widget.geometry(), but all these functions return height defined in number of characters. I think it would be possible to create the same widget in a frame and then write frame.winfo_height() which would return size in pixels, but this is not so elegant solution.
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/65832270
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/65832270
upvote count: 2
has comment: http://stackoverflow.com/comment/81954420

http://stackoverflow.com/q/47515454
score: 2
type: AnsweredQuestion
has body: I am working on a segmentation problem where given an image, each RGB value corresponds to a class label. The problem I have is to efficiently map RGB values from an image (numpy array) to a corresponding class label image. Let's provide the following simplified example: color2IdMap {(100,0,100):0, (0,200,0):2} labelOld array([[[100,0,100], [0,200,0]], [[100,0,100], [0,200,0]]], dtype=uint8) (in a real example the colorIdMap will have about 20 entries and labelOld will be an array of shape: (1024,512,3)) Now I want the result to be the following mapped array. with shape: (1024,512) labelNew array([[ 0, 2], [ 0, 2]]) I attempted to do this with loops and list comprehensions but both methods are quite slow (about ~10seconds per image, which is a big number for 250K images). And I am wondering if there is a faster way of doing it. Attempted method 1: labelNew = np.empty((1052,1914), dtype=np.uint8) for i in range(1052): for j in range(1914): labelNew[i, j] = color2IdMap[tuple(labelOld[i, j])] Attempted method 2: labelNew = [[color2IdMap[tuple(x)] for x in y] for y in labelOld] So, my question is if there is any faster and more efficient way of doing this?
has comment: http://stackoverflow.com/comment/81986963
has title: Mapping RGB values in an image to a corresponding ID using a dictionary
has answer: http://stackoverflow.com/a/47515679
accepted answer: http://stackoverflow.com/a/47515679
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
upvote count: 2
tagged with: arrays
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/71867539
possible better answer: http://stackoverflow.com/a/71867539
tagged with: image
has comment: http://stackoverflow.com/comment/82035990

http://stackoverflow.com/comment/81755344
comment on: http://stackoverflow.com/a/47400597
score: 0
type: Comment
has text: Why are you using `form_invalid` and not `form_valid`?
type: AnswerComment

http://stackoverflow.com/comment/81965462
type: AnswerComment
has text: Additionally, it may be useful to run `pyupdater collect-debug-info`, and link the output of that here. This question appears to be specific to `pyupdater` now though, which I have no experience with, so I'll bow out.
score: 0
comment on: http://stackoverflow.com/a/47504352
type: Comment

http://stackoverflow.com/a/47536072
has body: You can use random.choices instead of random.choice. It is new in version 3.6. ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]] ColourSeq = random.choices(ColourList, k=6) print(ColourSeq)
score: 2
has comment: http://stackoverflow.com/comment/82029045
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47535582
upvote count: 2
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47535582

http://stackoverflow.com/q/47416893
has comment: http://stackoverflow.com/comment/81788588
type: Question
answer count: 1
has body: I have a model class called Foo, with the following fields start and duration. class Foo(models.Model): start = models.DateTimeField() duration = models.DurationField() I want to filter all the entries from the Foo table by checking that the start plus duration is less than a certain time.
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47417233
has comment: http://stackoverflow.com/comment/81788122
has answer: http://stackoverflow.com/a/47417233
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/43323724
has title: Calculation sum of two fields to filter entries
has comment: http://stackoverflow.com/comment/81788233
tagged with: sql
tagged with: orm
tagged with: mysql

http://stackoverflow.com/q/47456055
tagged with: cython
has answer: http://stackoverflow.com/a/47456397
type: Question
has answer: http://stackoverflow.com/a/47461277
answer count: 2
type: UnansweredQuestion
has body: In my code, I am trying to define a dynamic array with changing number of the rows and columns, depends on the new conditions inside the function, meaning I might add more rows or columns. I tried to make two dimensional pointer arrays and I want to be able to pass this 2-D pointer array as an argument to a function. This is the small part of my code: Update: test.pyx from libc.string cimport memset import numpy as np cimport numpy as np cimport cython from cython.view cimport array as cvarray from libc.stdlib cimport malloc, free from libc.math cimport log, exp from cython_gsl cimport * import ctypes cdef gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937) cdef int** zeros2(dim): assert len(dim) == 2 cdef int i cdef int **matrix matrix = &lt;int**&gt; malloc(sizeof(int*) * dim[0]) for i from 0 &lt;= i &lt; dim[0]: matrix[i] = &lt;int*&gt; malloc(sizeof(int) * dim[1]) memset(matrix[i], 0, sizeof(int) * dim[1]) return matrix @cython.cdivision(True) @cython.wraparound(False) @cython.boundscheck(False) cdef void generator(double* alpha,int* D, double* m): cdef Py_ssize_t i for i from 0 &lt;= i &lt; D[0]: m[i]=gsl_ran_beta(r, alpha[0], 1) return @cython.cdivision(True) @cython.boundscheck(False) @cython.wraparound(False) cdef void initializer(double* alpha, int* D, int* N, double* m, int** Z ): cdef int i, j generator(alpha, D, &amp;m[0]) for i from 0 &lt;= i &lt; D[0]: for j from 0 &lt;= j &lt; N[0]: Z[j][i]= gsl_ran_bernoulli(r, m[i]) print Z[j][i] return def run(int n, int d, double alpha): cdef np.ndarray[double, ndim=1, mode='c'] mu=np.empty((d,), dtype=ctypes.c_double) cdef int **Z = zeros2((n, d)) initializer(&amp;alpha, &amp;d, &amp;n, &amp;mu[0], &lt;int **&gt;(&amp;Z[0][0]) ) setup.py from distutils.core import setup, Extension from Cython.Build import cythonize from numpy import get_include import numpy import cython_gsl from Cython.Distutils import build_ext ext_modules = [ Extension( "test", ["test.pyx"], libraries=cython_gsl.get_libraries(), library_dirs=[cython_g…
score: 0
tagged with: arrays
tagged with: python
tagged with: http://stackoverflow.com/tag/c
tagged with: pointers
has title: passing a two dimensional dynamic pointer array as an argument to a function in cython

http://stackoverflow.com/comment/81864450
has text: Show the models.py where I assume you have a relationship between the user model and the supplierssignup model (because you probably need that relationship for this to work).
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47454771

http://stackoverflow.com/q/47454108
has body: I am currently building a desktop software. As my graphical skills are limited, I chose C++ QT to make it fast and clean (On top of the .ui files, I coded a lot in .cpp files to modify the behaving of the windows, etc). The application is supposed to be a graphical interface for a Python Web scraper using Selenium that I built earlier this year. The deployment should be cross-plateform (Windows / MacOS) so the main goal is to make this project easy to compile and deploy in .exe / .app. I cannot use mac/windeployqt unfortunatly as I added many .cpp files to the project. My application is made of two parts : The python scraper The C++ QT GUI But here is the problem, I don't know how to interconnect those two parts. I am facing a dilemma, with multiple possible outcomes : I rebuild the python scraper in C++ using QtWebDriver which is going to be a pain in the ... I use pyuic5 to translate my .ui files in .py and then I recode my .cpp files in .py, which may take a while and is not really convenient. I use QT Python script embedding to call my python scraper but I'll have more work to make it deployable and provide dependencies rm -rf -no-preserve-root / Both parts of the software are already fully coded and functionnal. The GUI is already deployable thanks to appdmg Which solutions should I take to make this easily maintainable and deployable ? Which one would be considered "best-practice" in my case ?
type: Question
has title: How to build a QT Application efficently?
type: UnansweredQuestion
tagged with: python
tagged with: qt
tagged with: c++
score: 0
has answer: http://stackoverflow.com/a/47457843
answer count: 1

http://stackoverflow.com/comment/81959371
has text: A common strategy for solving block puzzles like this is [backtracking](https://en.wikipedia.org/wiki/Backtracking). But whether or not you use backtracking you'll need to devise some way to evaluate block placements, apart from "does it fit here?". Eg you could calculate the bounding box of all the blocks currently on the board. A squarish bounding box is probably better. And a compact bounding box with few holes is probably better. But those are just guesses. :)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47500832

http://stackoverflow.com/comment/81857536
type: AnswerComment
has text: vao, that's it! Thanks! Is it possible to use this with any number of input dictionaries without extending the tuple here?
score: 0
comment on: http://stackoverflow.com/a/47451243
type: Comment

recommendation-engine
tags question: http://stackoverflow.com/q/47422077
tag name: recommendation-engine
type: Tag

http://stackoverflow.com/comment/82007600
comment on: http://stackoverflow.com/q/47525609
score: 0
type: Comment
type: QuestionComment
has text: As in your last questions, this is not currently possible. You need to extend the inbuilt classes to handle this yourself.

http://stackoverflow.com/a/47437740
answers question: http://stackoverflow.com/q/47437666
has comment: http://stackoverflow.com/comment/81831813
downvote count: 0
has comment: http://stackoverflow.com/comment/81831020
has body: using python 2, input interprets everything you enter (and it's also a security breach) Since numbers starting with 0 are considered as octal in python 2 (no longer true in python 3 where you have to use the 0o prefix), there's a syntax error because 0971558 contains digits higher than 7. I'd use raw_input to get a real string: scan = raw_input('Please scan your ID: ') if you want to convert as integer, int accepts leading zeroes all right so int(scan) will work without stripping them off. note that your original code works all right in python 3.
score: 3
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/81831952

http://stackoverflow.com/comment/81843243
has text: `return 'a' if a() else ('b' if b() else 'c')`
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47444009

http://stackoverflow.com/q/47477150
has comment: http://stackoverflow.com/comment/81909039
has body: I have run into a problem I can't explain: class A: def __init__(self, rid, title): self.rid = rid self.title = title self.b = [] def __add__(self, other): if type(other) == B: self.b += [other] def __str__(self): return self.rid + ' - ' + self.title def __repr__(self): return str(self) class B: def __init__(self, rid, title): self.rid = rid self.title = title b = B('123', 'abc') a = A('345', 'cde') print(a) a += b print(a) The first print results in the expected output: 345 - cde However, the second print (after the adding of b) results in: None Why is that? I am not changing the rid or the title of a nor do I create new and uninitialized instance called a, or am I?
has comment: http://stackoverflow.com/comment/81909174
tagged with: python
has comment: http://stackoverflow.com/comment/81913067
accepted answer: http://stackoverflow.com/a/47477296
has comment: http://stackoverflow.com/comment/81909032
type: Question
has answer: http://stackoverflow.com/a/47477296
score: 0
has comment: http://stackoverflow.com/comment/81909077
answer count: 1
has comment: http://stackoverflow.com/comment/81909011
upvote count: 1
has comment: http://stackoverflow.com/comment/81909111
downvote count: 1
has comment: http://stackoverflow.com/comment/81909278
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has title: Printing a class instance results in None if I change the class member values
has comment: http://stackoverflow.com/comment/81909056

http://stackoverflow.com/q/47537383
has comment: http://stackoverflow.com/comment/82031571
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47537510
has body: How do I make the backslash so that it becomes visible in the output of the code? I am trying to make a board for a game I am programming. however, the board contains backslashes '\' print(''' _____________________ / \ /_______________________\ | | | | | ''') but what I get is: &gt;&gt;&gt; _____________________ / /_______________________| | | | | &gt;&gt;&gt;
tagged with: python
has title: backslashes visible in output
upvote count: 2
score: 2
possible better answer: http://stackoverflow.com/a/47537418
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47537510
has answer: http://stackoverflow.com/a/47537418
has comment: http://stackoverflow.com/comment/82031622

http://stackoverflow.com/a/47408772
score: 0
has comment: http://stackoverflow.com/comment/81772117
answers question: http://stackoverflow.com/q/47408312
has body: Have you tried to split into a list and then removing blank elements?? f = open('file.txt', 'rb') raw_str = str(f.read()) full_list = raw_str.split(';') templist = list(filter(None, full_list)) by printing templist it gives a list of all elements. you can perform any action on it like to convert into a string again by using for loop according to your requirement. output is like-
type: Answer

http://stackoverflow.com/comment/81886044
type: Comment
score: 0
type: AnswerComment
has text: @a p. No, I'm afraid it's not what I want. There is no volume label in the out put. The volume label is actually the "name" of the partition.
comment on: http://stackoverflow.com/a/47464669

http://stackoverflow.com/a/47505870
answers question: http://stackoverflow.com/q/47463826
score: 0
type: Answer
has body: Note that you need nibbles only for debug purposes and you can exclude some operations: nibble0 = j[1] &gt;&gt; 4 nibble1 = j[1] &amp; 15 nibble2 = j[0] &gt;&gt; 4 k.append((nibble0 &lt;&lt; 12) | (nibble1 &lt;&lt; 8) | (nibble2 &lt;&lt; 4) | 0) is equivalent to k.append((j[1] &lt;&lt; 8) | (j[0] % F0)) and nibble3 = j[0] &amp; 15 nibble4 = j[3] &gt;&gt; 4 nibble5 = j[3] &amp; 15 k.append((nibble3 &lt;&lt; 12) | (nibble4 &lt;&lt; 8) | (nibble5 &lt;&lt; 4) | 0) is equivalent to k.append((j[0] &lt;&lt; 12) | (j[3] &lt;&lt; 4)) (if k gets 16-bit values, otherwise clear MSB bits of j[0])

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/47484199
tags question: http://stackoverflow.com/q/47524614
tags question: http://stackoverflow.com/q/47402505
tags question: http://stackoverflow.com/q/47448097
tags question: http://stackoverflow.com/q/47463730
tags question: http://stackoverflow.com/q/47430906
tags question: http://stackoverflow.com/q/47540148
tags question: http://stackoverflow.com/q/47419745
tags question: http://stackoverflow.com/q/47524748
tags question: http://stackoverflow.com/q/47534430
tags question: http://stackoverflow.com/q/47492450
tags question: http://stackoverflow.com/q/47520356
tags question: http://stackoverflow.com/q/47459088
tags question: http://stackoverflow.com/q/47506434
tags question: http://stackoverflow.com/q/47481373
tags question: http://stackoverflow.com/q/47441147
tags question: http://stackoverflow.com/q/47388241
tags question: http://stackoverflow.com/q/47508516
tags question: http://stackoverflow.com/q/47433769
tags question: http://stackoverflow.com/q/47460576
tags question: http://stackoverflow.com/q/47506128
tag name: json
tags question: http://stackoverflow.com/q/47501450
tags question: http://stackoverflow.com/q/47447960
tags question: http://stackoverflow.com/q/47521264
tags question: http://stackoverflow.com/q/47514923
tags question: http://stackoverflow.com/q/47441197
tags question: http://stackoverflow.com/q/47483988
tags question: http://stackoverflow.com/q/47449350
tags question: http://stackoverflow.com/q/47389138
tags question: http://stackoverflow.com/q/47463593
tags question: http://stackoverflow.com/q/47502006
tags question: http://stackoverflow.com/q/47533175
tags question: http://stackoverflow.com/q/47384271
tags question: http://stackoverflow.com/q/47460593
tags question: http://stackoverflow.com/q/47518195
tags question: http://stackoverflow.com/q/47485691
tags question: http://stackoverflow.com/q/47515137
tags question: http://stackoverflow.com/q/47475790
tags question: http://stackoverflow.com/q/47413175
tags question: http://stackoverflow.com/q/47540354
tags question: http://stackoverflow.com/q/47396732
tags question: http://stackoverflow.com/q/47447906
tags question: http://stackoverflow.com/q/47437704
tags question: http://stackoverflow.com/q/47494702
tags question: http://stackoverflow.com/q/47516976
tags question: http://stackoverflow.com/q/47398054
tags question: http://stackoverflow.com/q/47397759
tags question: http://stackoverflow.com/q/47535911
tags question: http://stackoverflow.com/q/47465735
tags question: http://stackoverflow.com/q/47458775
tags question: http://stackoverflow.com/q/47403782
tags question: http://stackoverflow.com/q/47391715
tags question: http://stackoverflow.com/q/47497031
tags question: http://stackoverflow.com/q/47508048
tags question: http://stackoverflow.com/q/47465930
tags question: http://stackoverflow.com/q/47526002
tags question: http://stackoverflow.com/q/47413992
tags question: http://stackoverflow.com/q/47407537
tags question: http://stackoverflow.com/q/47423673
tags question: http://stackoverflow.com/q/47385922
type: Tag
tags question: http://stackoverflow.com/q/47518902
tags question: http://stackoverflow.com/q/47434333
tags question: http://stackoverflow.com/q/47386523
tags question: http://stackoverflow.com/q/47508790
tags question: http://stackoverflow.com/q/47446008
tags question: http://stackoverflow.com/q/47461823
tags question: http://stackoverflow.com/q/47504564
tags question: http://stackoverflow.com/q/47474664
tags question: http://stackoverflow.com/q/47414684
tags question: http://stackoverflow.com/q/47462085
tags question: http://stackoverflow.com/q/47453611
tags question: http://stackoverflow.com/q/47472245
tags question: http://stackoverflow.com/q/47522258
tags question: http://stackoverflow.com/q/47430767
tags question: http://stackoverflow.com/q/47485792
tags question: http://stackoverflow.com/q/47538420
tags question: http://stackoverflow.com/q/47514710
tags question: http://stackoverflow.com/q/47453136

http://stackoverflow.com/a/47477880
accepted answer of: http://stackoverflow.com/q/47477809
upvote count: 1
has comment: http://stackoverflow.com/comment/81911892
type: Answer
has comment: http://stackoverflow.com/comment/81911926
answers question: http://stackoverflow.com/q/47477809
score: 1
type: AcceptedAnswer
downvote count: 0
has body: You need to keep a reference to the photo. imageInside = PhotoImage(file = "images/inside.gif") imageLabel = Label(inside,image = imageInside) imageLabel.grid(row =1, columnspan = 2) imageLabel.photo_ref = imageInside # keep a reference!

http://stackoverflow.com/q/47502181
has comment: http://stackoverflow.com/comment/81960255
has comment: http://stackoverflow.com/comment/81960302
type: AnsweredQuestion
has body: I have a polygon set in GIS with a lot of polygons. My task is to find two polygons with max distance between them [two polygons that are the farthest/farthermost, my english is funny :( ] This is my code so far, but I stopped because output gives me the the max value that is not correct. Help please. This is my code: # -*- coding: utf-8 -*- from shapely.wkb import loads from osgeo import ogr datoteka=ogr.Open("sth.shp") sloj=datoteka.GetLayerByName("katastar") udaljenosti=[] for i in sloj: cestica1=loads(i.GetGeometryRef().ExportToWkb()) for j in sloj: cestica2=loads(j.GetGeometryRef().ExportToWkb()) udaljenosti.append(cestica1.distance(cestica2)) max_udaljenost=max(udaljenosti) print max_udaljenost datoteka.Destroy() i know i have a lot of unnecessary stuff in the code but I'll fix that when i fix this maximum distance.
has comment: http://stackoverflow.com/comment/81960446
tagged with: shapely
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Max distance between polygons in a polygon set
accepted answer: http://stackoverflow.com/a/47509581
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47509581
tagged with: python

http://stackoverflow.com/q/47504501
has answer: http://stackoverflow.com/a/68992303
has comment: http://stackoverflow.com/comment/81965048
tagged with: python
tagged with: recurrent-neural-network
has body: What does the tokenizing mean in the the contex. I keep getting this error and I am unable to train my model. Please can somebody review my sample dataset and code to see where I have gone wrong ? For reference the traceback is as follows: (keras_tf) G:\Python\integer_sequencing&gt;python MyTest.py Using TensorFlow backend. Traceback (most recent call last): File "MyTest.py", line 20, in &lt;module&gt; trainset= pd.read_csv('G:/Python/integer_sequencing/sample.csv') File "C:\Users\sarah\Anaconda3\envs\keras_tf\lib\site-packages\pandas\io\parsers.py", line 655, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Users\sarah\Anaconda3\envs\keras_tf\lib\site-packages\pandas\io\parsers.py", line 411, in _read data = parser.read(nrows) File "C:\Users\sarah\Anaconda3\envs\keras_tf\lib\site-packages\pandas\io\parsers.py", line 1005, in read ret = self._engine.read(nrows) File "C:\Users\sarah\Anaconda3\envs\keras_tf\lib\site-packages\pandas\io\parsers.py", line 1748, in read data = self._reader.read(nrows) File "pandas\_libs\parsers.pyx", line 890, in pandas._libs.parsers.TextReader.read (pandas\_libs\parsers.c:10862) File "pandas\_libs\parsers.pyx", line 912, in pandas._libs.parsers.TextReader._read_low_memory (pandas\_libs\parsers.c:11138) File "pandas\_libs\parsers.pyx", line 966, in pandas._libs.parsers.TextReader._read_rows (pandas\_libs\parsers.c:11884) File "pandas\_libs\parsers.pyx", line 953, in pandas._libs.parsers.TextReader._tokenize_rows (pandas\_libs\parsers.c:11755) File "pandas\_libs\parsers.pyx", line 2184, in pandas._libs.parsers.raise_parser_error (pandas\_libs\parsers.c:28765) pandas.errors.ParserError: Error tokenizing data. C error: Expected 14 fields in line 3, saw 57 (keras_tf) G:\Python\integer_sequencing&gt; My code is as follows: import numpy as np from numpy import array import matplotlib.pyplot as plt import pandas as pd import math from keras.models import Sequential from keras.layers import Dense from keras.layers import SimpleRNN from…
type: Question
has comment: http://stackoverflow.com/comment/81964792
tagged with: deep-learning
type: UnansweredQuestion
score: 0
answer count: 1
tagged with: keras
has title: Error tokenizing data. C error: Expected 14 fields in line 3, saw 57

http://stackoverflow.com/comment/82036474
score: 0
type: AnswerComment
has text: You should link to a particular commit, otherwise the line number in the link will drift.
type: Comment
comment on: http://stackoverflow.com/a/47539680

http://stackoverflow.com/q/47526946
linked to: http://stackoverflow.com/q/31570096
has answer: http://stackoverflow.com/a/51154028
linked to: http://stackoverflow.com/q/21547073
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/68520964
has title: flask_restplus add_namespace keep getting no attribute 'as_view'
downvote count: 0
tagged with: python
score: 4
tagged with: flask
possible better answer: http://stackoverflow.com/a/68520964
type: AnsweredQuestion
has body: I writing a flask, trying to organize it by using Blueprint with Namespace, following this tutorial I had faced some problem, and had look around internet and had review solution in 1 and 2. The first one is not relevant to what I doing, and the second one the solution just doesn't fix my problem. Here are my code: project/project.py from flask import Flask, jsonify, url_for from .apis.apis import api app = Flask(__name__) app.register_blueprint(api, url_prefix="/api") project/apis/apis.py from flask import Blueprint from .user.authentication import auth from flask_restplus import Api, apidoc, Resource blueprint = Blueprint("api", __name__) api = Api(blueprint, doc='/docs', ui=False) api.add_namespace(auth, path="/auth") #Keep getting error at this line project/apis/user/authentication.py from flask_restplus import Namespace auth = Namespace('auth', description='Authentication') @auth.route("/test") def authentication(): return "test" Stack Trace Traceback (most recent call last): File "/home/gaara/Python/Flask-Api/project/__init__.py", line 1, in &lt;module&gt; from .project import app File "/home/gaara/Python/Flask-Api/project/project.py", line 3, in &lt;module&gt; from .apis.apis import api File "/home/gaara/Python/Flask-Api/project/apis/apis.py", line 13, in &lt;module&gt; api.add_namespace(auth, path="/auth") File "/home/gaara/Python/Flask-Api/venv/lib/python3.6/site-packages/flask_restplus/api.py", line 413, in add_namespace self.register_resource(ns, resource, *self.ns_urls(ns, urls), **kwargs) File "/home/gaara/Python/Flask-Api/venv/lib/python3.6/site-packages/flask_restplus/api.py", line 255, in register_resource self._register_view(self.app, resource, *urls, **kwargs) File "/home/gaara/Python/Flask-Api/venv/lib/python3.6/site-packages/flask_restplus/api.py", line 276, in _register_view resource_func = self.output(resource.as_view(endpoint, self, *resource_class_args, AttributeError: 'function' object has no attribute 'as_view' I am not sure why I keep gett…
accepted answer: http://stackoverflow.com/a/51154028

http://stackoverflow.com/comment/81729936
comment on: http://stackoverflow.com/q/47387713
has text: @furas thank you for both answers. The thing that was missing was to defing `i=x`. please post it as a valid answer.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47463583
answer count: 1
has title: Translate python to PHP (need to understand this python condition/iteration syntax)
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47463681
tagged with: python
tagged with: php
type: Question
downvote count: 0
has body: I am reading through a python piece of code that I need to understand in order to port it in PHP. I can understand basic python syntax. However I came across following piece of code, and I do not really get it. player = next((p for p in player_list if p['team'] == team), None) As in, is it doing the following: Check if p['team'] == team If yes, then iterate using for p in player_list take the value of each p and put it in p well...I have no idea what next is doing here :( I just need to understand the syntax/grammar of above statement, so I can write equivalent in PHP. I unable to figure it out since PHP does not support such constructs. Any help is appreciated
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47463681

http://stackoverflow.com/a/47516794
has body: you may just reset the index at the end or define a local variable and use it in `arange' function. update the variable with the numbers of rows for each file you read.
score: 0
answers question: http://stackoverflow.com/q/47515644
type: Answer
accepted answer of: http://stackoverflow.com/q/47515644
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81989700

http://stackoverflow.com/q/47489272
upvote count: 1
linked to: http://stackoverflow.com/q/1225637
has answer: http://stackoverflow.com/a/47489430
favorite count: 0
type: Question
tagged with: latex
has title: dynamic latex code in a matplotlib title
duplicate of: http://stackoverflow.com/q/1225637
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81934164
tagged with: python
has body: I am working on dynamic plots on jupyter with matplotlib, which means in a for loop each different cycle provides a different plot as in the example below import matplotlib.pyplot as plt import numpy as np import time import matplotlib as mpl mpl.rcParams['lines.linewidth'] = 2 plt.ion() %matplotlib notebook x = np.arange(-10, 10, 0.01) fig = plt.figure(figsize = (12, 7)) ax = fig.add_subplot(111) ax.grid() plt.show() for j in range(1,5): ax.set_title(r"%6.2f $y = \frac{\sin{(\pi x j)}}{(\pi x j)}$" % j) y = np.sin( np.pi*x*j )/( np.pi*x*j ) line, = ax.plot(x, y, 'b') fig.canvas.draw() time.sleep(1) if j != 4: line.remove() The line "ax.set_title" provides the title which has both a constant latex code and a number that changes over the time. My issue is that I can change a number in the title out of the latex code but I really don't know how to change a piece INSIDE the latex code. In the previous example, for each different loop, I would like not only a different plot but also a title with a different latex code which provides a different result as reported here Is there anyone who can suggest me anything about it?
tagged with: jupyter-notebook
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47489430
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47464586
has body: Checking length and compare first 3 letters with last 3 letters: is_equal = True if len(s) &gt;= 6 and s[:3] == s[-3:][::-1] else False
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47464529
answers question: http://stackoverflow.com/q/47464529
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81883937
downvote count: 0

http://stackoverflow.com/comment/123207545
comment on: http://stackoverflow.com/a/47571289
type: Comment
has text: @GuilhermeCorrea vlc by default buffers 5 seconds, go to settings and lower the buffer to 0 ms
type: AnswerComment
score: 1

http://stackoverflow.com/a/47459310
answers question: http://stackoverflow.com/q/47459149
score: 0
has body: Since you say it's an ndarray, I assume that numpy is allowed. Does this work for what you're looking for? np.round(np.clip(predict, 0, None))
type: Answer

button
tags question: http://stackoverflow.com/q/47408474
tags question: http://stackoverflow.com/q/47471725
tags question: http://stackoverflow.com/q/47459727
tags question: http://stackoverflow.com/q/47459072
tags question: http://stackoverflow.com/q/47475783
tag name: button
tags question: http://stackoverflow.com/q/47394455
type: Tag
tags question: http://stackoverflow.com/q/47527880
tags question: http://stackoverflow.com/q/47433316

http://stackoverflow.com/q/47432320
type: Question
tagged with: python
type: UnansweredQuestion
has title: Is there any option to check if email id exists or not using python script?
linked to: http://stackoverflow.com/q/11120350
score: 2
upvote count: 2
has body: I have a code where emails are being sent to the given ID using smtp and if the mail id does not exists then mail wont get delivered. So, I want to capture the email ID's if they do not exist. Can this be done by python script?
downvote count: 0
duplicate of: http://stackoverflow.com/q/11120350
tagged with: smtp
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47432395

http://stackoverflow.com/comment/82021182
comment on: http://stackoverflow.com/a/47532103
type: Comment
score: 0
type: AnswerComment
has text: you made the same typo in your comment you did in pip. pip install unidecode from unidecode import unidecode

http://stackoverflow.com/comment/82030426
comment on: http://stackoverflow.com/q/47521124
score: 0
type: Comment
type: QuestionComment
has text: When you open your browser with localhost:8080, you should be seeing an error as you don't have anything defined for that URL. Perhaps you have an 'old' version of your webserver still running on 8080? That symptoms you describe do not match your code.

http://stackoverflow.com/a/47488655
has body: range(n) gives you a sequence of numbers from 0 to n - 1. If you replace the range function by its sequence in your code you basically get this: for i in [0, 1]: primes[4 - i] = primes[i] Each time you loop, i will start from 0 and get bigger and bigger. Which in turn means that 4 - i will start from 4 and get smaller. 1st loop: 4 -i = 4 - 0 = 4 2nd loop: 4 - i = 4 - 1 = 3 (and so on if your value in range was bigger than 2) The line primes[4 - i] = primes[i] means that you're assigning to the index 4 - i the value stored at the index i. In your example, your loop is actually doing this: 1st loop: primes[4] = primes[0] 2nd loop: primes[3] = primes[1] Giving you the result you currently have.
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47488410
score: 2
upvote count: 3

http://stackoverflow.com/a/47410542
score: 0
has body: check out numpy.reshape. Example with 10 numbers with open('xx.txt') as f: txt = f.read() import pandas as pd import numpy as np txt_sep = np.array(txt.split()) txt_sep = txt_sep.reshape(5,-1) df = pd.DataFrame(txt_sep) output: df 0 1 0 1 2 1 3 4 2 5 6 3 7 8 4 9 10 In your case: txt_sep = txt_sep.reshape(500,-1) But this will only work if you have exactly 10000x500 numbers, but is fixable if this is your case.
type: Answer
answers question: http://stackoverflow.com/q/47410242
has comment: http://stackoverflow.com/comment/81774610

http://stackoverflow.com/comment/81768629
score: 0
comment on: http://stackoverflow.com/q/47407720
has text: @user3159253 it's not valid JSON, I assume it's already parsed into a python object.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47439282
has body: This: for player in players: player = Character() will create a new Character instance for each item in players (not using the item itself) and assign it to the player variable (each time ovverridding the previous assignment). This won't of course change anything to your players list. After the loop is terminated, you get one single Character() instance bound to the player variable, and that's all. IOW, you'd get the same practical result replacing the loop with a single: player = Character() but it won't obviously be of any use. print(red.life) Where have you defined a variable named red ? or if i try print("red".life) "red" is a string. A string has no attribute life. for some reason it uses player as object for the class but I want the element of the list to be used! The "elements of the list" (I assume you mean the players list) are strings too. If you want to get a list of Character instances instead, you can get it that what: class Character(object): def __init__(self, name): self.name = name self.life = 50 playernames = ["red", "green", "blue", "42"] players = [Character(name) for name in playernames] but that will still not create any variables named red, green etc, just a list of Character instances. If you want to be able to retrieve specific Character instances, you will either need to explicitly create variables or use a dict. Creating variables: red = Character("red") yellow = Character("yellow") # etc but this means all your characters are hardcoded - you cannot have more or less players nor name them differently etc. Using a dict: playernames = ["red", "green", "blue", "42"] players = {name:Character(name) for name in playernames} print(players["red"].life) print(players["green"].life) # etc
has comment: http://stackoverflow.com/comment/81837023
answers question: http://stackoverflow.com/q/47438914
type: Answer
has comment: http://stackoverflow.com/comment/81834907
score: 1
downvote count: 0
upvote count: 1

exists
tags question: http://stackoverflow.com/q/47475838
type: Tag
tag name: exists

memory
tags question: http://stackoverflow.com/q/47474155
tag name: memory
tags question: http://stackoverflow.com/q/47517106
tags question: http://stackoverflow.com/q/47485373
type: Tag
tags question: http://stackoverflow.com/q/47516434
tags question: http://stackoverflow.com/q/47442733
tags question: http://stackoverflow.com/q/47404203
tags question: http://stackoverflow.com/q/47392697

http://stackoverflow.com/q/47528362
type: Question
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/82013040
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82013057
has body: I have a DataFrame named df has column GENDER, AGE and ID and others columns, and there is another DataFrame named df_2 which has only 3 columns GENDER, AGE and ID too. I want to update the value of GENDER and AGE in df with values from df_2. So my ideas is df_id = df.ID.tolist() df_2_id = df_2.ID.tolist() df = df.set_index('ID') df_2 = df_2.set_index('ID') # all the ids in df_2_id are in df_id for id in tqdm.tqdm_notebook(df_2_id): df.loc[id, 'GENDER'] = df_2.loc[id, 'GENDER'] df.loc[id, 'AGE'] = df_2.loc[id, 'AGE'] However, the for loop only has 17.2 iterations per seconds, and it around takes 2 hours to update the data. How can I make it faster?
has comment: http://stackoverflow.com/comment/82013202
has answer: http://stackoverflow.com/a/47528602
tagged with: python
accepted answer: http://stackoverflow.com/a/47528602
has title: Fater update pandas DataFrame

http://stackoverflow.com/q/47499069
downvote count: 0
has title: Conflict between Style() and ThemedStyle()
answer count: 1
tagged with: ttk
has comment: http://stackoverflow.com/comment/81955189
favorite count: 0
has body: I'm using Tkinter and ttk to create a GUI in Python. I want to have two separate themes for the UI that the user can configure. One of these options is the vista theme called using the following code: from tkinter import Tk from tkinter.ttk import Style root = Tk() root.style = Style() root.style.theme_use('vista') Another option is the black theme called using: from tkinter import Tk from ttkthemes import ThemedStyle root = Tk() root.style = ThemedStyle() root.style.theme_use('black') I am having some issues because I want users to be able to switch themes while the program is running. Applying these themes separately (i.e., applying a theme, closing the program and applying the other theme on launch) works fine. I start to encounter problems when calling root.style = ThemedStyle() followed by root.style = Style() somewhere later in the code when switching from the vista theme to the black theme: if self.ui_theme == 'Dark': self.root.style = ThemedStyle() theme = 'black' self.root.tk_setPalette(background='#2f3136') else: self.root.style = Style() theme = 'vista' self.root.tk_setPalette(background='#f0f0f0') self.root.style.theme_use(theme) On top of that, going from black to vista and back to black again causes the following error: error reading package index file C:/Python34/Lib/site-packages/ttkthemes/themes/pkgIndex.tcl: Theme plastik already exists which I assume happens when calling self.root.style = ThemedStyle() twice in the same instance. Is there a way to get around this without forcing users to restart the application when applying a new theme? Thanks in advance.
score: 2
type: AnsweredQuestion
tagged with: python
type: Question
upvote count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/47499996
accepted answer: http://stackoverflow.com/a/47499996

http://stackoverflow.com/comment/115307546
has text: Worked for me on Mac!
score: 0
comment on: http://stackoverflow.com/a/61454044
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47452303
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47453015
has title: How to display variable in qmessagebox using creator in pyqt5
linked to: http://stackoverflow.com/q/22139023
tagged with: python
upvote count: 4
score: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47453015
downvote count: 0
tagged with: qmessagebox
answer count: 1
tagged with: pyqt5
favorite count: 0
type: Question
has body: I am trying to display a variable with some message in qmessagebox using creator. I found similar post here: pyqt: Variable values in QMessageBox output? but it does not work within the creator. Any suggestions how to amend the code below so that it worked?: purchaseValue = col2SumUp.sum() msgbox = QMessageBox(QMessageBox.Information, "Value: %s" % purchaseValue, QMessageBox.Ok)

http://stackoverflow.com/comment/81927775
type: AnswerComment
has text: I am happy that's I could helped you.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47458153

http://stackoverflow.com/a/47554384
accepted answer of: http://stackoverflow.com/q/47536186
has comment: http://stackoverflow.com/comment/82246106
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47536186
downvote count: 0
has comment: http://stackoverflow.com/comment/82115597
score: 5
has body: You have too look at "pixel regions". These are (scantily) described here. Basically, given a layer: You can get a region that covers the layer like this: region=layer.get_pixel_rgn(0, 0, layer.width,layer.height) You can access pixels by indexing: pixel=region[x,y] this returns a string of 1/3/4 bytes (see region.bpp), so for instance a white pixel is returned as '\xff\xff\xff' and a red one as '\xff\x00\x00' (assuming no alpha channel: 3bpp). You can also access areas with slices, so the 4 pixels in the top left corner are: cornerNW=region[0:2,0:2] This returns a string of 12 bytes (16 with alpha-channel) '\xff\x00\x00\xff\x00\x00\xff\x00\x00\xff\x00\x00'. This works in the other direction, you can assign to an area: region[0:2,0:2]='\xff'*12 # set to white Direct layer&lt;>nparray functions A pair of functions I use in my current experiments: # Returns NP array (N,bpp) (single vector ot triplets) def channelData(layer): region=layer.get_pixel_rgn(0, 0, layer.width,layer.height) pixChars=region[:,:] # Take whole layer bpp=region.bpp return np.frombuffer(pixChars,dtype=np.uint8).reshape(len(pixChars)/bpp,bpp) def createResultLayer(image,name,result): rlBytes=np.uint8(result).tobytes(); rl=gimp.Layer(image,name,image.width,image.height,image.active_layer.type,100,NORMAL_MODE) region=rl.get_pixel_rgn(0, 0, rl.width,rl.height,True) region[:,:]=rlBytes image.add_layer(rl,0) gimp.displays_flush()
upvote count: 5
has comment: http://stackoverflow.com/comment/82117622
type: Answer

lxml
tags question: http://stackoverflow.com/q/47399807
tags question: http://stackoverflow.com/q/47460196
tags question: http://stackoverflow.com/q/47449354
tags question: http://stackoverflow.com/q/47427653
type: Tag
tag name: lxml
tags question: http://stackoverflow.com/q/47433632
tags question: http://stackoverflow.com/q/47445236

http://stackoverflow.com/a/47401622
answers question: http://stackoverflow.com/q/47401563
downvote count: 0
type: Answer
has body: It seems you're using a variable occCode when you mean to use x. def stringSlice(x): if type(x) != str: raise Exception("The input is not a string.") elif len(x) != 21: #Note this is where things got changed!!! raise ValueError("The input is not exactly 21 characters.") else: slice1 = x[0:6] slice2 = x[6:12] slice3 = x[13:] return slice1, slice2, slice3
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47401563

http://stackoverflow.com/comment/81742777
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47393181
score: 0
has text: `curl http://127.0.0.1:5000/ --data-urlencode query='SELECT COUNT(*) FROM usage'` is all you need. It'll do a `POST` request with `application/x-www-form-urlencoded` content type. Your endpoint already expects form data and a `POST` method.

http://stackoverflow.com/a/47480218
answers question: http://stackoverflow.com/q/47466227
has body: You can try this: # domain: a valid domain # fields: list if field ex: ['name', 'partner_id'] self.env['address.add'].read_group(domain, fields, groupy=['partner_id']) you can read the documentation in models.py
score: 0
type: Answer

http://stackoverflow.com/q/47491429
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81939243
has title: Swapping two columns in a 2D list
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/81938185
favorite count: 0
answer count: 2
tagged with: nested-lists
has answer: http://stackoverflow.com/a/47491662
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81938803
has body: what would be the quickest way to get to : [[0, 2, 0, 0],\ [0, 2, 0, 0],\ [0, 2, 0, 0],\ [0, 2, 0, 0]] from: [[0, 0, 2, 0],\ [0, 0, 2, 0],\ [0, 0, 2, 0],\ [0, 0, 2, 0]] without using numpy or any other external library
has answer: http://stackoverflow.com/a/47491628
has comment: http://stackoverflow.com/comment/81938127
type: Question

http://stackoverflow.com/a/47492982
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/82089536
has body: It seems like this line returns None: lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=10,maxLineGap=100) And then on the next line for x1,y1,x2,y2 in lines[0] fails, due to lines is None. You need to make sure now that cv2.HoughLinesP() returns correct data or add a check to check like: if lines: for x1,y1,x2,y2 in lines[0]: ...
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81944480
answers question: http://stackoverflow.com/q/47492640

http://stackoverflow.com/a/47500263
answers question: http://stackoverflow.com/q/47500129
upvote count: 2
has body: You can use SAX Streams to get the inner text content of the xml element. SAX is the better way to parse xml without reading the whole XML into the memory aka DOM Python SAX
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/47421043
score: 2
type: AnsweredQuestion
tagged with: timetable
tagged with: pandas
downvote count: 0
answer count: 1
tagged with: scheduled-tasks
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81797275
has body: I am currently working on a small project (Python 3.6.2) for automated timetable creation based on input I crawl from my college website. For creating the timetable and storing the appointments (and later reorganizing them, to find "better" schedules) I currently use Pandas DataFrame structure and am not fully satisfied. I want appointments to occupy multiple cells. 08:55:00 09:40:00 09:50:00 Mod, Spez, Sem 11:30:00 11:40:00 13:20:00 13:30:00 Systemnahe und parallele Programmierung - Ü 01 15:10:00 15:20:00 16:00:00 16:05:00 16:15:00 Modellierung, Spezifikation und Semantik - Ü 02 17:00:00 17:55:00 The first appointment for example takes place from 09:50 to 11:40 and should therefore occupy these slots. A quick solution would be to just put the name of this appointment in every timeslot it occupies but this wouldn't feel and look very clean. I want to export it to Excel when I'm finished. So my question is, how do I accomplish this or am I wrong with using DataFrames all along?
upvote count: 2
has comment: http://stackoverflow.com/comment/81796909
accepted answer: http://stackoverflow.com/a/47421303
has comment: http://stackoverflow.com/comment/81796798
tagged with: python
has comment: http://stackoverflow.com/comment/81796735
has title: Python Pandas Cells with different size
has answer: http://stackoverflow.com/a/47421303

http://stackoverflow.com/a/47491622
has body: Warren Weckesser pointed out that your problems stemmed from missing padding in your NumPy dtype. While it's true that you can fix it manually by adding explicit pad fields, you can also fix it automatically with the align=True option to np.dtype: align : bool, optional Add padding to the fields to match what a C compiler would output for a similar C-struct. Also, you might consider representing your structure in NumPy with nested arrays, for example instead of this: ('qw', np.float32),('qx', np.float32),('qy', np.float32),('qz', np.float32) You could do: ('q', np.float32, 4) Then any value in arr.q will be an array of length 4, which depending on your application may be easier to deal with.
upvote count: 2
answers question: http://stackoverflow.com/q/47491371
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81938560
has comment: http://stackoverflow.com/comment/81938493
has comment: http://stackoverflow.com/comment/81938588
type: Answer

http://stackoverflow.com/a/69650795
upvote count: 3
downvote count: 0
score: 3
type: Answer
has body: The actual issue here is that you have default=uuid.uuid4, where postgres expects a string in UUID format. You'll want something like default=lambda: str(uuid.uuid4())
answers question: http://stackoverflow.com/q/47429929

http://stackoverflow.com/a/47507794
score: 3
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/81971729
has body: Well, i'm not exactly sure that it is what you want, because i never used Anomaly part of your dataset, and just take color info from Score array import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as c d = {'Score': [0.25, 0.52, 0.26, 0.22, 0.31, 2.45, 3.68, 41.3, 87, 91], 'Thr1': 16.5, 'Thr2': 45.5, 'Anomaly': [0, 0, 0, 0, 0, 0, 0, 1, 1, 1]} df = pd.DataFrame(data = d) r = df['Score'] theta = df.index.values fig = plt.figure() ax = fig.add_subplot(111, projection = 'polar') #Add thresholds ax.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*d['Thr1'], c='g', ls='--') ax.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*d['Thr2'], c='r', ls='--') #Add colors colors = ['g' if v &lt; d['Thr1'] else 'y' if v &lt; d['Thr2'] else "r" for v in r] sc = ax.scatter(theta, r, c=colors) plt.show()
downvote count: 0
answers question: http://stackoverflow.com/q/47476809

http://stackoverflow.com/comment/82309900
comment on: http://stackoverflow.com/a/47418070
type: Comment
score: 0
type: AnswerComment
has text: the db transaction should be self.env.db_transaction(""" UPDATE ticket_custom SET value=%s WHERE name=%s AND ticket=%s """, (wikilink, 'recipe_link', ticket.id)) I tried to edit your answer but it was rejected (???)

http://stackoverflow.com/comment/81953127
comment on: http://stackoverflow.com/q/47498458
type: Comment
type: QuestionComment
has text: I don't think that is where the problem is, because it is absolutely working for me just as you have presented it.
score: 0

http://stackoverflow.com/q/47508106
has title: static files doesn't load on cache clear?
score: 1
has body: I have a Django project when I set Debug=true and cache clear when running the static files will not load. If I set it to false the page will load with static files. Any solution to this problem
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47509720
has comment: http://stackoverflow.com/comment/81972046
favorite count: 0
type: Question
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47509720
type: AnsweredQuestion

http://stackoverflow.com/q/47397916
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81749387
has answer: http://stackoverflow.com/a/47417620
tagged with: python
tagged with: pygame
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81749049
upvote count: 2
type: UnansweredQuestion
score: 1
has body: I'm trying to delay one of my enemies shots in my pygame code that is a space invaders/bullet hell game. Unfortunately, I seem to be having a problem with delaying the shot of an enemy. import pygame import random import time import os import threading pygame.time.set_timer ( pygame.USEREVENT , 450 ) event_500ms = pygame.USEREVENT + 1 pygame.time.set_timer(event_500ms, 500) class Alien2 (pygame.sprite.Sprite): def __init__(self): # Call the parent class (Sprite) constructor super().__init__() self.image = pygame.Surface([20, 15]) self.image = pygame.image.load("alien3.png").convert() self.image.set_colorkey(WHITE) self.rect = self.image.get_rect() def update(self): pos = pygame.mouse.get_pos() dx = pos[0] - self.rect.x + 18 dx *= .05 self.rect.x += dx def BossPowers(): bullet3 = Bullet3() # Set the bullet so it is where the player is bullet3.rect.x = alien2.rect.x + 47 bullet3.rect.y = alien2.rect.y + 57 # Add the bullet to the lists all_sprites_list.add(bullet3) bullet2_list.add(bullet3) def BossPowers2(): bullet4 = Bullet4() # Set the bullet so it is where the player is bullet4.rect.x = alien2.rect.x + 47 bullet4.rect.y = alien2.rect.y + 57 # Add the bullet to the lists all_sprites_list.add(bullet4) bullet2_list.add(bullet4) def delay(): #threading.Timer(5.0, delay).start() bullet2 = Bullet2() # Set the bullet so it is where the player is bullet2.rect.x = alien2.rect.x + 47 bullet2.rect.y = alien2.rect.y + 57 # Add the bullet to the lists all_sprites_list.add(bullet2) bullet2_list.add(bullet2) BossPowers() BossPowers2() Ignore my spaghetti code here, I've been working on this game for a bit, and sometimes being efficient slips my mind while not done: # --- Event Processing for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if level % 2 == 0: all_sprites_list.add(alien2) alien2_list.add(alien2) for block in block_list: block_list.remove(block) all_sprites_list.remove(block) #t = threading.Timer(2, delay) #t.start() #if event.type == event_50…
has comment: http://stackoverflow.com/comment/81789120
has answer: http://stackoverflow.com/a/47401345
has title: Delaying an enemies shot
tagged with: delay
has comment: http://stackoverflow.com/comment/81749117

http://stackoverflow.com/comment/81799484
has text: How do I set those paths to my system?
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47422458

http://stackoverflow.com/a/47537982
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47535406
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47535406
has comment: http://stackoverflow.com/comment/82045012
has comment: http://stackoverflow.com/comment/82691040
type: AcceptedAnswer
has body: nested_list = [[a, a + 1], [a + 2, a + 3]] produces 3 new arrays (the sums) plus a list of pointers to those arrays. That's just basic Python interpreter action. b = np.array(nested_list): np.array is a complex compiled function, so without some serious digging it is hard to tell exactly what it does. My impression from previous use, and especially errors when components don't exactly match in size, is that it scans the input to determine the highest-dimensional array that it can create, and then plugs the pieces in, with type conversions if needed. It's easy to do time comparisons; harder to track memory use. But assuming that data copying is the biggest time consumer, time tests are probably a good proxy for memory use. And unless we are hitting memory errors, we are usually more concerned with time than memory use. In [565]: alist = [[a,a+1],[a+2,a+3]] In [566]: allist = [[a.tolist(), (a+1).tolist()],[(a+2).tolist(), (a+3).tolist()]] In [567]: timeit np.array(alist) 6.74 µs ± 63.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [568]: timeit np.array(allist) 9.92 µs ± 286 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Working from the nested list of arrays is a bit faster than working from the pure list equivalent. It may be copying those arrays to the target as blocks. Individual stacks is noticeably slower, though it also creates the a+n arrays as well: In [569]: timeit c = np.vstack([np.hstack([a, a + 1]), np.hstack([a + 2, a + 3])]) 37.8 µs ± 39 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) np.stack acts the same as np.array (with the default axis). It too uses concatenate: In [570]: timeit np.stack(alist) 28.7 µs ± 262 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) Including the a+n calculations into the timing may be fairer: In [571]: %%timeit ...: alist = [[a,a+1],[a+2,a+3]] ...: np.stack(alist) ...: 38.6 µs ± 509 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [572]: %%timeit ...: alist = …
type: Answer

http://stackoverflow.com/comment/82081801
type: AnswerComment
comment on: http://stackoverflow.com/a/47561073
score: 0
has text: I would like the output to be printed to `stdout` and not `stderr`, as I treat the two streams differently. Also, the program seems to hang, probably because of the non-closed thread. Could you fix these issues?
type: Comment

http://stackoverflow.com/comment/81918324
type: QuestionComment
comment on: http://stackoverflow.com/q/47480111
type: Comment
score: 1
has text: They're negative numbers, they're not increasing.

http://stackoverflow.com/q/47463277
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47463422
linked to: http://stackoverflow.com/q/5122465
accepted answer: http://stackoverflow.com/a/47468265
type: Question
has body: I have a setup.py file like this (not in pwd, not in Python path, a random file somewhere): import ext_modules config = { 'name': 'mesos.executor', 'version': '1.4.1', 'description': 'Mesos native executor driver implementation', 'author': 'Apache Mesos', 'author_email': 'dev@mesos.apache.org', 'url': 'http://pypi.python.org/pypi/mesos.executor', 'namespace_packages': [ 'mesos' ], 'packages': [ 'mesos', 'mesos.executor' ], 'package_dir': { '': 'src' }, 'install_requires': [ 'mesos.interface == 1.4.1' ], 'license': 'Apache 2.0', 'keywords': 'mesos', 'classifiers': [ ], 'ext_modules': [ ext_modules.executor_module ] } from setuptools import setup setup(**config) And from an external (Python) script I'd like to import config["install_requires"]. I'm looking for the most minimalist way of doing this as it's intended to be run from other scripts that might even not be Python. A Python one-liner would be awesome.
has answer: http://stackoverflow.com/a/47468265
has comment: http://stackoverflow.com/comment/81881348
tagged with: python
possible better answer: http://stackoverflow.com/a/47463422
favorite count: 0
has title: Import a variable from setup.py from an external script
tagged with: python-import

http://stackoverflow.com/comment/81994868
score: 1
comment on: http://stackoverflow.com/a/47481098
has text: Nice! Numba is pretty amazing sometimes.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82752753
type: Comment
comment on: http://stackoverflow.com/a/47503449
score: 0
type: AnswerComment
has text: @Alexander sorry for the late reply, found a lot of stuff here I didn't understand so spent the time to learn about it. This solution, with some minor tweaks, worked as intended. Thanks!

http://stackoverflow.com/a/47479579
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47479468
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47479468
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81914366
has body: The argument shell=True will only execute the command in a shell, in the default shell in your system /bin/sh. To start a new terminal window, you need to specify the terminal: subprocess.Popen(["xterm", "python"]) The above line opens a new xterm terminal window and executes python command in it.

http://stackoverflow.com/a/47523867
downvote count: 0
answers question: http://stackoverflow.com/q/47523823
score: 3
type: Answer
has body: argmin will return the index of the smallest element of the array passed; however, because this array starts at 20, you will need to add that starting point of your sublist, to obtain the index of the same smallest element in the original array: start = 20 print(np.argmin(L[start:]) + start)
upvote count: 3

http://stackoverflow.com/comment/81928814
score: 0
has text: I'd suggest filtering on `key` rather than `lineno` -- as I read it, the change at https://github.com/keimina/python_trace/commit/5ea2cfff31ec1ace4a2e6ca3f3c76f83218e52d7 would ignore a call from a function in one module to a function in another, if the callee is at the same line as the caller. Otherwise, though, that looks like a good fix.
type: Comment
comment on: http://stackoverflow.com/a/47485323
type: AnswerComment

http://stackoverflow.com/q/47503071
has answer: http://stackoverflow.com/a/47503348
answer count: 4
favorite count: 0
type: Question
score: 2
tagged with: list
has comment: http://stackoverflow.com/comment/81962017
tagged with: for-loop
upvote count: 2
downvote count: 0
has body: I'm trying to create a big list that will contain lists of strings. I iterate over the input list of strings and create a temporary list. Input: ['Mike','Angela','Bill','\n','Robert','Pam','\n',...] My desired output: [['Mike','Angela','Bill'],['Robert','Pam']...] What i get: [['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...] Code: for i in range(0,len(temp)): temporary = [] while(temp[i] != '\n' and i&lt;len(temp)-1): temporary.append(temp[i]) i+=1 bigList.append(temporary)
has title: While loop within for loop for list of lists
accepted answer: http://stackoverflow.com/a/47503108
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47503108
linked to: http://stackoverflow.com/q/4322705
possible better answer: http://stackoverflow.com/a/47503101
has answer: http://stackoverflow.com/a/47503231
has answer: http://stackoverflow.com/a/47503101
tagged with: python

http://stackoverflow.com/comment/81729215
type: Comment
type: QuestionComment
has text: Yes, BST is british summer time which is 1 hour ahead of GMT.
score: 0
comment on: http://stackoverflow.com/q/47387009

http://stackoverflow.com/q/47423213
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81802166
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81814537
has comment: http://stackoverflow.com/comment/81801696
type: Question
has comment: http://stackoverflow.com/comment/133799317
has title: Custom readonly_fields and has_delete_permission on Django admin TabularInline
tagged with: django-admin
type: UnansweredQuestion
has body: I have an admin.TabularInline. I need to configure dinamically readonly_fields and I need to enable or disable deleting with has_delete_permission checking some fields in current object. Is possible this? What have I check in this method ? def has_delete_permission(self, request, obj=None): Where can I found che current saved object (not parent object)?

http://stackoverflow.com/a/47471794
has comment: http://stackoverflow.com/comment/81898150
downvote count: 0
answers question: http://stackoverflow.com/q/47471725
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81898574
has comment: http://stackoverflow.com/comment/81898267
type: Answer
has body: You need to use set method when changing a StringVar's value. as in replace: y = value with: y.set(value)
accepted answer of: http://stackoverflow.com/q/47471725
upvote count: 2
score: 2

http://stackoverflow.com/a/47463700
downvote count: 0
has body: In your program test is a string. Strings normally don't get quoted when dumped, but if their interpretation would be ambiguous, they will be. That is the reason why your output has the single quotes around them: to make sure that on reading back in this node is not incorrectly interpreted as a mapping instead of a string. Removing the non-existent quotes with .strip() therefore doesn't do anything. You should work backwards from what you what you want to accomplish (you actually want a mapping instead of a string, as one can see from the output). If you load your desired output, you will see that the value for test1_routable_net is a python dict (or a subclass thereof), so make sure that is what you assign to test: import sys import ruamel.yaml yaml = ruamel.yaml.YAML() test = { 'get_param': 'abc_routable_net' } with open('./test1.yaml') as fp: data = yaml.load(fp) data['resources'].update({'test1_routable_net': test}) yaml.dump(data, sys.stdout) Which gives: resources: name:{get_param: vname} ssh_keypair: {get_param: ssh_keypair} test1_routable_net: get_param: abc_routable_net This is semantically the same as your desired output, but since you want the get_param: abc_routable_net in flow-style, you could add: yaml.default_flow_style=None to get your desired output. You can also look at assigning, to test, a ruamel.comments.CommentedMap, which gives you more fine grained control over its style (and comments, etc.).
answers question: http://stackoverflow.com/q/47441501
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/81961159
type: Comment
type: QuestionComment
has text: for example I delete the else statement and nothing printed
score: 0
comment on: http://stackoverflow.com/q/47502650

http://stackoverflow.com/comment/81933908
score: 0
has text: @hpaulj: for my education, is it discouraged because it doesn't append in place?
type: Comment
comment on: http://stackoverflow.com/q/47487763
type: QuestionComment

http://stackoverflow.com/comment/81777063
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47411872
has text: But since the images can have different width and height, the shapes are not uniform of the images.

http://stackoverflow.com/a/47418807
has body: You could use an simple function: def searchList(term,searchlist): for row in range(len(searchlist)): if term in searchlist[row][0]['bu']: return row
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47417364

http://stackoverflow.com/q/47441351
tagged with: python
possible better answer: http://stackoverflow.com/a/58986339
has title: Using Paramiko with SOCKS proxy
tagged with: paramiko
has answer: http://stackoverflow.com/a/58986339
tagged with: proxy
type: AnsweredQuestion
score: 7
tagged with: ssh
tagged with: socks
upvote count: 7
favorite count: 0
accepted answer: http://stackoverflow.com/a/47448612
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47448612
has body: I an trying to use Paramiko with SOCKS proxy (SecureCRT or PuTTY configured as SOCKS proxy). I am using the below code import paramiko,socks host, port = '127.0.0.1', 1080 # Set up your proxy information for this socket sock=socks.socksocket() sock.set_proxy( proxy_type=socks.SOCKS4, addr=host, port=port, ) # Connect the socket sock.connect((host, port)) # Create your Paramiko Transport transport = paramiko.Transport(sock) transport.connect( username='username', #<------not sure if it is needed, the socks proxy needs no username/password password='secret', ) client = paramiko.client.SSHClient.connect('remotedevice', username='usernameonremotedevice',sock=sock) stdin, stdout, stderr=client.exec_command("ls -la") # Do stuff # Clean up client.close() transport.close() The above approach seems to confuse Paramiko since it is using 127.0.0.1 for both. My issue originated in the Paramiko libraries used by Exscript so I wanted to simplify to see if this would work .... This is the log that SecureCRT shows with each attempt [LOCAL] : Starting port forward from 127.0.0.1 on local 127.0.0.1:1080 to remote 127.0.0.1:1080. [LOCAL] : Could not start port forwarding from local service 127.0.0.1:3106 to 127.0.0.1:1080. Reason: The channel could not be opened because the connection failed. Server error details: Connection refused The script fails like below: Traceback (most recent call last): File "C:\Users\Username\Documents\Eclipse\ESNetworkDiscovery\ParamikoProxyTest.py", line 24, in <module> sock.connect((host, port)) File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 96, in wrapper return function(*args, **kwargs) File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 813, in connect negotiate(self, dest_addr, dest_port) File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 667, in _negotiate_SOCKS4 raise SOCKS4Error("{0:#04x}: {1}".format(status, error)) socks.SOCKS4Error: 0x5b: Request rejected or failed
linked to: http://stackoverflow.com/q/10670217
downvote count: 0

http://stackoverflow.com/a/47455437
answers question: http://stackoverflow.com/q/47437197
has body: Since version 4.5 Tornado will close the connection automatically if it receives more than 10 MiB of data in a single websocket frame (message). So, you don't have to worry about someone sending huge data in a single message. You can see this in the source code. It's also mentioned in the docs of WebsocketHandler in the second-last paragraph. If you'd like to change the default frame limit you can pass your Application class an argument called websocket_max_message_size with the size in bytes. app = tornado.web.Application( # your handlers etc, websocket_max_message_size=128 )
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/47437197
type: Answer

http://stackoverflow.com/a/47438906
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47438715
has body: You can use itertools.groupby and dateutils in Python3: import itertools s = [ ["1", "someone", "cool", "RO", "AC", "SKST", "yes", "2/24/2017 0:00", "2/24/2017 10:51"], ["102", "another", "person", "RO", "AC", "SKST", "No", "1/26/2015 15:54", "1/26/2015 15:54"], ["102", "another", "person", "RO", "AC", "SKST", "NO", "6/29/2015 0:00", "6/29/2015 12:36"], ["102", "another", "person", "RO", "AC", "SKST", "yes", "8/31/2017 0:00", "8/31/2017 13:12"], ["62", "again", "someoneelse", "RO", "AC", "SKST", "No", "1/30/2017 0:00", "1/30/2017 13:49"], ] new_data = [(a, sorted([i[1:] for i in list(b)], key=lambda x:dateutil.parser.parse(x[-1]))) for a, b in itertools.groupby(sorted(s, key=lambda x:x[0]), key=lambda x:x[0])] final_data = [[a]+b[-1] for a, b in new_data] for i in final_data: print(i) Output: ['1', 'someone', 'cool', 'RO', 'AC', 'SKST', 'yes', '2/24/2017 0:00', '2/24/2017 10:51'] ['102', 'another', 'person', 'RO', 'AC', 'SKST', 'yes', '8/31/2017 0:00', '8/31/2017 13:12'] ['62', 'again', 'someoneelse', 'RO', 'AC', 'SKST', 'No', '1/30/2017 0:00', '1/30/2017 13:49']
score: 1

http://stackoverflow.com/q/47408891
downvote count: 0
answer count: 1
has body: I use wand-py but I can't write into Image.metadata , what shoud I do?
favorite count: 0
type: Question
has title: How to remove image metadata using wand python
tagged with: python
tagged with: image
score: 2
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47409215
tagged with: wand
tagged with: metadata
upvote count: 2
has answer: http://stackoverflow.com/a/47409215

http://stackoverflow.com/comment/81885780
score: 0
type: AnswerComment
has text: Thanks so much. But `rect = np.where(img==1)` or `rect = np.where(img==255)`? Because output of the function `skimage.transform.rotate` return value between 0 to 1
comment on: http://stackoverflow.com/a/47465514
type: Comment

http://stackoverflow.com/comment/81858295
has text: Exactly my thought. Best way to deal with this imo.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47451735

http://stackoverflow.com/comment/81845615
comment on: http://stackoverflow.com/a/47438167
type: Comment
score: 0
type: AnswerComment
has text: Thank you for this great explanation! Unfortunately I cant upvote your answer because I’m a newbie :(. I will upvote it as soon as I have the rights. Upvoting my question will help me upvoting you ;)

http://stackoverflow.com/q/47410196
has comment: http://stackoverflow.com/comment/81773814
has comment: http://stackoverflow.com/comment/81773796
downvote count: 5
tagged with: python
has title: python shorter code to get list value
type: AnsweredQuestion
tagged with: list
score: -5
upvote count: 0
answer count: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/81773926
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47410335
has body: year=[1,2,3,5,4,5,5] name=["alex","tom","amy","mary","peter","david","tim"] maxyear=([i for i, x in enumerate(year) if x == max(year)]) I want these code below shorter,wanna write in one line only,like I defiened the maxyear list. oldername=[] for i in maxyear: oldername.append(name[i])
has answer: http://stackoverflow.com/a/47410335

http://stackoverflow.com/q/47430544
answer count: 6
tagged with: google-colaboratory
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72481939
tagged with: pandas
tagged with: pydrive
has title: Load xlsx file from drive in colaboratory
downvote count: 0
possible better answer: http://stackoverflow.com/a/63330622
linked to: http://stackoverflow.com/q/48697643
has answer: http://stackoverflow.com/a/77209232
has body: How can I import MS-excel(.xlsx) file from google drive into colaboratory? excel_file = drive.CreateFile({'id':'some id'}) does work(drive is a pydrive.drive.GoogleDrive object). But, print excel_file.FetchContent() returns None. And excel_file.content() throws: TypeErrorTraceback (most recent call last) in () ----> 1 excel_file.content() TypeError: '_io.BytesIO' object is not callable My intent is (given some valid file 'id') to import it as an io object, which could be read by pandas read_excel(), and finally get a pandas dataframe out of it.
score: 13
has answer: http://stackoverflow.com/a/70515007
has answer: http://stackoverflow.com/a/63330622
tagged with: excel
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47440841
has answer: http://stackoverflow.com/a/66280555
has answer: http://stackoverflow.com/a/47440841
tagged with: python

http://stackoverflow.com/a/47422300
answers question: http://stackoverflow.com/q/47422178
has body: I prefer a list comprehension: l = [{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}, {'type' : 'truck'...} d = [d for d in l if (key, value) in d.items() and (key, value) in d.items()]
type: Answer
score: 0

http://stackoverflow.com/q/47536287
answer count: 4
has comment: http://stackoverflow.com/comment/82029677
has answer: http://stackoverflow.com/a/47536452
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47536473
has answer: http://stackoverflow.com/a/47536722
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82029924
has answer: http://stackoverflow.com/a/47536532
has title: Python text file into dictionary not working
has comment: http://stackoverflow.com/comment/82029591
has body: So the file text, which I'm supposed to transfer to a dictionary for a phonebook, looks like this: Name1 Name2 Numbers Name3 Name4 Numbers2 and so on.. What I've tried: def read(): file1=open("file.txt","r") dict={} for line in file1: line=line.split() if not line:continue dict[line[0]]=line[1:] print(dict) When I run it, it prints nothing. Thank you!
tagged with: phonebook
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/81780539
score: 0
has text: OMG, I found an error in my initial question. If "--headless" is enabled, then I get errors and strange behaviour. When it is not, it is OK, but I want to run headless.
comment on: http://stackoverflow.com/q/47391823
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81795662
has text: @Sayse The mystery has vanished FYI :)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47415234

http://stackoverflow.com/a/47530714
type: Answer
has body: If you want it manually for last four months of the year today = datetime.today() months = [today.replace(month=m).strftime(format) for m in range(9,13)] Returns ['September 2017', 'October 2017', 'November 2017', 'December 2017']
accepted answer of: http://stackoverflow.com/q/47530422
score: 1
has comment: http://stackoverflow.com/comment/82100433
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47530422

http://stackoverflow.com/comment/81847504
type: Comment
comment on: http://stackoverflow.com/a/47441507
has text: That's the bytes literal, which indicates the data is not a string (caused because you encoded data to UTF-8. Python ignores that in comparisons etc, so it should not be a worry. If you want to remove it though, try solution added above.
type: AnswerComment
score: 0

http://stackoverflow.com/a/47539109
score: 0
answers question: http://stackoverflow.com/q/47538605
type: Answer
has body: Basically you need to count how many songs get put into the playlist, which is easy because at any given time its length is len(playlist). You're also not taking much advantage of the csv module, nor how Python will automatically close files if you use the with statement when opening them. Here's essentially a rewrite of your code show how to do all these things: import random import csv genre_list = "Pop","Rock","Rap" random_genre = random.choice(genre_list) name = input("Enter name for the playlist: ") MAX_SONGS = 5 playlist = [] with open("song.csv", "r", newline="") as file: for row in csv.reader(file): if row[2] == random_genre: playlist.append(row) if len(playlist) &gt;= MAX_SONGS: break print(playlist) newfilename = name + ".csv" with open(newfilename, "w", newline="") as newfile: writer = csv.writer(newfile) writer.writerows(playlist) print("done!")

http://stackoverflow.com/comment/81754962
type: QuestionComment
has text: Thank you. But I get a "IndexError: list index out of range" when I run the code now. It's so weird. This code is presented in a book.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47400620

http://stackoverflow.com/comment/81907622
type: Comment
has text: Could you provide more details? This code is running without an issue, I think something related to your file system is broken while running the code.
score: 2
comment on: http://stackoverflow.com/q/47476304
type: QuestionComment

http://stackoverflow.com/q/47488016
possible better answer: http://stackoverflow.com/a/47488403
has body: So I have a python script (let's call it file_1.py) that overwrites the content of a text file with new content, and it works just fine. I have another python script (file_2.py) that reads the file and performs actions on the data in the file. With file_2.py I've been trying to get when the text file is edited by file_1.py and then do some stuff with the new data as soon as it's added. I looked into the subprocess module but I couldn't really figure out how to use it across different files. Here's what I have so far: file_1.py: with open('text_file.txt','w') as f: f.write(assemble(''.join(data))) # you can ignore what assemble does, this part already works. file_2.py: while True: f = open('text_file.txt','r') data = f.read() function(data) f.close() I thought that since I close and reopen the file every loop, the data in the file would be updated. However, it appears I was wrong, as the data remains the same even though the file was updated. So how can I go about doing this?
tagged with: text-files
has answer: http://stackoverflow.com/a/47488403
type: Question
answer count: 2
upvote count: 1
has title: Getting when a text file is edited by another program
has answer: http://stackoverflow.com/a/47488321
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/47488321

http://stackoverflow.com/a/47469492
accepted answer of: http://stackoverflow.com/q/47469433
score: 3
answers question: http://stackoverflow.com/q/47469433
type: Answer
has body: Extract my_dict's values as a list of lists* Join each sub-list together (flatten dict_values) to form a flat list Sort each element by commit_number *list of lists on python2. On python3, a dict_values object is returned. from itertools import chain res = sorted(chain.from_iterable(my_dict.values()), key=lambda x: x['commit_number'], reverse=True) [{'commit_number': '15', 'name': 'anna'}, {'commit_number': '14', 'name': 'john'}, {'commit_number': '12', 'name': 'jack'}, {'commit_number': '11', 'name': 'andy'}, {'commit_number': '10', 'name': 'steve'}] On python2, you'd use dict.itervalues instead of dict.values to the same effect.
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47514876
answers question: http://stackoverflow.com/q/47447116
type: Answer
has body: While Klipfolio does not have any Python integrations, Klipfolio does connect to various types of SQL databases. One work around is to dump your processed data from Python into a SQL database and then connect that SQL database with Klipfolio to make data sources to build the visualization.
score: 0

http://stackoverflow.com/comment/81863725
type: AnswerComment
comment on: http://stackoverflow.com/a/47452563
score: 0
has text: I tried to change it to: ar=pandas.read_csv(fname, sep = '(\.\w+\s\d+\:)') no luck.
type: Comment

http://stackoverflow.com/comment/81910274
comment on: http://stackoverflow.com/q/47477371
type: Comment
type: QuestionComment
score: 0
has text: What is the value of "latent_size"?

http://stackoverflow.com/a/47521390
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47521187
has body: You can retrieve the information from coinmarketcap using their API. https://coinmarketcap.com/api/ This will allow you to request data from them, sometimes with given parameters (e.g. the currency) and you'll retrieve the data in a JSON format, which you can then again parse and display with python. There are plenty of API tutorials out there for python on the web. Good luck!
score: 0
answers question: http://stackoverflow.com/q/47521187

http://stackoverflow.com/q/47453010
has answer: http://stackoverflow.com/a/47455241
has title: Scrapy - close method body is not executed
score: 0
has answer: http://stackoverflow.com/a/47453177
tagged with: web-scraping
tagged with: scrapy
type: Question
answer count: 2
type: UnansweredQuestion
has body: Can't figure out why my close method is not being executed. I have to process two lists of urls. One list have to be processed first and exported and the second list should be processed then. The problem is that close method is just called (breakpoint stops at the def ) but not executed. Do you know why? # coding=utf-8 from bot.items import TestItem from scrapy import Spider, Request, signals from scrapy.exceptions import DontCloseSpider from scrapy.xlib.pydispatch import dispatcher class IndexSpider(Spider): name = 'index_spider' allowed_domains = ['www.doman.org'] def start_requests(self): for url in ["https://www.doman.org/eshop"]: yield Request(url, callback=self.parse_main_page) def parse_main_page(self, response): self.categories = [some tuples] self.subcategories = [some tuples] def close(self, spider): # Execution ends here pass # This is not being executed if self.categories: for cat in self.categories: url = "https://www.doman.org/search/getAjaxResult?categoryId={}".format(cat[0]) yield Request(url, meta={'tup': cat, 'priority': 0}, priority=0, callback=self.parse_category) self.categories = [] raise DontCloseSpider
tagged with: python

http://stackoverflow.com/a/47495744
answers question: http://stackoverflow.com/q/47495596
upvote count: 3
has body: Why not use functions and cut down on some duplication in the process? def ask_input(prompt, error_msg, validation_fn): while True: data = raw_input(prompt) if validation_fn(data): return data print(error_msg) name = ask_input("NAME PLEASE\n", "Please chars dude", lambda x: x.isalpha()) age = ask_input("Please type your age\n", "Please digits only", lambda x: x.isdigit()) In this case, the prompt (what to ask the user), an error message (what to provide on invalid input), and a validation function are provided to the ask_input() function. This hides the while loop behind the function call and gives you something more meaningful to read in the code. The lambda functions are just an easy way to help do the validation. You could do this instead: def isalpha(x): return x.isalpha() def isdigit(x): return x.isdigit() name = ask_input("NAME PLEASE\n", "Please chars dude", isalpha) age = ask_input("Please type your age\n", "Please digits only", isdigit)
type: Answer
downvote count: 0
score: 3

http://stackoverflow.com/a/47502548
has comment: http://stackoverflow.com/comment/81997377
upvote count: 2
has body: Firstly, you seem to be using the 'flame' feature of Pyro4, which requires the pickle serialization protocol. This is powerful, but not without problems. Are you sure you want/need to use flame? I hope you are aware of its security implications. http://pyro4.readthedocs.io/en/latest/flame.html Now, your actual question consists of three parts (try to make your future questions more about just a single issue, that makes answering them a lot simpler) To answer the first part of your question: As you already found out yourself, you cannot assume that all types can just be transported over the network and magically just work on the other side. Especially with pickle this only works if the module in which the type is defined, is available on both sides. In your case, it seems that the psutil module is not available on your client side, hence the pickle error when it tries to deserialize the object returned by psutil.cpu_times(). The solution could be to install psutil on your client side as well. You also discovered an alternative solution: don't pass objects of custom types over the wire, but stick to builtin types as much as possible. When you convert the result to a tuple or list or dict, these can be serialized and deserialized without any issues (if all the objects they contain are of a builtin type as well). To answer the second part of your question: This code looks like you're trying to find a workaround for the problem in the first question? Anyway, the error should be clear; it means what it says: that the remote object your proxy is connected to, doesn't have the method exposed that you're trying to call. You should add a @Pyro4.expose decoration to properly expose it. That said, you're already using Flame, so why aren't you using its remote module feature? See http://pyro4.readthedocs.io/en/latest/flame.html#flame-object-and-examples For example (I assume you installed psutil on the client side): import Pyro4.utils.flame Pyro4.config.SERIALIZER = "pickle" fla…
accepted answer of: http://stackoverflow.com/q/47486024
has comment: http://stackoverflow.com/comment/81969566
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81982688
answers question: http://stackoverflow.com/q/47486024

http://stackoverflow.com/q/47521958
answer count: 1
has comment: http://stackoverflow.com/comment/82000693
has comment: http://stackoverflow.com/comment/82000640
favorite count: 0
has body: I'm currently coding a program that is supposed to: 1) Open a file which has names along with grades on each line (I have successfully done this and put the contents of each line into an array). 2) Evaluate the data and find the max, min, and average. I am stuck in the second part because if I try to use the max or min function pertaining to the array, I have an error code that pops up, since the values in the array are technically a string. So my question is how do I only get the value of the numbers? Would a parallel list be more useful and if so how would I implement that? Here's my code so far: def getGrades(filename): try: gradeArray = [] with open("Grades.txt", "r") as f: for line in f: gradeArray.append(line.find()) except: print("Could not open", filename) return(gradeArray)
type: Question
has comment: http://stackoverflow.com/comment/82000434
has answer: http://stackoverflow.com/a/47522086
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82000825
tagged with: python
has comment: http://stackoverflow.com/comment/82000426
upvote count: 2
has title: Python File reading and writing
score: 0
downvote count: 2

firefox
type: Tag
tags question: http://stackoverflow.com/q/47394510
tag name: firefox

http://stackoverflow.com/comment/81887913
type: QuestionComment
comment on: http://stackoverflow.com/q/47408608
has text: @ChrisMartin, thanks for the link. I guess it is a RAM problem (based on htop)
score: 0
type: Comment

http://stackoverflow.com/q/47455454
has comment: http://stackoverflow.com/comment/81893888
has answer: http://stackoverflow.com/a/47472449
has body: I am trying to index matrix based on the size. I am getting TypeError: argument has wrong size in images[i,:] = img[ind[i]*rows*cols:(ind[i]+1)*rows*cols] loop, not sure what is going on there. But the labels[i] = lbl[ind[i]] works fine. def read(digits, target_index): rows=28 cols=28 #lbl = array("b", reformatData['target']) if target_index == -1: data = dataset[:, :-1] target = dataset[:, -1] elif target_index == 0: data = dataset[:, 1:] print "data size: ", data.size,"length", type(data) #output: data size: 791840 length &lt;type 'numpy.ndarray'&gt; target = dataset[:, 0] print "data size: ", target.size,"length", type(target) #output data size: 1010 length &lt;type 'numpy.ndarray'&gt; lbl =np.asarray(target.flatten()) print "length labell", lbl.size, "length", type(lbl) # output length labell 1010 length &lt;type 'numpy.ndarray'&gt; img=np.asarray(data[0].flatten()) print "length of image: ",img.size, "length", type(img) #output length of image: 784 length &lt;type 'numpy.ndarray'&gt; ind = [ k for k in xrange(lbl.size) if lbl[k] in digits] print "index length ", len(ind), "length", type(ind) #output index length 1010 length &lt;type 'list'&gt; images = matrix(0, (len(ind), rows*cols)) print "images length ", images.size, "images type", type(images) #output: images length (1010, 784) images type &lt;type 'cvxopt.base.matrix'&gt; labels = matrix(0, (len(ind), 1)) print "lables length ", labels.size, "labels type", type(labels) #output: lables length (1010, 1) labels type &lt;type 'cvxopt.base.matrix'&gt; for i in xrange(len(ind)): images[i,:] = img[ind[i]*rows*cols:(ind[i]+1)*rows*cols] #output: see error below labels[i] = lbl[ind[i]] return images, labels print read(digits=digits1, target_index=target_index) Traceback (most recent call last): File "svm.py", line 79, in &lt;module&gt; print read(digits=digits1, target_index=target_index) File "svm.py", line 74, in read images[i,:] = img[ind[i]*rows*cols:(ind[i]+1)*rows*cols] TypeError: argument has wrong size sam…
upvote count: 0
has comment: http://stackoverflow.com/comment/81868106
has title: TypeError: argument has wrong size
answer count: 1
tagged with: scikit-learn
tagged with: svm
favorite count: 0
has comment: http://stackoverflow.com/comment/81868797
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81867235
type: UnansweredQuestion
tagged with: python
score: -1
downvote count: 1

http://stackoverflow.com/q/47442086
type: Question
has comment: http://stackoverflow.com/comment/81840873
answer count: 0
type: UnansweredQuestion
has body: There is TensorFlow tutorial code here that goes over how to load MNIST images. I modified it slightly for my own usage. My goal: plot the first MNIST training image and save it. I am working on a remote system, and I can't get the display to work, so I just want to save the image without looking at it first. Here's what I have so far: import numpy as np from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import argparse import matplotlib matplotlib.use('pdf') import matplotlib.pyplot as plt def get_data(): #Import data, return training data mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) return mnist.train.images if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default="/tmp/mnist/data") FLAGS, unparsed = parser.parse_known_args() x_data = get_data() #first training image is x_data[0], has shape (784,) first_image = x_data[0] first_image = np.array(first_image, dtype='float') pixels= first_image.reshape((28,28)) mnist_fig = plt.figure() plt.plot(pixels) plt.imshow(pixels, cmap="gray") savefig_val = "first_image" mnist_fig.savefig(savefig_val+".pdf") And here is the image that is produced: Problems: I'm pretty sure that's supposed to be a clearly recognizable digit, and it isn't. It also shouldn't have colours across the top of the image.
has comment: http://stackoverflow.com/comment/81840732
tagged with: python
has title: MNIST: plot first training image and save using matplotlib
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81840200
tagged with: tensorflow

discord
tags question: http://stackoverflow.com/q/47509597
tag name: discord
tags question: http://stackoverflow.com/q/47448401
type: Tag
tags question: http://stackoverflow.com/q/47404166
tags question: http://stackoverflow.com/q/47441564
tags question: http://stackoverflow.com/q/47521971
tags question: http://stackoverflow.com/q/47496850
tags question: http://stackoverflow.com/q/47382772

http://stackoverflow.com/q/47435904
has comment: http://stackoverflow.com/comment/81826345
has comment: http://stackoverflow.com/comment/81826620
has title: Loop in python script preventing webpage reloading
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81826241
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81826193
answer count: 0
has comment: http://stackoverflow.com/comment/81826954
has comment: http://stackoverflow.com/comment/81826146
type: UnansweredQuestion
has body: Afternoon all, I have a webpage that is being used to write NFC tags. When I submit the form on the page PHP sends the variables to the python script. This script (write.py) checks that the read.py script is killed and processes the write request. This part works fine. The issue I have is when I recall the read.py, it contains a loop which is preventing the web page from refreshing once the write is complete. I have tried calling the read.py from inside the PHP script and at the end of the write.py and the same thing happens. I have also tried adding a & to the end of the read.py command. Could someone please have a look at what I have so far and let me know what I am doing wrong and how I would go about fixing it please. Cheers, Blinky HTML/PHP <?php session_start(); if( !empty( $_POST ) ) { echo "Write to card using python"; $company = $_POST[ 'company' ]; $name = $_POST[ 'name' ]; $email = $_POST[ 'email' ]; $cmd = "sudo python write.py '$company' '$name' '$email' &"; $resp = shell_exec( $cmd ); if( strpos( $resp, 'written' ) !== false ) { header("Location: http://192.168.1.176/index.php"); } unset( $_POST ); } ?> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post"> 1 2 3 4 read.py #!/usr/bin/env python # -*- coding: utf8 -*- import RPi.GPIO as GPIO import MFRC522 import signal import MySQLdb import os from datetime import datetime os.system("sudo kill $(ps aux | grep 'write.py' | awk '{print $2}')") db = MySQLdb.connect(host="", user="", passwd="", db="") cursor = db.cursor() continue_reading = True # Capture SIGINT for cleanup when the script is aborted def end_read(signal,frame): global continue_reading print "Ctrl+C captured, ending read." continue_reading = False GPIO.cleanup() # Hook the SIGINT signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 MIFAREReader = MFRC522.MFRC522() # Welcome message print "Welcome to the MFRC522 data read example" print "Press Ctrl-C to stop." # This loop keeps checking for chips. If one …
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81826114
tagged with: php
has comment: http://stackoverflow.com/comment/81826852
linked to: http://stackoverflow.com/q/3595685
has comment: http://stackoverflow.com/comment/81826595
tagged with: python-2.7

http://stackoverflow.com/q/47529097
upvote count: 4
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/82016456
accepted answer: http://stackoverflow.com/a/47529924
has body: I have a following file structure: mymodule/ __init__.py mylib.py test.py File mymodule/__init__.py: # mymodule/__init__.py def call_me(): module = __import__('.mylib') module.my_func() File mymodule/mylib.py: # mymodule/mylib.py def my_func(): print("hi!") File test.py: # test.py from mymodule import call_me call_me() If I run python3 test.py it fails with the error: module = __import__('.mylib') ImportError: No module named '.mylib' I want to perform a relative import inside of call_me that equals to the static import from . import mylib. How can I do it?
has answer: http://stackoverflow.com/a/47529924
downvote count: 0
has title: How to perform a dynamic relative import in Python 3?
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47529910
has answer: http://stackoverflow.com/a/47529910
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/82016125

http://stackoverflow.com/comment/82142931
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47529800
has text: My bad. I double checked, and in order to install inside a virtualenv, *apt-get* does not work. Try using this command instead, whe you are inside your virtualenv: `pip install pyasn1 pyasn1-modules`
type: AnswerComment

http://stackoverflow.com/comment/82030653
type: Comment
score: 0
type: QuestionComment
has text: Have you installed the gmaps plugin for jupyter? https://github.com/pbugnion/gmaps try their basic example once you have installed the plugin and let me know if it works.
comment on: http://stackoverflow.com/q/47536735

http://stackoverflow.com/a/47446692
has body: Assuming that t and s are TreeNode objects, where do you declare them? Is it possible that you're passing undeclared variables to Solution?
type: Answer
answers question: http://stackoverflow.com/q/47446586
has comment: http://stackoverflow.com/comment/81848714
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/a/47420723
answers question: http://stackoverflow.com/q/47419784
has comment: http://stackoverflow.com/comment/81798135
has comment: http://stackoverflow.com/comment/81798152
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81798242
has body: I think this is more pythonic but still needs something. def modcmd(arg): exe = sys.executable + ' ' prefix = sys.prefix + '/bin/' cmd = exe + prefix + arg os.system('clear') os.system(cmd)
has comment: http://stackoverflow.com/comment/81798255
score: -2
type: Answer
has comment: http://stackoverflow.com/comment/81798112
has comment: http://stackoverflow.com/comment/81797899

http://stackoverflow.com/a/47426824
accepted answer of: http://stackoverflow.com/q/47426796
has comment: http://stackoverflow.com/comment/81825852
upvote count: 3
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/81829754
has body: IIUC using replace df2.replace(df1.set_index('A').T.to_dict('r')[0]).replace(0,'') Out[830]: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 hi bye nay nay no 1 no bye bye hi nay Or we can using map d=df1.set_index('A').T.to_dict('r')[0] df2.apply(lambda x :x.map(d)).fillna('')
has comment: http://stackoverflow.com/comment/81825404
has comment: http://stackoverflow.com/comment/81830184
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47426796
has comment: http://stackoverflow.com/comment/81830162
has comment: http://stackoverflow.com/comment/81808505
has comment: http://stackoverflow.com/comment/81808538

calibration
tag name: calibration
type: Tag
tags question: http://stackoverflow.com/q/47471177

http://stackoverflow.com/q/47453384
has comment: http://stackoverflow.com/comment/81862501
type: Question
answer count: 0
downvote count: 0
has body: In dataquest.io the following code returns all int columns. but in jupyter it returns only the int32 column. what goes wrong? df = pd.DataFrame({'a':[1,2,3,4,5],'b':[11,22,33,44,55],'c':[.1,.2,.3,.4,.5]}) df['a'] = df['a'].astype('int') df['b'] = df['b'].astype('int64') df['c'] = df['c'].astype('float64') df a b c 0 1 11 .1 1 2 22 .2 2 3 33 .3 3 4 44 .4 4 5 55 .5 int32 int64 float64 int_32 = df.select_dtypes(include=['int']) in dataquest.io the previous code returns: a c 0 1 11 1 2 22 2 3 33 3 4 44 4 5 55 but in jupyter it returns: a 0 1 1 2 2 3 3 4 4 5 dataquest uses pandas 18.0 and I use pandas 20 .what do you think cause this problem?
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81942203
has title: python - Selecting Pandas Columns by dtype
tagged with: pandas
has comment: http://stackoverflow.com/comment/81862338
has comment: http://stackoverflow.com/comment/81862236
has comment: http://stackoverflow.com/comment/81942208
has comment: http://stackoverflow.com/comment/81862020
has comment: http://stackoverflow.com/comment/81942205
score: 1
favorite count: 0

http://stackoverflow.com/q/47490444
upvote count: 3
has comment: http://stackoverflow.com/comment/83139901
tagged with: sqlite
downvote count: 0
answer count: 1
has body: This is the simplified code for my telegram bot import telegram.bot, telegram, sqlite3 from telegram.ext import Updater,CommandHandler,MessageHandler,Filters class DatabaseManager(object): def __init__(self, db): self.conn = sqlite3.connect(db) self.conn.execute('pragma foreign_keys = on') self.conn.commit() self.cur = self.conn.cursor() def query(self, arg): self.cur.execute(arg) self.conn.commit() return self.cur def __del__(self): self.conn.close() def regcheck(uid): for row in dbmgr.query("SELECT * FROM users WHERE id="+str(uid)+";"): print "regcheck is running" #this is never printed if row == "": return 1 else: return 0 def start(bot, update): if regcheck(update.message.chat_id) == 1: bot.send_message(chat_id=update.message.chat_id, text="OK") else: bot.send_message(chat_id=update.message.chat_id,text="FAIL") def main(): global dbmgr dbmgr = DatabaseManager("usr.sql") for row in dbmgr.query("select * from users WHERE id="+str(uid)+";"): print row #this works perfectly fine updater = Updater(token=token) dispatcher = updater.dispatcher start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) updater.start_polling() updater.idle() if __name__ == '__main__': main() I understand, that using a global variable for dbmgr is sub-optimal, but this is my first python-telegram-bot project, and I am not aware of a (better, or at least working) way to accomplish this. Why does row in the main() get printed, but the dbmgr.query in regcheck() gets stuck?
has comment: http://stackoverflow.com/comment/86482244
has comment: http://stackoverflow.com/comment/86539653
favorite count: 0
type: Question
tagged with: python-telegram-bot
tagged with: telegram
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/62913690
score: 3
tagged with: python-2.7
has title: Sqlite connection in python-telegram-bot
has comment: http://stackoverflow.com/comment/81961117

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/47500557
tags question: http://stackoverflow.com/q/47438699
type: Tag

http://stackoverflow.com/comment/81756401
has text: @samanhamidi No problem!
comment on: http://stackoverflow.com/a/47400758
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47439566
has comment: http://stackoverflow.com/comment/81834991
tagged with: http://stackoverflow.com/tag/xml
has title: How to find, read and replace a value in XML file with Python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81834020
answer count: 2
has body: This is my example XML file: Hide your heart Bonnie Tyler UK CBS Records 9.90 1988 1 I want to change the value in the the tag data with key "times" and add 1 to it every time I start the script from the terminal. I tried first of all to read the element with: import xml.etree.ElementTree e = xml.etree.ElementTree.parse('test.xml').getroot() for atype in e.findall('data'): times=(atype.get('times')) But i'm already stuck because it doesn't work. If I try to print "times" I get no output from the terminal. My Idea was to read it, with a function add to this value 1 and replace it with the total of the sum (2 in this case). And save the modified XML file. It should be easy to do but I can't figure it out. EDIT I had to read better the documentation, I tried with: import xml.etree.ElementTree as ET tree = ET.parse('test.xml') root = tree.getroot() times = root[0][7].text newTimes = int(times) + 1 times = newTimes tree.write('test.xml') It read correctly the value, add 1 but gives an error if I try to write the file. What am I doing wrong? EDIT 2 I found the solution, read below my own answer.
has answer: http://stackoverflow.com/a/47441130
accepted answer: http://stackoverflow.com/a/47441130
type: Question
possible better answer: http://stackoverflow.com/a/47439713
tagged with: python
has answer: http://stackoverflow.com/a/47439713

http://stackoverflow.com/q/47442471
has answer: http://stackoverflow.com/a/47457296
answer count: 4
downvote count: 6
score: -5
has comment: http://stackoverflow.com/comment/81840081
has body: I have written a code that converts Megabytes to Gigabytes and vice versa the problem is that after the user choses from which unit will he convert he will be prompted to enter the value.I want to print "please enter a word" and return to the top of the code if the user didn't enter anything.Please tell me how to do that.
upvote count: 1
has answer: http://stackoverflow.com/a/47442616
has answer: http://stackoverflow.com/a/47442542
favorite count: 0
has comment: http://stackoverflow.com/comment/81840035
type: Question
has title: How to return to a top of a code Python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47443044
tagged with: python

http://stackoverflow.com/comment/81952530
has text: Thanks @unutbu. Confirmation: `%timeit grp = somedf.groupby('someBoolColumn'); grp['someBoolColumn'].count() 482 µs ± 7.69 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)`
comment on: http://stackoverflow.com/a/47498659
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81989386
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47515906
has text: @DavidCain, You are correct. Definitely a Census API situation. Apparently, that is their code for data they no longer maintain, despite maintaining the fields.
score: 2

http://stackoverflow.com/q/47415382
has title: How to plot an interval in one axis
favorite count: 0
accepted answer: http://stackoverflow.com/a/47418565
type: Question
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/47418565
tagged with: python
has comment: http://stackoverflow.com/comment/81789844
has comment: http://stackoverflow.com/comment/81785044
score: -3
has body: I'm new to python and I'm trying to plot some couples (x,y) in one axis X in the form of an interval. For example if I have the following couples (2,3),(2,4),(4,4),(1,3), I should produce the graph in the picture below. I try this code but it doesn't give me the right result def DrawGraph (RM): for i in range(0,RM.shape[0]-1): c1=lastOne2(RM,i) ax1=plt.subplot(1,1,1) if c1[0] == c1[1]: plt.plot(c1[0],c1[1],'ro') if c1[0] &lt; c1[1]: ax1.barh(c1[0], c1[1], height=0.05) if c1[0] &gt; c1[1]: ax1.barh(c1[1], c1[0], height=0.05) return plt
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47419971
tagged with: matplotlib
downvote count: 3
has answer: http://stackoverflow.com/a/47419971

http://stackoverflow.com/a/48312447
accepted answer of: http://stackoverflow.com/q/47514341
type: Answer
answers question: http://stackoverflow.com/q/47514341
has comment: http://stackoverflow.com/comment/83610743
has body: You might find vix useful (can be found @ https://github.com/naim94a/vix or with pip install vix). This library wraps the VIX API in a safe way (RAII) and is object oriented. import vix host = vix.VixHost() host.connect() vm = host.open_vm("C:\\Virtual Machines\\MyVM.vmx") vm.login(username="GuestUserName", password="GuestPassword") vm.proc_run("C:\\GuestExecutable.exe") Of course, if you would like to wrap the calls yourself the official documentation can be found here: https://www.vmware.com/support/developer/vix-api/vix115_reference/index2.html
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47466329
type: Answer
answers question: http://stackoverflow.com/q/47435503
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You should create a provider state, given entity 6000d04d-d5d6-4a5f-81d3-7d8a72b46174 exists that will set up the entity with the correct UID before the interaction is replayed. To use contract testing to its fullest potential, you need to be able to control the data in the provider for each interaction. If you can't, then contract tests are not a good fit for your problem space. Have a read of https://docs.pact.io/documentation/provider_states.html and https://github.com/pact-foundation/pact-ruby/wiki/Why-Pact-may-not-be-the-best-tool-for-testing-public-APIs
score: 2
accepted answer of: http://stackoverflow.com/q/47435503

http://stackoverflow.com/comment/81804265
score: 2
comment on: http://stackoverflow.com/q/47424682
type: Comment
type: QuestionComment
has text: What is the shape of the array? (Check, for example, `t.shape`.) A numpy array with shape (1, 2) has length 1.

http://stackoverflow.com/a/47441268
accepted answer of: http://stackoverflow.com/q/47437582
has body: You have some mistakes and some things I think are mistakes, but maybe just a different implementation. You are adding your gradients to your weights, when you should be subtracting your gradient multiplied by a step size. This is why your weights shoot up to 1.0 in only a single iteration. These: w3 += a3.T.dot(a4delta) Should be something like this: w3 -= addBias(a3).T.dot(a4delta) * step Also, I don't think you have the correct formulation for the partial derivative of the sigmoid function. I think these: a3delta = a4delta.dot(w3.T) * (1 * (1 - a3)) Should be: a3delta = a4delta.dot(w3.T) * (a3 * (1 - a3)) You should also initialize your weight around zero with something like: ep = 0.12 w = np.random.random((39, 39)) * 2 * ep - ep Most implementations add a bias node to each layer, you're not doing that. It complicates things a little, but I think it will make it converge faster. For me, this converges on a confident answer in 200 iterations: # Weights have different shapes to account for bias node w = np.random.random((39, 39)) * 2 * ep - ep w2 = np.random.random((40, 39))* 2 * ep - ep w3 = np.random.random((40, 1)) * 2 * ep - ep ep = 0.12 w = np.random.random((39, 39)) * 2 * ep - ep w2 = np.random.random((40, 39))* 2 * ep - ep w3 = np.random.random((40, 1)) * 2 * ep - ep def addBias(mat): return np.hstack((np.ones((mat.shape[0], 1)), mat)) step = -.1 for j in range(200): # Forward prop a2 = 1/(1 + np.exp(- addBias(x).dot(w))) a3 = 1/(1 + np.exp(- addBias(a2).dot(w2))) a4 = 1/(1 + np.exp(- addBias(a3).dot(w3))) # Back prop a4delta = (y - a4) # need to remove bias nodes here a3delta = a4delta.dot(w3[1:,:].T) * (a3 * (1 - a3)) a2delta = a3delta.dot(w2[1:,:].T) * (a2 * (1 - a2)) # Gradient Descent # Multiply gradient by step then subtract w3 -= addBias(a3).T.dot(a4delta) * step w2 -= addBias(a2).T.dot(a3delta) * step w -= addBias(x).T.dot(a2delta) * step print(np.rint(a4))
type: Answer
answers question: http://stackoverflow.com/q/47437582
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81865983
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47454144
has text: I have edited it, thanks !
score: 0

http://stackoverflow.com/q/47418621
has answer: http://stackoverflow.com/a/47418689
has comment: http://stackoverflow.com/comment/81791680
has title: Error compiling python
linked to: http://stackoverflow.com/q/21122540
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47418698
answer count: 2
has answer: http://stackoverflow.com/a/47418698
has comment: http://stackoverflow.com/comment/81791758
downvote count: 2
duplicate of: http://stackoverflow.com/q/21122540
has comment: http://stackoverflow.com/comment/81791352
upvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81791784
has body: Whenever I try to execute this code: name = input("What's your name?") print("Hello World", name) By running the command python myprogram.py on the command line, it gives me this error: What's your name?John Traceback (most recent call last): File "HelloWorld.py", line 1, in &lt;module&gt; name = input("What's your name?") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'John' is not defined It asks me the name but as soon as I type it and press enter it crashes, what does the error mean? Thanks.
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16179875
accepted answer: http://stackoverflow.com/a/47418689

http://stackoverflow.com/q/47480961
accepted answer: http://stackoverflow.com/a/47481208
type: Question
has comment: http://stackoverflow.com/comment/81916918
has body: I have the following function macd, macdsignal, macdhist = talib.MACD(df.Close.values, fastperiod=12, slowperiod=26, signalperiod=9) I want to make those new values part of my existing dataframe, how can I do that? This is what I tried df['macd'], df['macdsignal'], df['macdhist'] = talib.MACD(df.Close.values, fastperiod=12, slowperiod=26, signalperiod=9) Edit to add a before and after Before Close 10 10 10 After Close macd macdsignal macdhist 10 1.1 3.8 5.7 10 3.2 8.7 4.2 10 1.9 9.5 1.2
has comment: http://stackoverflow.com/comment/81917225
has answer: http://stackoverflow.com/a/47481208
tagged with: list
tagged with: pandas
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has title: multiple list outputs created by a function, how do i put this to a dataframe?
has comment: http://stackoverflow.com/comment/81917024
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81916967
tagged with: python
has comment: http://stackoverflow.com/comment/81916844

http://stackoverflow.com/a/47397221
type: AcceptedAnswer
has body: Primary problem I see: you're starting your loop j=0 at 0 when it should start at 1 in-order to print your desired result. If this was your html (a condensed version of the actual page), and you're trying to get the text associated with this tag: html = '''01/AMI/RDOE/2017 01/ct/2017 108/2017/CNSS 1/2017 09/2017/CZC 65/2017/TGR 20/2017/DMSPK 05/INDH/2017 13/CS/2017 158/2017/RRA''' You should use regex like so: import re soup = BeautifulSoup(html, 'lxml') for item in soup.findAll('span', {"id": re.compile( "ctl0_CONTENU_PAGE_resultSearch_tableauResultSearch_ctl\d+_reference")}): item.get_text() Returns: '01/AMI/RDOE/2017' '01/ct/2017' '108/2017/CNSS' '1/2017' '09/2017/CZC' '65/2017/TGR' '20/2017/DMSPK' '05/INDH/2017' '13/CS/2017' '158/2017/RRA'
answers question: http://stackoverflow.com/q/47395826
score: 0
accepted answer of: http://stackoverflow.com/q/47395826
type: Answer
has comment: http://stackoverflow.com/comment/81771452

http://stackoverflow.com/comment/81872078
has text: AUTH_USER_MODEL = "users.MyUser"
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47448636
score: 0

http://stackoverflow.com/comment/81721961
type: QuestionComment
has text: You might want to ask at the Code Review site instead. https://codereview.stackexchange.com/. This question might be closed for being too broad because it's really 'what do you think? how can it be improved?'. If your question could be answered by an entire book, or has many valid answers (but no way to determine which - if any - are correct), then it is probably too broad for the SO format
comment on: http://stackoverflow.com/q/47384440
score: 1
type: Comment

http://stackoverflow.com/comment/81834489
type: QuestionComment
comment on: http://stackoverflow.com/q/47434852
score: 0
has text: @bruno desthuilliers, yes, it is a xml data string, as shown below: >>> r.content '<?xml version="1.0" encoding="utf-8" ?> \n \n \n'
type: Comment

http://stackoverflow.com/comment/81931143
score: 1
comment on: http://stackoverflow.com/q/47488091
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. Please check out this article to help you ask better questions https://stackoverflow.com/help/how-to-ask

http://stackoverflow.com/a/47429418
accepted answer of: http://stackoverflow.com/q/47407970
answers question: http://stackoverflow.com/q/47407970
type: AcceptedAnswer
has body: Removed all python and Anaconda installations and reinstall only Anaconda solved the issue. I had multiple installations for both Python and Anaconda...
score: 0
type: Answer

http://stackoverflow.com/a/47433617
accepted answer of: http://stackoverflow.com/q/47433181
downvote count: 0
type: Answer
score: 8
upvote count: 8
has body: The problem here is not the encoding itself but the correct encoding to pass to `request'. You need to quote the url as follows: import urllib.request import urllib.parse imglinks = ["http://www.katytrailweekly.com/Files/MalibuPokeMatt_©Marple_449-EDITED_15920174118.jpg"] for link in imglinks: link = urllib.parse.quote(link,safe=':/') # &lt;- here filename = link.split('/')[-1] urllib.request.urlretrieve(link, filename) This way your © symbol is encoded as %C2%A9 as the web server wants. The safe parameter is specified to prevent quote to modify also the : after http. Is up to you to modify the code to save the file with the correct original filename. ;)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47433181

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/47398769

http://stackoverflow.com/q/47468334
downvote count: 0
has title: Issue with importing xgboost on python jupyter notebook after installing xgboost
tagged with: xgboost
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has body: I have successfully installed xgboost on my mac using jupyer notebook by typing !pip install xgboost However, when I import xgboost, the message below is what I see.. Error: OSError: dlopen(/Users/KeonPark/anaconda3/lib/python3.6/site-packages/xgboost/./lib/libxgboost.so, 6): Library not loaded: /usr/local/opt/gcc/lib/gcc/5/libgomp.1.dylib Referenced from: /Users/KeonPark/anaconda3/lib/python3.6/site-packages/xgboost/./lib/libxgboost.so Reason: image not found Please help.....
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/comment/81932850
type: Comment
has text: Please add that to the question in a code block.
comment on: http://stackoverflow.com/q/47488859
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81992465
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47517718
has text: yes, sorry for my stupidity:D
type: Comment

http://stackoverflow.com/a/47502726
has comment: http://stackoverflow.com/comment/81961862
has body: What, exactly, does your Python script do? I think you might be falling victim to the XY problem here. If you need speed and you can implement your Python code in Javascript, then I don't think I can recommend anything less than rewriting your code. Another option you might have is to execute your python script once per session and have it take an input (via REST or something) and return its output like that, but that honestly might be more work depending on your script.
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81961336
accepted answer of: http://stackoverflow.com/q/47502496
answers question: http://stackoverflow.com/q/47502496
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47504121
tagged with: pyinstaller
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/124798868
has body: I keep getting: AttributeError: 'NoneType' object has no attribute 'is_downloaded'. I am trying to integrate pyupdater with an executable. My amazon folder contains: pyu_test-win-1.0.zip and versions.gz which I upload. Error: {} {} nothing new Traceback (most recent call last): File "C:/Users/D1/Desktop/31/pyu_test.py", line 25, in &lt;module&gt; if app_update.is_downloaded(): AttributeError: 'NoneType' object has no attribute 'is_downloaded' Process finished with exit code 1 I'm getting also unresolved reference client_config as well as ClientConfig is underlined when I hover. This is for: pyu_test.py from pyupdater.client import Client from client_config import ClientConfig APP_NAME = 'pyu_test' APP_VERSION = '1.0' def print_status_info(info): total = info.get(u'total') downloaded = info.get(u'downloaded') status = info.get(u'status') print (downloaded, total, status) client = Client(ClientConfig(), refresh=True, progress_hooks=[print_status_info]) app_update = client.update_check(APP_NAME, APP_VERSION) if app_update is not None: app_update.download() else: print("nothing new") if app_update.is_downloaded(): app_update.extract_overwrite() client_config class ClientConfig(object): PUBLIC_KEY = '+WDWADADAWDADDWDW' APP_NAME = 'pyu_test' COMPANY_NAME = 'pyu_test' UPDATE_URLS = ['https://console.aws.amazon.com/s3/buckets/xWAXWED/?region=us-east-2&amp;tab=overview'] MAX_DOWNLOAD_RETRIES = 3 Any ideas how I can address this. Cheers.
has comment: http://stackoverflow.com/comment/81964285
tagged with: python
has comment: http://stackoverflow.com/comment/81964342
accepted answer: http://stackoverflow.com/a/47504352
has answer: http://stackoverflow.com/a/47504352
has title: AttributeError: 'NoneType' object has no attribute 'is_downloaded'
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81964370
linked to: http://stackoverflow.com/q/8949252
tagged with: upload
answer count: 1
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/47506043
favorite count: 0
type: Question
answer count: 0
tagged with: oauth
has title: How to use authentication token in Django with Django OAuth Toolkit (not REST)
type: UnansweredQuestion
downvote count: 0
has body: I'm using the following library http://django-oauth-toolkit.readthedocs.io/ which seems to not be as well documented as I would like, and after I followed its tutorial I am able to have a working system in which I have protected views that need the authorization token, and I can access them using curl and adding the token. Curl is nice to test, but it's not practical, and I failed at developing it. So I have a very simple protected view: class Test(ProtectedResourceView): def get(self, request, *args, **kwargs): return HttpResponse('Hello, OAuth2!') If I try to access, I will get a 403, and if I ask for the token and put it in the header using curl I can actually get it to work. In the other hand, I have another view that gets the authorization_token, lifetime, refresh_token, .. in a dictionary (after using JSON from Django). At this point I'm lost. I don't know what to do with the authorization token so that the user can actually use it and access to the protected view. I tried to manually add the token to the cookies but it didn't work and doesn't seem to be a good idea neither. I guess after I do something, the user can access the protected view. Thanks.
tagged with: django
upvote count: 1
score: 1
tagged with: python

http://stackoverflow.com/q/47438202
tagged with: python
linked to: http://stackoverflow.com/q/419163
has comment: http://stackoverflow.com/comment/81830969
answer count: 0
has title: Python3: command line interface and module import?
tagged with: argparse
has comment: http://stackoverflow.com/comment/81831435
score: 0
has comment: http://stackoverflow.com/comment/81831449
type: Question
tagged with: python-3.x
has body: So I have the following directory structure my_dir my_mod __init__.py myfile.py and in myfile.py I have a nice command line interface via argparse. But what if sometimes I want to import a function from this script and use it as if it were a module? e.g. from myfile import myfunc when I do this I get an error, mostly because I do some preprocess of the command line arguments which are all none in this case. from this S.O. post, I know how I can tell if python is called from the command line: import sys, os if os.isatty(sys.stdin.fileno()): # do things The inclusions of this line and corresponding replacement of my argument preprocessing does not solve this issue. What should I do?
has comment: http://stackoverflow.com/comment/81830931
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4213091

http://stackoverflow.com/comment/82038694
type: QuestionComment
comment on: http://stackoverflow.com/q/47523856
has text: Your question is a bit confusing. Is accounting_scenarios a method to compute a field? Can you show us how do you define isbn? I'm not sure, but inside your for loop, you are using "self." instead "record."... I think that may be an issue... It might be necessary to use @api.multi as well...
score: 1
type: Comment

http://stackoverflow.com/q/47419232
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Kivy: Increasing space needed in BoxLayout?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47425788
has answer: http://stackoverflow.com/a/47425788
tagged with: python
tagged with: kivy
has body: I have a lot jammed in the top left corner of my current GUI that I'm trying to basically spread out and have my image be a normal size (similar to the mock up shown below). I guess I need to expand the Y direction downward to fit it at (making the top region larger to fit it all)? However, when I change size_hint_y to > 1 it spaces the text upward and it cuts off outside of the GUI. Any ideas? Thanks very much! Current Layout: My goal: My kv file: #:kivy 1.10.0 &lt;WeatherWidget&gt;: cols: 1 BoxLayout: size_hint_y: None BoxLayout: size_hint_x: 1 size_hint_y: 1 orientation: "vertical" Image: source: 'Code32.png' keep_ratio: False halign: 'center' Label: text: root.current_temperature()[:3] bold: True font_size: 40 Label: text: root.high_low_temp(0) font_size: 15 color: [1,255,1,1] Label: text: root.get_location() font_size: 15 color: [1,1,1,1] bold: True Label: text: root.sunrise() font_size: 10 color: [1,1,1,1] Label: text: root.sunset() font_size: 10 color: [1,1,1,1] BoxLayout: orientation: 'vertical' Image: source: 'Code32.png' Label: text: root.forecast_day(1) Label: text: root.high_low_temp(1) font_size: 12 color: [1,255,1,1] Label: text: root.forecast_day(2) Label: text: root.forecast_day(3) Label: text: root.forecast_day(4) Label: text: root.forecast_day(5) BoxLayout: size_hint_y: None BoxLayout: orientation: 'vertical' Button: text: root.TimeHours + ':' + root.TimeMinutes size_hint_x: 1 font_size: 40 size: self.size bold: True halign: 'center' Label: text: root.current_date() size_hint_x: 1 font_size: 15 bold: True halign: 'center'
type: AnsweredQuestion
tagged with: kivy-language

http://stackoverflow.com/q/47503817
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47507090
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81963450
type: Question
tagged with: odoo
has comment: http://stackoverflow.com/comment/81964428
tagged with: python
has comment: http://stackoverflow.com/comment/81964116
has title: Only checks the last row instead of entire rows
tagged with: python-2.7
tagged with: odoo-10
type: AnsweredQuestion
has body: Here is the python Odoo code to cross check each every rows of two separate classes.But it show only the last row check instead of the entire row and column ! Can anybody help me ! @api.multi def compare_gstr(self): for gstr_file in self: err={} result=[] gstr_upload = self.env['bi.gstr.upload'].search([('gstr_upload_id','=', gstr_file.id)]) gstr = self.env['bi.gstr'].search([('gstr2_id','=', gstr_file.id)]) for details in gstr_upload: # for det in gstr: if details.gstin: gstin = self.env['bi.gstr'].search([('gstr2_id','=', gstr_file.id),('gst_recipient','=', details.gstin)]) if not gstin: err['GST Number']=str(details.gstin)+' Missmatch' if details.b2b_inv_inum: b2b_inv_inum = self.env['bi.gstr'].search([('gstr2_id','=', gstr_file.id),('invoice_ids','=', details.b2b_inv_inum)]) if not b2b_inv_inum: err['Invoice Number']=str(details.b2b_inv_inum)+' Missmatch' if details.b2b_inv_idt: b2b_inv_idt = self.env['bi.gstr'].search([('gstr2_id','=', gstr_file.id),('invoice_date','=', details.b2b_inv_idt)]) if not b2b_inv_idt: err['Invoice Date']=str(details.b2b_inv_idt)+' Missmatch' if details.b2b_inv_val: b2b_inv_val = self.env['bi.gstr'].search([('gstr2_id','=', gstr_file.id),('invoice_value','=', details.b2b_inv_val)]) if not b2b_inv_val: err['Invoice Value']=str(details.b2b_inv_val)+' Missmatch' result.append(err) raise UserError(_(str(err)))
has comment: http://stackoverflow.com/comment/81963917
accepted answer: http://stackoverflow.com/a/47507090

amazon-athena
type: Tag
tag name: amazon-athena
tags question: http://stackoverflow.com/q/47529156

http://stackoverflow.com/a/47443327
answers question: http://stackoverflow.com/q/47443291
has comment: http://stackoverflow.com/comment/81841916
type: AcceptedAnswer
downvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47443291
has comment: http://stackoverflow.com/comment/81841681
has body: You may use list comprehension expression with list slicing as: &gt;&gt;&gt; indexes = [4, 2, 4, 6] &gt;&gt;&gt; values = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] &gt;&gt;&gt; [values[sum(indexes[:i]):sum(indexes[:i+1])] for i, index in enumerate(indexes)] [[0, 1, 2, 3], [0, 1], [2, 3, 0, 1], [2, 3, 0, 1, 2, 3]]
upvote count: 3
score: 1
has comment: http://stackoverflow.com/comment/81842202
has comment: http://stackoverflow.com/comment/81842078

http://stackoverflow.com/q/47497322
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: dry
has title: Call a classmethod from __init__ without repeating the classname
answer count: 1
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81949950
tagged with: class-method
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47497394
has body: I would like to call the classmethod addInstances from within __init__ without repeating the class name Foo. class Foo(): myInstances = {} @classmethod def addInstance(cls, name, obj): cls.myInstances[name]=obj def __init__(self, name): Foo.addInstance(name, self) # class name "Foo" is repeated #use the class if __name__ == "__main__": Foo('testName') print(Foo.myInstances) The code above does what i expect it to do. However "Foo" is repeated. Replacing the line Foo.addInstance(name, self) # class name "Foo" is repeated with cls.addInstance(name, self) leads to NameError: name 'cls' is not defined.
has answer: http://stackoverflow.com/a/47497394

http://stackoverflow.com/comment/82027354
type: QuestionComment
comment on: http://stackoverflow.com/q/47535208
score: 0
has text: I agree with @DanielRoseman, but anyway for me is Shift+Tab after selecting the code.
type: Comment

http://stackoverflow.com/comment/81930789
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47487523
has text: Have you tried to profile? What's the bottleneck?
score: 1

http://stackoverflow.com/q/47467847
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47467938
answer count: 1
type: Question
has title: Adding multiple values from a list as separate numbered keys to a dictonary
has answer: http://stackoverflow.com/a/47467938
tagged with: python
tagged with: dictionary
has body: I have a dictionary containing a profile. Every profile has a different amount of "abouts". For example Person 1 has: "lives there", "works there", "eats this". Person 2 has: "lives there". All my profiles are in a for loop which I didn't copy here. In this for loop I made a new loop where I want to get the range of the "abouts" and then create multiple variables containing the content of the "abouts". All this I want to write to my dictionary friend. As output I want: friend = { "screenname": profilename, "id": profileid, "username": username, "about 1": # lives in "about 2": # works at # and so on until all the "abouts" are found and written in the dict. } If I run this code it only puts the latest "about" in my dictionary. for i in range(len(abouts)): friend = { "screenname": profilename, "id": profileid, "username": username, "about " + str(i): abouts[i] }

http://stackoverflow.com/q/47449925
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/43096972
linked to: http://stackoverflow.com/q/15672743
linked to: http://stackoverflow.com/q/45081760
tagged with: clipboard
has body: In a pyQt application, I'm copying matplotlib figures (self.canvas) to a QClipboard instance using either cb = QClipboard(self) img = QImage(self.canvas.grab()) cb.setImage(img) or img = QPixmap(self.canvas.grab()) self.cb.setPixmap(img) Both work well, however, I haven't managed to control the resolution of the exported image. This would be possible by creating and exporting a temporary file, however, this is slow and has potential problems due to file system restrictions: self.canvas.figure.savefig(self.temp_file, dpi = 300, type = 'png') temp_img = QImage(self.temp_file) cb.setImage(temp_img) So, is there a way to set the resolution of the copied image without taking a detour through the file system? ------------------------------------- Edit: I just found out that the above doesn't work under pyqt4. Instead, you can use img = QPixmap.grabWidget(self.canvas) self.cb.setPixmap(img) ------------------------------------- Edit: Another solution that nearly works is the following piece of code, unfortunately it changes the colors (back to matplotlib defaults?): # construct image from raw rgba data, this changes the colormap: size = self.canvas.size() width, height = size.width(), size.height() im = QImage(self.canvas.buffer_rgba(), width, height, QImage.Format_ARGB32) self.cb.setImage(im)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47453170
tagged with: python
linked to: http://stackoverflow.com/q/43483101
tagged with: dpi
upvote count: 3
score: 3
has title: Copy matplotlib figure to QClipboard with increased resolution
downvote count: 0
tagged with: pyqt
tagged with: matplotlib

http://stackoverflow.com/a/47504748
type: Answer
has comment: http://stackoverflow.com/comment/81965294
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: If you're looking to remove braces from a string, you could do so with str.strip - &gt;&gt;&gt; '[1234]'.strip('[]') '1234' As for your current method, your regular expression is the culprit here. I'm not sure what you think it does, but it definitely isn't right. One possible regex solution would be - &gt;&gt;&gt; re.match(r'\[(.*?)\]', '[1234]').group(1) '1234' \[ # opening brace (.*?) # match-all capture group \] # closing brace
accepted answer of: http://stackoverflow.com/q/47504616
answers question: http://stackoverflow.com/q/47504616

http://stackoverflow.com/comment/81730542
type: QuestionComment
has text: You mean if I replace my `.to_csv` using your example? It works. I can get the first ten rows in the csv file but compact together (not tab-separated) @jezrael
score: 0
comment on: http://stackoverflow.com/q/47388570
type: Comment

http://stackoverflow.com/a/47439728
type: Answer
type: AcceptedAnswer
has body: One could ask differently: How would matplotlib know which line to drag if you click on any of them? Answer: it wouldn't, because it has three callbacks, one for each line and will execute them all. The solution is hence to first check if the line clicked is actually the line to be moved inside the 'pick_event' callback: if event.artist == self.line: # register other callbacks (On a different note: You would benefit from not calling canvas.draw() so often, but instead canvas.draw_idle()) import matplotlib.pyplot as plt import matplotlib.lines as lines class draggable_lines: def __init__(self, ax, kind, XorY): self.ax = ax self.c = ax.get_figure().canvas self.o = kind self.XorY = XorY if kind == "h": x = [-1, 1] y = [XorY, XorY] elif kind == "v": x = [XorY, XorY] y = [-1, 1] self.line = lines.Line2D(x, y, picker=5) self.ax.add_line(self.line) self.c.draw_idle() self.sid = self.c.mpl_connect('pick_event', self.clickonline) def clickonline(self, event): if event.artist == self.line: print("line selected ", event.artist) self.follower = self.c.mpl_connect("motion_notify_event", self.followmouse) self.releaser = self.c.mpl_connect("button_press_event", self.releaseonclick) def followmouse(self, event): if self.o == "h": self.line.set_ydata([event.ydata, event.ydata]) else: self.line.set_xdata([event.xdata, event.xdata]) self.c.draw_idle() def releaseonclick(self, event): if self.o == "h": self.XorY = self.line.get_ydata()[0] else: self.XorY = self.line.get_xdata()[0] print (self.XorY) self.c.mpl_disconnect(self.releaser) self.c.mpl_disconnect(self.follower) fig = plt.figure() ax = fig.add_subplot(111) Vline = draggable_lines(ax, "h", 0.5) Tline = draggable_lines(ax, "v", 0.5) Tline2 = draggable_lines(ax, "v", 0.1) plt.show()
downvote count: 0
score: 8
answers question: http://stackoverflow.com/q/47439355
upvote count: 8
accepted answer of: http://stackoverflow.com/q/47439355

http://stackoverflow.com/comment/81951750
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47496680
has text: The best solution in this case is put a delay longer than usual. When the scraper encounter that captcha, solve it manually and when you are done then you can find the rest working as you want. Sometimes it may break cause within that time you may not be able to solve that captcha. That's it.
type: Comment

http://stackoverflow.com/q/47493017
has comment: http://stackoverflow.com/comment/82061406
has body: While following the MacOS installation and after successfully running the .configuration script, I get an error when attempting to build the pip package. The error in terminal shows as follows: Sat Nov 25 22:47:25 EST 2017 : === Building wheel error in tensorflow setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected ',' or end-of-list in backports.weakref &gt;= 1.0rc1; python_version &lt; "3.4" at ; python_version &lt; "3.4" The full error message is: Laurences-MacBook-Pro-3:tensorflow qaneuro$ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg Sat Nov 25 22:47:21 EST 2017 : === Using tmpdir: /var/folders/7t/77lrlr0n56z9s05dbzl42lq00000gn/T/tmp.XXXXXXXXXX.1suikQIy ~/ex5/tensorflow/bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles ~/ex5/tensorflow ~/ex5/tensorflow /var/folders/7t/77lrlr0n56z9s05dbzl42lq00000gn/T/tmp.XXXXXXXXXX.1suikQIy ~/ex5/tensorflow Sat Nov 25 22:47:25 EST 2017 : === Building wheel error in tensorflow setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected ',' or end-of-list in backports.weakref &gt;= 1.0rc1; python_version &lt; "3.4" at ; python_version &lt; "3.4" Has anyone else had this problem or can provide advice on how they solved it?
favorite count: 0
type: Question
tagged with: bazel
has comment: http://stackoverflow.com/comment/81941318
has comment: http://stackoverflow.com/comment/81941227
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81941283
downvote count: 0
upvote count: 1
tagged with: pip
has comment: http://stackoverflow.com/comment/81941231
has comment: http://stackoverflow.com/comment/82018925
has comment: http://stackoverflow.com/comment/81941260
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81950915
score: 1
has comment: http://stackoverflow.com/comment/81946502
has comment: http://stackoverflow.com/comment/82024687
has title: Tensorflow installation error building a .whl file
tagged with: python

http://stackoverflow.com/comment/81930422
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47487498
score: 0
has text: I just saw your links up there. you won't get much better answers for this question than those.

http://stackoverflow.com/comment/81734769
type: Comment
type: QuestionComment
score: 0
has text: That makes sense! I got another error after fixing the previous, InvalidArgumentError (see above for traceback): Expected dimension in the range [-1, 1), but got 1
comment on: http://stackoverflow.com/q/47390035

http://stackoverflow.com/a/47413241
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47413170
has comment: http://stackoverflow.com/comment/81780125
has body: Correcting your code would look like this: order = ["1","2","3","4","5"] words = ["Apple","Boat","Carrot","Dragonfly","Education"] for i in range(0,5): print(words[int(order[i])]) But this is nowhere near a clean solution. You are messing with the indexes far too much. A better way to do this would be this: for x in order: print(words[int(x)-1]) All this said, there is nothing random about what you are doing. Consider using random.shuffle() for that. Like so: from random import shuffle order = ["1","2","3","4","5"] words = ["Apple","Boat","Carrot","Dragonfly","Education"] shuffle(order) # the shuffling is done in-place for i in [int(c)-1 for c in order]: print(words[i]) # prints Carrot Dragonfly Education Boat Apple
upvote count: 2
has comment: http://stackoverflow.com/comment/81779938
type: Answer
has comment: http://stackoverflow.com/comment/81779927
has comment: http://stackoverflow.com/comment/81780416
score: 2
accepted answer of: http://stackoverflow.com/q/47413170
has comment: http://stackoverflow.com/comment/81780573

http://stackoverflow.com/a/47456389
accepted answer of: http://stackoverflow.com/q/47455850
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47455850
type: AcceptedAnswer
has body: arr contains other values besides 255. (Evaluate np.where(arr != 255) to see where.) The reason why you are seeing so many 255's is because the image contains a white border. To remove the white border, see Joe Kington's or matehat's method. For example, using Joe Kington's method (controlling the extent): from PIL import Image import io from matplotlib import pyplot as plt import numpy as np fig, ax = plt.subplots() ax.axis('off') ax.text(0.0,0.0,"Test", fontsize=45) ax.imshow(np.random.random((3,3))) with io.BytesIO() as memf: extent = ax.get_window_extent() extent = extent.transformed(fig.dpi_scale_trans.inverted()) fig.savefig(memf, format='PNG', bbox_inches=extent) memf.seek(0) img = Image.open(memf).convert('RGB') arr = np.asarray(img) img.save('/tmp/out.png')
type: Answer

http://stackoverflow.com/comment/81993379
type: Comment
comment on: http://stackoverflow.com/a/47511103
type: AnswerComment
score: 0
has text: @CHANDRAMURUGAN my bad, was a typo.

http://stackoverflow.com/comment/81995857
score: 0
has text: @JaredSmith I'm afraid most of that was Greek to me. Care to expand that into an answer since the only current answer suggests the opposite?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47518985

http://stackoverflow.com/comment/81918785
has text: there is the `sed` command, which is awful but works, depending on how you want to solve this problem, i personally would create a little python script to call it with an arg.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47481902

http://stackoverflow.com/q/47526959
has comment: http://stackoverflow.com/comment/82010032
upvote count: 0
answer count: 1
tagged with: rename
has comment: http://stackoverflow.com/comment/82009985
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82010360
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47527101
has title: Rename folders containing a certain string
score: -2
downvote count: 2
tagged with: python
has body: I would like to use a Python script to look for folders containing a certain string in its name and replace the entirety of that name to another. Like this: The data is nested inside folders LastName FirstName The script should go to each of those folders and rename the following folders. ep2d_diff_e_2d_tra_7 ep2d_diff_e_2d_tra_ADC_8 t1_blade_tra_darkfl_6 t1_blade_tra_darkfl_14 t2_blade_tra_320_9 t2_fl2d_tra_hemo_5 t2_tirm_tra_darkfluid_blade_4 to DWI ADC T1 KM T2 Hemo Flair Those numbers at the end are not always consistant so should just be dropped. You can see those 2 are quite similar..The only difference being, that the one has a higher number in the postscript. (It might be 8 and 12 or other numbers) t1_blade_tra_darkfl_6 t1_blade_tra_darkfl_14 How would I best go about it?

http://stackoverflow.com/comment/81896640
has text: there is not need to return result if i am mistaken right
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47470787
type: Comment

http://stackoverflow.com/q/47493293
has title: Why does mypy say I have too many arguments
has answer: http://stackoverflow.com/a/47502107
type: AnsweredQuestion
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47502107
favorite count: 0
tagged with: mypy
has body: I've got a class which has a method that creates instances of the class. class Bar: @classmethod def create(cls, foo: int): return cls(foo) def __init__(self, foo: int) -&gt; None: pass When I run mypy against it, it says mypytest.py:4: error: Too many arguments for "Bar" It seems like a bug to me, because this works fine class Bar: @classmethod def create(cls, foo): return cls(foo) def __init__(self, foo: int) -&gt; None: pass I don't understand why a class method which defines the type of a parameter should break the creation of an instance. Am I missing something?
score: 9
type: Question
upvote count: 9
tagged with: python

http://stackoverflow.com/q/47440377
has comment: http://stackoverflow.com/comment/81835794
has comment: http://stackoverflow.com/comment/81836346
has comment: http://stackoverflow.com/comment/81835702
score: 0
upvote count: 2
linked to: http://stackoverflow.com/q/12330522
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81835872
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/81835832
tagged with: string-length
has comment: http://stackoverflow.com/comment/81835784
favorite count: 0
has title: Python len() confusion
has comment: http://stackoverflow.com/comment/81836305
has comment: http://stackoverflow.com/comment/81836101
has comment: http://stackoverflow.com/comment/81836137
has comment: http://stackoverflow.com/comment/81835886
tagged with: python
has answer: http://stackoverflow.com/a/47440470
has body: I'm not sure what I'm doing wrong here, spent all day googling and reading python books.. I have the following function: def extract(inNo, inputFile2, outputFile): ifile = open(inputFile2, 'r') ofile = open(outputFile, 'w') lines = ifile.readlines() for line in lines: print(str(len(line))) if str(len(line)) == str(inNo): ofile.write(line) I'm trying to understand len(), I seem to get odd results when using it. My input file is the following: 1 22 333 4444 55555 666666 7777777 88888888 Now if I use '7' as the inNo variable, the output (i.e., print) I get is: 2 3 4 5 6 7 8 8 and the output file becomes: 666666 I'm sure from checking in python.exe length count start from 1 i.e: len('123') would give a result of 3 Is my understanding of len() wrong, or am I coding it wrong? Essentially, what this function does is; it takes an input, an output and a character length as arguments. These come from a different function and the 2nd function calls this one with arguments. This function reads lines from the input file. For every line, it gets the character length and compares it to the input No. If they are equal it should write that line to the output file. I assume as I have no "else:" it should carry on the iteration. The print() function allows me to see exactly what it has calculated as the length. When I try to add '- 1' or '+ 1' to the len() i.e. (len(line) + 1) it causes even more odd things start to happen.
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47505569
has comment: http://stackoverflow.com/comment/82018289
has comment: http://stackoverflow.com/comment/82253663
score: 1
accepted answer of: http://stackoverflow.com/q/47505488
answers question: http://stackoverflow.com/q/47505488
has body: The simplest answer I can think of right away is to use an NLP library such as TextBlob. You can read the entire documentation here. It is very simple and easy to use. The documentation is also pretty good. from textblob import TextBlob user_input = "What the user had said goes here" blob = textBlob(user_input) print(blob.sentiment) #this gives both subjectivity and polarity.
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/82004981
comment on: http://stackoverflow.com/a/47524170
score: 0
type: Comment
has text: Yeah, if it's an error with the library, that's a more involved issue. My final suggestion would be that it might be related to the double quotes in the string. Perhaps try removing the double quotes from the string and see if you're getting the same error. If that changes things, we have a path forward from there.
type: AnswerComment

http://stackoverflow.com/comment/82009424
comment on: http://stackoverflow.com/a/47526609
type: Comment
type: AnswerComment
score: 0
has text: thnx but he gives me this error Error: [Errno 2] No such file or directory: 'test.csv'

http://stackoverflow.com/comment/81934408
type: Comment
comment on: http://stackoverflow.com/q/47489459
type: QuestionComment
score: 0
has text: That worked perfectly!

http://stackoverflow.com/a/47463422
has comment: http://stackoverflow.com/comment/82034848
has body: In the doc : https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly In your case: import importlib setup_file = "path/to/setup.py" spec = importlib.util.spec_from_file_location("setup", setup_file) setup = importlib.util.module_from_spec(spec) spec.loader.exec_module(setup) # And now access it print(setup.config["install_requires"])
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82034477
answers question: http://stackoverflow.com/q/47463277
type: Answer

http://stackoverflow.com/a/47414600
has body: Run command with sudo. sudo pip install &lt;pkg_name&gt; OR install it using --user option which installs the package only for the current user and not for all pip install &lt;pkg_name&gt; --user
type: Answer
answers question: http://stackoverflow.com/q/47403218
score: 0

http://stackoverflow.com/comment/81950778
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47497117
type: Comment
has text: Do you need a "Tree" class? a way to pretty-print the ancestors of a node for the dictionary-tree you have now? or both?

http://stackoverflow.com/comment/81884362
comment on: http://stackoverflow.com/q/47464697
score: 0
type: Comment
type: QuestionComment
has text: The traceback indicates you aren't running code from a file, but apparently entered directly into an iPython session.

http://stackoverflow.com/comment/81859411
type: QuestionComment
type: Comment
has text: Since I'm going to use only hardcoded ffmpeg commands in _subprocess.Popen_, I guess then there is no problem to use _shell=True_ without list of strings? However, it actually works in both ways, at least on Windows.. Regarding un-referenced objects, as you can see I'm just returning PID for a new child process that has been opened. PID number is then used to create coresponding file which will be used for periodical subprocess activity check, so returned PID number can be freely removed by garbage collector? Please correct me if I missed somethig...
score: 0
comment on: http://stackoverflow.com/q/47434228

http://stackoverflow.com/a/47433671
answers question: http://stackoverflow.com/q/47433627
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47433627
has comment: http://stackoverflow.com/comment/81822069
type: AcceptedAnswer
has body: def is_cube(volume): return int(round(volume ** (1/3.))) ** 3 == volume
type: Answer
score: 3

http://stackoverflow.com/q/47512793
has title: Bokeh Stacked Bar- adding text label next to the bar
has body: I am trying to create a stacked bar using Bokeh 0.12.4. I am able to create the bar using the chart interface. However, I have trouble adding the label next to the bar. More specifically: Is there a way that I can add the label to each bar using bar()? I know the chart interface has limitations. If not, how do I create stacked bar chart using plotting interface and create labels next to each bar?(I don't want the label to be on the bar, as you can see, some of the sections are really small, if on the bar, all the text will be clustered together.) How do I move the legend outside the bar chart area? Because it is hiding some of the bar currently. For the tooltip, what should I use to show the value? Right now I am using "y" but the value is not correct. df = pd.DataFrame(tb, columns=['Files Due', 'Files Past Due', 'Files WIP', 'No Errors', 'Errors Explained', 'Files Failed - Pending Resolution', 'date']) bar = Bar(df, values=blend('Files Due', 'Files Past Due', 'Files WIP', 'No Errors', 'Errors Explained', 'Files Failed - Pending Resolution', name='Number of Files', labels_name='KPI'), label=cat(columns='date', sort=False), stack=cat(columns='KPI', sort=False), color=color(columns='KPI', palette=['#BE4248', '#21374B', '#D7DADB', '#586473', '#E7DACB','#4A89AA'], sort=False), legend='top_right', tooltips=[('Status', '@KPI'),('Number of Files', '@y')], bar_width=0.2, ylabel='KPI') js5, div5 = components(bar) Bokeh stacked bar chart
score: 1
tagged with: bar-chart
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50781047
type: UnansweredQuestion
tagged with: stacked-chart
tagged with: python
tagged with: bokeh

http://stackoverflow.com/comment/81855759
has text: Your loops will only ever give you one value and your last loop tries to assign a whole worksheet to a single cell.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47442631
score: 0

http://stackoverflow.com/comment/81975359
score: 0
type: Comment
type: QuestionComment
has text: One of you commenters should probably write this as an answer.
comment on: http://stackoverflow.com/q/47509869

http://stackoverflow.com/comment/81733596
has text: That would be true for a circle, yes. For other markers, e.g. if you took `"$.$"`, it cannot be determined that easily.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47389449
score: 0

http://stackoverflow.com/comment/81813846
type: Comment
type: AnswerComment
has text: Dear, I have edited my question and getting output... I have edited expected output please help me for getting expected output
comment on: http://stackoverflow.com/a/47427792
score: 0

http://stackoverflow.com/comment/81848312
comment on: http://stackoverflow.com/a/47446167
type: Comment
score: 0
type: AnswerComment
has text: Very helpful. Not able to figure out why the actual csv isn't writing with your script on my Windows setup. Simply replaced the filename with my path to the xml but I'm getting nothing. Also, to clarify even further all I want is to grab _ALL_ tags in these XMLs; so it's a big undertaking. There are even more children that are repetitions that I'll have to tweak. Your outline is helping as a general rule, however.

http://stackoverflow.com/comment/81905718
type: Comment
has text: I managed to impose files=np.loadtxt('files3',dtype=str) into the script as the dataset contain 48 files representing half hourly rainfall for 24 hours..the result is amazing although the iteration took quite sometimes..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47474075

http://stackoverflow.com/comment/92612149
type: QuestionComment
comment on: http://stackoverflow.com/q/47512989
score: 0
type: Comment
has text: Is there a solution for this please feedback.

http://stackoverflow.com/q/47427767
has comment: http://stackoverflow.com/comment/81824028
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81819811
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81817800
upvote count: 1
has comment: http://stackoverflow.com/comment/81824275
favorite count: 0
has comment: http://stackoverflow.com/comment/81815822
tagged with: opencv
has comment: http://stackoverflow.com/comment/81824169
score: 1
has comment: http://stackoverflow.com/comment/81818652
tagged with: python
has answer: http://stackoverflow.com/a/47435625
has body: I am doing a project in python.I want to detect rectangle shape object by opening the webcam using python.I had tried it but I didn't get accurate Answer.I show the object in front of webcam If any finger touched our object it doesn't recognize our object.please anyone can help me.Thanks in Advance:) Here is my code: py: import math import numpy as np import cv2 #dictionary of all contours contours = {} #array of edges of polygon approx = [] #scale of the text scale = 2 #camera cap = cv2.VideoCapture(0) print("press q to exit") # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) #calculate angle def angle(pt1,pt2,pt0): dx1 = pt1[0][0] - pt0[0][0] dy1 = pt1[0][1] - pt0[0][1] dx2 = pt2[0][0] - pt0[0][0] dy2 = pt2[0][1] - pt0[0][1] return float((dx1*dx2 + dy1*dy2))/math.sqrt(float((dx1*dx1 + dy1*dy1))*(dx2*dx2 + dy2*dy2) + 1e-10) while(cap.isOpened()): #Capture frame-by-frame ret, frame = cap.read() if ret==True: #grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #Canny canny = cv2.Canny(frame,80,240,3) #contours canny2, contours, hierarchy = cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) for i in range(0,len(contours)): #approximate the contour with accuracy proportional to #the contour perimeter approx = cv2.approxPolyDP(contours[i],cv2.arcLength(contours[i],True)*0.02,True) #Skip small or non-convex objects if(abs(cv2.contourArea(contours[i]))&lt;100 or not(cv2.isContourConvex(approx))): continue x,y,w,h = cv2.boundingRect(contours[i]) vtc = len(approx) if(vtc==4): cv2.putText(frame,'RECTANGLE',(x,y),cv2.FONT_HERSHEY_SIMPLEX,scale,(255,255,255),2,cv2.LINE_AA) #Display the resulting frame out.write(frame) cv2.imshow('frame',frame) cv2.imshow('canny',canny) if cv2.waitKey(1) == 1048689: #if q is pressed break #When everything done, release the capture cap.release() cv2.destroyAllWindows() Here is my output: Non Working output Working output
type: Question
has comment: http://stackoverflow.com/comment/81818497
has comment: http://stackoverflow.com/comment/81818912
has title: how to detect rectangle shape object using python
has comment: http://stackoverflow.com/comment/81818080
has comment: http://stackoverflow.com/comment/81822073

http://stackoverflow.com/comment/136789562
score: 0
type: AnswerComment
has text: I also had the header issue, but my data was correct. This is more like work-around. The Python pandas package has a bug.
type: Comment
comment on: http://stackoverflow.com/a/47404280

http://stackoverflow.com/comment/81938249
has text: don't know exactly what was causing the problem, but I rewrote the connection cursor and changed to single quotation and it worked, thanks a lot!
comment on: http://stackoverflow.com/a/47383932
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47485944
has comment: http://stackoverflow.com/comment/82019873
has body: I used if-elif instead of If Sa=raw_input('enter something A: ') Sb=raw_input('enter something B: ') Sc=Sa.lower() Sd=Sb.lower() count = 0 for val in Sc: for char in Sd: if char == val: count = count + 1 if count == 0: print("Bad") elif Sc in Sd or Sd in Sc: print('Good') else: print('Almost Good')
has comment: http://stackoverflow.com/comment/82019829
type: Answer
has comment: http://stackoverflow.com/comment/82022036
has comment: http://stackoverflow.com/comment/82022561
has comment: http://stackoverflow.com/comment/82022692
has comment: http://stackoverflow.com/comment/82020953
has comment: http://stackoverflow.com/comment/82021288
score: 0
has comment: http://stackoverflow.com/comment/81927192
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47485638
answers question: http://stackoverflow.com/q/47485638

http://stackoverflow.com/a/47491751
score: 2
has body: you can use "bitwise and" for masks like as follows: item = mydf["Item Name"]=="Pregabalin" typ = mydf["type"]=="Pregabalin 300mg" mydf[item &amp; typ] or simply (in the following case we must use parentheses because of Operator precedence rules): mydf[(mydf["Item Name"]=="Pregabalin") &amp; (mydf["type"]=="Pregabalin 300mg")]
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81939063
answers question: http://stackoverflow.com/q/47491733
has comment: http://stackoverflow.com/comment/81961477
accepted answer of: http://stackoverflow.com/q/47491733
type: Answer
has comment: http://stackoverflow.com/comment/81961394
has comment: http://stackoverflow.com/comment/81961325

http://stackoverflow.com/comment/81864589
score: 1
comment on: http://stackoverflow.com/a/47454832
type: Comment
has text: if I understand it correctly, the [bytecode](https://repl.it/repls/WickedAccurateAntbear) suggests it is a bit faster. It is a **`load global + binary and` vs `load attribute`**
type: AnswerComment

http://stackoverflow.com/q/47485847
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81928439
has comment: http://stackoverflow.com/comment/81930535
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47514693
has comment: http://stackoverflow.com/comment/81927294
has comment: http://stackoverflow.com/comment/81928433
has comment: http://stackoverflow.com/comment/81927364
upvote count: 3
has comment: http://stackoverflow.com/comment/81927246
has answer: http://stackoverflow.com/a/47514693
has comment: http://stackoverflow.com/comment/81928432
has comment: http://stackoverflow.com/comment/81926651
has title: Installing Tensorflow using python3.6 failing
has comment: http://stackoverflow.com/comment/81927879
tagged with: tensorflow
favorite count: 0
type: Question
has body: This my environment at present $ pip show tensorflow Name: tensorflow Version: 1.4.0 Summary: TensorFlow helps the tensors flow Home-page: https://www.tensorflow.org/ Author: Google Inc. Author-email: opensource@google.com License: Apache 2.0 Location: /usr/local/lib/python3.6/site-packages Requires: wheel, tensorflow-tensorboard, enum34, six, numpy, protobuf $ pip show protobuf Name: protobuf Version: 3.5.0 Summary: Protocol Buffers Home-page: https://developers.google.com/protocol-buffers/ Author: protobuf@googlegroups.com Author-email: protobuf@googlegroups.com License: 3-Clause BSD License Location: /usr/local/lib/python3.6/site-packages Requires: six, setuptools $pip show six Name: six Version: 1.11.0 Summary: Python 2 and 3 compatibility utilities Home-page: http://pypi.python.org/pypi/six/ Author: Benjamin Peterson Author-email: benjamin@python.org License: MIT Location: /usr/local/lib/python3.6/site-packages Requires: Traceback (most recent call last): File "", line 1, in File "/Users/joson/tensorflow/lib/python3.6/site-packages/tensorflow/init.py", line 24, in from tensorflow.python import * File "/Users/joson/tensorflow/lib/python3.6/site-packages/tensorflow/python/init.py", line 51, in from tensorflow.python import pywrap_tensorflow File "/Users/joson/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "/Users/joson/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in from tensorflow.python.pywrap_tensorflow_internal import * File "/Users/joson/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "/Users/joson/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, descri…

http://stackoverflow.com/comment/81800886
comment on: http://stackoverflow.com/a/47422872
has text: This is still a flawed solution: `w+` **truncates** the file prior to opening it, and a `read()` followed by a `write()` will just **append** the written string.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47492649
accepted answer: http://stackoverflow.com/a/47492709
has comment: http://stackoverflow.com/comment/81941174
has answer: http://stackoverflow.com/a/47492709
favorite count: 0
type: Question
tagged with: python-3.x
has title: TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' / Base conversions
upvote count: 0
downvote count: 2
answer count: 1
tagged with: python
score: -2
type: AnsweredQuestion
has body: Here is my code and I just don't get this code is not working. def theBase(n, b): convertString = "0123456789" if n &lt; b: return convertString[n] else: return toBase(n//b,b) + convertString[n%b] def toBase(n, b): print(theBase(n, b), end="") def main(): n = int(input()) b = int(input()) print(n, "in base", b, "is ", end="") toBase(n, b) if __name__ == "__main__": main() Do not modify main function

http://stackoverflow.com/comment/81894442
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Then I am satisfied too. Let's see what OP thinks ;)
comment on: http://stackoverflow.com/a/47469789
type: Comment
score: 0

http://stackoverflow.com/a/47484879
has body: Since the data you're trying to parse seems to be multipart/form-data, i think the best approach is cgi.parse_multipart. For this you'll need the request body and the boundary, which you can get from Content-Type headers with cgi.parse_header. An example: import cgi from io import BytesIO import requests data = {'param1':'val1', 'param2':'val2'} files = {'param3':('fname', 'fdata')} r = requests.post('http://httpbin.org', data=data, files=files) boundary = cgi.parse_header(r.request.headers['Content-Type'])[1] boundary['boundary'] = boundary['boundary'].encode() data = cgi.parse_multipart(BytesIO(r.request.body), boundary) print(data) {'param1': [b'val1'], 'param2': [b'val2'], 'param3': [b'fdata']} The result is a dictionary with the field names and a list of values (as bytes) for each field. You could then decode the first item of values in data to get a dict of strings. data = {k:v[0].decode() for k,v in data.items()} print(data) {'param1': 'val1', 'param2': 'val2', 'param3': 'fdata'}
accepted answer of: http://stackoverflow.com/q/47483031
answers question: http://stackoverflow.com/q/47483031
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47487279
has body: You don't need any if statements for this task, you can use a simple for loop to descend into your nested dictionary. from pprint import pprint def path_append(path, item, location, content): for k in location: path = path[k] path[item] = {"Content": content} # test E = {"C:":{"Desktop.fld":{"Hello.txt":{"Content":"Hello, World"}}}} print('old') pprint(E) path_append(E, "Hi.txt", ["C:", "Desktop.fld"], "Hi There, World") print('\nnew') pprint(E) output old {'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'}}}} new {'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'}, 'Hi.txt': {'Content': 'Hi There, World'}}}} BTW, you shouldn't use dict as a variable name because that shadows the built-in dict type. Also, it's conventional in Python to use lower-case for normal variable and function names. All uppercase is used for constants, and capitalized names are used for classes. Please see the PEP 8 -- Style Guide for Python Code for further details. I also noticed that the code block at the start of your question uses If instead of the correct if syntax, but perhaps that's supposed to be pseudo-code.
downvote count: 0
answers question: http://stackoverflow.com/q/47487024
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47487024
has comment: http://stackoverflow.com/comment/81932482
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/49322360
downvote count: 0
answers question: http://stackoverflow.com/q/47498293
type: Answer
has body: In the last for loop of your code, you are repeatedly assigning to the variable token its attribute token.lemma_ and then doing this again and again (overwriting this at every iteration and not keeping track of the previous values). Instead, assuming that your dataframe contains strings, as in example = pd.DataFrame({"col1":["this is spacy lemmatization testing.", "some programming books are better than others", "sounds like a quote from the Smiths"]}) apply and list comprehensions can do the job with: example["col1"].apply(lambda row: " ".join([w.lemma_ for w in nlp(row)]))
score: 8
upvote count: 8

http://stackoverflow.com/a/47515944
answers question: http://stackoverflow.com/q/47515025
has body: Thanks but that still won't work because i want to have the different values in different columns in the database. I was able to resolve the problem by creating a second dictionary that counts the number of times a label occurs. From this dict I add the count after the name of the label if label not in count_dict: count_dict[label] = 1 dict[label] = value else: count_dict[label] += 1 label = label + ' ' + str(count_dict[label]) dict[label] = value Resulting output: { 'slaapkamer': '8 m²', 'slaapkamer 2': '7 m²' }
type: Answer
score: 0

http://stackoverflow.com/a/47495642
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47495326
score: 1
has body: You can do the following. Chunk the string appropriately and then use the zip(*...) transpositioning pattern: def group(seq, n): return [seq[i:i+n] for i in range(0, len(seq), n)] &gt;&gt;&gt; a = '54776f204f6e65204e696e652054776f' &gt;&gt;&gt; list(zip(*group(group(a, 2), 4))) [('54', '4f', '4e', '20'), ('77', '6e', '69', '54'), ('6f', '65', '6e', '77'), ('20', '20', '65', '6f')]

http://stackoverflow.com/comment/82001391
score: 0
comment on: http://stackoverflow.com/q/47519802
has text: What's the `dtype` of `r_arr` and of the result of the `convert`? `convert_to_tensor` doesn't say anything about copy or not; where did you read about it?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82027865
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47523018
has text: if your `sin` and `cos` need radians then your angles are wrong (I see `+/-10`) you should convert them to radians first ... `+/-10*rad` where `rad=M_PI/180.0` ... `M_PI=3.1415...`
type: QuestionComment

http://stackoverflow.com/comment/82035664
comment on: http://stackoverflow.com/a/47539082
score: 0
has text: Thank you for the answer! Do you recommend the threaded example given you have a good idea of what I am trying to do which is run multiple trading scripts for different symbols all at the same time after market open at 9:30 EST?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47494960
tagged with: python
accepted answer: http://stackoverflow.com/a/50705390
type: AnsweredQuestion
has body: I am trying to scrape some date from the webpage soundseasy.com.au, but sometimes I get the error: AttributeError: 'SoundseasySpider' object has no attribute 'crawler' Here is my code, which use selenium web driver(self.browser instance) to fetch data from the dynamic page: import scrapy from ProductsScraper.items import ProductDataItem, ProductDataLoader from utilities.common import MODE_SINGLE from utilities.DynamicPageLoader import DynamicPageLoader def start_requests(self): # scrape multi page data for page_count, url in zip(self.pages_counts, self.start_urls): yield scrapy.Request(url=url, callback=self.multi_parse, meta={'page_count': page_count}, dont_filter=True) def multi_parse(self, response): """ Method fetched the pages, gets the product url links and scrape it by calling parse_product """ selector = self.get_dynamic_page(url=response.url, page_count=response.meta.get('page_count', '1')) product_urls = selector.xpath('//div[@class="isp_product_info"]/a/@href').extract() self.logger.info('{} items should be scraped from the page: {},' ' scroll_count:{}'.format(len(product_urls), response.url, response.meta.get('page_count', '1'))) for product_url in product_urls: # construct absolute url url = "https://www.{}{}".format(self.allowed_domains[0], product_url) yield scrapy.Request(url=url, callback=self.parse_product, dont_filter=True) def get_dynamic_page(self, url, page_count): """ Fetch dynamic page using DynamicDownloader and return selector object """ # construct search page url with the page count included pages_url = url + '&amp;page_num={}'.format(page_count) self.logger.info("get_dynamic_page: {}".format(pages_url)) self.browser.load_page(pages_url) return scrapy.Selector(text=self.browser.get_html_page()) What I am doing wrong? Any help is appreciated. EDIT: I got the exception below: File "/home/user/python3.6.1/lib/python3.6/site-packages/Twisted-17.9.0-py3.6-linux-x86_64.egg/twisted/internet/defer.py", line 1384, in _inlineCallbacks result = resu…
has answer: http://stackoverflow.com/a/50705390
has comment: http://stackoverflow.com/comment/81968214
answer count: 1
tagged with: selenium
downvote count: 0
upvote count: 1
tagged with: scrapy
has comment: http://stackoverflow.com/comment/81948012
has comment: http://stackoverflow.com/comment/81945004
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81946959
has comment: http://stackoverflow.com/comment/81947395
has title: Scrapy AttributeError: 'SoundseasySpider' object has no attribute 'crawler'
has comment: http://stackoverflow.com/comment/81945064
score: 1

http://stackoverflow.com/q/47512664
tagged with: http://stackoverflow.com/tag/csv
score: 0
has title: merge tsv files in one csv by extracting particular columns and naming the column as file name
has comment: http://stackoverflow.com/comment/82079135
has comment: http://stackoverflow.com/comment/82096781
type: Question
tagged with: python-3.x
has body: I have multiple tsv files in folder. From each file I have to extract 1st column which is the abundance and 5th column which is ID, there are no headers for columns. I have to merge these columns from each file in one file and give their headers as there file name. Also I have to compare check if all the ID'a are present, if not then value should be zero. One of the sample files File_Name1 looks like: 0.11 31 31 U 0 unclassified 99.89 29001 0 - 1 root 99.89 29001 0 - 131567 cellular organisms 99.89 29001 64 D 2 Bacteria 59.94 17401 270 - 1783272 Terrabacteria group 53.47 15522 8 P 1239 Firmicutes 52.10 15127 998 C 186801 Clostridia 37.83 10982 494 O 186802 Clostridiales 20.61 5983 89 F 186803 Lachnospiraceae 16.95 4922 8 G 1506553 Lachnoclostridium 14.53 4219 0 S 84030 [Clostridium] saccharolyticum Similarly I have multiple files. The file I want is like : ID File_Name1 File_Name2 186802 16.95 37.88 1506553 20.61 0 84030 14.53 0.05 I have tried something like this: import glob import csv directory = "C:\kraken\kraken_13266" txt_files = glob.glob(directory+"\*.kraken") for txt_file in txt_files: with open(txt_file, "rt") as input_file, open('output.csv', "wt") as out_file: in_txt = csv.reader(input_file, delimiter='\t') for line in in_txt: firstcolumns = line[:1] lastcolumns = line[-2].strip().split(",") allcolumns = firstcolumns + lastcolumns I'm stuck at this point. How should I proceed further.
has comment: http://stackoverflow.com/comment/82078850
has answer: http://stackoverflow.com/a/47571328
answer count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47571328

http://stackoverflow.com/q/47399913
answer count: 1
downvote count: 1
score: 6
has comment: http://stackoverflow.com/comment/82571050
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29576993
has title: Exscript: How do I switch between interactive and non interactive sessions?
has comment: http://stackoverflow.com/comment/82578353
tagged with: python
has body: I am trying to programaticaly open a session with a Unix server and then release the control to the user of the script till Ctrl+y is pressed after which the program should take control I am using Eclipse and WinPython 2.7. here is the code from Exscript.util.interact import read_login from Exscript.protocols import SSH2 def Test (): print "Interactive session closed" account = read_login() # Prompt the user for his name and password conn = SSH2() conn.set_driver('generic') # We choose to use SSH2 conn.connect('remmotehostip') # Open the SSH connection conn.login(account) # Authenticate on the remote host conn.execute('uname -a') # Execute the "uname -a" command print conn.response conn.interact({'\031': Test()}) conn.send('exit\r') # Send the "exit" command conn.close() the above fails with Traceback (most recent call last): File "C:\Users\mynamehere\Documents\Eclipse\ESNetworkDiscovery\TestInteractiveSession.py", line 20, in &lt;module&gt; conn.interact({'\031': Test()}) File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\Exscript\protocols\SSH2.py", line 364, in interact return self._open_shell(self.shell, key_handlers, handle_window_size) File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\Exscript\protocols\Protocol.py", line 1190, in _open_shell return self._open_windows_shell(channel, key_handlers, handle_window_size) TypeError: _open_windows_shell() takes exactly 3 arguments (4 given) What am I doing wrong ?
has comment: http://stackoverflow.com/comment/82575130
tagged with: exscript
has answer: http://stackoverflow.com/a/47804159
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82575331
upvote count: 7

http://stackoverflow.com/a/47533978
has body: so I figured out there is a forum for plotly and someone answered there (https://community.plot.ly/t/gantt-cropped-text/7053/3). I managed to solve the problem programmatically. I calculate the max width of the task column in pixel using a function. After creating the chart I use an uptade method and give the max width as an argument. Then I display the chart. def max_length_col(column,font='OpenSans-Regular.ttf', font_size=14): '''Calculates the max length of a column of a dataframe / a panda serie in pixels. Default keyword arguments values are useful to adapt the length of the y axis of a plotly gantt chart. Args: column: panda serie font: ttf filename (look under ...\Windows\Font, get the exact name by right-clicking on a ttf file and then go to properties) font_size : font size as an int Example: In: df_gantt =pd.DataFrame([ {'Task': 'Anthony Clark', 'Start': '2017-12-13', 'Finish': '2018-02-23'}, {'Task': 'Ariosto Li Fonti', 'Start': '2017-12-15', 'Finish': '2018-01-23'}, {'Task': 'Cettina Trevisano', 'Start': '2017-12-20', 'Finish': '2018-03-08'}]) column_len = max_length_col(df_gantt['Task']) print(column_len) Out: 117 Returns: Length of the column in pixel as an int ''' from PIL import ImageFont #pip install pillow font = ImageFont.truetype(font,font_size) # should already be installed, if not download it and save under Windows/Font length_list = [] for row in range(len(column)): text = str(column[row]) size = font.getsize(text) length_list.append(size[0]) # append length in pixel (size[1] for heigth) max_length_px = max(length_list) return max_length_px import pandas as pd from plotly.offline import init_notebook_mode, iplot from plotly.graph_objs import * init_notebook_mode(connected=True) # initiate notebook for offline plot import plotly.figure_factory as ff df_gantt2 =pd.DataFrame([ {'Task': 'Anthony Clark', 'Start': '2017-12-13', 'Finish': '2018-02-23'}, {'Task': 'Ariosto Li Fonti', 'Start': '2017-12-15', 'Finish': '2018-01-23'}, {'Task': 'Cettina Tre…
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47516276
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/47385038
answers question: http://stackoverflow.com/q/47384440
type: Answer
has body: Your algorithm is O(n^2) since it is two nested loops. Each single step of the outer loop you loop through the entire list in the inner loop. This means the time will increase dramatically as the list length increases. It is also unnecessary. Instead, you can loop through once and just note which key value has been seen at each list index. This works efficiently in a single pass: from collections import OrderedDict od=OrderedDict() for i, ld in enumerate(parentElement): od.setdefault(ld['key'], []).append(i) &gt;&gt;&gt; od OrderedDict([('K', [0, 5, 8]), ('L', [1, 6]), ('M', [2, 3, 4, 7])]) &gt;&gt;&gt; od.values() [[0, 5, 8], [1, 6], [2, 3, 4, 7]] Since we are using an ordered dict, which maintains insertion order, no post sorting is required to create a list with the order of the original list. (Python 3.6 that is not necessary.) Or, if you want the alternate representation: &gt;&gt;&gt; {l[0]:l[1:] for l in od.values()} {0: [5, 8], 1: [6], 2: [3, 4, 7]} With this form, you do not need to use an Ordered Dict since the order does not matter for the mapping of the first element to the remainder elements.
score: 0

http://stackoverflow.com/a/47509437
has body: Use replace() : &gt;&gt;&gt; s = 'Arabidopsis thaliana' &gt;&gt;&gt; s.replace(s.split()[0], s[0]) 'A thaliana' In the rare case, according to mrCarnivore if the first word is occurring multiple times we could use maxreplace parameter &gt;&gt;&gt; s = 'Arabidopsis Arabidopsis thaliana' &gt;&gt;&gt; s.replace(s.split()[0], s[0], 1) 'A Arabidopsis bologna'
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81976456
has comment: http://stackoverflow.com/comment/81974864
accepted answer of: http://stackoverflow.com/q/47509304
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47509304
has comment: http://stackoverflow.com/comment/81974761

http://stackoverflow.com/comment/83712952
comment on: http://stackoverflow.com/a/47732558
type: AnswerComment
score: 1
has text: The brew install script from brew.sh does things that brew doctor does not (yet) know to take care of.
type: Comment

http://stackoverflow.com/comment/81831076
comment on: http://stackoverflow.com/a/47437910
score: 0
type: AnswerComment
has text: Thank you, i am a noob in programming. appreciate for your help
type: Comment

http://stackoverflow.com/a/47602867
answers question: http://stackoverflow.com/q/47458172
has body: You need to source /usr/local/bin/virtualenvwrapper.sh in your .bashrc (you don't need to export it).
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/81939665
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47492077
score: 0
has text: @ᴬᴶᵁᴾᴾᴬᴸ `d = defaultdict(list) for lst in flat_list: key = len(lst) d[key].append(lst)`? grouping with dicts is always very straightforward.

http://stackoverflow.com/comment/81872792
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47459072
has text: Yes i know, sorry. Didn't think of it
score: 0

http://stackoverflow.com/comment/120472426
has text: Great to hear @sheharbano!
comment on: http://stackoverflow.com/a/47502166
score: 0
type: Comment
type: AnswerComment

python-extensions
tags question: http://stackoverflow.com/q/47511947
type: Tag
tag name: python-extensions

http://stackoverflow.com/a/47524984
type: Answer
accepted answer of: http://stackoverflow.com/q/47524358
has body: You have several problems here. First, you're using the wrong geometry manager. The pack geometry manager, as the name implies, packs the widgets as close together as possible. That's not what you want. The grid geometry manager lets you put the widgets into a table-like layout with rows and columns. If you put the Browse button into the first column and the Quit button into the last column, you'll be a step closer. Second, your Application window contains three child widgets and you're only putting two of them into a geometry manager. How that is going to mess you up I don't even want to think about. So I put the label into column 1, the Quit button into column 2, and the Browse button into column 0. The Quit button I gave a "sticky" value of "e" so it will be attached to the east (right) side of its allocated space. Third, all the geometry managers try to compact the widgets as much as possible unless you specifically tell it to do otherwise. I told the grid manager to expand column 2 so that the extra space gets assigned to the cell that holds the Quit button. Fourth, you need to tell the pack manager to expand the top widget so that it spans the entire window. The directive for that is fill="x". Fifth, you have a redundant call to the pack manager at the end of your createWidgets function. import tkinter as tk from tkinter.ttk import * class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack(fill="x") self.createWidgets() self.master.title("Log Parser") def createWidgets(self): self.Run_Main = tk.Button(self) self.Run_Main["text"] = "Browse.." # self.Run_Main["fg"] = "blue" self.Run_Main["command"] = self.Sayhello self.Label = tk.Label(self) self.Label["text"] = 'Processing...' self.progressbar = Progressbar(mode="indeterminate", maximum=20) self.QUIT = tk.Button(self) self.QUIT["text"] = "Quit!" self.QUIT["command"] = self.quit self.Label.grid(row=0, column=1) self.Run_Main.grid(row=0, column=0, sticky="w") self.QU…
score: 0
answers question: http://stackoverflow.com/q/47524358
has comment: http://stackoverflow.com/comment/82020430
has comment: http://stackoverflow.com/comment/82006681
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82082536

http://stackoverflow.com/comment/81999109
type: Comment
type: QuestionComment
score: 0
has text: Yes, so don't use `xlim` before creating the figure. And since for the figure you already need some `x`, don't use `xlim` at all.
comment on: http://stackoverflow.com/q/47514526

http://stackoverflow.com/comment/81744909
type: Comment
has text: how about `list(map(lambda x: x, [])) or dict(Counter('hello'))`, meeting the requirements to use map and lambda ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/47395819
score: 3

http://stackoverflow.com/q/47402225
answer count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45773871
tagged with: python
has title: Python sqlalchemy trying to write pandas dataframe to SQL Server using .to_sql
has body: I have a python code through which I am getting a pandas dataframe "df". I am trying to write this dataframe to Microsoft SQL server. I am trying to connect through the following code by I am getting an error import pyodbc from sqlalchemy import create_engine engine = create_engine('mssql+pyodbc:///?odbc_connect=DRIVER={SQL Server};SERVER=bidept;DATABASE=BIDB;UID=sdcc\neils;PWD=neil!pass') engine.connect() df.to_sql(name='[BIDB].[dbo].[Test]',con=engine, if_exists='append') However at the engine.connect() line I am getting the following error sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)') Can anyone tell me what I am missing. I am using Microsoft SQL Server Management Studio - 14.0.17177.0 I connect to the SQL server through the following Server type: Database Engine Server name: bidept Authentication: Windows Authentication for which I log into my windows using username : sdcc\neils and password : neil!pass I am new to databases and python. Kindly let me know if you need any additional details. Any help will be greatly appreciated. Thank you in advance.
linked to: http://stackoverflow.com/q/47416699
score: 2
tagged with: sql-server
upvote count: 2
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/82909425
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47424163

http://stackoverflow.com/comment/81917886
score: 0
comment on: http://stackoverflow.com/q/47481475
type: QuestionComment
has text: You generally wouldn't try to `del(self)` as a way of removing an class instance. You've also overridden `__del__`. Why not just remove that user if they wish to close their account?
type: Comment

http://stackoverflow.com/a/47462329
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47461781
has body: This answer is a bit more brute force and less elegant, but it shows some of the more basic pandas data frame building operations in a very clear and readable way. I think you will find ways to do this more elegantly over time. import pandas as pd # Prepare data set for dataframe table = 'year','value' value = 0 for year in range(2004,2010,1): value += 1 array = [year, value] table.append(array) headers = table.pop(0) df = pd.DataFrame(table, columns=headers) # Bucketize the data in a new dataframe tableNew = 'year','value' sum = 0 for i in range(len(df)): year = df.iloc[i]['year'] value = df.iloc[i]['value'] sum += value if (year % 5) == 0: tableNew.append([year, sum]) sum = 0 while year % 5 != 0: i += 1 year += 1 value = 0 sum += value if (year % 5) == 0: tableNew.append([year, sum]) newHeaders = tableNew.pop(0) dfNew = pd.DataFrame(tableNew,columns=newHeaders) print dfNew Output: year value 0 2005 3 1 2010 18
type: Answer

http://stackoverflow.com/a/74262494
answers question: http://stackoverflow.com/q/47426546
has body: Try import from setuptools import setup
type: Answer
score: 0

http://stackoverflow.com/comment/98612502
score: 0
type: Comment
has text: I was just asking the same as you. Asking for help to get an elegant way to do it :/
type: AnswerComment
comment on: http://stackoverflow.com/a/55981558

http://stackoverflow.com/q/47481284
upvote count: 1
type: UnansweredQuestion
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47688921
type: Question
has body: I'm trying to install the statistics model in Python 3.6.1, but I get the following exception error. Does anyone have any idea what it can be? I have installed Visual C++. I do not know if I should install something else. Microsoft Windows [Versión 10.0.15063] (c) 2017 Microsoft Corporation. Todos los derechos reservados. C:\Users\Sebastián&gt;cd C:\Users\Sebastián\AppData\Local\Programs\Python\Python36 C:\Users\Sebastián\AppData\Local\Programs\Python\Python36&gt;cd Scripts C:\Users\Sebastián\AppData\Local\Programs\Python\Python36\Scripts&gt;pip install statsmodels Collecting statsmodels Using cached statsmodels-0.8.0.tar.gz Installing collected packages: statsmodels Running setup.py install for statsmodels ... error Exception: Traceback (most recent call last): File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str return s.decode(sys.__stdout__.encoding) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 148: invalid continuation byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 878, in install spinner=spinner, File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess line = console_to_str(proc.stdout.readline()) File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\p…
has title: error in installing statsmodels for python 3.6.1
tagged with: statsmodels
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81935435
has comment: http://stackoverflow.com/comment/81922715
downvote count: 0

http://stackoverflow.com/a/47463798
answers question: http://stackoverflow.com/q/47463490
score: 1
type: Answer
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47463490
has body: You can add \n to preserve new lines or \s to preserve any white spaces. For \s it's this code: import re class TextCleaner: uncleanText = open("words.txt").read() cleanText = re.sub('[^A-Za-z0-9\s]+', '', uncleanText) open('words.txt', 'w').write(cleanText)

http://stackoverflow.com/q/47393801
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
has title: How to retrieve elements of an array from a python dictionary
has comment: http://stackoverflow.com/comment/81741364
has answer: http://stackoverflow.com/a/47394396
answer count: 1
has body: I have a python dictionary generated using code.It's in this format { (127016, 2015, 'FY'): { 'id': array([], dtype=int32), 'index': { ('ID698971838', 'OR'): { 'id': array([], dtype=int32), 'elems': { ('PCT_AP_CUST_ID', 'I'): array([-1]) } } } } Here is my first 3 elements of Dictionary [((701091, 2013, 'FY'), {'id': array([], dtype=int90), 'APs': {('AP010977414', 'OR'): {'id': array([], dtype=int90), 'elems': {('M_Group_CUST_ID', 'I'): array([-1]), ('ISO_AP', 'I'): array([-1])}}}}), ((701111, 2013, 'FY'), {'id': array([], dtype=int90), 'APs': {('AP911117711', 'OR'): {'id': array([], dtype=int90), 'elems': {('ISO_AP', 'I'): array([-1])}}}}), ((701077, 2013, 'FY'), {'id': array([], dtype=int90), 'APs': {('AP090419711', 'OR'): {'id': array([], dtype=int90), 'elems': {('M_CTL_SELL_TYP', 'I'): array([ -1, 99919, 99970, 74071, 10909, 11910, 991997, 991994, 991999, 997000, 997001, 997000, 997009, 997001, 997007, 997001, 997007, 997004, 997009, 997010, 997011, 997010, 997019, 997011, 997017, 997011, 997017, 997014, 997019, 997000, 997001, 997000, 997009, 997001, 997007, 997001, 997007, 997004, 997009, 997090, 997091, 997090, 997099, 997091, 997097, 997091, 997097, 997094, 997099, 997010, 997011, 997010, 997019, 997011, 997017, 997011, 997017, 997014, 997019, 997070, 997071, 997070, 997079, 997071, 997077, 997071, 997077, 997074, 997079, 997010, 997011, 997010, 997019, 997011, 997017, 997011, 997017, 997014, 997019, 997070, 997901, 997907, 997904, 997909, 997990, 997991, 997990, 997999, 997991, 997997, 997991, 997997, 997994, 997999, 997910, 997911, 997910, 997919, 997911, 997917, 997911, 997917, 997914, 997919, 997970, 997971, 997970, 997979, 997971, 997977, 997971, 997977, 997974, 997979, 997910, 994744, 994749, 994790, 994791, 994790, 994799, 994791, 994797, 994791, 994797, 994794, 994799, 994400, 994401, 994400, 994409, 994401, 994407, 994401, 994407, 994404, 994409, 994410, 994411, 994410, 994419, 994411, 994417, 994411, 994417, 994414, 994419, 994400, 994401, 994400, …
downvote count: 1

http://stackoverflow.com/q/47400218
answer count: 4
score: 2
has comment: http://stackoverflow.com/comment/81754039
tagged with: bash
has body: I have a file with a list of adjectives A - Z How can I print the first word beginning with A, then the first word beginning with B ... all the way to Z? I thought grep might be the way. But open to others, awk, python...other. Some sample outputs: $ cat adjectives.txt | head Adamant: unyielding; a very hard substance Adroit: clever, resourceful Amatory: sexual Animistic: quality of recurrence or reversion to earlier form Antic: clownish, frolicsome Arcadian: serene Baleful: deadly, foreboding Bellicose: quarrelsome (its synonym belligerent can also be a noun) Bilious: unpleasant, peevish Boorish: crude, insensitive $ cat adjectives.txt | grep '^[ABCDE]' | head Adamant: unyielding; a very hard substance Adroit: clever, resourceful Amatory: sexual Animistic: quality of recurrence or reversion to earlier form Antic: clownish, frolicsome Arcadian: serene Baleful: deadly, foreboding Bellicose: quarrelsome (its synonym belligerent can also be a noun) Bilious: unpleasant, peevish Boorish: crude, insensitive So my sample output would be: Adamant: unyielding; a very hard substance Baleful: deadly, foreboding ... Irksome: annoying Jejune: dull, puerile ... Wheedling: flattering Zealous: eager, devoted File in full from here $ cat adjectives.txt Adamant: unyielding; a very hard substance Adroit: clever, resourceful Amatory: sexual Animistic: quality of recurrence or reversion to earlier form Antic: clownish, frolicsome Arcadian: serene Baleful: deadly, foreboding Bellicose: quarrelsome (its synonym belligerent can also be a noun) Bilious: unpleasant, peevish Boorish: crude, insensitive Calamitous: disastrous Caustic: corrosive, sarcastic; a corrosive substance Cerulean: sky blue Comely: attractive Concomitant: accompanying Contumacious: rebellious Corpulent: obese Crapulous: immoderate in appetite Defamatory: maliciously misrepresenting Didactic: conveying information or moral instruction Dilatory: causing delay, tardy Dowdy: shabby, old-fashioned; an unkempt woman Efficaciou…
upvote count: 2
type: UnansweredQuestion
tagged with: awk
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/81754096
type: Question
has comment: http://stackoverflow.com/comment/81754072
has answer: http://stackoverflow.com/a/47400385
has answer: http://stackoverflow.com/a/47400492
tagged with: grep
has title: Print out the first occurrence of a word in a file beginning with each letter in the Alphabet
has answer: http://stackoverflow.com/a/47400356
tagged with: python
has answer: http://stackoverflow.com/a/47400390

http://stackoverflow.com/a/47522712
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47522541
has body: you were almost there: In [87]: df.assign(oldest=df'A','B'.min(1), latest=df'A','B'.max(1)) Out[87]: A B oldest latest 0 2010/1/1 2013/3/1 2010/1/1 2013/3/1 1 2014/2/1 2012/1/3 2012/1/3 2014/2/1
score: 2
answers question: http://stackoverflow.com/q/47522541
upvote count: 2

inheritance
tags question: http://stackoverflow.com/q/47397734
tags question: http://stackoverflow.com/q/47407887
tags question: http://stackoverflow.com/q/47420141
tags question: http://stackoverflow.com/q/47479664
tags question: http://stackoverflow.com/q/47428874
tag name: inheritance
tags question: http://stackoverflow.com/q/47517595
tags question: http://stackoverflow.com/q/47442944
tags question: http://stackoverflow.com/q/47445137
tags question: http://stackoverflow.com/q/47513077
type: Tag
tags question: http://stackoverflow.com/q/47535061
tags question: http://stackoverflow.com/q/47470664
tags question: http://stackoverflow.com/q/47513038

http://stackoverflow.com/comment/81968518
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47465777
has text: glad that I helped
type: AnswerComment

http://stackoverflow.com/comment/81850120
score: 0
type: Comment
type: QuestionComment
has text: @wrneoin You have a key-dict pair. You need a key-list of dict pair if you want to add multiple separate dicts.
comment on: http://stackoverflow.com/q/47447419

http://stackoverflow.com/q/47403538
has title: How to split list of strings into sublists where len("".join(sublist)) <= N?
has answer: http://stackoverflow.com/a/47403599
has comment: http://stackoverflow.com/comment/81761222
accepted answer: http://stackoverflow.com/a/47403599
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81761501
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81761176
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81761282
upvote count: 0
has comment: http://stackoverflow.com/comment/81761349
has comment: http://stackoverflow.com/comment/81761131
has body: I'm given a list of strings and a length limit N. I have to write a function to accumulate consecutive strings in the list until the next string would exceed the N limit. I have to return a list of lists, where each list is the largest consecutive substring not to exceed N characters total. See the test case below for an example. Also, if any single string in the list is longer than N, I have to print a useful message and return. def break_lst(lst, size): def len_lst(l): return len("".join(l)) result = [] sublst = [] for i, v in enumerate(lst): sublst.append(v) ls = len_lst(sublst) if ls == size: result.append(sublst) sublst = [] elif ls &gt; size: prev_sublst = sublst[:-1] if not prev_sublst or len_lst(prev_sublst) &gt; size: raise Exception("Error: use a bigger size than " + str(size)) else: result.append(prev_sublst) sublst = [] return result if __name__ == "__main__": lst = ["1", "22", "333", "4444", "55555", "666666", "7777777", "88888888"] for i in range(17): try: print(i, break_lst(lst, size=i)) except Exception as e: print(e) The above code it's not only ugly but also buggy, it's giving me this output: Error: use a bigger size than 0 Error: use a bigger size than 1 Error: use a bigger size than 2 Error: use a bigger size than 3 Error: use a bigger size than 4 Error: use a bigger size than 5 Error: use a bigger size than 6 Error: use a bigger size than 7 8 [['1', '22', '333'], ['55555'], ['7777777']] 9 [['1', '22', '333'], ['55555'], ['7777777']] 10 [['1', '22', '333', '4444'], ['55555'], ['7777777']] 11 [['1', '22', '333', '4444'], ['666666']] 12 [['1', '22', '333', '4444'], ['666666']] 13 [['1', '22', '333', '4444'], ['666666', '7777777']] 14 [['1', '22', '333', '4444'], ['666666', '7777777']] 15 [['1', '22', '333', '4444', '55555'], ['666666', '7777777']] 16 [['1', '22', '333', '4444', '55555']] When the expected output should be: Error: use a bigger size than 0 Error: use a bigger size than 1 Error: use a bigger size than 2 Error: use a bigger size than 3…
answer count: 1
downvote count: 1

http://stackoverflow.com/q/47415088
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
upvote count: 7
score: 7
answer count: 1
favorite count: 0
type: Question
has title: Pandas one liner to filter rows by nunique count on a specific column
has body: In pandas, I regularly use the following to filter a dataframe by number of occurrences df = df.groupby('A').filter(lambda x: len(x) &gt;= THRESHOLD) Assume df has another column 'B' and I want to filter the dataframe this time by the count of unique values on that column, I would expect something like df = df.groupby('A').filter(lambda x: len(np.unique(x['B'])) &gt;= THRESHOLD2) But that doesn't seem to work, what would be the right approach?
has answer: http://stackoverflow.com/a/47415132
tagged with: python
accepted answer: http://stackoverflow.com/a/47415132

http://stackoverflow.com/comment/81865498
has text: I've put the extra brackets in but its still not working, I will post a link to the above comment after authorisation of posting a link
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47455558

http://stackoverflow.com/comment/82029192
type: AnswerComment
has text: since you are doing membership tests to check the condition and casting to `list`, why not cast to `set` instead that would be faster?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47535880

http://stackoverflow.com/comment/81771956
comment on: http://stackoverflow.com/a/47397426
score: 0
type: Comment
type: AnswerComment
has text: This is perfect. I knew I could somehow walk the tree, but the key idea here is the "if args==(t,)" I would have definitely not know that this is even possible! Thanks!

http://stackoverflow.com/a/47516688
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47516659
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47516659
score: 3
has body: You don't need a lambda for that, just call the built-in dict on the result from zip: dict_distances = dict(zip(xy, distances)) Builds a mapping from the 2-tuple returned by zip.

http://stackoverflow.com/comment/81729247
score: 2
comment on: http://stackoverflow.com/q/47387713
has text: `lambda event, x=i : self.but_callback(event, x)`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81995473
score: 0
type: Comment
type: QuestionComment
has text: I a plotting the data from MATLAB with Python....
comment on: http://stackoverflow.com/q/47518631

http://stackoverflow.com/a/47478237
answers question: http://stackoverflow.com/q/47477771
has body: You are probably using sqlite as the database. You must not use that on Heroku, as it is stored on the ephemeral file system. Use the proper Postgres add-on.
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81886852
score: 0
type: AnswerComment
has text: You forgot the case insensitivity requirement.
comment on: http://stackoverflow.com/a/47466152
type: Comment

http://stackoverflow.com/q/47479033
score: 1
has comment: http://stackoverflow.com/comment/81913285
accepted answer: http://stackoverflow.com/a/47479129
tagged with: python
type: Question
downvote count: 0
answer count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/47479152
has answer: http://stackoverflow.com/a/47479129
duplicate of: http://stackoverflow.com/q/123198
has answer: http://stackoverflow.com/a/47479152
tagged with: copy
favorite count: 0
tagged with: timestamp
has comment: http://stackoverflow.com/comment/81913130
has answer: http://stackoverflow.com/a/47479124
type: AnsweredQuestion
has title: Python copy file but keep original
has body: Python query. I want to take a copy of a file, called randomfile.dat, and add a timestamp to the end of the copied file. However, I want to keep the original file too. So in my current directory (no moving files) I would end up with: randomfile.dat randomfile.dat.201711241923 (or whatever the timestamp format is..) Can someone advise? Anything I have tried causes me to lose the original file.

http://stackoverflow.com/comment/81933041
score: 0
has text: Just as you wouldn't call `sns.distplot(x=sns.barplot(x))` or so, you should not put a `palplot` into the arguments of `barplot`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47488856

http://stackoverflow.com/a/47419091
has body: I believe I have figured out the answer, it seems that in order to activate subprocess-mode within a for loop, you can do it explicitly with an uncaptured subprocess using the $[] syntax: from glob import glob import os for $fn in glob('*.md'): _, $bname = os.path.split($fn) $[pandoc $fn &gt; $bname.html] In order to get the python variables to propagate into the subprocess, it seems you need to declare them as $varname.
has comment: http://stackoverflow.com/comment/81792297
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47418800

http://stackoverflow.com/a/69928458
has body: In case you faced this issue while using pytest-django package, check that your haven't created new migrations with --reuse-db option in your pytest.ini
answers question: http://stackoverflow.com/q/47517981
score: 0
type: Answer

sklearn-pandas
tags question: http://stackoverflow.com/q/47485203
type: Tag
tag name: sklearn-pandas
tags question: http://stackoverflow.com/q/47476036
tags question: http://stackoverflow.com/q/47397337

http://stackoverflow.com/comment/81763131
has text: @yoda nice to see your activity on SO too, like unix forums `+1`
type: Comment
comment on: http://stackoverflow.com/a/47399153
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81816405
comment on: http://stackoverflow.com/a/47430612
score: 0
type: AnswerComment
type: Comment
has text: @M.Jones : honest suggestion ,read basics of python first :) || hint for what you asked : `a = "123"` then `for i in a: print(i)` ...: 1 2 3

http://stackoverflow.com/q/47475618
has title: Python splitting text in a column
has body: Splitting Text in a Column into Multiple Rows in a DataFrame df = pd.DataFrame({'age':['34','22','19'],'Ticket':['23:44:55','66:77:88','43:68:05 56:34:12'],'PlusOne':['0','0','1'],}) Split out the two values in the third row ticket_series = df['Ticket'].str.split(' ').apply(pd.Series, 1).stack() Get rid of the stack: Drop the level to line up with the DataFrame ticket_series.index = ticket_series.index.droplevel(-1) ticketdf = pd.DataFrame(ticket_series) del df['Ticket'] df.join(ticketdf) df I don't understand why it can't join together!!
tagged with: python
accepted answer: http://stackoverflow.com/a/47475655
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47475655
favorite count: 0
type: Question

http://stackoverflow.com/comment/81743468
has text: never mind, I think your 2nd regex works fine when there is a string value like `' 354.72-'` (has leading spaces in the string) in `amount` column
comment on: http://stackoverflow.com/a/47394765
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47462671
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47462734
has title: Create column that makes summation to a scalar
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47462734
has body: I have the following df: valor BB 435.116 CEL -1439.250 DI 132.300 AC 560.500 and the following scalar: x=2000 what is the best way of generating a new column that makes the summation to valor in each row? The desired output would look something like this: valor summ BB 435.116 2435.116 CEL -1439.250 995.866 DI 132.300 1128.166 AC 560.500 1688.666 where to the initial scalar adds the value in the corresponding row Is there a simple way to perform this?
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
tagged with: dataframe

http://stackoverflow.com/q/47504248
has comment: http://stackoverflow.com/comment/81999395
tagged with: numpy
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81965787
has body: I have two graphs that share the same x-axis. They are both time series with 2880 times (4 months with hourly data). I have an array with the values of precipitation for every hour (2880). I want to overlay this data via a vertical bar chart over the first graph, so that the bars width is equivalent to 1 hr and centered over the corresponding hour. My issue is that the widths of the bars are too wide and overlap with each other. I have tried changing the width option to width=1/24 in the plot with no success (bars don't appear at all). Here is a snippet of the code where I do not set the width at all. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import matplotlib.dates as mdates import datetime import pandas as pd import numpy as np t = np.arange(datetime.datetime(2010,1,01,0), datetime.datetime(2010,5,01,0),datetime.timedelta(hours=1)).astype(datetime.datetime) stn_temp = np.random.rand(2880) model_temp = stn_temp-0.2 stn_rh = np.random.randint(0,100,2880) model_rh = stn_rh -1 fig, (ax1,ax2) = plt.subplots(2,1,sharex=True) ax1.plot(t,stn_temp,'r',linewidth=0.3) ax1.plot(t,model_temp,'k',linewidth=0.3) minor_ticks_temp = np.arange(min(stn_temp),max(stn_temp),1) ax1.set_yticks(minor_ticks_temp, minor=True) myFmt = mdates.DateFormatter('%m-%d') ax1.xaxis.set_major_formatter(myFmt) ax1.legend(loc=0) ax1.set_ylabel('2 m Temperature ($^\circ$C)') ax1 = ax1.twinx() ax1.bar(t,prec,alpha=0.7,color='g') ax1.set_ylabel('Accumulated \n Precipitation (mm)') ax2.plot(t,stn_RH,'b',linewidth=0.3) ax2.plot(t,rh,'k',linewidth=0.3) ax2.set_ylim([0,100.5]) ax2.set_ylabel('Relative Humidity (%)') fig.tight_layout() The widths of the bars should be a lot smaller, only the width of an hour. This image is a zoomed in version to show the bar width issue.
has comment: http://stackoverflow.com/comment/82032294
has comment: http://stackoverflow.com/comment/81975497
tagged with: weather
tagged with: matplotlib
tagged with: python
has title: Python barchart overlapping vertical bars
type: Question

http://stackoverflow.com/comment/82044282
comment on: http://stackoverflow.com/a/47543574
score: 0
type: Comment
has text: I found a better solution, I am working on it right now, and its much easier than the methods you just list. Once I finish it hope soon :) , I will post it here as an answer, so maybe it will help some one. Thank you so much.
type: AnswerComment

http://stackoverflow.com/comment/81915841
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47480455
type: QuestionComment
has text: Can you please post your full code? Because there is nothing on `row = 0` that would raise a `TypeError`.

http://stackoverflow.com/comment/82112838
score: 0
type: Comment
has text: I think, "Because urllib.request imports them" doesn't cut it. From my point of view, "module A importing module B, and module B importing module C" doesn't mean that module C gets available from module A. What do you say of [my explanation](https://stackoverflow.com/questions/47459717/does-importing-a-module-in-python-execute-all-the-modules-imports-in-local-scop#comment81876008_47459951)? On a side note, your showing how to inspect the matter was pretty educational.
type: AnswerComment
comment on: http://stackoverflow.com/a/47460544

http://stackoverflow.com/comment/81874945
has text: okay the number of elements is fixed? e.g. 3 then 3 then again 3 etc ??
type: QuestionComment
comment on: http://stackoverflow.com/q/47460105
score: 0
type: Comment

http://stackoverflow.com/a/64621147
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47393362
type: Answer
has body: If we have 2d arrays then we can do the follwoing A = np.zeros((5,2)) B = np.ones((5,2)) row_a, col_a = np.shape(A) row_b, col_b = np.shape(B) Mix columns in alternating fashion assert row_a == row_b, 'number of rows should be same' np.ravel([A,B],order="F").reshape(row_a,col_a+col_b) This will give array([[0., 1., 0., 1.], [0., 1., 0., 1.], [0., 1., 0., 1.], [0., 1., 0., 1.], [0., 1., 0., 1.]]) To mix rows assert col_a == col_b, 'number of cols should be same' np.ravel([A,B],order="F").reshape(col_a,row_a+row_b).T Which will give array([[0., 0.], [1., 1.], [0., 0.], [1., 1.], [0., 0.], [1., 1.], [0., 0.], [1., 1.], [0., 0.], [1., 1.]])

http://stackoverflow.com/comment/81745291
comment on: http://stackoverflow.com/q/47395258
has text: It works in my tests when I give the password in the command line with `-pw pass`. So you should elaborate *Using -pw in command doesnt work* (remember, *doesn't work* means nothing and is helpless for other readers). Without more details, I just see this question as *unclear*.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85254390
comment on: http://stackoverflow.com/q/47407929
type: Comment
type: QuestionComment
score: 0
has text: hi, @vaibhavshetti I'm also struggling with PayPal python rest SDK but I'm stuck on the client side. I don't know how I can pass csrf-token from client side within the PayPal script. can you help me, how you have submitted the request from template to this view?

http://stackoverflow.com/a/47453466
type: Answer
has body: The printout of the MRO shows you exactly why this is. Python calls the parent methods in that specific order, hence the name. It calls A2's method, which has a super call so then calls A1's method; but A1 does not in turn call super so the chain stops there.
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47453399
answers question: http://stackoverflow.com/q/47453399

http://stackoverflow.com/comment/81936754
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47490708
has text: Can you specify your requirement explicitly? Your second statement still may not work as your requirement expects. From first look, I guess because order of precedence having `and` executed before `!=`. You'd better to wrapped them around like `(num != 0) and (den != 0)` if you want to have `and ` executed last.
score: 0

http://stackoverflow.com/q/47460273
answer count: 0
downvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/81875261
tagged with: command
favorite count: 0
type: Question
has body: I am struggling to write a command using either python or a bash script that inputs responses to commands. For example, I may install a program using a command and it responds with the Y/n prompt. I know there is a -y flag for the command sudo apt install. However, I also want to be able to enter and retype passwords after doing the sudo passwd ubuntu command. How do I address this in a program?
type: UnansweredQuestion
tagged with: python
has title: Interactive Responses in CLI
tagged with: command-line-interface
score: 2
upvote count: 2
tagged with: bash

http://stackoverflow.com/comment/81754908
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47400652
type: Comment
has text: I have change the code to the above but am now getting an error numpy.float64' object has no attribute 'iloc'

datetime
tags question: http://stackoverflow.com/q/47403803
tags question: http://stackoverflow.com/q/47521630
tags question: http://stackoverflow.com/q/47458722
tags question: http://stackoverflow.com/q/47505590
tags question: http://stackoverflow.com/q/47531712
tags question: http://stackoverflow.com/q/47404691
tag name: datetime
tags question: http://stackoverflow.com/q/47424775
tags question: http://stackoverflow.com/q/47390563
tags question: http://stackoverflow.com/q/47528906
tags question: http://stackoverflow.com/q/47413871
tags question: http://stackoverflow.com/q/47450938
tags question: http://stackoverflow.com/q/47424151
tags question: http://stackoverflow.com/q/47437633
tags question: http://stackoverflow.com/q/47469640
tags question: http://stackoverflow.com/q/47444607
type: Tag
tags question: http://stackoverflow.com/q/47522232
tags question: http://stackoverflow.com/q/47443605
tags question: http://stackoverflow.com/q/47524363
tags question: http://stackoverflow.com/q/47527272
tags question: http://stackoverflow.com/q/47507470
tags question: http://stackoverflow.com/q/47472878
tags question: http://stackoverflow.com/q/47410264
tags question: http://stackoverflow.com/q/47457312
tags question: http://stackoverflow.com/q/47473877
tags question: http://stackoverflow.com/q/47406787
tags question: http://stackoverflow.com/q/47477376
tags question: http://stackoverflow.com/q/47481618
tags question: http://stackoverflow.com/q/47520892
tags question: http://stackoverflow.com/q/47487140
tags question: http://stackoverflow.com/q/47491017
tags question: http://stackoverflow.com/q/47418295
tags question: http://stackoverflow.com/q/47509168
tags question: http://stackoverflow.com/q/47396204

http://stackoverflow.com/comment/81913317
type: QuestionComment
type: Comment
has text: Sounds like you don't fully understands what a priority queue does. It's usually a heap, not a linked list, which means it's unordered except the top element.
score: 0
comment on: http://stackoverflow.com/q/47478978

http://stackoverflow.com/q/47493365
has title: wxPython Matplotlib.pyplot Conflict?
tagged with: python
linked to: http://stackoverflow.com/q/50196561
has body: I have met this pretty weird bug when using wxPython today. This simple code works fine: import wx app = wx.App() frame = wx.Frame(None, -1, 'simple.py') frame.Show() app.MainLoop() However, once I add an import statement for matplotlib.pyplot at top: import matplotlib.pyplot as plt # then same code as above... the simple window does not show up anymore (without errors, program halts). Anyone know what the problem is? Env: macOS High Sierra, Python 3.6.3, wxPython 4.0.0b2, matplotlib 2.1.0 Thanks!
tagged with: macos
has answer: http://stackoverflow.com/a/49581927
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87452350
tagged with: user-interface
has answer: http://stackoverflow.com/a/47507637
tagged with: wxpython
accepted answer: http://stackoverflow.com/a/47507637
type: Question
possible better answer: http://stackoverflow.com/a/49581927
type: AnsweredQuestion

http://stackoverflow.com/comment/81824685
has text: @Elis I didn't understand what you want. But I will try to read some minds. I used `time.time()` method to calculate `start_time` and `finish_time` and then did `finish_time - start_time` to get how long it took for each function. Is that what you wanted me to answer?
comment on: http://stackoverflow.com/q/47434724
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47388788
has comment: http://stackoverflow.com/comment/81732300
has body: Since you have not posted any tried code so i have no idea what exactly you are looking. But as you stated : For example, func_1 and func_2 would take only x_1, while func_3 and func_4 take both x_1 and X_2 I am providing you Example solution, This is not exact solution You can take help, Hint from this solution: def func1(*args): print("This is func1") return args def func2(*args): print("This is func2") return args def func3(*args): print("This is func3") return args def func4(*args): print("This is func4") return args func_list=[func1,func2,func3,func4] argument_list=['x1','x2'] for func in func_list: if func==func1: print(func1(argument_list[0])) elif func==func2: print(func2(argument_list[0])) elif func==func3: print(func3(argument_list[0],argument_list[1])) else: print(func4(argument_list[0], argument_list[1])) output: This is func1 ('x1',) This is func2 ('x1',) This is func3 ('x1', 'x2') This is func4 ('x1', 'x2')
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47387087
answers question: http://stackoverflow.com/q/47387087

bash
tags question: http://stackoverflow.com/q/47398554
tags question: http://stackoverflow.com/q/47420369
tags question: http://stackoverflow.com/q/47409820
tags question: http://stackoverflow.com/q/47540445
type: Tag
tags question: http://stackoverflow.com/q/47442153
tags question: http://stackoverflow.com/q/47408608
tags question: http://stackoverflow.com/q/47413270
tags question: http://stackoverflow.com/q/47510830
tags question: http://stackoverflow.com/q/47513658
tags question: http://stackoverflow.com/q/47531502
tags question: http://stackoverflow.com/q/47510091
tags question: http://stackoverflow.com/q/47519632
tags question: http://stackoverflow.com/q/47398489
tags question: http://stackoverflow.com/q/47443988
tags question: http://stackoverflow.com/q/47481902
tags question: http://stackoverflow.com/q/47502041
tags question: http://stackoverflow.com/q/47513024
tags question: http://stackoverflow.com/q/47475204
tags question: http://stackoverflow.com/q/47514185
tags question: http://stackoverflow.com/q/47460273
tags question: http://stackoverflow.com/q/47480707
tags question: http://stackoverflow.com/q/47400218
tag name: bash
tags question: http://stackoverflow.com/q/47413175
tags question: http://stackoverflow.com/q/47426914
tags question: http://stackoverflow.com/q/47491175
tags question: http://stackoverflow.com/q/47406095

http://stackoverflow.com/a/54794137
type: Answer
has body: I extended the example code of numerica to batches and replaced the itertool part: num_examples = 5 num_epochs = 4 batch_size = 2 num_iters = int(num_examples * num_epochs / batch_size) features = tf.data.Dataset.range(num_examples) labels = tf.data.Dataset.range(num_examples) data = tf.data.Dataset.zip((features, labels)) data = data.shuffle(num_examples) epoch = tf.data.Dataset.range(num_epochs) data = epoch.flat_map( lambda i: tf.data.Dataset.zip(( data, tf.data.Dataset.from_tensors(i).repeat(), tf.data.Dataset.range(num_examples) )) ) # to flatten the nested datasets data = data.map(lambda samples, *cnts: samples+cnts ) data = data.batch(batch_size=batch_size) it = data.make_one_shot_iterator() x, y, ep, st = it.get_next() with tf.Session() as sess: for _ in range(num_iters): x_, y_, ep_, st_ = sess.run([x, y, ep, st]) print(f'step {st_}\t epoch {ep_} \t x {x_} \t y {y_}')
answers question: http://stackoverflow.com/q/47410778
score: 0

http://stackoverflow.com/comment/81782452
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47412219
score: 0
has text: Thank you for the suggestion, but i think that is not necessary (i didnt understand all of it though). Is there a way to emit only a single key from the mapper? If i use the condition `if key>18: print max(value)` it prints out the maximum value for the list associated with key 18. Is there a way i print out the key of the biggest integer?

amazon-ec2
tags question: http://stackoverflow.com/q/47432432
type: Tag
tags question: http://stackoverflow.com/q/47382863
tags question: http://stackoverflow.com/q/47385841
tag name: amazon-ec2
tags question: http://stackoverflow.com/q/47402770
tags question: http://stackoverflow.com/q/47403218

http://stackoverflow.com/q/47440161
has answer: http://stackoverflow.com/a/47446080
tagged with: polynomials
accepted answer: http://stackoverflow.com/a/47446080
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81840406
has comment: http://stackoverflow.com/comment/81838584
possible better answer: http://stackoverflow.com/a/47444602
has title: Vectorizing numpy polyfit for moving window
tagged with: python
has comment: http://stackoverflow.com/comment/81839633
has answer: http://stackoverflow.com/a/47444602
score: 2
upvote count: 2
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81839110
answer count: 2
downvote count: 0
has body: I'd like to vectorize following function def nppolyfit(pnp_array, **kwargs): """ Moving polyfit """ win_size = kwargs['length'] degree = kwargs['degree'] xdata = range(win_size) res = np.zeros(pnp_array.shape) for i in range(win_size, len(pnp_array) + 1): res[i-1] = np.poly1d(np.polyfit(xdata , pnp_array[i - win_size : i], deg = degree))(win_size) return res What was done so far: def rolling_window(a, window): shp = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shp, strides=strides) def nppolyfitv(pnp_array, **kwargs): """ Moving polyfit """ win_size = kwargs['length'] degree = kwargs['degree'] xdata = np.arange(win_size) ydata = rolling_window(pnp_array, win_size).T fit = np.polyfit(xdata, ydata, deg = degree) res = np.zeros(len(pnp_array)) res[win_size-1:] = np.polynomial.polynomial.polyval(np.zeros(len(pnp_array)), fit).T[len(pnp_array) - 1,:] return res But it looks like I am missing something or doing wrong. Could you please correct me? Maybe there is another more effective solution? Thanks. Test case: import numpy as np npd = np.arange(30) win_size1 = 11 degree = 1 c1 = nppolyfit(npd, length=win_size1, degree=degree) c1v = nppolyfitv(npd, length=win_size1, degree=degree) print(c1) print(c1v) And results are: [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 30. 59. 88. 117. 146. 175. 204. 233. 262. 291. 320. 349. 378. 407. 436. 465. 494. 523. 552.]

http://stackoverflow.com/comment/106405100
type: AnswerComment
has text: Just load the model or weight and run the training process. This will start the training from the previous parameters you saved.
score: 0
comment on: http://stackoverflow.com/a/56814150
type: Comment

http://stackoverflow.com/a/47469035
type: Answer
answers question: http://stackoverflow.com/q/47468174
score: 0
has body: A way to get around the string immutability in python is to rebuild the string. This is an example to change a character to upercase at a certain index: index=3 string="abcdefgh" string= string[:index]+string[index].upper()+ string[index+1:] print(string) This will print out: abcDefgh

http://stackoverflow.com/comment/81950414
score: 0
comment on: http://stackoverflow.com/a/47497394
type: Comment
type: AnswerComment
has text: Note that `self.__class__.addInstance` is slightly different from `self.addInstance`, as the former does not allow a method overridden in a subclass to be called. Use the form that does what you want. The issue here isn't really one of convention, but rather that if there is no *instance* attribute named `addInstance`, Python next tries to find class attributes by that name using the MRO.

http://stackoverflow.com/a/47459527
has body: This is implemented as view_as_blocks in skimage.util: blocks = skimage.util.view_as_blocks(a,(2,2)) maxs = blocks.max((2,3))
answers question: http://stackoverflow.com/q/47458521
downvote count: 0
type: Answer
score: 3
upvote count: 3

qweb
tags question: http://stackoverflow.com/q/47429537
type: Tag
tag name: qweb

http://stackoverflow.com/comment/81854344
comment on: http://stackoverflow.com/q/47449354
type: Comment
type: QuestionComment
has text: Did you already try to parse it without success? Half the point of an html parser is that it can tolerate badly formed html just like a browser would. Missing closing tags should not present an issue
score: 1

http://stackoverflow.com/comment/81857821
type: Comment
type: QuestionComment
has text: Can you share the error stack trace? If no error observed set the Trace level logs & try to get some info. Else you have to Debug your code to find what's going wrong.
score: 1
comment on: http://stackoverflow.com/q/47451131

http://stackoverflow.com/q/47484199
tagged with: python
type: Question
answer count: 0
tagged with: api
has comment: http://stackoverflow.com/comment/81923227
type: UnansweredQuestion
score: 0
has body: When I try to use the streamable API to create mirrors of twitch clips I sometimes get the following error: ERROR: SnappyCallousSkirretSuperVinlin: Failed to parse JSON (caused by ValueError("Expecting \',\' delimiter: line 38 column 76 (char 2027)",)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. This error does not always happen, but I can't find any difference between the URLs that cause it and the URLs that do not cause a error. My code: import requests url = 'https://clips.twitch.tv/SnappyCallousSkirretSuperVinlin' api_url = 'https://api.streamable.com/import' headers = {'User-Agent': 'clip bot'} params = {'url': url} r = requests.get( api_url, auth=('username', 'password'), headers=headers, params=params) print(r.content) The streamable API docs: https://streamable.com/documentation
has title: streamable api error: Failed to parse JSON
tagged with: python-requests
has comment: http://stackoverflow.com/comment/81925050
has comment: http://stackoverflow.com/comment/81925171
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/81849643
comment on: http://stackoverflow.com/q/47447155
score: 0
type: Comment
type: QuestionComment
has text: you should add ```total count``` in employee_list.

http://stackoverflow.com/comment/81856540
has text: Changed it to driver.find_element_by_tag_name("a").click() .. but the click doesn´t happen. In the screenshot it is still on the same page
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47450128
type: AnswerComment

http://stackoverflow.com/comment/81916866
type: QuestionComment
has text: Hi! In your second section, each `item` is a dictionary (a grocery item), no? If so, then you don't need the second `for` loop there; you access the item's price with `item['price']`.
score: 2
comment on: http://stackoverflow.com/q/47480955
type: Comment

http://stackoverflow.com/comment/81961981
type: Comment
comment on: http://stackoverflow.com/q/47502985
type: QuestionComment
has text: @user2357112 is right; the key is that the first example does not stop the loop when `x` reaches `1`, and the range is one too small for prime input.
score: 0

python-ldap
tags question: http://stackoverflow.com/q/47397341
type: Tag
tag name: python-ldap

http://stackoverflow.com/comment/81761176
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47403538
score: 0
has text: @Prune Yeah, sure, btw... why did someone downvote this question? As far as I understand it follows SO rules, even if it's newbie-level... :/

http://stackoverflow.com/a/47518412
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47517979
has body: That's because filler is not defined. What is filler? Is filler a string? Is filler a number? In the context of your function stringCombination you have not defined what "filler" is. You are most likely looking for a default "fillValue" in that case your function signature should be something like: def stringCombination( string1, string2, fillValue = " "): Perhaps you defined "filler" as a global variable. In that case your code should look something like this: DEFAULT_FILL_VALUE = " " def stringCombination( string1, string2, fillValue = DEFAULT_FILL_VALUE): I recommend instead of using "filler" for your global variable, you should use a clear capitalized name. I am assuming of course that you want a default fill value of a space: " ". If you want a comma or something else, just replace the space with your desired character. The other issue with your code is this line: filler = string2[-1] if len(string1) &gt; len(string2) else string[-1] You have 3 parameters that are passed into your function: string1, string2 and fillValue. So in the context of your function you can ONLY manipulate string1, string2 and fillValue. Manipulating or assigning "filler" and "string" do not really make sense here, (although I feel "string" is just a typo, did you mean string1?). If you are intentionally trying to modify filler and it is a global variable, I highly advise against doing this... this is just bad coding practice. You should capitalize all your global variables and make sure they remain constant!
accepted answer of: http://stackoverflow.com/q/47517979
type: AcceptedAnswer

http://stackoverflow.com/a/47540583
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47540395
has body: It's an issue with scope. When you call DaC1WD (because that's a REALLY long function name), it makes a variable within it for the log. When the function finishes, everything within it is lost. What you need to do is return the log file and then call the logger with the log file as an arg.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81903223
type: AnswerComment
comment on: http://stackoverflow.com/a/47472272
score: 0
type: Comment
has text: frame_all_train[video_count][frame_count][pixel_height_count] [pixel_width_count] = frame[pixel_height_count,pixel_width_count] I can only form a 4D form with my data, I am not sure that how to add one more dimension because I don't know what value I should put into the 5th dimension...

http://stackoverflow.com/comment/81854453
type: QuestionComment
comment on: http://stackoverflow.com/q/47449818
type: Comment
has text: I think there's a better solution with a heap.
score: 0

http://stackoverflow.com/comment/81746335
score: 0
comment on: http://stackoverflow.com/a/47395031
type: Comment
has text: So it goes to settings.py?
type: AnswerComment

http://stackoverflow.com/comment/81815409
type: QuestionComment
comment on: http://stackoverflow.com/q/47411740
has text: @olricson I found that it occurred with all github files. I reinstalled my pc, and that fixed 99% of issues occurring. I think there might still be issues I'll verify and confirm, but a fresh system clean and reinstall did wonders :)
score: 0
type: Comment

http://stackoverflow.com/comment/81769349
has text: The way to do this in Python would be with something like `def decrease_health(loss): health -= loss; if health < 0: raise PanicHealthNegative()`
score: 1
comment on: http://stackoverflow.com/a/47407962
type: Comment
type: AnswerComment

http://stackoverflow.com/a/68992303
has body: This is because your file (G:/Python/integer_sequencing/sample.csv) has a problem. For example, some rows may have a different number of fields, meaning that a different number of comma in this case, as follows: 1. a, b, c 2. d, e, f 3. g, h, i, j # This third line has a problem. 4. k, l, m Line 3 may have a value including ',', so it makes Pandas confused. This is a common problem when you read a csv file :)
score: 0
answers question: http://stackoverflow.com/q/47504501
type: Answer

http://stackoverflow.com/comment/81980509
score: 0
type: AnswerComment
type: Comment
has text: @TarakShah: Why would you need to check for not equal 0?
comment on: http://stackoverflow.com/a/47509337

http://stackoverflow.com/q/47519701
has comment: http://stackoverflow.com/comment/81997814
has comment: http://stackoverflow.com/comment/81997638
has comment: http://stackoverflow.com/comment/82000692
has title: Where in on a list of string in sqlite 3
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/82004410
tagged with: sqlite
has comment: http://stackoverflow.com/comment/82007633
has comment: http://stackoverflow.com/comment/81996929
has comment: http://stackoverflow.com/comment/81996165
has body: I am training a ML model on a huge dataset. I have converted the CSV to a SQL database. But, I have encountered a problem in correctly retrieving data for each batch. custs= #list of 1000 customers df=pd.read_sql_query('SELECT * FROM transactions WHERE cust_id IN (%s)'% (",".join(map(str,custs))) ,con=disk_engine) This gives me all the records of the customers. But, say, if I want only last three transactions of a customer. months= #list containing the required months, custs= #each cust_id is repeated thrice df=pd.read_sql_query('SELECT * FROM transactions WHERE cust_id IN (%s) AND month IN (%s)' % (",".join(map(str,custs)),",".join(map(str,months))) ,con=disk_engine) This doesn't work because the AND statement is applied to whole list. Therefore, I created a new column which is a string combination of customer_id and month and this key is unique for each record. key= #str(cust_id) +'_'+ str(month) I can't use the join statement for a list of keys. What method will work here? I tried to use placeholders here but since I am new to SQL, I didn't make much progress. EDIT The data has 116 columns. 113 of them are modelling variables and there is a DV column. The other two columns are cust_id and month. The data is for 8 months and each customer has 1 or 0 transactions per month. Therefore, a customer might have transactions ranging from 1 to 8 in the database. For training a batch I pick 1000 customers and a month at random from a list in memory . For example if I picked list contains cust_id=1 and month=4, then I need transaction for month [2,3,4] for this customer. For cust_id=20 and month=2 I'll use [1,1,2] If a transaction is missing then also I pad with the last transaction.
type: Question
has comment: http://stackoverflow.com/comment/82026046
has comment: http://stackoverflow.com/comment/81996782
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47423687
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47423770
score: 0
has title: Ways to display money in python without using the decimal package
answer count: 2
possible better answer: http://stackoverflow.com/a/47423708
has answer: http://stackoverflow.com/a/47423708
linked to: http://stackoverflow.com/q/1995615
tagged with: floating-point
type: Question
duplicate of: http://stackoverflow.com/q/1995615
tagged with: python
accepted answer: http://stackoverflow.com/a/47423770
has body: I want to have Python declare a float variable and then display that variable to two decimal points, even if the number is an integer. For example: def floatToMoney: # Some kind of function that outputs two decimal places foo = float(6) print(floatToMoney(foo)) boo = float(3.14159) print(floatToMoney(boo)) and have an output of: 6.00 3.14 I know that round() can do this, but again if the number is an integer it doesn't display the decimal places. I found the decimal package, but is there any way to do this without having to import any packages?

http://stackoverflow.com/comment/81752220
type: AnswerComment
comment on: http://stackoverflow.com/a/47399374
type: Comment
has text: @GiorgioCavicchioli I mean, you could also just do the same in a for-loop... the crux of the matter is you should check equality with your target as you iterate, and `if int_to_delete in i:` is totally redundant!
score: 0

http://stackoverflow.com/comment/82069097
has text: Is it easy to calculate the jitter and pitch for the same windows, in order to enrich my MFCC features? Is it straight forward to do so?
type: Comment
comment on: http://stackoverflow.com/a/47555651
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81847858
type: Comment
score: 0
type: AnswerComment
has text: Thanks for your suggestion to use `tf.train.piecewise_constant`. Please can you show me how to use this function to set the training rate in **log scale**?
comment on: http://stackoverflow.com/a/47445874

http://stackoverflow.com/comment/82008513
type: Comment
type: QuestionComment
has text: pip install matplotlib_venn
comment on: http://stackoverflow.com/q/47526269
score: 0

http://stackoverflow.com/a/47530371
has comment: http://stackoverflow.com/comment/82019074
has comment: http://stackoverflow.com/comment/82020274
score: 1
has comment: http://stackoverflow.com/comment/82017454
has comment: http://stackoverflow.com/comment/82072785
downvote count: 0
answers question: http://stackoverflow.com/q/47530191
upvote count: 1
has comment: http://stackoverflow.com/comment/82056645
has comment: http://stackoverflow.com/comment/82021624
has comment: http://stackoverflow.com/comment/82254761
type: Answer
has body: In any folder from which you want to import source files you need to have existing init.py file. I would advise structure like: dir/ main.py dir1/frontend.py dir1/__init__.py dir2/backend.py dir2/__init__.py Then you import them in following fashion (in main.py): import dir1.frontend import dir2.backend

http://stackoverflow.com/comment/82079125
type: AnswerComment
score: 0
has text: The double flash works. This works for me: a = os.system("net use \\\networkfile\\Programs") . Thank you for all your help. I appreciate it.
type: Comment
comment on: http://stackoverflow.com/a/47539017

http://stackoverflow.com/q/47417432
upvote count: 2
downvote count: 0
has body: I have a DataFrame 'df' and a list of strings 'l'. I want to iterate through the list and find the rows of the DataFrame matching with strings from the list. Following code works fine if there are no brackets in the list elements. It seems like the regex is not defined properly and somehow the double brackets are not getting matched. import pandas as pd import re d = {'col1': ['100-(abc)','qwe-100-(abc)', '100-(abc)1', 'xyz', 'xyz2', 'zzz'], 'col2': ['100', '1001','200', '300', '400', '500']} df = pd.DataFrame(d) lst = ['100-(abc)', 'xyz'] for l in lst: print("======================") pattern = re.compile(r"(" + l + ")$") print(df[df.col1.str.contains(pattern, regex=True)]) result: ====================== Empty DataFrame Columns: [col1, col2] Index: [] ====================== col1 col2 3 xyz 300 Expected result: ====================== col1 col2 0 100-(abc) 100 1 qwe-100-(abc) 1001 ====================== col1 col2 3 xyz 300
accepted answer: http://stackoverflow.com/a/47417930
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47417930
tagged with: regex
has title: Python - Match variable regex including double brackets
has answer: http://stackoverflow.com/a/47417708
type: Question
possible better answer: http://stackoverflow.com/a/47417708
answer count: 2

http://stackoverflow.com/a/62913690
downvote count: 0
upvote count: 1
has body: Try to change initialization of SQLite connection: self.conn = sqlite3.connect(db, check_same_thread=False) Read more about here: Using SQLite In Multi-Threaded Applications SQLITE_THREADSAFE=&lt;0 or 1 or 2&gt;
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47490444

http://stackoverflow.com/q/47433198
answer count: 1
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
type: Question
has answer: http://stackoverflow.com/a/47433253
has body: My views.py is def searchnew(request): if request.method == 'POST': name = request.POST.get('name') loc = request.POST.get('location') d = { 'name': name, 'loc' : loc, } return render(request,"searchnew.html",d) else: name = request.GET.get('name') na = { 'name': name, } return render(request,"searchnew.html",na) I have GET request and other POST request. How can I able to handle GET request in this case? This is my GET request &lt;a v-bind:href="'searchnew/?name='+post.name"&gt;{{post.name}}&lt;/a&gt; I am getting error as IndentationError: unexpected indent How can I able to pass this name?
tagged with: django
tagged with: javascript
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47433253
linked to: http://stackoverflow.com/q/45621722
type: AnsweredQuestion
upvote count: 0
has title: How can I able to handle both GET and POST requests in views.py in python vue js?
tagged with: vue.js

http://stackoverflow.com/a/47504485
type: Answer
answers question: http://stackoverflow.com/q/47463987
score: 0
type: AcceptedAnswer
has body: The problem I was having is because of the fact that from sklearn.preprocessing import StandardScaler changes dimension of my data. Instead of using StandardScaler , I just used preprocessing.scale for each input in my (50k,(784,1)) dim dataset. That is, I used the scale function to each (784,1) data on axis = 1 and added them using a for loop. This slowed down the program but worked. If anyone knows a better way please let me know in the answer section.
accepted answer of: http://stackoverflow.com/q/47463987

http://stackoverflow.com/q/47535866
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47624348
has comment: http://stackoverflow.com/comment/82055504
has comment: http://stackoverflow.com/comment/82055163
has comment: http://stackoverflow.com/comment/82055457
has body: Some minimal code of what I'm working on. Some parameters may seem redundant, but I didn't bother removing all of them. import matplotlib import matplotlib.gridspec as gridspec matplotlib.use("macosx") import matplotlib.pyplot as plt import pandas as pd import seaborn as sns def plot_overlaid_2d_hist(data, plot_axis_x, plot_axis_y, plot_axis_x_lab, plot_axis_y_lab, group_by = "group_name"): # don't mind this for now df = data # Figure aspect w, h = plt.figaspect(1) fig = plt.figure(figsize = (w, h)) # Count the number of groups to make plots for n_groups = len(df.groupby(group_by)) gs = gridspec.GridSpec(nrows = n_groups, ncols = 1) subplot_id = 0 # Reshape data to make it work for name, group in df.groupby(group_by, sort = False): # Initialize subplot fig.add_subplot(gs[subplot_id, 0]) # Check if we get subplots with pyplot if subplot_id == 0: col = "red" else: col = "blue" plt.plot(x, y, color = col) # instantiate JointGrid # g = sns.JointGrid(group[plot_axis_x], # group[plot_axis_y], # data = group, # space = 0, # xlim = (0, 1.2), # ylim = (0, 1)) # # # Fix labels # g = g.set_axis_labels(xlabel = str(plot_axis_x_lab), # ylabel = str(plot_axis_y_lab)) # # # center scatter plot on top # g = g.plot_joint(plt.scatter, # s = 0.5, # alpha = 1, # linewidth = 1) # # # marginals plot # g = g.plot_marginals(sns.distplot, # kde = True, # kde_kws = dict(linewidth = 2, # alpha = 1, # bw = "Scott"), # hist_kws = dict(alpha = 1)) # Next plot in row +1 subplot_id += 1 # Output plt.tight_layout() # Attempts to fix alignment of subplot layout and axis titles plt.show() # quick data to check if the plots end up where they should x = [0.5, 0.5, 0.4, 0.4] y = [0.6, 0.4, 0.3, 0.4] grp = ["a", "a", "b", "b"] df = pd.DataFrame({"x":x, "y":y, "grp": grp}) plot_overlaid_2d_hist(data = df, group_by = "grp", plot_axis_x_lab = "x", plot_axis_y_lab = "x", plot_axis_y = "x", plot_axis_x = "x") Running the code with all seaborn plots (g) commented out shows that it works fine for native pyplot,…
linked to: http://stackoverflow.com/q/35042255
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23969619
has comment: http://stackoverflow.com/comment/82038780
tagged with: seaborn
has answer: http://stackoverflow.com/a/47624348
tagged with: python
has title: How to iteratively populate matplotlib gridspec with a multipart seaborn plot?
linked to: http://stackoverflow.com/q/6309472
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/35042255
tagged with: pandas
upvote count: 1
score: 1
tagged with: matplotlib

http://stackoverflow.com/comment/81978861
has text: I thought I did something similar, but can't find it in my code and its been awhile...try playing/searching how to use the SOCIAL_AUTH_XXX_SCOPE variables, or other variables for social auth (where XXX = auth system like FACEBOOK)
type: Comment
comment on: http://stackoverflow.com/q/47511216
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82018427
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47529791
has text: How might the hash be used to distinguish between "¡No lo sé!" and "¡No lo se!"?

http://stackoverflow.com/comment/81883585
has text: Maybe you should say `opentable.extend(node.generatenodes())` instead of `append`.
comment on: http://stackoverflow.com/q/47464418
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81797073
comment on: http://stackoverflow.com/q/47421305
score: 1
type: Comment
type: QuestionComment
has text: You might want to check out some of the ideas in here: https://stackoverflow.com/questions/16458340/python-equivalent-of-zip-for-dictionaries

http://stackoverflow.com/comment/82008290
comment on: http://stackoverflow.com/q/47526059
score: 0
type: Comment
type: QuestionComment
has text: No. I'm not sure the assert 'value in dataframe.index' will use hashtable under the hood.

http://stackoverflow.com/q/47483587
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49523717
answer count: 2
tagged with: tkinter
score: 1
tagged with: user-interface
downvote count: 0
tagged with: events
upvote count: 1
has body: This is a dialog form class : ** update full workable source code showing the problem from tkinter import * class SGForm: created_form = False def __init__(self, root, title=""): self.form = Toplevel(root) self.form.wm_title(title) self.input = dict() self.var = StringVar() SGForm.created_form = True def getform(self): return self.form def addinput(self, name, text ,var = None): p = Frame(self.form) p.pack(side="top", fill="both", expand=True, padx=10, pady=10) l = Label(p, text=text) l.pack(side="left", fill="both", expand=True, padx=10, pady=10) self.input[name] = Entry(p, textvariable=var) self.input[name].pack(side="left", fill="both", expand=True, padx=10, pady=10) def addbutton(self, text, signal, func): p = Frame(self.form) p.pack(side="top", fill="both", expand=True, padx=10, pady=10) b = Button(p, text=text) b.pack(side="left", fill="both", expand=True, padx=10, pady=10) b.bind(signal, func) def showandreturn(self): value = dict() value['firstname'] = self.var.get() SGForm.created_form = False return value def closeform(self, event): self.form.destroy() def customform(self): self.addinput('entfirstname', 'frist name', self.var) self.addbutton('close','&lt;Button-1&gt;', self.closeform) #example calling dialog class root = Tk() def evntshow(event): form = SGForm(root) form.customform() root.wait_window(form.getform()) test = form.showandreturn() print(test) button = Button(root, text='show') button.pack() button.bind('&lt;Button-1&gt;', evntshow) root.mainloop() Each time the button get pressed eventaddperson get triggered, when exiting the function the button animation of the main window get stuck on press status, I am looking for a way to refresh the gui or what if I am doing something wrong how to fix it?
has comment: http://stackoverflow.com/comment/81924801
has comment: http://stackoverflow.com/comment/81923166
has comment: http://stackoverflow.com/comment/81923679
favorite count: 0
has title: tkinter button animation stuck after using wait_window()
type: Question
has comment: http://stackoverflow.com/comment/81926665
has answer: http://stackoverflow.com/a/47486029
has answer: http://stackoverflow.com/a/49523717
tagged with: dialog
tagged with: python
accepted answer: http://stackoverflow.com/a/47486029

http://stackoverflow.com/comment/81812737
score: 1
type: Comment
has text: I would suggest you have a look at the scikit-learn tutorial. There, they show the classification of handwritten digits. http://scikit-learn.org/stable/tutorial/basic/tutorial.html#introduction If you can get your input into the same format as the Digits dataset, you should be able to follow the tutorial point-for-point
type: QuestionComment
comment on: http://stackoverflow.com/q/47425872

http://stackoverflow.com/a/47450367
score: 4
type: Answer
answers question: http://stackoverflow.com/q/47450228
upvote count: 4
has body: First Thoughts: "Everything in python is an object" I couldn't find anything in the docs, but as everything in python is an object i would shoot for object. def my_function(my_other_function: object) -&gt; dict: some code To proof it: if isinstance(my_function, my_function, object): print("yes") &gt;yes Anyhow, this might not be too explicit, therefore: Seconds thoughts: Using proper type hints Based on what COLDSPEED commented, a more explicit type hint would be using typing import typing def my_function(my_other_function:typing.Callable):-&gt;dict: pass "The only way that annotations take on meaning is when they are interpreted by third-party libraries". Which means, for your source-code itself, it doesn't change anything. Just wanted to mention it.
accepted answer of: http://stackoverflow.com/q/47450228
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81855921

http://stackoverflow.com/comment/81817833
comment on: http://stackoverflow.com/a/47430828
score: 0
type: Comment
type: AnswerComment
has text: @bFig8 If you are asking about that `-1`, here's something to help out - https://stackoverflow.com/questions/41776579/.

http://stackoverflow.com/a/47529163
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Here are two solutions. The first one is based on the link provided by vivek-harikrishnan and explained here. It creates continuous numbers for the intervals and cumulatively counts the occurrences within such intervals. #%% first solution # create intervals and count occurrences per interval df['interval'] = (df['event'] != df['event'].shift(1)).astype(int).cumsum() df['count'] = df.groupby(['event', 'interval']).cumcount() + 1 # now group by intervals df.groupby('interval').last() The second solution is based on the answer above given by maxu. Similar to the first idea it also creates interval numbers but also finds the start/end timestamp for such intervals. #%% second solution df = df.reset_index() # create intervals df = df.groupby(df['event'].ne(df['event'].shift()).cumsum()) # calc start/end times and count occurances at the same time df.apply(lambda x: pd.DataFrame({ 'start':[x['time'].min()], 'end':[x['time'].max()], 'event':[x['event'].iloc[0]], 'count':[len(x)]})).reset_index(drop=True)
answers question: http://stackoverflow.com/q/47527776

http://stackoverflow.com/q/47449444
upvote count: 1
score: 1
answer count: 1
has title: How to use flask-oauthlib with flask-login together?
favorite count: 0
type: Question
tagged with: single-sign-on
has answer: http://stackoverflow.com/a/47532413
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: flask
has body: For now, I'm trying to use flask-oauthlib with flask-login together. flask-oauthlib provides a simple way to use oauth, but I want a login manager to automatically redirect all users who are not logged in to /login. In flask-login, I can use login_required to accomplish this. But how could I achieve this by flask-oauthlib? Further, how to manage session when using flask-oauthlib? I understand how SSO works, but I'm confusing how could I know if this token is expired or not?
tagged with: flask-login
tagged with: flask-oauthlib

http://stackoverflow.com/comment/82384327
type: Comment
type: QuestionComment
has text: @Alex, can you update your question to give your new PYTHONPATH and the follow the instruction in my step 2. Tell me the results when you go to the directory of your caffe executable and try importing your module from Python.
comment on: http://stackoverflow.com/q/47512686
score: 0

http://stackoverflow.com/comment/82011451
type: AnswerComment
comment on: http://stackoverflow.com/a/47526001
has text: Okay. So in steps_per_epoch you need to mention number of batches which in your case are 1500/batch_size.
type: Comment
score: 0

http://stackoverflow.com/q/47469579
has comment: http://stackoverflow.com/comment/81903483
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81894035
has body: I am a Python beginner and wrote a function for a simple moving average strategy. I created a portfolio DataFrame inside the function and now I want to use this DataFrame outside of the function for plotting some graphs. My solution is: return portfolio - but this does not work. Can anybody help me? This is my code: import numpy as np import pandas as pd import matplotlib.pyplot as plt # Import a data source - FSE-Data with Index 'Date' all_close_prices = pd.read_csv('FSE_daily_close.csv') all_close_prices = all_close_prices.set_index('Date') # Fill NaN Values with the last available stock price - except for Zalando all_close_prices = all_close_prices.fillna(method='ffill') # Import ticker symbols ticker_list = list(all_close_prices) # Zalando 'FSE/ZO1_X' (position row 99) - doesn't begin in 2004 # Drop Zalando all_close_prices.drop('FSE/ZO1_X', axis=1) # Also from the ticker list ticker_list.remove('FSE/ZO1_X') # Create an empty signal dataframe with datetime index equivalent to the stocks signals = pd.DataFrame(index=all_close_prices.index) def ma_strategy(ticker, long_window, short_window): # Calculate the moving avergaes moving_avg_long = all_close_prices.rolling(window=long_window, min_periods=1).mean() moving_avg_short = all_close_prices.rolling(window=short_window, min_periods=1).mean() moving_avg_short = moving_avg_short moving_avg_long = moving_avg_long # Add the two MAs for the stocks in the ticker_list to the signals dataframe for i in ticker_list: signals['moving_avg_short_' + i] = moving_avg_short[i] signals['moving_avg_long_' + i] = moving_avg_long[i] # Set up the signals for i in ticker_list: signals['signal_' + i] = np.where(signals['moving_avg_short_' + i] &gt; signals['moving_avg_long_' + i], 1, 0) signals['positions_' + i] = signals['signal_' + i].diff(periods=1) #Backtest initial_capital = float(100000) # Create a DataFrame `positions` with index of signals positions = pd.DataFrame(index=all_close_prices) # Create a new column in the positions Da…
has answer: http://stackoverflow.com/a/47469748
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81893497
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81903416
has comment: http://stackoverflow.com/comment/81893775
has title: Use a pandas DataFrame created inside a function outside of the function
accepted answer: http://stackoverflow.com/a/47469748
has comment: http://stackoverflow.com/comment/81894081
downvote count: 0
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/81736089
score: 0
has text: I have So many documents in my db... im just show format of my document for example.. In my code, im put static date i have document in between that range of date. but, it empty result
comment on: http://stackoverflow.com/a/47391132
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81768480
type: AnswerComment
comment on: http://stackoverflow.com/a/47387639
type: Comment
has text: when I use request.POST method is not changing
score: 0

http://stackoverflow.com/comment/81912796
has text: Could you rather create a [Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve)? We can't go through your entire code each time you have a problem.
comment on: http://stackoverflow.com/q/47478332
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81956668
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47500535
has text: why was `(1, 'A', 'C')` missed from the result?
score: 0

http://stackoverflow.com/q/47421787
has title: Making a simple grid of lists
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81798011
tagged with: list
answer count: 2
downvote count: 2
upvote count: 1
has body: Hello guys I need help with doing gaming grid of game Man don't get angry. I should do a function which makes a grid of format n*n this is how it look for n=9 and I need to do it generally for every odd number, the width of arms is 3 and the length is n. It should be done with list of lists because then I have to make a figure to go around this grid so I will need the coordinates. I made this gaming grid by for cycle def gensachovnicu(n): matica='*'' ' matica1='X ' matica2='D ' for j in range(n): for i in range(n): if i&lt;((n-3)//2) and j&lt;((n-3)//2): print(' ',end='') elif i&lt;((n-3)//2) and j&gt;(n-((n-3)//2)-1): print(' ',end='') elif i&gt;(n-((n-3)//2)-1) and j&lt;((n-3)//2): print(' ',end='') elif i&gt;(n-((n-3)//2)-1) and j&gt;(n-((n-3)//2)-1): print(' ',end='') elif i==(n//2) and j&gt;0 and j&lt;(n-1) and j!=(n//2): print(matica2,end='') elif i==(n//2) and j==(n//2): print(matica1,end='') elif j==(n//2) and i&gt;0 and i&lt;(n-1): print(matica2,end="") else: print(matica,end='') print() but it is so long and I cant handle him.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47423038
has comment: http://stackoverflow.com/comment/81798190
has answer: http://stackoverflow.com/a/47423038
possible better answer: http://stackoverflow.com/a/47442329
tagged with: python
has comment: http://stackoverflow.com/comment/81798014
has answer: http://stackoverflow.com/a/47442329
has comment: http://stackoverflow.com/comment/81798101
has comment: http://stackoverflow.com/comment/81798000

http://stackoverflow.com/comment/82008353
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47526255
has text: So if you want to use keyword arguments. The format string needs to be pulled apart and supplied as individual components?

bokeh
tags question: http://stackoverflow.com/q/47405628
tags question: http://stackoverflow.com/q/47510655
tags question: http://stackoverflow.com/q/47442426
tags question: http://stackoverflow.com/q/47489804
tags question: http://stackoverflow.com/q/47512793
type: Tag
tags question: http://stackoverflow.com/q/47434701
tags question: http://stackoverflow.com/q/47517922
tags question: http://stackoverflow.com/q/47500045
tag name: bokeh
tags question: http://stackoverflow.com/q/47473773
tags question: http://stackoverflow.com/q/47466065

node.js
tags question: http://stackoverflow.com/q/47527948
tags question: http://stackoverflow.com/q/47410305
tags question: http://stackoverflow.com/q/47535356
tags question: http://stackoverflow.com/q/47508990
tags question: http://stackoverflow.com/q/47524748
tags question: http://stackoverflow.com/q/47392830
tags question: http://stackoverflow.com/q/47449241
tags question: http://stackoverflow.com/q/47496470
tags question: http://stackoverflow.com/q/47494142
tags question: http://stackoverflow.com/q/47437760
type: Tag
tags question: http://stackoverflow.com/q/47483103
tag name: node.js
tags question: http://stackoverflow.com/q/47518835
tags question: http://stackoverflow.com/q/47427481
tags question: http://stackoverflow.com/q/47467343
tags question: http://stackoverflow.com/q/47435918
tags question: http://stackoverflow.com/q/47423762

http://stackoverflow.com/q/47389499
upvote count: 1
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/47391106
favorite count: 0
type: Question
has body: I have a silly question. I'm working on Pyhton using the Intellij IDE. I'm trying to import the below: from sklearn.preprocessing import Imputer However, I receive the following error: Traceback (most recent call last): from sklearn.preprocessing import Imputer Can you please help with this?
has title: Python scikit-learn Imputer import error
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/81752600
has comment: http://stackoverflow.com/comment/81732233
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/81732179

http://stackoverflow.com/q/47462108
tagged with: excel
has answer: http://stackoverflow.com/a/47462198
type: Question
has answer: http://stackoverflow.com/a/47462595
has body: I have a huge dataset in a csv file and want to filter one of the columns if they are equal to 334 and then export all the dataset into a excel file! when the file is filtered it can be used in a excel file. so far I could manage to write this code but I do not know how to filter the column and then export all into a excel file. import itertools import csv from itertools import islice with open("eee.csv", 'r') as my_file: reader = csv.reader(my_file) for row in itertools.islice(reader, 100): print (row)
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Filtering a CSV file column and then export it to excel
score: 0
has answer: http://stackoverflow.com/a/47462296
answer count: 3
has comment: http://stackoverflow.com/comment/81879035
has comment: http://stackoverflow.com/comment/81879627

http://stackoverflow.com/comment/81973206
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47507988
type: Comment
has text: I've now removed the `process.wait ()`, but it's still hanging.

http://stackoverflow.com/comment/133396507
type: QuestionComment
comment on: http://stackoverflow.com/q/47539880
score: 0
has text: "The amount of lists will be decided by the user, while the code is running." Then they will certainly not be in separate variables, but in a list of lists instead... **right**?
type: Comment

http://stackoverflow.com/q/47487904
has comment: http://stackoverflow.com/comment/81931961
has body: I have a set comprehension that works perfectly, but i need to add multiple values to that set after the comprehension. Add function only takes one argument, and even if only 1 argument is given, it returns None. Update function takes only iterables. def ss(y,z): return {x**2 for x in range(y)}.add(y,z) How to achieve such a thing using set comprehension.
score: -4
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81931503
has answer: http://stackoverflow.com/a/47488170
type: UnansweredQuestion
has title: Adding values after set comprehension
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/81931114
has comment: http://stackoverflow.com/comment/81931462

http://stackoverflow.com/comment/81740666
has text: @Torxed Where do you see HTTPS? The CURL command in the question contains an HTTP URL, and so does the `python -m fatartifacts.web.cli` invokation. `print(url)` before the request gives `http://localhost:5000/root.bar/test/1.0/jre`. -- The `https://` is only added when the URL does not already have a scheme.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47392822

http://stackoverflow.com/q/47534373
has answer: http://stackoverflow.com/a/47537542
downvote count: 0
has title: Django - Save modelformset data to session in CBV
tagged with: django
linked to: http://stackoverflow.com/q/21174686
score: 1
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/41609332
linked to: http://stackoverflow.com/q/47056480
favorite count: 0
has body: Goal: I'm trying to save modelformset data to session. I have a view where a same set of form fields need to be filled out for items chosen from a checkbox in a previous view. Problem: My modelformset somehow returns only the last set of inputs after cleaned_data (but I can see all inputs in request.POST). I don't get validation or any kind of errors (If I switch the inputs, the input that was passing before does not pass cleaned_data) request.POST &lt;QueryDict: {'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'csrfmiddlewaretoken': ['#abbr', '#abbr', '#abbr'], 'form-0-pd_month': ['8', '5', '7'], 'form-0-pd_day': ['28', '28', '28'], 'form-0-pd_year': ['2017', '2017', '2017'], 'form-0-var': ['t1', 't2', 't3'], 'form-0-id': ['', '', '']}&gt; cleaned_data {'pd': datetime.date(2017, 7, 28), 'var': 't3', 'id': None} I checked In a Django Formset being returned in a Post, all Forms are showing all fields changed even though none have Django save only first form of formset Django formset only adding one form Only last label input value being returned in Django and 100 more as well as Django doc but none of these work for me. Code: I pasted as minimal code as possible without compromising the big picture. views.py #checklist view class VView(CreateView): form_class = VForm template_name = 'b/ve.html' def post(self, request): form = VForm(request.POST) if form.is_valid(): val = form.cleaned_data['ve'] name = [] for obj in val: temp = dict(V.LIB).get(obj) name.append(temp) request.session['val'] = val request.session['name'] = name return HttpResponseRedirect('/b/d/') #fill in same fields for each selection in VView class DView(CreateView): template_name = 'b/d.html' def get(self, request): name = request.session['name'] formset = VarDFormSet() return render(request, self.template_name, {'name': name, 'formset': formset}) def post(self, request): formset = VarDFormSet(request.POST) if formset.is_valid(): fo…
type: Question
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21959989
tagged with: forms
tagged with: django-generic-views

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/47422566
tags question: http://stackoverflow.com/q/47496309

http://stackoverflow.com/comment/81919928
has text: type(key): <class 'str'> repr(key): '\x7f'
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47481955

http://stackoverflow.com/comment/81942640
type: Comment
comment on: http://stackoverflow.com/a/47447405
type: AnswerComment
has text: The more you know! Done. :) Thanks again.
score: 0

ntlm-authentication
tags question: http://stackoverflow.com/q/47515172
tag name: ntlm-authentication
type: Tag

http://stackoverflow.com/comment/81854078
has text: 1. Specific Album, 2. I want to update not display
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47448587
type: Comment

http://stackoverflow.com/comment/82506172
comment on: http://stackoverflow.com/a/47737955
score: 0
type: AnswerComment
type: Comment
has text: Thanks for the help. I wasn't able to get that to work for my needs. However, a friend suggested I give this a try: - Convert the date field to using Pandas datetime df['date'] = pd.to_datetime(df['date']) - Then, filter the months and days I want: df.loc[(df['date'].dt.month==07) & (df['date'].dt.day==14)] So far, that seems to have solved my issue.

http://stackoverflow.com/comment/81950980
comment on: http://stackoverflow.com/q/47497809
type: Comment
has text: It looks like this script is used to redirects to another URL. It also ensures that the URL will only work for sometime hours in your case) and then change (a technique used in a lot of video streaming websites).
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81972479
type: Comment
has text: @user1767754, can you show me how to do that??
type: QuestionComment
comment on: http://stackoverflow.com/q/47508048
score: 0

http://stackoverflow.com/a/47499938
accepted answer of: http://stackoverflow.com/q/47499876
upvote count: 18
type: AcceptedAnswer
score: 18
downvote count: 0
has body: range doesn't return a list in Python3, so range(2, 10) + ["J", "Q", "K", "A"] doesn't work, but list(range(2, 10)) + ["J", "Q", "K", "A"] does. You can also use itertools.chain to concatenate iterables: from itertools import chain chain(range(2, 10), ["J", "Q", "K", "A"]) # or even shorter: chain(range(2, 10), "JQKA") # as strings themselves are iterables # so this comprehension will work deck = [ (value, suit) for value in chain(range(2, 10), "JQKA") for suit in "HCDS" ] The nested comprehension does, of course, constitute a cartesian product which you can also use a util for: from itertools import product deck = list(product(chain(range(2, 10), "JQKA"), "HCDS"))
answers question: http://stackoverflow.com/q/47499876
type: Answer

http://stackoverflow.com/q/47400285
tagged with: telegram
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81754168
upvote count: 1
has comment: http://stackoverflow.com/comment/81754951
tagged with: python
has comment: http://stackoverflow.com/comment/81754379
tagged with: php
has title: Upload image to telegra.ph with PHP
has answer: http://stackoverflow.com/a/47403422
has body: I don't know the Python language. Can someone help me understand whether I correctly converted this to PHP? I want to upload a file to http://telegra.ph with PHP, but I don't know how to upload from PHP. This code is an example from a Python Telegraph API wrapper library: import requests with open('/Users/python273/Desktop/123345.jpeg', 'rb') as f: print( requests.post( 'http://telegra.ph/upload', files={'file': ('file', f, 'image/jpeg')} # image/gif, image/jpeg, image/jpg, image/png, video/mp4 ).json() ) And this is my PHP code that doesn't work. Is there something wrong? $url = 'http://example.com/image.jpg'; $img = 'http://telegra.ph/upload/'; $ch = curl_init($url); $fp = fopen($img, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); When I run this code, I see the following error: Warning: copy(telegra.ph/upload): failed to open stream: HTTP wrapper does not support writeable connections
linked to: http://stackoverflow.com/q/64177086
answer count: 1
has comment: http://stackoverflow.com/comment/81754815
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/81781656
score: 0
type: AnswerComment
has text: Do u mean reason for the Index Error?
comment on: http://stackoverflow.com/a/47413212
type: Comment

http://stackoverflow.com/a/47461016
has body: with open("test file.txt", "r+") as file: oneNum = [0 for _ in range(5)] # Easier to adjust later for line in file: position = [num.strip() for num in line.split(',')].index('1') oneNum[position] += 1
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47460850

http://stackoverflow.com/comment/81830994
comment on: http://stackoverflow.com/q/47437464
score: 0
has text: This is a Tableau log file, kind of a "black box" for me (since Tableau don't support log parsing). I need a solution which could be flexible enough to iterate through thousands of rows while still capturing the inner JSON in the square brackets, in case there is one.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47488012
answer count: 2
has title: How to remove all occurrences of sub strings between two tags from a string?
linked to: http://stackoverflow.com/q/753052
possible better answer: http://stackoverflow.com/a/47488093
has answer: http://stackoverflow.com/a/47488093
has body: I'm trying to remove all occurrences of substrings between and in the below string and also remove and : txt = ' Large pythons were the subject of many a news story \n last year due to the fact that there were at least two deaths directly attributable to them . Tragically, the deaths would not have happened had the owners of these snakes kept them safely, and responsibly, contained. The following article, by David Chiszar, Hobart M. Smith, <a href= Albert Petkus and Joseph Dougherty , was recently published in the Bulletin of the Chicago Herpetological Society, and represents the first clear, and accurate, account of the death that occurred July 1993 \n' I wrote the following code to remove these tags for three occurrences of substrings. def remsubstr( s, first, last ): if first and last not in s: return s try: start = s.index( first ) + len( first ) end = s.index( last, start ) d = (s[:start] +" "+ s[end:]).replace(' ', '').replace(' \n', '') started = d.index(" " ) ended = d.index(" ") + len(" ") nw = d.replace(d[started:ended], '') if first and last in nw: start = nw.index( first ) + len( first ) end = nw.index( last, start ) d1 = (nw[:start] +" "+ nw[end:]) started = d1.index(" " ) ended = d1.index(" ") + len(" ") nw1 = d1.replace(d1[started:ended], '') if first and last in nw1: start = nw1.index( first ) + len( first ) end = nw1.index( last, start ) d2 = (nw1[:start] +" "+ nw1[end:]) started = d2.index(" " ) ended = d2.index(" ") + len(" ") nw2 = d2.replace(d2[started:ended], '') return nw2 return nw1 return nw except ValueError: return "" I'm able to remove all the required tags using the above code for the example: remsubstr(txt," ", " ") Result: 'Large pythons were a news story last year due to the fact that there were at least two deaths . Tragically, the deaths would not have happened had safely, and responsibly, contained. The following article, by David Chiszar, Hobart M. Smith, <a href= Albert Petkus and Joseph Dougherty , was recently published in the …
has answer: http://stackoverflow.com/a/47488336
has comment: http://stackoverflow.com/comment/81930867
favorite count: 0
score: -1
type: Question
downvote count: 2
accepted answer: http://stackoverflow.com/a/47488336
upvote count: 1
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81931040
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81930915

http://stackoverflow.com/a/47439727
has comment: http://stackoverflow.com/comment/81876395
has comment: http://stackoverflow.com/comment/81834558
answers question: http://stackoverflow.com/q/47439545
has comment: http://stackoverflow.com/comment/81876694
has comment: http://stackoverflow.com/comment/81834636
type: Answer
has comment: http://stackoverflow.com/comment/81876742
has comment: http://stackoverflow.com/comment/81876948
has body: IIUC, use isin: df['ColC'] = df.ColA.isin(df.ColB).astype(int)
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81834568

http://stackoverflow.com/comment/81939711
score: 0
type: AnswerComment
has text: Another thing. What's the idea behind subplots? From what I read they are plots of thesame figure that are copies. Would i be able to subplots for what I am doing and would it be better than 3 figures if I am trying to fit the three normal distribution plots on one page? I'm looking for optimum quality while taking up less space on a page.
type: Comment
comment on: http://stackoverflow.com/a/47491365

http://stackoverflow.com/comment/82017036
has text: `import statsmodels.api as sm `
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47529066

http://stackoverflow.com/comment/81989205
type: Comment
score: 0
has text: @Mia ... have you looked at the duplicate answer? Have you tried using a for-loop? Or just the equivalent list-comprehension? (although, I would stick to simpler constructs until you have a handle on the basics of the language, learn to walk before you run)
type: QuestionComment
comment on: http://stackoverflow.com/q/47516158

http://stackoverflow.com/comment/81854872
type: Comment
score: 0
has text: What is the question?
type: QuestionComment
comment on: http://stackoverflow.com/q/47446909

http://stackoverflow.com/comment/82021477
comment on: http://stackoverflow.com/q/47532529
score: 1
type: Comment
type: QuestionComment
has text: maybe format your code before posting a question?

http://stackoverflow.com/comment/81850480
type: QuestionComment
comment on: http://stackoverflow.com/q/47447624
score: 0
has text: @Nurzhan Nogerbek There might be a chance of duplicate entry for apps in your project like **users** I guess and also check the order as well.
type: Comment

http://stackoverflow.com/q/47465610
upvote count: 1
has comment: http://stackoverflow.com/comment/81899243
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0
has title: correct way to implement thread python
tagged with: python
has comment: http://stackoverflow.com/comment/81886968
has comment: http://stackoverflow.com/comment/81917854
has comment: http://stackoverflow.com/comment/81898799
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/81887369
has body: I am implement a simple simulator of soccer with python using threads and lock, the app works fine but I have doubts in the way that implement the thread it seems to me that the first team has an advantage because is executing first. def jugar(Equipo1, Equipo2): # Busco las probabilidades de encajar por cada equipo prob_encajar_eq1 = Equipo1.probabilidad_encajar() prob_encajar_eq2 = Equipo2.probabilidad_encajar() def jugar_equipo1(defensa_rival): semaforo.acquire() if Equipo1.hacer_pases(): Equipo1.shoot(defensa_rival) semaforo.release() def jugar_equipo2(defensa_rival): semaforo.acquire() if Equipo2.hacer_pases(): Equipo2.shoot(defensa_rival) semaforo.release() hilo_equipo1 = threading.Thread(name = 'hilo_eq1', target = jugar_equipo1, args = (prob_encajar_eq2,)) hilo_equipo2 = threading.Thread(name = 'hilo_eq2', target = jugar_equipo2, args = (prob_encajar_eq1,)) hilo_equipo1.start() hilo_equipo2.start() hilo_equipo1.join() hilo_equipo2.join() to make several attempts both teams, I do a cicle for a few seconds and inside the function jugar() which is the one that does the work with threads but here is were I have the doubts, because every time that jugar is executing the threads are declared again. if __name__ == '__main__': cargar_informacion() eqA = Equipo(equipoA, ranking_eqA) eqB = Equipo(equipoB, ranking_eqB) probabilidades = porcenajes_ranking(ranking_eqA) eqA.cargar_probabilidades(probabilidades) probabilidades = porcenajes_ranking(ranking_eqB) eqB.cargar_probabilidades(probabilidades) starttime=time.time() tiempo = 0 # creo la barra de progreso bar = progressbar.ProgressBar(widgets=[ progressbar.Percentage(), progressbar.Bar(), ], max_value=100).start() # hacemos que el juego tarde aproximadamente 10seg en simularse. while tiempo &lt; 10: time.sleep(0.3 - ((time.time() - starttime) % 0.3)) jugar(eqA,eqB) tiempo = time.time() - starttime bar += 2.8 bar.finish() # Para que finalice la barra de progreso resultados_finales(eqA, eqB) # Mostramos el resultado fin…
has comment: http://stackoverflow.com/comment/81900740

http://stackoverflow.com/comment/81803574
score: 0
has text: Thanks Niema for the suggestion. Excellent point. I edited the count if statements to be > or equal, but I am afraid that didn't solve it either. They say: "If several possible consensus strings exist, then you may return any one of them" so I would have thought iterating over the bases as such would be okay.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47424246

http://stackoverflow.com/comment/81809209
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47427348
has text: The solution is intuitive and great, and I was thinking why this didnt occur to me. Seems my pandas really got rustic. Thanks a lot for your time.

http://stackoverflow.com/comment/81867302
has text: Or any directory above that directory for that matter. So far. No permission issues I'm seeing in that directory so far.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47455977
type: QuestionComment

http://stackoverflow.com/a/47387042
has body: You need to do it in below way. This way has a problem of random order of writing data in the csv: with open("output.csv", "a", newline='') as fp: writer = csv.writer(fp, dialect='excel') writer.writerow(exported_data[0].keys()) for line in exported_data: print(line) writer.writerow(line.values()) You did everything right, but when you pass a dictionary, keys are taken as list, so you need to specify what needs to be written to csv - line.values() If you are interested in the order of the keys, then do it below way: with open("output.csv", "a", newline='') as fp: writer = csv.writer(fp, dialect='excel') header_list = ['time,value1,value10,value2,value3,value4,value5,value6,value7,value8,value9'] writer.writerow(header_list) for line in exported_data: print(line) writer.writerow([line[kn] for kn in header_list])
has comment: http://stackoverflow.com/comment/81727203
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81731301
has comment: http://stackoverflow.com/comment/81727397
answers question: http://stackoverflow.com/q/47386655
has comment: http://stackoverflow.com/comment/81727434
has comment: http://stackoverflow.com/comment/81732849
has comment: http://stackoverflow.com/comment/81727255
has comment: http://stackoverflow.com/comment/81727773
has comment: http://stackoverflow.com/comment/81731502
has comment: http://stackoverflow.com/comment/81727540
has comment: http://stackoverflow.com/comment/81727690
accepted answer of: http://stackoverflow.com/q/47386655
has comment: http://stackoverflow.com/comment/81727739
has comment: http://stackoverflow.com/comment/81727666
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81727165

http://stackoverflow.com/comment/82076466
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47531396
has text: Creating a policy for each table is an overhead yes, but you only have to do it once. If you write a script to do so and check it into the repo, it doesn't feel so bad. Re: syncing db and application layer. Actually, this is mostly handled by setting the session variable appropriately with one line of code and the rest is handled inside the policies. The only catch is that if this particular field changes via a migration, that might create a security flaw. I'm planning to mitigate this with some integration tests. I feel like it's simpler to maintain compared to multitenancy.

rewriting
tag name: rewriting
tags question: http://stackoverflow.com/q/47415746
type: Tag

http://stackoverflow.com/comment/81926214
has text: @hpaulj I know that there are a few similar questions - but I did not find any answer that delivers a true replacement. In my question I commented on the workaround drom selected answer in the question you linked. It just does not really work.
score: 0
comment on: http://stackoverflow.com/q/47479572
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47460715
duplicate of: http://stackoverflow.com/q/65113967
downvote count: 0
accepted answer: http://stackoverflow.com/a/47460947
has body: import pygame as pg import sys pg.init() buttonFont = pg.font.SysFont("garamond", 25) screenGray = pg.Color('gray80') buttonGray2 = pg.Color('gray50') textColour = pg.Color('navy') screen = pg.display.set_mode((800, 600)) clock = pg.time.Clock() class Button(pg.sprite.Sprite): def __init__(self, text, x, y, width, height, colour): super().__init__() self.image = pg.Surface((width, height)) self.image.fill(colour) self.rect = self.image.get_rect() txt = buttonFont.render(text, True, textColour) txtRect = txt.get_rect(center = self.rect.center) self.image.blit(txt, txtRect) self.rect.topleft = x, y def isPressed(self, event): if event.type == pg.MOUSEBUTTONDOWN: if self.rect.collidepoint(event.pos): return True return False def FrontPage(): screen.fill(screenGray) Continue = Button('Continue', 105, 455, 120, 50, buttonGray2) buttonsGroup1 = pg.sprite.Group(Continue) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() elif Continue.isPressed(event): Menu() buttonsGroup1.draw(screen) pg.display.flip() clock.tick(60) def Menu(): screen.fill(screenGray) Scytale = Button('Scytale', 105,105,140,65, buttonGray2) Caesar = Button('Caesar', 330,105,140,65, buttonGray2) Vigenere = Button('Vigenere', 555,105,140,65, buttonGray2) Enigma = Button('Enigma', 105,430,140,65,buttonGray2) PublicKey = Button('Public Key', 330,430,140,65, buttonGray2) Rijndael = Button('Rijndael', 555,430,140,65, buttonGray2) buttonsGroup2 = pg.sprite.Group(Scytale,Caesar,Vigenere,Enigma,PublicKey,Rijndael) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() buttonsGroup2.draw(screen) clock.tick(60) FrontPage() Above is the stripped back code of my FrontPage, that has a button on it that, when clicked, should take the user to the menu screen where 6 more buttons are displayed to move onto the users chosen encryption method. However, when I press the Continue button, nothing happens. Is it because there is something wrong with the Butt…
has answer: http://stackoverflow.com/a/47460947
type: AnsweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/65264616
tagged with: python
tagged with: pygame
favorite count: 0
type: Question
has title: Calling a PyGame Function, from clicking a Object-Orientated PyGame Button
duplicate of: http://stackoverflow.com/q/65264616
upvote count: 2
score: 2

http://stackoverflow.com/a/53112700
upvote count: 1
answers question: http://stackoverflow.com/q/47523742
has body: The dict returned by _getexif() is indexed by the tag id, not some string name. In this case the GPSInfo tag id is 8825 in hex (34853 in decimal). See the end of table 17 in section 4.6.8 of the EXIF spec. However, the GPSInfo tag is dict of GPS tags indexed also by tag id. In table 15 in section 4.6.6, we see that the latitude direction (named GPSLatitudeRef) has an id of 1, which your code had correct. So you should get what you want by using the following line: latitude_direction = inputfile._getexif()[0x8825][1]
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81751412
type: Comment
score: 0
type: QuestionComment
has text: @SuperStew : The Selenium2Library for Robot Framework is the culprit here. Other libraries for Robot and selenium for other platforms can work with later versions.
comment on: http://stackoverflow.com/q/47398321

http://stackoverflow.com/a/47433720
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47432198
answers question: http://stackoverflow.com/q/47432198
has comment: http://stackoverflow.com/comment/81867869
type: Answer
has comment: http://stackoverflow.com/comment/81867983
downvote count: 0
score: 1
upvote count: 1
has body: Check this I used rolling which will roll over the given frequency and do the mathematical operations like sum,mean etc. In this you need to know the start and end datetime values. Code: df.timestamp=pd.to_datetime(df.timestamp) df.set_index('timestamp',inplace=True) df = df.rolling('15s').mean() mask = pd.date_range('2016-03-11 07:37:40','2016-03-11 07:38:05',freq='10S') df = df.loc[mask] df value 2016-03-11 07:37:40 24.601800 2016-03-11 07:37:50 24.602767 2016-03-11 07:38:00 24.598067 Use your desired window instead of '15s' in rolling as well as date_range that I used.Let me know this works for you.

http://stackoverflow.com/comment/81817408
score: 1
type: Comment
type: QuestionComment
has text: You can not sort 2 different types. For e.g. which one is greater, an integer 5 or a string "Hello" ?
comment on: http://stackoverflow.com/q/47431431

http://stackoverflow.com/a/47504139
has body: Another groupby solution: from itertools import groupby list_one = ["Alex", "Alex", "John", "Alex", "John", "John"] list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"] l2iter = iter(list_two) list_three, list_four = zip(*((key, ' '.join(next(l2iter) for whatever in grp)) for key, grp in groupby(list_one)))
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47503883
upvote count: 2
answers question: http://stackoverflow.com/q/47503883
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47454455
tagged with: openedge
type: Question
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/19482730
has answer: http://stackoverflow.com/a/47454685
has answer: http://stackoverflow.com/a/47455939
accepted answer: http://stackoverflow.com/a/47455939
tagged with: pyodbc
favorite count: 0
has body: I am new to python and pyodbc I try to print the first a row from a table from a progress openedge database. (Windows 7) Here is the code block that is not running: cursor.execute("select my-nr, my-dt-my from mytable") row = cursor.fetchone() print(row.my-nr, row.my-dt-my) This gives errors undefined name: 'nr' undefined name 'dt' undefined name 'my' I guess it has something to do with the minus - symbols behind the dot . in print(row.my-nr, row.my-dt-my) It was easy to print out the table names and column names from the database earlier but for some reason printing out rows is harder. Any ideas how to get the rows printed?
type: AnsweredQuestion
has title: Referencing row values in pyodbc when column name contains dashes (hyphens)
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/47455841
possible better answer: http://stackoverflow.com/a/47455841
tagged with: python
has comment: http://stackoverflow.com/comment/81863460

http://stackoverflow.com/a/47516234
has comment: http://stackoverflow.com/comment/81989402
has comment: http://stackoverflow.com/comment/81996420
has comment: http://stackoverflow.com/comment/82035444
has comment: http://stackoverflow.com/comment/82026458
has comment: http://stackoverflow.com/comment/81989724
has comment: http://stackoverflow.com/comment/82027687
has comment: http://stackoverflow.com/comment/82030547
has comment: http://stackoverflow.com/comment/82026649
has comment: http://stackoverflow.com/comment/82027903
has body: You need to convert your script in a function first, then you iterate over each line of the csv file, you extract the value you need and assign it the to ofile variable.Finally, run the function passing ofile as an argument. I can't be more precise since you haven't posted any example of the actual csv, but the implementation should look something like this: import time import pysftp import sys import os from datetime import datetime import calendar import zipfile import re def myscript(ofile): oupload = pysftp.Connection(host="xxxx", username="sxx", password="xNxxxx") d = datetime.utcnow() unixtime=calendar.timegm(d.utctimetuple()) month = datetime.now().strftime("%m") string = ofile+month+".*\.txt$" possibleFiles = oupload.listdir("/") for filename in possibleFiles: filedate = re.search(string, filename) if filedate: newfile = filename timestamp = oupload.stat(newfile).st_atime if timestamp != unixtime: newtime=unixtime + 1800 zipname = ofile+str(newtime)+'.sync.zip' create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED) oupload.get(newfile, newfile) oupload.close() newfilename = ofile+str(newtime)+'.sync' os.rename(newfile, newfilename) create_zip.write(newfilename) create_zip.close() else: print "No file found" mycsv = 'mydocument.csv' with open(mycsv, 'r') as f: for line in f: if not line.startswith('\n'): #skip empty lines ofile = line.strip() #assuming you have only one column myscript(ofile)
type: Answer
has comment: http://stackoverflow.com/comment/82029019
has comment: http://stackoverflow.com/comment/82008762
has comment: http://stackoverflow.com/comment/81992413
has comment: http://stackoverflow.com/comment/82030362
score: 0
has comment: http://stackoverflow.com/comment/81989354
has comment: http://stackoverflow.com/comment/82030089
answers question: http://stackoverflow.com/q/47515994

http://stackoverflow.com/comment/81911699
comment on: http://stackoverflow.com/q/47478332
score: 1
has text: `0` (zero) is integer number so you don't need `int()` - you can do `rand_mem = 0`. `randint()` returns integer number so you don't need `int()` - you can do `x = randint(1, rowcount)`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81918876
comment on: http://stackoverflow.com/q/47481880
score: 0
has text: I also updated the question with results of the run, and now I'm more confused since the functions seem to produce different results.
type: Comment
type: QuestionComment

superclass
type: Tag
tag name: superclass
tags question: http://stackoverflow.com/q/47464535

http://stackoverflow.com/q/47492722
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81940822
has title: Stats: Probability of Sequence given Binomial distribution?
tagged with: python
possible better answer: http://stackoverflow.com/a/47492810
has answer: http://stackoverflow.com/a/47492810
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/47492782
has answer: http://stackoverflow.com/a/47492782
tagged with: statistics
has body: I'm trying to find a function in numpy that gives the probability of observing a sequence given an initial binomial probability distribution. For example, if the sequence was [H, T, H, T, H, T, H, T] and H both had 0.5 probabilities, is there a function that will give the low probability of observing these counts of H and T (order doesn't matter)? I was trying to follow the example in the numpy documentation, but my code below is giving a very low probability (5.8%) when it should be near 50%: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.binomial.html#numpy.random.binomial import numpy as np p_H = 0.5 p_T = 1 - p_H seq = ['H', 'T', 'H', 'T', 'H', 'T', 'H', 'T'] num_H = seq.count('H') p_obs = sum(np.random.binomial(num_H, p_H, 1000)==num_H)/1000 print('Probability of observing', num_H, 'H:',p_obs) I imagine I'm missing something obvious, but I can't seem to figure it out. Thanks!

http://stackoverflow.com/a/47488333
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81931941
has body: Use numpy + vstack instead: a=np.array(np.random.rand(20,10)) b=np.array(np.random.rand(1,10)) a.shape (20,10) a=np.vstack([a,b]) a.shape (21, 10)
type: Answer
answers question: http://stackoverflow.com/q/47487763